code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function mycallback(error, object) { if (!callback) return; if (error || !object) callback(null); else callback(WebInspector.RemoteObject.fromPayload(object)); }
@param {?Protocol.Error} error @param {RuntimeAgent.RemoteObject} object
mycallback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/RemoteObject.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/RemoteObject.js
MIT
function remoteObjectBinder(error, properties) { if (error) { callback(null); return; } var result = []; for (var i = 0; properties && i < properties.length; ++i) { var property = properties[i]; if (property.get || property.set) { if (property.get) result.push(new WebInspector.RemoteObjectProperty("get " + property.name, WebInspector.RemoteObject.fromPayload(property.get), property)); if (property.set) result.push(new WebInspector.RemoteObjectProperty("set " + property.name, WebInspector.RemoteObject.fromPayload(property.set), property)); } else result.push(new WebInspector.RemoteObjectProperty(property.name, WebInspector.RemoteObject.fromPayload(property.value), property)); } callback(result); }
@param {?Protocol.Error} error @param {Array.<WebInspector.RemoteObjectProperty>} properties
remoteObjectBinder
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/RemoteObject.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/RemoteObject.js
MIT
function evaluatedCallback(error, result, wasThrown) { if (error || wasThrown) { callback(error || result.description); return; } function setPropertyValue(propertyName, propertyValue) { this[propertyName] = propertyValue; } delete result.description; // Optimize on traffic. RuntimeAgent.callFunctionOn(this._objectId, setPropertyValue.toString(), [{ value:name }, result], undefined, propertySetCallback.bind(this)); if (result._objectId) RuntimeAgent.releaseObject(result._objectId); }
@param {?Protocol.Error} error @param {RuntimeAgent.RemoteObject} result @param {boolean=} wasThrown
evaluatedCallback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/RemoteObject.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/RemoteObject.js
MIT
function mycallback(error, result, wasThrown) { callback((error || wasThrown) ? null : WebInspector.RemoteObject.fromPayload(result)); }
@param {function(*)} functionDeclaration @param {Array.<RuntimeAgent.CallArgument>|undefined} args @param {function(?WebInspector.RemoteObject)} callback
mycallback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/RemoteObject.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/RemoteObject.js
MIT
function mycallback(error, result, wasThrown) { callback((error || wasThrown) ? null : result.value); }
@param {function(*)} functionDeclaration @param {Array.<RuntimeAgent.CallArgument>|undefined} args @param {function(*)} callback
mycallback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/RemoteObject.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/RemoteObject.js
MIT
function persist() { window.localStorage["resource-history"] = JSON.stringify(filteredRegistry); }
@param {number} type @param {WebInspector.ResourceDomainModelBinding} binding
persist
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/Resource.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/Resource.js
MIT
function parseNameValue(pair) { var parameter = {}; var splitPair = pair.split("=", 2); parameter.name = splitPair[0]; if (splitPair.length === 1) parameter.value = ""; else parameter.value = splitPair[1]; return parameter; }
@param {string} queryString @return {Array.<Object>}
parseNameValue
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/Resource.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/Resource.js
MIT
get titleText() { return this._titleText; }
@constructor @extends {TreeElement} @param {boolean=} hasChildren @param {boolean=} noIcon
titleText
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ResourcesPanel.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ResourcesPanel.js
MIT
get itemURL() { return "category://" + this._categoryName; }
@constructor @extends {WebInspector.BaseStorageTreeElement} @param {boolean=} noIcon
itemURL
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ResourcesPanel.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ResourcesPanel.js
MIT
function callback(resource) { if (resource.path === url) { resourceURL = resource.url; return true; } }
@return {?string} null if the specified resource MUST NOT have a URL (e.g. "javascript:...")
callback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ResourceUtils.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ResourceUtils.js
MIT
function didEditScriptSource(error, callFrames) { if (!error) this._source = newSource; callback(error, callFrames); }
@this {WebInspector.Script} @param {?Protocol.Error} error @param {Array.<DebuggerAgent.CallFrame>|undefined} callFrames
didEditScriptSource
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/Script.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/Script.js
MIT
function typeWeight(treeElement) { if (treeElement instanceof WebInspector.NavigatorFolderTreeElement) { if (treeElement.isDomain) return 1; return 2; } return 3; }
@constructor @extends {TreeOutline} @param {Element} element
typeWeight
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ScriptsNavigator.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ScriptsNavigator.js
MIT
function viewGetter() { return this.visibleView; }
@constructor @implements {WebInspector.EditorContainerDelegate} @extends {WebInspector.Panel}
viewGetter
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ScriptsPanel.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ScriptsPanel.js
MIT
function contentCallback(mimeType, content) { if (this._outlineWorker) this._outlineWorker.terminate(); this._outlineWorker = new Worker("ScriptFormatterWorker.js"); this._outlineWorker.onmessage = this._didBuildOutlineChunk.bind(this); const method = "outline"; this._outlineWorker.postMessage({ method: method, params: { content: content, id: this.visibleView.uiSourceCode.id } }); }
@param {WebInspector.UISourceCode} uiSourceCode @return {WebInspector.SourceFrame}
contentCallback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ScriptsPanel.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ScriptsPanel.js
MIT
get defaultFocusedElement() { return this._filesSelectElement; }
@implements {WebInspector.ScriptsPanel.FileSelector} @extends {WebInspector.Object} @constructor
defaultFocusedElement
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ScriptsPanel.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ScriptsPanel.js
MIT
function filterOutContentScripts(uiSourceCode) { return !uiSourceCode.isContentScript; }
@param {WebInspector.SearchConfig} searchConfig @param {function(Object)} searchResultCallback @param {function(boolean)} searchFinishedCallback
filterOutContentScripts
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/ScriptsSearchScope.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/ScriptsSearchScope.js
MIT
set small(x) { this._small = x; if (this._listItemNode) { if (this._small) this._listItemNode.addStyleClass("small"); else this._listItemNode.removeStyleClass("small"); } }
@constructor @extends {TreeElement} @param {string=} subtitle @param {Object=} representedObject @param {boolean=} hasChildren
small
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/SidebarTreeElement.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/SidebarTreeElement.js
MIT
function consume(e) { e.consume(true); }
@param {Function=} onmove @param {Function=} onstart @param {Function=} onstop
consume
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/Spectrum.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/Spectrum.js
MIT
get disabled() { return this._disabled; }
@extends {WebInspector.Object} @constructor @param {number=} states
disabled
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/StatusBarButton.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/StatusBarButton.js
MIT
function computedStyleCallback(computedStyle) { delete this._refreshUpdateInProgress; if (this._lastNodeForInnerRefresh) { delete this._lastNodeForInnerRefresh; this._refreshUpdate(editedSection, forceFetchComputedStyle, userCallback); return; } if (this.node === node && computedStyle) this._innerRefreshUpdate(node, computedStyle, editedSection); if (userCallback) userCallback(); }
@param {WebInspector.StylePropertiesSection=} editedSection @param {boolean=} forceFetchComputedStyle @param {function()=} userCallback
computedStyleCallback
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/StylesSidebarPane.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/StylesSidebarPane.js
MIT
get inherited() { return this._inherited; }
@constructor @extends {TreeElement} @param {?WebInspector.StylesSidebarPane} parentPane
inherited
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/StylesSidebarPane.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/StylesSidebarPane.js
MIT
get text() { return this._element.textContent; }
Clients should never attach any event listeners to the |element|. Instead, they should use the result of this method to attach listeners for bubbling events or the |blurListener| parameter to register a "blur" event listener on the |element| (since the "blur" event does not bubble.) @param {Element} element @param {function(Event)} blurListener
text
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/TextPrompt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/TextPrompt.js
MIT
get historyData() { // FIXME: do we need to copy this? return this._data; }
Whether to coalesce duplicate items in the history, default is true. @type {boolean}
historyData
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/TextPrompt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/TextPrompt.js
MIT
function updateBoundaries(record) { this._overviewCalculator.updateBoundaries(record); return false; }
@constructor @extends {WebInspector.Object} @implements {WebInspector.TimelinePresentationModel.Filter}
updateBoundaries
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/TimelineOverviewPane.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/TimelineOverviewPane.js
MIT
function getContent(element) { if (element.tagName === "INPUT" && element.type === "text") return element.value; else return element.textContent; }
@param {Element} element @param {WebInspector.EditingConfig=} config
getContent
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/UIUtils.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/UIUtils.js
MIT
function windowLoaded() { window.addEventListener("focus", WebInspector._windowFocused, false); window.addEventListener("blur", WebInspector._windowBlurred, false); document.addEventListener("focus", WebInspector._focusChanged.bind(this), true); window.removeEventListener("DOMContentLoaded", windowLoaded, false); }
@param {WebInspector.ContextMenu} contextMenu @param {Node} contextNode @param {Event} event
windowLoaded
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/UIUtils.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/UIUtils.js
MIT
function highlightSearchResult(element, offset, length, domChanges) { var result = highlightSearchResults(element, [{offset: offset, length: length }], domChanges); return result.length ? result[0] : null; }
@param {Element} element @param {number} offset @param {number} length @param {Array.<Object>=} domChanges
highlightSearchResult
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/utilities.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/utilities.js
MIT
function highlightSearchResults(element, resultRanges, changes) { return highlightRangesWithStyleClass(element, resultRanges, "webkit-search-result", changes); }
@param {Element} element @param {Array.<Object>} resultRanges @param {Array.<Object>=} changes
highlightSearchResults
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/utilities.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/utilities.js
MIT
function highlightRangesWithStyleClass(element, resultRanges, styleClass, changes) { changes = changes || []; var highlightNodes = []; var lineText = element.textContent; var ownerDocument = element.ownerDocument; var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var snapshotLength = textNodeSnapshot.snapshotLength; if (snapshotLength === 0) return highlightNodes; var nodeRanges = []; var rangeEndOffset = 0; for (var i = 0; i < snapshotLength; ++i) { var range = {}; range.offset = rangeEndOffset; range.length = textNodeSnapshot.snapshotItem(i).textContent.length; rangeEndOffset = range.offset + range.length; nodeRanges.push(range); } var startIndex = 0; for (var i = 0; i < resultRanges.length; ++i) { var startOffset = resultRanges[i].offset; var endOffset = startOffset + resultRanges[i].length; while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset) startIndex++; var endIndex = startIndex; while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset) endIndex++; if (endIndex === snapshotLength) break; var highlightNode = ownerDocument.createElement("span"); highlightNode.className = styleClass; highlightNode.textContent = lineText.substring(startOffset, endOffset); var lastTextNode = textNodeSnapshot.snapshotItem(endIndex); var lastText = lastTextNode.textContent; lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset); changes.push({ node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent }); if (startIndex === endIndex) { lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode); changes.push({ node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement }); highlightNodes.push(highlightNode); var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset)); lastTextNode.parentElement.insertBefore(prefixNode, highlightNode); changes.push({ node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement }); } else { var firstTextNode = textNodeSnapshot.snapshotItem(startIndex); var firstText = firstTextNode.textContent; var anchorElement = firstTextNode.nextSibling; firstTextNode.parentElement.insertBefore(highlightNode, anchorElement); changes.push({ node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement }); highlightNodes.push(highlightNode); firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset); changes.push({ node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent }); for (var j = startIndex + 1; j < endIndex; j++) { var textNode = textNodeSnapshot.snapshotItem(j); var text = textNode.textContent; textNode.textContent = ""; changes.push({ node: textNode, type: "changed", oldText: text, newText: textNode.textContent }); } } startIndex = endIndex; nodeRanges[startIndex].offset = endOffset; nodeRanges[startIndex].length = lastTextNode.textContent.length; } return highlightNodes; }
@param {Element} element @param {Array.<Object>} resultRanges @param {string} styleClass @param {Array.<Object>=} changes
highlightRangesWithStyleClass
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/utilities.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/utilities.js
MIT
function createPlainTextSearchRegex(query, flags) { // This should be kept the same as the one in ContentSearchUtils.cpp. var regexSpecialCharacters = "[](){}+-*.,?\\^$|"; var regex = ""; for (var i = 0; i < query.length; ++i) { var c = query.charAt(i); if (regexSpecialCharacters.indexOf(c) != -1) regex += "\\"; regex += c; } return new RegExp(regex, flags || ""); }
@param {string} query @param {string=} flags @return {RegExp}
createPlainTextSearchRegex
javascript
node-pinus/pinus
tools/pinus-admin-web/public/front/utilities.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/front/utilities.js
MIT
function calcLengthLength (length) { if (length >= 0 && length < 128) return 1 else if (length >= 128 && length < 16384) return 2 else if (length >= 16384 && length < 2097152) return 3 else if (length >= 2097152 && length < 268435456) return 4 else return 0 }
calcLengthLength - calculate the length of the remaining length field @api private
calcLengthLength
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function writeLength (stream, length) { var buffer = lengthCache[length] if (!buffer) { buffer = genBufLength(length) if (length < 16384) lengthCache[length] = buffer } stream.write(buffer) }
writeLength - write an MQTT style length field to the buffer @param <Buffer> buffer - destination @param <Number> pos - offset @param <Number> length - length (>0) @returns <Number> number of bytes written @api private
writeLength
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function writeString (stream, string) { var strlen = Buffer.byteLength(string) writeNumber(stream, strlen) stream.write(string, 'utf8') }
writeString - write a utf8 string to the buffer @param <Buffer> buffer - destination @param <Number> pos - offset @param <String> string - string to write @return <Number> number of bytes written @api private
writeString
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function writeNumber (stream, number) { return stream.write(numCache[number]) }
writeNumber - write a two byte number to the buffer @param <Buffer> buffer - destination @param <Number> pos - offset @param <String> number - number to write @return <Number> number of bytes written @api private
writeNumber
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function writeStringOrBuffer (stream, toWrite) { if (toWrite && typeof toWrite === 'string') writeString(stream, toWrite) else if (toWrite) { writeNumber(stream, toWrite.length) stream.write(toWrite) } else writeNumber(stream, 0) }
writeStringOrBuffer - write a String or Buffer with the its length prefix @param <Buffer> buffer - destination @param <Number> pos - offset @param <String> toWrite - String or Buffer @return <Number> number of bytes written
writeStringOrBuffer
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function MqttClient (streamBuilder, options) { var k var that = this if (!(this instanceof MqttClient)) { return new MqttClient(streamBuilder, options) } this.options = options || {} // Defaults for (k in defaultConnectOptions) { if (typeof this.options[k] === 'undefined') { this.options[k] = defaultConnectOptions[k] } else { this.options[k] = options[k] } } this.options.clientId = this.options.clientId || defaultId() this.streamBuilder = streamBuilder // Inflight message storages this.outgoingStore = this.options.outgoingStore || new Store() this.incomingStore = this.options.incomingStore || new Store() // Should QoS zero messages be queued when the connection is broken? this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero // map of subscribed topics to support reconnection this._subscribedTopics = {} // Ping timer, setup in _setupPingTimer this.pingTimer = null // Is the client connected? this.connected = false // Are we disconnecting? this.disconnecting = false // Packet queue this.queue = [] // connack timer this.connackTimer = null // Reconnect timer this.reconnectTimer = null // MessageIDs starting with 1 this.nextId = Math.floor(Math.random() * 65535) // Inflight callbacks this.outgoing = {} // Mark connected on connect this.on('connect', function () { if (this.disconnected) { return } this.connected = true var outStore = null outStore = this.outgoingStore.createStream() // Control of stored messages outStore.once('readable', function () { function storeDeliver () { var packet = outStore.read(1) var cb if (!packet) { return } // Avoid unnecesary stream read operations when disconnected if (!that.disconnecting && !that.reconnectTimer && that.options.reconnectPeriod > 0) { outStore.read(0) cb = that.outgoing[packet.messageId] that.outgoing[packet.messageId] = function (err, status) { // Ensure that the original callback passed in to publish gets invoked if (cb) { cb(err, status) } storeDeliver() } that._sendPacket(packet) } else if (outStore.destroy) { outStore.destroy() } } storeDeliver() }) .on('error', this.emit.bind(this, 'error')) }) // Mark disconnected on stream close this.on('close', function () { this.connected = false clearTimeout(this.connackTimer) }) // Setup ping timer this.on('connect', this._setupPingTimer) // Send queued packets this.on('connect', function () { var queue = this.queue function deliver () { var entry = queue.shift() var packet = null if (!entry) { return } packet = entry.packet that._sendPacket( packet, function (err) { if (entry.cb) { entry.cb(err) } deliver() } ) } deliver() }) // resubscribe this.on('connect', function () { if (this.options.clean && Object.keys(this._subscribedTopics).length > 0) { this.subscribe(this._subscribedTopics) } }) // Clear ping timer this.on('close', function () { if (that.pingTimer !== null) { that.pingTimer.clear() that.pingTimer = null } }) // Setup reconnect timer on disconnect this.on('close', this._setupReconnect) events.EventEmitter.call(this) this._setupStream() }
MqttClient constructor @param {Stream} stream - stream @param {Object} [options] - connection options (see Connection#connect)
MqttClient
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function process () { var packet = packets.shift() var done = completeParse if (packet) { that._handlePacket(packet, process) } else { completeParse = null done() } }
setup the event handlers in the inner stream. @api private
process
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function closeStores () { that.disconnected = true that.incomingStore.close(function () { that.outgoingStore.close(cb) }) }
end - close connection @returns {MqttClient} this - for chaining @param {Boolean} force - do not wait for all in-flight messages to be acked @param {Function} cb - called when the client has been closed @api public
closeStores
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function Store () { if (!(this instanceof Store)) { return new Store() } this._inflights = {} }
In-memory implementation of the message store This can actually be saved into files.
Store
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function validateTopic (topic) { var parts = topic.split('/') for (var i = 0; i < parts.length; i++) { if (parts[i] === '+') { continue } if (parts[i] === '#') { // for Rule #2 return i === parts.length - 1 } if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) { return false } } return true }
Validate a topic to see if it's valid or not. A topic is valid if it follow below rules: - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#' - Rule #2: Part `#` must be located at the end of the mailbox @param {String} topic - A topic @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
validateTopic
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function validateTopics (topics) { if (topics.length === 0) { return 'empty_topic_list' } for (var i = 0; i < topics.length; i++) { if (!validateTopic(topics[i])) { return topics[i] } } return null }
Validate an array of topics to see if any of them is valid or not @param {Array} topics - Array of topics @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
validateTopics
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function parseAuthOptions (opts) { var matches if (opts.auth) { matches = opts.auth.match(/^(.+):(.+)$/) if (matches) { opts.username = matches[1] opts.password = matches[2] } else { opts.username = opts.auth } } }
Parse the auth attribute and merge username and password in the options object. @param {Object} [opts] option object
parseAuthOptions
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function connect (brokerUrl, opts) { if ((typeof brokerUrl === 'object') && !opts) { opts = brokerUrl brokerUrl = null } opts = opts || {} if (brokerUrl) { opts = xtend(url.parse(brokerUrl, true), opts) if (opts.protocol === null) { throw new Error('Missing protocol') } opts.protocol = opts.protocol.replace(/:$/, '') } // merge in the auth options if supplied parseAuthOptions(opts) // support clientId passed in the query string of the url if (opts.query && typeof opts.query.clientId === 'string') { opts.clientId = opts.query.clientId } if (opts.cert && opts.key) { if (opts.protocol) { if (['mqtts', 'wss'].indexOf(opts.protocol) === -1) { /* * jshint and eslint * complains that break from default cannot be reached after throw * it is a foced exit from a control structure * maybe add a check after switch to see if it went through default * and then throw the error */ /* jshint -W027 */ /* eslint no-unreachable:1 */ switch (opts.protocol) { case 'mqtt': opts.protocol = 'mqtts' break case 'ws': opts.protocol = 'wss' break default: throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!') break } /* eslint no-unreachable:0 */ /* jshint +W027 */ } } else { // don't know what protocol he want to use, mqtts or wss throw new Error('Missing secure protocol key') } } if (!protocols[opts.protocol]) { var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1 opts.protocol = [ 'mqtt', 'mqtts', 'ws', 'wss' ].filter(function (key, index) { if (isSecure && index % 2 === 0) { // Skip insecure protocols when requesting a secure one. return false } return (typeof protocols[key] === 'function') })[0] } if (opts.clean === false && !opts.clientId) { throw new Error('Missing clientId for unclean clients') } function wrapper (client) { if (opts.servers) { if (!client._reconnectCount || client._reconnectCount === opts.servers.length) { client._reconnectCount = 0 } opts.host = opts.servers[client._reconnectCount].host opts.port = opts.servers[client._reconnectCount].port opts.hostname = opts.host client._reconnectCount++ } return protocols[opts.protocol](client, opts) } return new MqttClient(wrapper, opts) }
connect - connect to an MQTT broker. @param {String} [brokerUrl] - url of the broker, optional @param {Object} opts - see MqttClient#constructor
connect
javascript
node-pinus/pinus
tools/pinus-admin-web/public/js/util/browserMqtt.js
https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js
MIT
function prepareMoveTransition (frags) { var transition = transitionEndEvent && // css transition supported? frags && frags.length && // has frags to be moved? frags[0].node.__v_trans // has transitions? if (transition) { var node = frags[0].node var moveClass = transition.id + '-move' var moving = node._pendingMoveCb var hasTransition = false if (!moving) { // sniff whether element has a transition duration for transform // with the move class applied addClass(node, moveClass) var type = transition.getCssTransitionType(moveClass) if (type === 'transition') { var computedStyles = window.getComputedStyle(node) var transitionedProps = computedStyles[transitionProp + 'Property'] if (/\btransform(,|$)/.test(transitionedProps)) { hasTransition = true } } removeClass(node, moveClass) } if (moving || hasTransition) { frags.forEach(function (frag) { frag._oldPos = frag.node.getBoundingClientRect() }) return true } } }
Check if move transitions are needed, and if so, record the bounding client rects for each item. @param {Array<Fragment>|undefined} frags @return {Boolean|undefined}
prepareMoveTransition
javascript
vuejs/vue-animated-list
vue-animated-list.js
https://github.com/vuejs/vue-animated-list/blob/master/vue-animated-list.js
MIT
function applyMoveTransition (frags) { frags.forEach(function (frag) { frag._newPos = frag.node.getBoundingClientRect() }) frags.forEach(function (frag) { var node = frag.node var oldPos = frag._oldPos if (!oldPos) return if (!frag.moved) { // transition busting to ensure correct bounding rect: // if an element has an ongoing transition and not "reinserted", // the bounding rect will not be calculated at its target position, // but rather an in-transition position. var p = node.parentNode var next = node.nextSibling p.removeChild(node) p.insertBefore(node, next) } var dx = oldPos.left - frag._newPos.left var dy = oldPos.top - frag._newPos.top if (dx !== 0 || dy !== 0) { frag.moved = true node.style.transform = node.style.WebkitTransform = 'translate(' + dx + 'px, ' + dy + 'px)' node.style.transitionDuration = '0s' } else { frag.moved = false } }) Vue.nextTick(function () { var f = document.documentElement.offsetHeight frags.forEach(function (frag) { var node = frag.node var moveClass = node.__v_trans.id + '-move' if (frag.moved) { addClass(node, moveClass) node.style.transform = node.style.WebkitTransform = '' node.style.transitionDuration = '' if (node._pendingMoveCb) { off(node, transitionEndEvent, node._pendingMoveCb) } node._pendingMoveCb = function cb () { off(node, transitionEndEvent, cb) node._pendingMoveCb = null removeClass(node, moveClass) } on(node, transitionEndEvent, node._pendingMoveCb) } }) }) }
Apply move transitions. Calculate new target positions after the move, then apply the FLIP technique to trigger CSS transforms. @param {Array<Fragment>} frags
applyMoveTransition
javascript
vuejs/vue-animated-list
vue-animated-list.js
https://github.com/vuejs/vue-animated-list/blob/master/vue-animated-list.js
MIT
countObjProps = function (obj) { var k, l = 0; for (k in obj) { if (obj.hasOwnProperty(k)) { l++; } } return l; }
@name Hyphenator-docLanguages @description An object holding all languages used in the document. This is filled by {@link Hyphenator-gatherDocumentInfos} @type {Object} @private
countObjProps
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
createElem = function (tagname, context) { context = context || contextWindow; if (document.createElementNS) { return context.document.createElementNS('http://www.w3.org/1999/xhtml', tagname); } else if (document.createElement) { return context.document.createElement(tagname); } }
@name Hyphenator-onHyphenationDone @description A method to be called, when the last element has been hyphenated or the hyphenation has been removed from the last element. @see Hyphenator.config @type {function()} @private
createElem
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
onError = function (e) { window.alert("Hyphenator.js says:\n\nAn Error ocurred:\n" + e.message); }
@name Hyphenator-selectorFunction @description A function that has to return a HTMLNodeList of Elements to be hyphenated. By default it uses the classname ('hyphenate') to select the elements. @see Hyphenator.config @type {function()} @private
onError
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
getLang = function (el, fallback) { if (!!el.getAttribute('lang')) { return el.getAttribute('lang').toLowerCase(); } // The following doesn't work in IE due to a bug when getAttribute('xml:lang') in a table /*if (!!el.getAttribute('xml:lang')) { return el.getAttribute('xml:lang').substring(0, 2); }*/ //instead, we have to do this (thanks to borgzor): try { if (!!el.getAttribute('xml:lang')) { return el.getAttribute('xml:lang').toLowerCase(); } } catch (ex) {} if (el.tagName !== 'HTML') { return getLang(el.parentNode, true); } if (fallback) { return mainLanguage; } return null; }
@name Hyphenator-getLang @description Gets the language of an element. If no language is set, it may use the {@link Hyphenator-mainLanguage}. @param {Object} el The first parameter is an DOM-Element-Object @param {boolean} fallback The second parameter is a boolean to tell if the function should return the {@link Hyphenator-mainLanguage} if there's no language found for the element. @private
getLang
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
autoSetMainLanguage = function (w) { w = w || contextWindow; var el = w.document.getElementsByTagName('html')[0], m = w.document.getElementsByTagName('meta'), i, text, e, ul; mainLanguage = getLang(el, false); if (!mainLanguage) { for (i = 0; i < m.length; i++) { //<meta http-equiv = "content-language" content="xy"> if (!!m[i].getAttribute('http-equiv') && (m[i].getAttribute('http-equiv').toLowerCase() === 'content-language')) { mainLanguage = m[i].getAttribute('content').toLowerCase(); } //<meta name = "DC.Language" content="xy"> if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'dc.language')) { mainLanguage = m[i].getAttribute('content').toLowerCase(); } //<meta name = "language" content = "xy"> if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'language')) { mainLanguage = m[i].getAttribute('content').toLowerCase(); } } } //get lang for frame from enclosing document if (!mainLanguage && doFrames && contextWindow != window.parent) { autoSetMainLanguage(window.parent); } //fallback to defaultLang if set if (!mainLanguage && defaultLanguage !== '') { mainLanguage = defaultLanguage; } //ask user for lang if (!mainLanguage) { text = ''; ul = navigator.language ? navigator.language : navigator.userLanguage; ul = ul.substring(0, 2); if (prompterStrings.hasOwnProperty(ul)) { text = prompterStrings[ul]; } else { text = prompterStrings.en; } text += ' (ISO 639-1)\n\n' + languageHint; mainLanguage = window.prompt(unescape(text), ul).toLowerCase(); } if (!supportedLang.hasOwnProperty(mainLanguage)) { if (supportedLang.hasOwnProperty(mainLanguage.split('-')[0])) { //try subtag mainLanguage = mainLanguage.split('-')[0]; } else { e = new Error('The language "' + mainLanguage + '" is not yet supported.'); throw e; } } }
@name Hyphenator-autoSetMainLanguage @description Retrieves the language of the document from the DOM. The function looks in the following places: <ul> <li>lang-attribute in the html-tag</li> <li>&lt;meta http-equiv = "content-language" content = "xy" /&gt;</li> <li>&lt;meta name = "DC.Language" content = "xy" /&gt;</li> <li>&lt;meta name = "language" content = "xy" /&gt;</li> </li> If nothing can be found a prompt using {@link Hyphenator-languageHint} and {@link Hyphenator-prompterStrings} is displayed. If the retrieved language is in the object {@link Hyphenator-supportedLang} it is copied to {@link Hyphenator-mainLanguage} @private
autoSetMainLanguage
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
gatherDocumentInfos = function () { var elToProcess, tmp, i = 0, process = function (el, hide, lang) { var n, i = 0, hyphenatorSettings = {}; if (hide && intermediateState === 'hidden') { if (!!el.getAttribute('style')) { hyphenatorSettings.hasOwnStyle = true; } else { hyphenatorSettings.hasOwnStyle = false; } hyphenatorSettings.isHidden = true; el.style.visibility = 'hidden'; } if (el.lang && typeof(el.lang) === 'string') { hyphenatorSettings.language = el.lang.toLowerCase(); //copy attribute-lang to internal lang } else if (lang) { hyphenatorSettings.language = lang.toLowerCase(); } else { hyphenatorSettings.language = getLang(el, true); } lang = hyphenatorSettings.language; if (supportedLang[lang]) { docLanguages[lang] = true; } else { if (supportedLang.hasOwnProperty(lang.split('-')[0])) { //try subtag lang = lang.split('-')[0]; hyphenatorSettings.language = lang; } else if (!isBookmarklet) { onError(new Error('Language ' + lang + ' is not yet supported.')); } } Expando.setDataForElem(el, hyphenatorSettings); elements.push(el); while (!!(n = el.childNodes[i++])) { if (n.nodeType === 1 && !dontHyphenate[n.nodeName.toLowerCase()] && n.className.indexOf(dontHyphenateClass) === -1 && !(n in elToProcess)) { process(n, false, lang); } } }; if (isBookmarklet) { elToProcess = contextWindow.document.getElementsByTagName('body')[0]; process(elToProcess, false, mainLanguage); } else { elToProcess = selectorFunction(); while (!!(tmp = elToProcess[i++])) { process(tmp, true, ''); } } if (!Hyphenator.languages.hasOwnProperty(mainLanguage)) { docLanguages[mainLanguage] = true; } else if (!Hyphenator.languages[mainLanguage].prepared) { docLanguages[mainLanguage] = true; } if (elements.length > 0) { Expando.appendDataForElem(elements[elements.length - 1], {isLast : true}); } }
@name Hyphenator-gatherDocumentInfos @description This method runs through the DOM and executes the process()-function on: - every node returned by the {@link Hyphenator-selectorFunction}. The process()-function copies the element to the elements-variable, sets its visibility to intermediateState, retrieves its language and recursivly descends the DOM-tree until the child-Nodes aren't of type 1 @private
gatherDocumentInfos
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
convertPatterns = function (lang) { var plen, anfang, ende, pats, pat, key, tmp = {}; pats = Hyphenator.languages[lang].patterns; for (plen in pats) { if (pats.hasOwnProperty(plen)) { plen = parseInt(plen, 10); anfang = 0; ende = plen; while (!!(pat = pats[plen].substring(anfang, ende))) { key = pat.replace(/\d/g, ''); tmp[key] = pat; anfang = ende; ende += plen; } } } Hyphenator.languages[lang].patterns = tmp; Hyphenator.languages[lang].patternsConverted = true; }
@name Hyphenator-convertPatterns @description Converts the patterns from string '_a6' to object '_a':'_a6'. The result is stored in the {@link Hyphenator-patterns}-object. @private @param {string} lang the language whose patterns shall be converted
convertPatterns
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
convertExceptionsToObject = function (exc) { var w = exc.split(', '), r = {}, i, l, key; for (i = 0, l = w.length; i < l; i++) { key = w[i].replace(/-/g, ''); if (!r.hasOwnProperty(key)) { r[key] = w[i]; } } return r; }
@name Hyphenator-convertExceptionsToObject @description Converts a list of comma seprated exceptions to an object: 'Fortran,Hy-phen-a-tion' -> {'Fortran':'Fortran','Hyphenation':'Hy-phen-a-tion'} @private @param {string} exc a comma separated string of exceptions (without spaces)
convertExceptionsToObject
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
loadPatterns = function (lang) { var url, xhr, head, script; if (supportedLang[lang] && !Hyphenator.languages[lang]) { url = basePath + 'patterns/' + supportedLang[lang]; } else { return; } if (isLocal && !isBookmarklet) { //check if 'url' is available: xhr = null; if (typeof XMLHttpRequest !== 'undefined') { xhr = new XMLHttpRequest(); } if (!xhr) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xhr = null; } } if (xhr) { xhr.open('HEAD', url, false); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.send(null); if (xhr.status === 404) { onError(new Error('Could not load\n' + url)); delete docLanguages[lang]; return; } } } if (createElem) { head = window.document.getElementsByTagName('head').item(0); script = createElem('script', window); script.src = url; script.type = 'text/javascript'; head.appendChild(script); } }
@name Hyphenator-loadPatterns @description Adds a &lt;script&gt;-Tag to the DOM to load an externeal .js-file containing patterns and settings for the given language. If the given language is not in the {@link Hyphenator-supportedLang}-Object it returns. One may ask why we are not using AJAX to load the patterns. The XMLHttpRequest-Object has a same-origin-policy. This makes the isBookmarklet-functionality impossible. @param {string} lang The language to load the patterns for @private @see Hyphenator-basePath
loadPatterns
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
prepareLanguagesObj = function (lang) { var lo = Hyphenator.languages[lang], wrd; if (!lo.prepared) { if (enableCache) { lo.cache = {}; //Export lo['cache'] = lo.cache; } if (enableReducedPatternSet) { lo.redPatSet = {}; } //add exceptions from the pattern file to the local 'exceptions'-obj if (lo.hasOwnProperty('exceptions')) { Hyphenator.addExceptions(lang, lo.exceptions); delete lo.exceptions; } //copy global exceptions to the language specific exceptions if (exceptions.hasOwnProperty('global')) { if (exceptions.hasOwnProperty(lang)) { exceptions[lang] += ', ' + exceptions.global; } else { exceptions[lang] = exceptions.global; } } //move exceptions from the the local 'exceptions'-obj to the 'language'-object if (exceptions.hasOwnProperty(lang)) { lo.exceptions = convertExceptionsToObject(exceptions[lang]); delete exceptions[lang]; } else { lo.exceptions = {}; } convertPatterns(lang); wrd = '[\\w' + lo.specialChars + '@' + String.fromCharCode(173) + '-]{' + min + ',}'; lo.genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + wrd + ')', 'gi'); lo.prepared = true; } if (!!storage) { try { storage.setItem('Hyphenator_' + lang, window.JSON.stringify(lo)); } catch (e) { //onError(e); } } }
@name Hyphenator-prepareLanguagesObj @description Adds a cache to each language and converts the exceptions-list to an object. If storage is active the object is stored there. @private @param {string} lang the language ob the lang-obj
prepareLanguagesObj
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
prepare = function (callback) { var lang, interval, tmp1, tmp2; if (!enableRemoteLoading) { for (lang in Hyphenator.languages) { if (Hyphenator.languages.hasOwnProperty(lang)) { prepareLanguagesObj(lang); } } state = 2; callback(); return; } // get all languages that are used and preload the patterns state = 1; for (lang in docLanguages) { if (docLanguages.hasOwnProperty(lang)) { if (!!storage && storage.getItem('Hyphenator_' + lang)) { Hyphenator.languages[lang] = window.JSON.parse(storage.getItem('Hyphenator_' + lang)); if (exceptions.hasOwnProperty('global')) { tmp1 = convertExceptionsToObject(exceptions.global); for (tmp2 in tmp1) { if (tmp1.hasOwnProperty(tmp2)) { Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2]; } } } //Replace exceptions since they may have been changed: if (exceptions.hasOwnProperty(lang)) { tmp1 = convertExceptionsToObject(exceptions[lang]); for (tmp2 in tmp1) { if (tmp1.hasOwnProperty(tmp2)) { Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2]; } } delete exceptions[lang]; } //Replace genRegExp since it may have been changed: tmp1 = '[\\w' + Hyphenator.languages[lang].specialChars + '@' + String.fromCharCode(173) + '-]{' + min + ',}'; Hyphenator.languages[lang].genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + tmp1 + ')', 'gi'); delete docLanguages[lang]; continue; } else { loadPatterns(lang); } } } // if all patterns are loaded from storage: callback if (countObjProps(docLanguages) === 0) { state = 2; callback(); return; } // else async wait until patterns are loaded, then callback interval = window.setInterval(function () { var finishedLoading = true, lang; for (lang in docLanguages) { if (docLanguages.hasOwnProperty(lang)) { finishedLoading = false; if (!!Hyphenator.languages[lang]) { delete docLanguages[lang]; //do conversion while other patterns are loading: prepareLanguagesObj(lang); } } } if (finishedLoading) { //console.log('callig callback for ' + contextWindow.location.href); window.clearInterval(interval); state = 2; callback(); } }, 100); }
@name Hyphenator-prepare @description This funtion prepares the Hyphenator-Object: If RemoteLoading is turned off, it assumes that the patternfiles are loaded, all conversions are made and the callback is called. If storage is active the object is retrieved there. If RemoteLoading is on (default), it loads the pattern files and waits until they are loaded, by repeatedly checking Hyphenator.languages. If a patterfile is loaded the patterns are converted to their object style and the lang-object extended. Finally the callback is called. @param {function()} callback to call, when all patterns are loaded @private
prepare
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
toggleBox = function () { var myBox, bdy, myIdAttribute, myTextNode, myClassAttribute, text = (Hyphenator.doHyphenation ? 'Hy-phen-a-tion' : 'Hyphenation'); if (!!(myBox = contextWindow.document.getElementById('HyphenatorToggleBox'))) { myBox.firstChild.data = text; } else { bdy = contextWindow.document.getElementsByTagName('body')[0]; myBox = createElem('div', contextWindow); myIdAttribute = contextWindow.document.createAttribute('id'); myIdAttribute.nodeValue = 'HyphenatorToggleBox'; myClassAttribute = contextWindow.document.createAttribute('class'); myClassAttribute.nodeValue = dontHyphenateClass; myTextNode = contextWindow.document.createTextNode(text); myBox.appendChild(myTextNode); myBox.setAttributeNode(myIdAttribute); myBox.setAttributeNode(myClassAttribute); myBox.onclick = Hyphenator.toggleHyphenation; myBox.style.position = 'absolute'; myBox.style.top = '0px'; myBox.style.right = '0px'; myBox.style.margin = '0'; myBox.style.backgroundColor = '#AAAAAA'; myBox.style.color = '#FFFFFF'; myBox.style.font = '6pt Arial'; myBox.style.letterSpacing = '0.2em'; myBox.style.padding = '3px'; myBox.style.cursor = 'pointer'; myBox.style.WebkitBorderBottomLeftRadius = '4px'; myBox.style.MozBorderRadiusBottomleft = '4px'; bdy.appendChild(myBox); } }
@name Hyphenator-switchToggleBox @description Creates or hides the toggleBox: a small button to turn off/on hyphenation on a page. @param {boolean} s true when hyphenation is on, false when it's off @see Hyphenator.config @private
toggleBox
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
hyphenateURL = function (url) { return url.replace(/([:\/\.\?#&_,;!@]+)/gi, '$&' + urlhyphen); }
@name Hyphenator-removeHyphenationFromElement @description Removes all hyphens from the element. If there are other elements, the function is called recursively. Removing hyphens is usefull if you like to copy text. Some browsers are buggy when the copy hyphenated texts. @param {Object} el The element where to remove hyphenation. @public
hyphenateURL
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
hyphenateElement = function (el) { var hyphenatorSettings = Expando.getDataForElem(el), lang = hyphenatorSettings.language, hyphenate, n, i, controlOrphans = function (part) { var h, r; switch (hyphen) { case '|': h = '\\|'; break; case '+': h = '\\+'; break; case '*': h = '\\*'; break; default: h = hyphen; } if (orphanControl >= 2) { //remove hyphen points from last word r = part.split(' '); r[1] = r[1].replace(new RegExp(h, 'g'), ''); r[1] = r[1].replace(new RegExp(zeroWidthSpace, 'g'), ''); r = r.join(' '); } if (orphanControl === 3) { //replace spaces by non breaking spaces r = r.replace(/[ ]+/g, String.fromCharCode(160)); } return r; }; if (Hyphenator.languages.hasOwnProperty(lang)) { hyphenate = function (word) { if (!Hyphenator.doHyphenation) { return word; } else if (urlOrMailRE.test(word)) { return hyphenateURL(word); } else { return hyphenateWord(lang, word); } }; if (safeCopy && (el.tagName.toLowerCase() !== 'body')) { registerOnCopy(el); } i = 0; while (!!(n = el.childNodes[i++])) { if (n.nodeType === 3 && n.data.length >= min) { //type 3 = #text -> hyphenate! n.data = n.data.replace(Hyphenator.languages[lang].genRegExp, hyphenate); if (orphanControl !== 1) { n.data = n.data.replace(/[\S]+ [\S]+$/, controlOrphans); } } } } if (hyphenatorSettings.isHidden && intermediateState === 'hidden') { el.style.visibility = 'visible'; if (!hyphenatorSettings.hasOwnStyle) { el.setAttribute('style', ''); // without this, removeAttribute doesn't work in Safari (thanks to molily) el.removeAttribute('style'); } else { if (el.style.removeProperty) { el.style.removeProperty('visibility'); } else if (el.style.removeAttribute) { // IE el.style.removeAttribute('visibility'); } } } if (hyphenatorSettings.isLast) { state = 3; documentCount--; if (documentCount > (-1000) && documentCount <= 0) { documentCount = (-2000); onHyphenationDone(); } } }
@name Hyphenator-hyphenateElement @description Takes the content of the given element and - if there's text - replaces the words by hyphenated words. If there's another element, the function is called recursively. When all words are hyphenated, the visibility of the element is set to 'visible'. @param {Object} el The element to hyphenate @private
hyphenateElement
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
hyphenateDocument = function () { function bind(fun, arg) { return function () { return fun(arg); }; } var i = 0, el; while (!!(el = elements[i++])) { if (el.ownerDocument.location.href === contextWindow.location.href) { window.setTimeout(bind(hyphenateElement, el), 0); } } }
@name Hyphenator-removeHyphenationFromDocument @description Does what it says ;-) @private
hyphenateDocument
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
removeHyphenationFromDocument = function () { var i = 0, el; while (!!(el = elements[i++])) { removeHyphenationFromElement(el); } state = 4; }
@name Hyphenator-createStorage @description inits the private var storage depending of the setting in storageType and the supported features of the system. @private
removeHyphenationFromDocument
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
storeConfiguration = function () { if (!storage) { return; } var settings = { 'STORED': true, 'classname': hyphenateClass, 'donthyphenateclassname': dontHyphenateClass, 'minwordlength': min, 'hyphenchar': hyphen, 'urlhyphenchar': urlhyphen, 'togglebox': toggleBox, 'displaytogglebox': displayToggleBox, 'remoteloading': enableRemoteLoading, 'enablecache': enableCache, 'onhyphenationdonecallback': onHyphenationDone, 'onerrorhandler': onError, 'intermediatestate': intermediateState, 'selectorfunction': selectorFunction, 'safecopy': safeCopy, 'doframes': doFrames, 'storagetype': storageType, 'orphancontrol': orphanControl, 'dohyphenation': Hyphenator.doHyphenation, 'persistentconfig': persistentConfig, 'defaultlanguage': defaultLanguage }; storage.setItem('Hyphenator_config', window.JSON.stringify(settings)); }
@name Hyphenator-storeConfiguration @description Stores the current config-options in DOM-Storage @private
storeConfiguration
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
restoreConfiguration = function () { var settings; if (storage.getItem('Hyphenator_config')) { settings = window.JSON.parse(storage.getItem('Hyphenator_config')); Hyphenator.config(settings); } }
@name Hyphenator.version @memberOf Hyphenator @description String containing the actual version of Hyphenator.js [major release].[minor releas].[bugfix release] major release: new API, new Features, big changes minor release: new languages, improvements @public
restoreConfiguration
javascript
cmod/bibliotype
js/Hyphenator.js
https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js
MIT
function createMeterValue(value): UnitValue { return { unit: 'm', value, }; }
The `type` keyword indicates that this is a flow specific declaration. These declarations are not part of the distributed code!
createMeterValue
javascript
ryyppy/flow-guide
tutorial/00-basics/05-recap.js
https://github.com/ryyppy/flow-guide/blob/master/tutorial/00-basics/05-recap.js
MIT
renderData = () => { switch (showAs) { case 'list': return this._renderList(data); case 'grid': return this._renderGrid(data); default: return null; } }
We define the structure of our props, which will usually be done during runtime via React.PropTypes
renderData
javascript
ryyppy/flow-guide
tutorial/01-react/00-intro.js
https://github.com/ryyppy/flow-guide/blob/master/tutorial/01-react/00-intro.js
MIT
performAction({ innerAccess, method, url, query, params, headers, body }) { this.app.meta.util.deprecated('ctx.performAction', 'ctx.meta.util.performAction'); return this.meta.util.performAction({ innerAccess, method, url, query, params, headers, body }); }
perform action of this or that module @param {string} options options @param {string} options.method method @param {string} options.url url @param {json} options.body body(optional) @return {promise} response.body.data or throw error
performAction
javascript
cabloy/cabloy
packages/egg-born-backend/app/extend/context.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js
MIT
function getText(locale, ...args) { const key = args[0]; if (!key) return null; // try locale let resource = ebLocales[locale] || {}; let text = resource[key]; if (text === undefined && locale !== 'en-us') { // try en-us resource = ebLocales['en-us'] || {}; text = resource[key]; } // equal key if (text === undefined) { text = key; } // format args[0] = text; return localeutil.getText.apply(localeutil, args); }
based on koa-locales https://github.com/koajs/locales/blob/master/index.js
getText
javascript
cabloy/cabloy
packages/egg-born-backend/lib/module/locales.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/module/locales.js
MIT
description() { return 'backend cov'; }
/dist/backend.js']; // check dev server const devServerRunning = yield utils.checkIfDevServerRunning({ warnWhenRunning: true, }); if (devServerRunning) return; yield super.run(context); } formatTestArgs({ argv, debugOptions }) { const testArgv = Object.assign({}, argv); /* istanbul ignore next
description
javascript
cabloy/cabloy
packages/egg-born-bin/lib/cmd/backend-cov.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/backend-cov.js
MIT
*curl(url, options) { return yield this.httpClient.request(url, options); }
send curl to remote server @param {String} url - target url @param {Object} [options] - request options @return {Object} response data
curl
javascript
cabloy/cabloy
packages/egg-born-bin/lib/cmd/test-update.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/test-update.js
MIT
*getPackageInfo(pkgName, withFallback) { this.log(`fetching npm info of ${pkgName}`); try { const result = yield this.curl(`${this.registryUrl}/${pkgName}/latest`, { dataType: 'json', followRedirect: true, maxRedirects: 5, timeout: 20000, }); assert(result.status === 200, `npm info ${pkgName} got error: ${result.status}, ${result.data.reason}`); return result.data; } catch (err) { if (withFallback) { this.log(`use fallback from ${pkgName}`); return require(`${pkgName}/package.json`); } throw err; } }
get package info from registry @param {String} pkgName - package name @param {Boolean} [withFallback] - when http request fail, whethe to require local @return {Object} pkgInfo
getPackageInfo
javascript
cabloy/cabloy
packages/egg-born-bin/lib/cmd/test-update.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/test-update.js
MIT
getRegistryByType(key) { switch (key) { case 'china': return 'https://registry.npmmirror.com'; case 'npm': return 'https://registry.npmjs.org'; default: { if (/^https?:/.test(key)) { return key.replace(/\/$/, ''); } // support .npmrc const home = homedir(); let url = process.env.npm_registry || process.env.npm_config_registry || 'https://registry.npmjs.org'; if (fse.existsSync(path.join(home, '.cnpmrc')) || fse.existsSync(path.join(home, '.tnpmrc'))) { url = 'https://registry.npmmirror.com'; } url = url.replace(/\/$/, ''); return url; } } }
get registryUrl by short name @param {String} key - short name, support `china / npm / npmrc`, default to read from .npmrc @return {String} registryUrl
getRegistryByType
javascript
cabloy/cabloy
packages/egg-born-bin/lib/cmd/test-update.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/test-update.js
MIT
get() { const loginInfo = Vue.prototype.$meta.store.getState('auth/loginInfo'); const loginConfig = loginInfo && loginInfo.config; if (!loginConfig) return config; return Vue.prototype.$utils.extend({}, config, loginConfig); }
front base config @todo welcome to pr @name config @property {object} base @property {string} base.locale='en-us' @property {boolean} base.jwt=false @property {object} nprogress @property {number} nprogress.debounce=500 @property {object} api @property {string} api.baseURL='' @property {boolean} api.debounce=200
get
javascript
cabloy/cabloy
packages/egg-born-front/src/base/mixin/config.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-front/src/base/mixin/config.js
MIT
function tryStringify(arg) { try { return JSON.stringify(arg); } catch (err) { // Populate the circular error message lazily if (!CIRCULAR_ERROR_MESSAGE) { try { const a = {}; a.a = a; JSON.stringify(a); } catch (err) { CIRCULAR_ERROR_MESSAGE = err.message; } } if (err.name === 'TypeError' && err.message === CIRCULAR_ERROR_MESSAGE) { return '[Circular]'; } throw err; } }
based on nodejs util.js https://github.com/koajs/locales/blob/master/index.js
tryStringify
javascript
cabloy/cabloy
packages/egg-born-localeutil/src/main.js
https://github.com/cabloy/cabloy/blob/master/packages/egg-born-localeutil/src/main.js
MIT
async _renderFile({ fileSrc, fileDest, fileDestAlt, data }) { // site const site = data.site; // language const language = site.language && site.language.current; // src const pathIntermediate = await this.getPathIntermediate(language); const fileName = path.join(pathIntermediate, fileSrc); // dest const pathDist = await this.getPathDist(site, language); const fileWrite = path.join(pathDist, fileDest); // data data._filename = fileName; data._path = fileSrc.replace('.ejs', ''); // env site data.env('site.path', data._path); // destFile for hot load let hotloadFile; if (data.article) { hotloadFile = `atom/${data.article.atomId}`; // update renderAt data.article.renderAt = new Date(this.ctx.bean.util.moment().unix() * 1000); } else { if ((this.app.meta.isTest || this.app.meta.isLocal) && fileDest.indexOf('.html') > -1) { hotloadFile = fileWrite; data.env('site.hotloadFile', hotloadFile); } } // load src let contentSrc = await fse.readFile(fileName); contentSrc = contentSrc ? contentSrc.toString() : ''; // load includes of plugins const pluginIncludes = await this._loadPluginIncludes({ site, language }); contentSrc = `${pluginIncludes}\n${contentSrc}`; // render const options = this.getOptions(); options.filename = fileName; let content = await ejs.render(contentSrc, data, options); content = await this._renderEnvs({ data, content }); content = await this._renderCSSJSes({ data, content }); // write await fse.outputFile(fileWrite, content); // alternative url if (fileDestAlt && fileDestAlt !== fileDest) { const fileWriteAlt = path.join(pathDist, fileDestAlt); await fse.outputFile(fileWriteAlt, content); } // renderAt must be updated after file rendered if (data.article) { // update renderAt await this.ctx.model.query( ` update aCmsArticle set renderAt=? where iid=? and atomId=? `, [data.article.renderAt, this.ctx.instance.id, data.article.atomId] ); } // socketio publish if (hotloadFile) { await this._socketioPublish({ hotloadFile, article: data.article }); } }
/*.ejs`); for (const item of indexFiles) { // data const data = await this.getData({ site }); // path const _fileSrc = item.substr(pathIntermediate.length + 1); let _fileDest = _fileSrc.substr('main/index/'.length).replace('.ejs', ''); if (_fileDest.indexOf('.') === -1) { _fileDest = `${_fileDest}.html`; } await this._renderFile({ fileSrc: _fileSrc, fileDest: _fileDest, data, }); } } async _writeSitemaps({ site, articles }) { // xml let xml = `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> `; for (const article of articles) { const loc = this.getUrl(site, site.language && site.language.current, article.url); const lastmod = moment(article.updatedAt).format(); xml += ` <url> <loc>${loc}</loc> <lastmod>${lastmod}</lastmod> </url> `; } xml += '</urlset>'; // save const pathDist = await this.getPathDist(site, site.language && site.language.current); const fileName = path.join(pathDist, 'sitemap.xml'); await fse.writeFile(fileName, xml); } async _writeSitemap({ site, article }) { const loc = this.getUrl(site, site.language && site.language.current, article.url); const lastmod = moment(article.updatedAt).format(); // load const pathDist = await this.getPathDist(site, site.language && site.language.current); const fileName = path.join(pathDist, 'sitemap.xml'); let xml; const exists = await fse.pathExists(fileName); if (!exists) { xml = `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>${loc}</loc> <lastmod>${lastmod}</lastmod> </url> </urlset>`; } else { xml = await fse.readFile(fileName); xml = xml.toString(); // remove const regexp = new RegExp(` {2}<url>\\s+<loc>[^<]*${article.url}[^<]*</loc>[\\s\\S]*?</url>[\\r\\n]`); xml = xml.replace(regexp, ''); // append xml = xml.replace( '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>${loc}</loc> <lastmod>${lastmod}</lastmod> </url>` ); } // save await fse.writeFile(fileName, xml); } async _renderStatic({ site }) { // static const pathIntermediate = await this.getPathIntermediate(site.language && site.language.current); const staticFiles = await eggBornUtils.tools.globbyAsync(`${pathIntermediate}/static/*
_renderFile
javascript
cabloy/cabloy
src/module-system/a-cms/backend/src/bean/local.build.js
https://github.com/cabloy/cabloy/blob/master/src/module-system/a-cms/backend/src/bean/local.build.js
MIT
async _renderFile({ fileSrc, fileDest, fileDestAlt, data }) { // site const site = data.site; // language const language = site.language && site.language.current; // src const pathIntermediate = await this.getPathIntermediate(language); const fileName = path.join(pathIntermediate, fileSrc); // dest const pathDist = await this.getPathDist(site, language); const fileWrite = path.join(pathDist, fileDest); // data data._filename = fileName; data._path = fileSrc.replace('.ejs', ''); // env site data.env('site.path', data._path); // destFile for hot load let hotloadFile; if (data.article) { hotloadFile = `atom/${data.article.atomId}`; // update renderAt data.article.renderAt = new Date(this.ctx.bean.util.moment().unix() * 1000); } else { if ((this.app.meta.isTest || this.app.meta.isLocal) && fileDest.indexOf('.html') > -1) { hotloadFile = fileWrite; data.env('site.hotloadFile', hotloadFile); } } // load src let contentSrc = await fse.readFile(fileName); contentSrc = contentSrc ? contentSrc.toString() : ''; // load includes of plugins const pluginIncludes = await this._loadPluginIncludes({ site, language }); contentSrc = `${pluginIncludes}\n${contentSrc}`; // render const options = this.getOptions(); options.filename = fileName; let content = await ejs.render(contentSrc, data, options); content = await this._renderEnvs({ data, content }); content = await this._renderCSSJSes({ data, content }); // write await fse.outputFile(fileWrite, content); // alternative url if (fileDestAlt && fileDestAlt !== fileDest) { const fileWriteAlt = path.join(pathDist, fileDestAlt); await fse.outputFile(fileWriteAlt, content); } // renderAt must be updated after file rendered if (data.article) { // update renderAt await this.ctx.model.query( ` update aCmsArticle set renderAt=? where iid=? and atomId=? `, [data.article.renderAt, this.ctx.instance.id, data.article.atomId] ); } // socketio publish if (hotloadFile) { await this._socketioPublish({ hotloadFile, article: data.article }); } }
/*.ejs`); for (const item of indexFiles) { // data const data = await this.getData({ site }); // path const _fileSrc = item.substr(pathIntermediate.length + 1); let _fileDest = _fileSrc.substr('main/index/'.length).replace('.ejs', ''); if (_fileDest.indexOf('.') === -1) { _fileDest = `${_fileDest}.html`; } await this._renderFile({ fileSrc: _fileSrc, fileDest: _fileDest, data, }); } } async _writeSitemaps({ site, articles }) { // xml let xml = `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> `; for (const article of articles) { const loc = this.getUrl(site, site.language && site.language.current, article.url); const lastmod = moment(article.updatedAt).format(); xml += ` <url> <loc>${loc}</loc> <lastmod>${lastmod}</lastmod> </url> `; } xml += '</urlset>'; // save const pathDist = await this.getPathDist(site, site.language && site.language.current); const fileName = path.join(pathDist, 'sitemap.xml'); await fse.writeFile(fileName, xml); } async _writeSitemap({ site, article }) { const loc = this.getUrl(site, site.language && site.language.current, article.url); const lastmod = moment(article.updatedAt).format(); // load const pathDist = await this.getPathDist(site, site.language && site.language.current); const fileName = path.join(pathDist, 'sitemap.xml'); let xml; const exists = await fse.pathExists(fileName); if (!exists) { xml = `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>${loc}</loc> <lastmod>${lastmod}</lastmod> </url> </urlset>`; } else { xml = await fse.readFile(fileName); xml = xml.toString(); // remove const regexp = new RegExp(` {2}<url>\\s+<loc>[^<]*${article.url}[^<]*</loc>[\\s\\S]*?</url>[\\r\\n]`); xml = xml.replace(regexp, ''); // append xml = xml.replace( '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>${loc}</loc> <lastmod>${lastmod}</lastmod> </url>` ); } // save await fse.writeFile(fileName, xml); } async _renderStatic({ site }) { // static const pathIntermediate = await this.getPathIntermediate(site.language && site.language.current); const staticFiles = await eggBornUtils.tools.globbyAsync(`${pathIntermediate}/static/*
_renderFile
javascript
cabloy/cabloy
src/module-system/a-cms/dist/backend.js
https://github.com/cabloy/cabloy/blob/master/src/module-system/a-cms/dist/backend.js
MIT
function updateFakeCursor(cm) { var className = 'cm-animate-fat-cursor'; var vim = cm.state.vim; var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); var to = offsetCursor(from, 0, 1); clearFakeCursor(vim); // In visual mode, the cursor may be positioned over EOL. if (from.ch == cm.getLine(from.line).length) { var widget = dom('span', { class: className }, '\u00a0'); vim.fakeCursorBookmark = cm.setBookmark(from, { widget: widget }); } else { vim.fakeCursor = cm.markText(from, to, { className: className }); } }
Keeps track of a fake cursor to support visual mode cursor behavior.
updateFakeCursor
javascript
cabloy/cabloy
src/module-system/a-codemirror/backend/static/lib/codemirror/keymap/vim.js
https://github.com/cabloy/cabloy/blob/master/src/module-system/a-codemirror/backend/static/lib/codemirror/keymap/vim.js
MIT
function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == '/') { state.tokenize = tokenBase; break; } maybeEnd = ch == '*'; } return ret('comment', 'comment'); }
/ var ch = stream.next(); if (ch == '@') { stream.eatWhile(/[\w\\\-]/); return ret('meta', stream.current()); } else if (ch == '/' && stream.eat('*')) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else if (ch == '<' && stream.eat('!')) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (ch == '=') ret(null, 'compare'); else if ((ch == '~' || ch == '|') && stream.eat('=')) return ret(null, 'compare'); else if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == '#') { stream.skipToEnd(); return ret('comment', 'comment'); } else if (ch == '!') { stream.match(/^\s*\w
tokenCComment
javascript
cabloy/cabloy
src/module-system/a-codemirror/backend/static/lib/codemirror/mode/nginx/nginx.js
https://github.com/cabloy/cabloy/blob/master/src/module-system/a-codemirror/backend/static/lib/codemirror/mode/nginx/nginx.js
MIT
function slideToLoop(index, speed, runCallbacks, internal) { if (index === void 0) { index = 0; } if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } if (typeof index === 'string') { /** * The `index` argument converted from `string` to `number`. * @type {number} */ const indexAsNumber = parseInt(index, 10); /** * Determines whether the `index` argument is a valid `number` * after being converted from the `string` type. * @type {boolean} */ const isValidNumber = isFinite(indexAsNumber); if (!isValidNumber) { throw new Error(`The passed-in 'index' (string) couldn't be converted to 'number'. [${index}] given.`); } // Knowing that the converted `index` is a valid number, // we can update the original argument's value. index = indexAsNumber; } const swiper = this; let newIndex = index; if (swiper.params.loop) { newIndex += swiper.loopedSlides; } return swiper.slideTo(newIndex, speed, runCallbacks, internal); }
Determines whether the `index` argument is a valid `number` after being converted from the `string` type. @type {boolean}
slideToLoop
javascript
cabloy/cabloy
src/module-system/a-swiper/backend/static/vendor/swiper/8.4.5/swiper-bundle.esm.browser.js
https://github.com/cabloy/cabloy/blob/master/src/module-system/a-swiper/backend/static/vendor/swiper/8.4.5/swiper-bundle.esm.browser.js
MIT
function toBeInstanceOf(actual, expected) { if (!(actual instanceof expected)) { throw new AssertionError({ message: 'Expected value to be instance:', operator: 'instanceOf', actual, expected, stackStartFn: toBeInstanceOf, }) } }
Tests that the actual object is an instance of the expected class.
toBeInstanceOf
javascript
stitchesjs/stitches
.task/internal/expect.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/expect.js
MIT
function toNotBeInstanceOf(actual, expected) { if (actual instanceof expected) { throw new AssertionError({ message: 'Expected value to be instance:', operator: 'instanceOf', actual, expected, stackStartFn: toNotBeInstanceOf, }) } }
Tests that the actual object is not an instance of the expected class.
toNotBeInstanceOf
javascript
stitchesjs/stitches
.task/internal/expect.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/expect.js
MIT
async function toThrow(actualFunction, expected) { let actual = undefined try { actual = await actualFunction() } catch (error) { // do nothing and continue return } throw new AssertionError({ message: 'Expected exception:', operator: 'throws', stackStartFn: toThrow, actual, expected, }) }
Tests that the actual function does throw when it is called.
toThrow
javascript
stitchesjs/stitches
.task/internal/expect.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/expect.js
MIT
async function toNotThrow(actualFunction, expected) { let actual = undefined try { actual = await actualFunction() // do nothing and continue return } catch (error) { throw new AssertionError({ message: 'Unexpected exception:', operator: 'doesNotThrow', stackStartFn: toThrow, actual, expected, }) } }
Tests that the actual function does not throw when it is called.
toNotThrow
javascript
stitchesjs/stitches
.task/internal/expect.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/expect.js
MIT
copydir = async function copydir(src, dst) { let copydir = async (src, dst) => { await mkdir(dst, { recursive: true }) for (const dirent of await readdir(src, { withFileTypes: true })) { await (dirent.isDirectory() ? copydir : copyFile)( src.dir.to(dirent.name), dst.dir.to(dirent.name) ) } } copydir(URL.from(src), URL.from(dst)) }
Asynchronously copies dir to dest. By default, dest is overwritten if it already exists.
copydir
javascript
stitchesjs/stitches
.task/internal/fs.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/fs.js
MIT
async readFileJson(/** @type {import('fs').PathLike | fs.FileHandle} */ path) { const json = await fs.readFile(path, 'utf8') /** @type {JSONValue} */ const data = JSON.parse(json) return data }
Asynchronously reads a file as parsed JSON.
readFileJson
javascript
stitchesjs/stitches
.task/internal/fs.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/fs.js
MIT
getProcessArgOf = (name) => { const lead = argv.indexOf('--' + name) + 1 const tail = lead ? argv.slice(lead).findIndex((arg) => arg.startsWith('--')) : 0 const vals = lead ? argv.slice(lead, ~tail ? lead + tail : argv.length) : [] return lead ? (vals.length ? vals : [true]) : vals }
Returns the values for a given process argument.
getProcessArgOf
javascript
stitchesjs/stitches
.task/internal/process.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/process.js
MIT
question = ( /** @type {string} */ query, /** @type {import('events').Abortable} */ opts = undefined ) => new Promise(resolver => { query = String(query).replace(/[^\s]$/, '$& ') opts = Object(opts) const int = readline.createInterface({ input: process.stdin, output: process.stdout, }) int.question(query, opts, answer => { int.close() resolver(answer) }) })
Displays the query, awaits user input, and returns the provided input.
question
javascript
stitchesjs/stitches
.task/internal/readline.js
https://github.com/stitchesjs/stitches/blob/master/.task/internal/readline.js
MIT
toString = () => { const { cssRules } = groupSheet.sheet return [].map .call(cssRules, (cssRule, cssRuleIndex) => { const { cssText } = cssRule let lastRuleCssText = '' if (cssText.startsWith('--sxs')) return '' if (cssRules[cssRuleIndex - 1] && (lastRuleCssText = cssRules[cssRuleIndex - 1].cssText).startsWith('--sxs')) { if (!cssRule.cssRules.length) return '' for (const name in groupSheet.rules) { if (groupSheet.rules[name].group === cssRule) { return `--sxs{--sxs:${[...groupSheet.rules[name].cache].join(' ')}}${cssText}` } } return cssRule.cssRules.length ? `${lastRuleCssText}${cssText}` : '' } return cssText }) .join('') }
@type {SheetGroup} Object hosting the hydrated stylesheet.
toString
javascript
stitchesjs/stitches
packages/core/src/sheet.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/sheet.js
MIT
createCSSMediaRule = (/** @type {string} */ sourceCssText, type) => { return /** @type {CSSMediaRule} */ ({ type, cssRules: [], insertRule(cssText, index) { this.cssRules.splice(index, 0, createCSSMediaRule(cssText, { import: 3, undefined: 1 }[(cssText.toLowerCase().match(/^@([a-z]+)/) || [])[1]] || 4)) }, get cssText() { return sourceCssText === '@media{}' ? `@media{${[].map.call(this.cssRules, (cssRule) => cssRule.cssText).join('')}}` : sourceCssText }, }) }
@type {GroupName} Name of the group.
createCSSMediaRule
javascript
stitchesjs/stitches
packages/core/src/sheet.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/sheet.js
MIT
walk = ( /** @type {Style} Set of CSS styles */ style, /** @type {string[]} Selectors that define the elements to which a set of CSS styles apply. */ selectors, /** @type {string[]} Conditions that define the queries to which a set of CSS styles apply. */ conditions, ) => { /** @type {keyof style} Represents the left-side "name" for the property (the at-rule prelude, style-rule selector, or declaration name). */ let name /** @type {style[keyof style]} Represents the right-side "data" for the property (the rule block, or declaration value). */ let data const each = (style) => { for (name in style) { /** Whether the current name represents an at-rule. */ const isAtRuleLike = name.charCodeAt(0) === 64 const datas = isAtRuleLike && Array.isArray(style[name]) ? style[name] : [style[name]] for (data of datas) { const camelName = toCamelCase(name) /** Whether the current data represents a nesting rule, which is a plain object whose key is not already a util. */ const isRuleLike = typeof data === 'object' && data && data.toString === toStringOfObject && (!config.utils[camelName] || !selectors.length) // if the left-hand "name" matches a configured utility // conditionally transform the current data using the configured utility if (camelName in config.utils && !isRuleLike) { const util = config.utils[camelName] if (util !== lastUtil) { lastUtil = util each(util(data)) lastUtil = null continue } } // otherwise, if the left-hand "name" matches a configured polyfill // conditionally transform the current data using the polyfill else if (camelName in toPolyfilledValue) { const poly = toPolyfilledValue[camelName] if (poly !== lastPoly) { lastPoly = poly each(poly(data)) lastPoly = null continue } } // if the left-hand "name" matches a configured at-rule if (isAtRuleLike) { // transform the current name with the configured media at-rule prelude name = toResolvedMediaQueryRanges(name.slice(1) in config.media ? '@media ' + config.media[name.slice(1)] : name) } if (isRuleLike) { /** Next conditions, which may include one new condition (if this is an at-rule). */ const nextConditions = isAtRuleLike ? conditions.concat(name) : [...conditions] /** Next selectors, which may include one new selector (if this is not an at-rule). */ const nextSelections = isAtRuleLike ? [...selectors] : toResolvedSelectors(selectors, name.split(comma)) if (currentRule !== undefined) { onCssText(toCssString(...currentRule)) } currentRule = undefined walk(data, nextSelections, nextConditions) } else { if (currentRule === undefined) currentRule = [[], selectors, conditions] /** CSS left-hand side value, which may be a specially-formatted custom property. */ name = !isAtRuleLike && name.charCodeAt(0) === 36 ? `--${toTailDashed(config.prefix)}${name.slice(1).replace(/\$/g, '-')}` : name /** CSS right-hand side value, which may be a specially-formatted custom property. */ data = ( // preserve object-like data isRuleLike ? data // replace all non-unitless props that are not custom properties with pixel versions : typeof data === 'number' ? data && !(camelName in unitlessProps) && !(name.charCodeAt(0) === 45) ? String(data) + 'px' : String(data) // replace tokens with stringified primitive values : toTokenizedValue( toSizingValue(camelName, data == null ? '' : data), config.prefix, config.themeMap[camelName] ) ) currentRule[0].push(`${isAtRuleLike ? `${name} ` : `${toHyphenCase(name)}:`}${data}`) } } } } each(style) if (currentRule !== undefined) { onCssText(toCssString(...currentRule)) } currentRule = undefined }
Walks CSS styles and converts them into CSSOM-compatible rules.
walk
javascript
stitchesjs/stitches
packages/core/src/convert/toCssRules.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toCssRules.js
MIT
each = (style) => { for (name in style) { /** Whether the current name represents an at-rule. */ const isAtRuleLike = name.charCodeAt(0) === 64 const datas = isAtRuleLike && Array.isArray(style[name]) ? style[name] : [style[name]] for (data of datas) { const camelName = toCamelCase(name) /** Whether the current data represents a nesting rule, which is a plain object whose key is not already a util. */ const isRuleLike = typeof data === 'object' && data && data.toString === toStringOfObject && (!config.utils[camelName] || !selectors.length) // if the left-hand "name" matches a configured utility // conditionally transform the current data using the configured utility if (camelName in config.utils && !isRuleLike) { const util = config.utils[camelName] if (util !== lastUtil) { lastUtil = util each(util(data)) lastUtil = null continue } } // otherwise, if the left-hand "name" matches a configured polyfill // conditionally transform the current data using the polyfill else if (camelName in toPolyfilledValue) { const poly = toPolyfilledValue[camelName] if (poly !== lastPoly) { lastPoly = poly each(poly(data)) lastPoly = null continue } } // if the left-hand "name" matches a configured at-rule if (isAtRuleLike) { // transform the current name with the configured media at-rule prelude name = toResolvedMediaQueryRanges(name.slice(1) in config.media ? '@media ' + config.media[name.slice(1)] : name) } if (isRuleLike) { /** Next conditions, which may include one new condition (if this is an at-rule). */ const nextConditions = isAtRuleLike ? conditions.concat(name) : [...conditions] /** Next selectors, which may include one new selector (if this is not an at-rule). */ const nextSelections = isAtRuleLike ? [...selectors] : toResolvedSelectors(selectors, name.split(comma)) if (currentRule !== undefined) { onCssText(toCssString(...currentRule)) } currentRule = undefined walk(data, nextSelections, nextConditions) } else { if (currentRule === undefined) currentRule = [[], selectors, conditions] /** CSS left-hand side value, which may be a specially-formatted custom property. */ name = !isAtRuleLike && name.charCodeAt(0) === 36 ? `--${toTailDashed(config.prefix)}${name.slice(1).replace(/\$/g, '-')}` : name /** CSS right-hand side value, which may be a specially-formatted custom property. */ data = ( // preserve object-like data isRuleLike ? data // replace all non-unitless props that are not custom properties with pixel versions : typeof data === 'number' ? data && !(camelName in unitlessProps) && !(name.charCodeAt(0) === 45) ? String(data) + 'px' : String(data) // replace tokens with stringified primitive values : toTokenizedValue( toSizingValue(camelName, data == null ? '' : data), config.prefix, config.themeMap[camelName] ) ) currentRule[0].push(`${isAtRuleLike ? `${name} ` : `${toHyphenCase(name)}:`}${data}`) } } } }
@type {style[keyof style]} Represents the right-side "data" for the property (the rule block, or declaration value).
each
javascript
stitchesjs/stitches
packages/core/src/convert/toCssRules.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toCssRules.js
MIT
toCssString = (declarations, selectors, conditions) => ( `${conditions.map((condition) => `${condition}{`).join('')}${selectors.length ? `${selectors.join(',')}{` : ''}${declarations.join(';')}${selectors.length ? `}` : ''}${Array(conditions.length ? conditions.length + 1 : 0).join('}')}` )
CSS right-hand side value, which may be a specially-formatted custom property.
toCssString
javascript
stitchesjs/stitches
packages/core/src/convert/toCssRules.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toCssRules.js
MIT
toHyphenCase = (/** @type {string} */ value) => ( // ignore kebab-like values value.includes('-') ? value // replace any upper-case letter with a dash and the lower-case variant : value.replace(/[A-Z]/g, (capital) => '-' + capital.toLowerCase()) )
Returns the given value converted to kebab-case.
toHyphenCase
javascript
stitchesjs/stitches
packages/core/src/convert/toHyphenCase.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toHyphenCase.js
MIT
toResolvedMediaQueryRanges = ( /** @type {string} */ media ) => media.replace( /\(\s*([\w-]+)\s*(=|<|<=|>|>=)\s*([\w-]+)\s*(?:(<|<=|>|>=)\s*([\w-]+)\s*)?\)/g, ( __, /** @type {string} 1st param, either the name or value in the query. */ p1, /** @type {string} 1st operator. */ o1, /** @type {string} 2nd param, either the name or value in the query. */ p2, /** @type {string} Optional 2nd operator. */ o2, /** @type {string} Optional 3rd param, always a value in the query.*/ p3 ) => { /** Whether the first param is a value. */ const isP1Value = mqunit.test(p1) /** Numeric shift applied to a value when an operator is `<` or `>`. */ const shift = 0.0625 * (isP1Value ? -1 : 1) const [name, value] = isP1Value ? [p2, p1] : [p1, p2] return ( '(' + ( o1[0] === '=' ? '' : (o1[0] === '>' === isP1Value ? 'max-' : 'min-') ) + name + ':' + (o1[0] !== '=' && o1.length === 1 ? value.replace(mqunit, (_, v, u) => Number(v) + shift * (o1 === '>' ? 1 : -1) + u) : value) + ( o2 ? ') and (' + ( (o2[0] === '>' ? 'min-' : 'max-') + name + ':' + (o2.length === 1 ? p3.replace(mqunit, (_, v, u) => Number(v) + shift * (o2 === '>' ? -1 : 1) + u) : p3) ) : '' ) + ')' ) } )
Returns a media query with polyfilled ranges.
toResolvedMediaQueryRanges
javascript
stitchesjs/stitches
packages/core/src/convert/toResolvedMediaQueryRanges.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toResolvedMediaQueryRanges.js
MIT
toResolvedSelectors = ( /** @type {string[]} Parent selectors (e.g. `["a", "button"]`). */ parentSelectors, /** @type {string[]} Nested selectors (e.g. `["&:hover", "&:focus"]`). */ nestedSelectors, ) => ( parentSelectors.length ? parentSelectors.reduce( (resolvedSelectors, parentSelector) => { resolvedSelectors.push( ...nestedSelectors.map( (selector) => ( selector.includes('&') ? selector.replace( /&/g, /[ +>|~]/.test(parentSelector) && /&.*&/.test(selector) ? `:is(${parentSelector})` : parentSelector ) : parentSelector + ' ' + selector ) ) ) return resolvedSelectors }, [] ) : nestedSelectors )
Returns selectors resolved from parent selectors and nested selectors.
toResolvedSelectors
javascript
stitchesjs/stitches
packages/core/src/convert/toResolvedSelectors.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toResolvedSelectors.js
MIT
toSizingValue = (/** @type {string} */ declarationName, /** @type {string} */ declarationValue) => ( declarationName in sizeProps && typeof declarationValue === 'string' ? declarationValue.replace( /^((?:[^]*[^\w-])?)(fit-content|stretch)((?:[^\w-][^]*)?)$/, (data, lead, main, tail) => ( lead + ( main === 'stretch' ? `-moz-available${tail};${toHyphenCase(declarationName)}:${lead}-webkit-fill-available` : `-moz-fit-content${tail};${toHyphenCase(declarationName)}:${lead}fit-content` ) + tail ), ) : String(declarationValue) )
Returns a declaration sizing value with polyfilled sizing keywords.
toSizingValue
javascript
stitchesjs/stitches
packages/core/src/convert/toSizingValue.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toSizingValue.js
MIT
toTokenizedValue = ( /** @type {string} */ value, /** @type {string} */ prefix, /** @type {string} */ scale, ) => value.replace( /([+-])?((?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?)?(\$|--)([$\w-]+)/g, ($0, direction, multiplier, separator, token) => ( separator == "$" == !!multiplier ? $0 : ( direction || separator == '--' ? 'calc(' : '' ) + ( 'var(--' + ( separator === '$' ? toTailDashed(prefix) + ( !token.includes('$') ? toTailDashed(scale) : '' ) + token.replace(/\$/g, '-') : token ) + ')' + ( direction || separator == '--' ? '*' + ( direction || '' ) + ( multiplier || '1' ) + ')' : '' ) ) ), )
Returns a declaration value with transformed token values.
toTokenizedValue
javascript
stitchesjs/stitches
packages/core/src/convert/toTokenizedValue.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/convert/toTokenizedValue.js
MIT
createCreateThemeFunction = ( config, sheet ) => ( createCreateThemeFunctionMap(config, () => (className, style) => { // theme is the first argument if it is an object, otherwise the second argument as an object style = typeof className === 'object' && className || Object(style) // class name is the first argument if it is a string, otherwise an empty string className = typeof className === 'string' ? className : '' /** @type {string} Theme name. @see `{CONFIG_PREFIX}t-{THEME_UUID}` */ className = className || `${toTailDashed(config.prefix)}t-${toHash(style)}` const selector = `.${className}` const themeObject = {} const cssProps = [] for (const scale in style) { themeObject[scale] = {} for (const token in style[scale]) { const propertyName = `--${toTailDashed(config.prefix)}${scale}-${token}` const propertyValue = toTokenizedValue(String(style[scale][token]), config.prefix, scale) themeObject[scale][token] = new ThemeToken(token, propertyValue, scale, config.prefix) cssProps.push(`${propertyName}:${propertyValue}`) } } const render = () => { if (cssProps.length && !sheet.rules.themed.cache.has(className)) { sheet.rules.themed.cache.add(className) const rootPrelude = style === config.theme ? ':root,' : '' const cssText = `${rootPrelude}.${className}{${cssProps.join(';')}}` sheet.rules.themed.apply(cssText) } return className } return { ...themeObject, get className() { return render() }, selector, toString: render, } }) )
Returns a function that applies a theme and returns tokens of that theme.
createCreateThemeFunction
javascript
stitchesjs/stitches
packages/core/src/features/createTheme.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/features/createTheme.js
MIT
createCssFunction = (config, sheet) => createCssFunctionMap(config, () => { const _css = (args, componentConfig = {}) => { let internals = { type: null, composers: new Set(), } for (const arg of args) { // skip any void argument if (arg == null) continue // conditionally extend the component if (arg[internal]) { if (internals.type == null) internals.type = arg[internal].type for (const composer of arg[internal].composers) { internals.composers.add(composer) } } // otherwise, conditionally define the component type else if (arg.constructor !== Object || arg.$$typeof) { if (internals.type == null) internals.type = arg } // otherwise, add a new composer to this component else { internals.composers.add(createComposer(arg, config, componentConfig)) } } // set the component type if none was set if (internals.type == null) internals.type = 'span' if (!internals.composers.size) internals.composers.add(['PJLV', {}, [], [], {}, []]) return createRenderer(config, internals, sheet, componentConfig) } const css = (...args) => _css(args) css.withConfig = (componentConfig) => (...args) => _css(args, componentConfig) return css })
Returns a function that applies component styles.
createCssFunction
javascript
stitchesjs/stitches
packages/core/src/features/css.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/features/css.js
MIT
createRenderer = (config, internals, sheet, { shouldForwardStitchesProp }) => { const [ baseClassName, baseClassNames, prefilledVariants, undefinedVariants ] = getPreparedDataFromComposers(internals.composers) const deferredInjector = typeof internals.type === 'function' || !!internals.type.$$typeof ? createRulesInjectionDeferrer(sheet) : null const injectionTarget = (deferredInjector || sheet).rules const selector = `.${baseClassName}${baseClassNames.length > 1 ? `:where(.${baseClassNames.slice(1).join('.')})` : ``}` const render = (props) => { props = typeof props === 'object' && props || empty // 1. we cannot mutate `props` // 2. we delete variant props // 3. we delete `css` prop // therefore: we must create a new props & css variables const { ...forwardProps } = props const variantProps = {} for (const name in prefilledVariants) { if (name in props) { if (!shouldForwardStitchesProp?.(name)) delete forwardProps[name] let data = props[name] if (typeof data === 'object' && data) { variantProps[name] = { '@initial': prefilledVariants[name], ...data, } } else { data = String(data) variantProps[name] = ( data === 'undefined' && !undefinedVariants.has(name) ? prefilledVariants[name] : data ) } } else { variantProps[name] = prefilledVariants[name] } } const classSet = new Set([ ...baseClassNames ]) // 1. builds up the variants (fills in defaults, calculates @initial on responsive, etc.) // 2. iterates composers // 2.1. add their base class // 2.2. iterate their variants, add their variant classes // 2.2.1. orders regular variants before responsive variants // 2.3. iterate their compound variants, add their compound variant classes for (const [composerBaseClass, composerBaseStyle, singularVariants, compoundVariants] of internals.composers) { if (!sheet.rules.styled.cache.has(composerBaseClass)) { sheet.rules.styled.cache.add(composerBaseClass) toCssRules(composerBaseStyle, [`.${composerBaseClass}`], [], config, (cssText) => { injectionTarget.styled.apply(cssText) }) } const singularVariantsToAdd = getTargetVariantsToAdd(singularVariants, variantProps, config.media) const compoundVariantsToAdd = getTargetVariantsToAdd(compoundVariants, variantProps, config.media, true) for (const variantToAdd of singularVariantsToAdd) { if (variantToAdd === undefined) continue for (const [vClass, vStyle, isResponsive] of variantToAdd) { const variantClassName = `${composerBaseClass}-${toHash(vStyle)}-${vClass}` classSet.add(variantClassName) const groupCache = (isResponsive ? sheet.rules.resonevar : sheet.rules.onevar ).cache /* * make sure that normal variants are injected before responsive ones * @see {@link https://github.com/stitchesjs/stitches/issues/737|github} */ const targetInjectionGroup = isResponsive ? injectionTarget.resonevar : injectionTarget.onevar if (!groupCache.has(variantClassName)) { groupCache.add(variantClassName) toCssRules(vStyle, [`.${variantClassName}`], [], config, (cssText) => { targetInjectionGroup.apply(cssText) }) } } } for (const variantToAdd of compoundVariantsToAdd) { if (variantToAdd === undefined) continue for (const [vClass, vStyle] of variantToAdd) { const variantClassName = `${composerBaseClass}-${toHash(vStyle)}-${vClass}` classSet.add(variantClassName) if (!sheet.rules.allvar.cache.has(variantClassName)) { sheet.rules.allvar.cache.add(variantClassName) toCssRules(vStyle, [`.${variantClassName}`], [], config, (cssText) => { injectionTarget.allvar.apply(cssText) }) } } } } // apply css property styles const css = forwardProps.css if (typeof css === 'object' && css) { if (!shouldForwardStitchesProp?.('css')) delete forwardProps.css /** @type {string} Inline Class Unique Identifier. @see `{COMPOSER_UUID}-i{VARIANT_UUID}-css` */ const iClass = `${baseClassName}-i${toHash(css)}-css` classSet.add(iClass) if (!sheet.rules.inline.cache.has(iClass)) { sheet.rules.inline.cache.add(iClass) toCssRules(css, [`.${iClass}`], [], config, (cssText) => { injectionTarget.inline.apply(cssText) }) } } for (const propClassName of String(props.className || '').trim().split(/\s+/)) { if (propClassName) classSet.add(propClassName) } const renderedClassName = forwardProps.className = [ ...classSet ].join(' ') const renderedToString = () => renderedClassName return { type: internals.type, className: renderedClassName, selector, props: forwardProps, toString: renderedToString, deferredInjector, } } const toString = () => { if (!sheet.rules.styled.cache.has(baseClassName)) render() return baseClassName } return define(render, { className: baseClassName, selector, [internal]: internals, toString, }) }
@type {string} Composer Unique Identifier. @see `{CONFIG_PREFIX}-?c-{STYLE_HASH}`
createRenderer
javascript
stitchesjs/stitches
packages/core/src/features/css.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/features/css.js
MIT
toString = () => { if (!sheet.rules.styled.cache.has(baseClassName)) render() return baseClassName }
@type {string} Inline Class Unique Identifier. @see `{COMPOSER_UUID}-i{VARIANT_UUID}-css`
toString
javascript
stitchesjs/stitches
packages/core/src/features/css.js
https://github.com/stitchesjs/stitches/blob/master/packages/core/src/features/css.js
MIT