id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
16,000
arendjr/selectivity
src/plugins/keyboard.js
moveHighlight
function moveHighlight(dropdown, delta) { var results = dropdown.results; if (!results.length) { return; } var resultItems = [].slice.call(dropdown.el.querySelectorAll('.selectivity-result-item')); function scrollToHighlight() { var el; if (dropdown.highlightedResult) { el = findResultItem(resultItems, dropdown.highlightedResult.id); } else if (dropdown.loadMoreHighlighted) { el = dropdown.$('.selectivity-load-more'); } if (el && el.scrollIntoView) { el.scrollIntoView(delta < 0); } } if (dropdown.submenu) { moveHighlight(dropdown.submenu, delta); return; } var defaultIndex = delta > 0 ? 0 : resultItems.length - 1; var index = defaultIndex; var highlightedResult = dropdown.highlightedResult; if (highlightedResult) { var highlightedResultItem = findResultItem(resultItems, highlightedResult.id); index = resultItems.indexOf(highlightedResultItem) + delta; if (delta > 0 ? index >= resultItems.length : index < 0) { if (dropdown.hasMore) { dropdown.highlightLoadMore(); scrollToHighlight(); return; } else { index = defaultIndex; } } } var resultItem = resultItems[index]; var result = Selectivity.findNestedById(results, selectivity.getRelatedItemId(resultItem)); if (result) { dropdown.highlight(result, { delay: !!result.submenu }); scrollToHighlight(); } }
javascript
function moveHighlight(dropdown, delta) { var results = dropdown.results; if (!results.length) { return; } var resultItems = [].slice.call(dropdown.el.querySelectorAll('.selectivity-result-item')); function scrollToHighlight() { var el; if (dropdown.highlightedResult) { el = findResultItem(resultItems, dropdown.highlightedResult.id); } else if (dropdown.loadMoreHighlighted) { el = dropdown.$('.selectivity-load-more'); } if (el && el.scrollIntoView) { el.scrollIntoView(delta < 0); } } if (dropdown.submenu) { moveHighlight(dropdown.submenu, delta); return; } var defaultIndex = delta > 0 ? 0 : resultItems.length - 1; var index = defaultIndex; var highlightedResult = dropdown.highlightedResult; if (highlightedResult) { var highlightedResultItem = findResultItem(resultItems, highlightedResult.id); index = resultItems.indexOf(highlightedResultItem) + delta; if (delta > 0 ? index >= resultItems.length : index < 0) { if (dropdown.hasMore) { dropdown.highlightLoadMore(); scrollToHighlight(); return; } else { index = defaultIndex; } } } var resultItem = resultItems[index]; var result = Selectivity.findNestedById(results, selectivity.getRelatedItemId(resultItem)); if (result) { dropdown.highlight(result, { delay: !!result.submenu }); scrollToHighlight(); } }
[ "function", "moveHighlight", "(", "dropdown", ",", "delta", ")", "{", "var", "results", "=", "dropdown", ".", "results", ";", "if", "(", "!", "results", ".", "length", ")", "{", "return", ";", "}", "var", "resultItems", "=", "[", "]", ".", "slice", ".", "call", "(", "dropdown", ".", "el", ".", "querySelectorAll", "(", "'.selectivity-result-item'", ")", ")", ";", "function", "scrollToHighlight", "(", ")", "{", "var", "el", ";", "if", "(", "dropdown", ".", "highlightedResult", ")", "{", "el", "=", "findResultItem", "(", "resultItems", ",", "dropdown", ".", "highlightedResult", ".", "id", ")", ";", "}", "else", "if", "(", "dropdown", ".", "loadMoreHighlighted", ")", "{", "el", "=", "dropdown", ".", "$", "(", "'.selectivity-load-more'", ")", ";", "}", "if", "(", "el", "&&", "el", ".", "scrollIntoView", ")", "{", "el", ".", "scrollIntoView", "(", "delta", "<", "0", ")", ";", "}", "}", "if", "(", "dropdown", ".", "submenu", ")", "{", "moveHighlight", "(", "dropdown", ".", "submenu", ",", "delta", ")", ";", "return", ";", "}", "var", "defaultIndex", "=", "delta", ">", "0", "?", "0", ":", "resultItems", ".", "length", "-", "1", ";", "var", "index", "=", "defaultIndex", ";", "var", "highlightedResult", "=", "dropdown", ".", "highlightedResult", ";", "if", "(", "highlightedResult", ")", "{", "var", "highlightedResultItem", "=", "findResultItem", "(", "resultItems", ",", "highlightedResult", ".", "id", ")", ";", "index", "=", "resultItems", ".", "indexOf", "(", "highlightedResultItem", ")", "+", "delta", ";", "if", "(", "delta", ">", "0", "?", "index", ">=", "resultItems", ".", "length", ":", "index", "<", "0", ")", "{", "if", "(", "dropdown", ".", "hasMore", ")", "{", "dropdown", ".", "highlightLoadMore", "(", ")", ";", "scrollToHighlight", "(", ")", ";", "return", ";", "}", "else", "{", "index", "=", "defaultIndex", ";", "}", "}", "}", "var", "resultItem", "=", "resultItems", "[", "index", "]", ";", "var", "result", "=", "Selectivity", ".", "findNestedById", "(", "results", ",", "selectivity", ".", "getRelatedItemId", "(", "resultItem", ")", ")", ";", "if", "(", "result", ")", "{", "dropdown", ".", "highlight", "(", "result", ",", "{", "delay", ":", "!", "!", "result", ".", "submenu", "}", ")", ";", "scrollToHighlight", "(", ")", ";", "}", "}" ]
Moves a dropdown's highlight to the next or previous result item. @param delta Either 1 to move to the next item, or -1 to move to the previous item.
[ "Moves", "a", "dropdown", "s", "highlight", "to", "the", "next", "or", "previous", "result", "item", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/plugins/keyboard.js#L26-L75
16,001
arendjr/selectivity
src/selectivity.js
Selectivity
function Selectivity(options) { /** * Reference to the currently open dropdown. */ this.dropdown = null; /** * DOM element to which this instance is attached. */ this.el = options.element; /** * Whether the input is enabled. * * This is false when the option readOnly is false or the option removeOnly is false. */ this.enabled = !options.readOnly && !options.removeOnly; /** * DOM element for the input. * * May be null as long as there is no visible input. It is set by initInput(). */ this.input = null; /** * Array of items from which to select. If set, this will be an array of objects with 'id' and * 'text' properties. * * If given, all items are expected to be available locally and all selection operations operate * on this local array only. If null, items are not available locally, and a query function * should be provided to fetch remote data. */ this.items = null; /** * Options passed to the Selectivity instance or set through setOptions(). */ this.options = {}; /** * Mapping of templates. * * Custom templates can be specified in the options object. */ this.templates = assign({}, Selectivity.Templates); /** * The last used search term. */ this.term = ''; this.setOptions(options); if (options.value) { this.setValue(options.value, { triggerChange: false }); } else { this.setData(options.data || null, { triggerChange: false }); } this.el.setAttribute('tabindex', options.tabIndex || 0); this.events = new EventListener(this.el, this); this.events.on({ blur: this._blur, mouseenter: this._mouseenter, mouseleave: this._mouseleave, 'selectivity-close': this._closed }); }
javascript
function Selectivity(options) { /** * Reference to the currently open dropdown. */ this.dropdown = null; /** * DOM element to which this instance is attached. */ this.el = options.element; /** * Whether the input is enabled. * * This is false when the option readOnly is false or the option removeOnly is false. */ this.enabled = !options.readOnly && !options.removeOnly; /** * DOM element for the input. * * May be null as long as there is no visible input. It is set by initInput(). */ this.input = null; /** * Array of items from which to select. If set, this will be an array of objects with 'id' and * 'text' properties. * * If given, all items are expected to be available locally and all selection operations operate * on this local array only. If null, items are not available locally, and a query function * should be provided to fetch remote data. */ this.items = null; /** * Options passed to the Selectivity instance or set through setOptions(). */ this.options = {}; /** * Mapping of templates. * * Custom templates can be specified in the options object. */ this.templates = assign({}, Selectivity.Templates); /** * The last used search term. */ this.term = ''; this.setOptions(options); if (options.value) { this.setValue(options.value, { triggerChange: false }); } else { this.setData(options.data || null, { triggerChange: false }); } this.el.setAttribute('tabindex', options.tabIndex || 0); this.events = new EventListener(this.el, this); this.events.on({ blur: this._blur, mouseenter: this._mouseenter, mouseleave: this._mouseleave, 'selectivity-close': this._closed }); }
[ "function", "Selectivity", "(", "options", ")", "{", "/**\n * Reference to the currently open dropdown.\n */", "this", ".", "dropdown", "=", "null", ";", "/**\n * DOM element to which this instance is attached.\n */", "this", ".", "el", "=", "options", ".", "element", ";", "/**\n * Whether the input is enabled.\n *\n * This is false when the option readOnly is false or the option removeOnly is false.\n */", "this", ".", "enabled", "=", "!", "options", ".", "readOnly", "&&", "!", "options", ".", "removeOnly", ";", "/**\n * DOM element for the input.\n *\n * May be null as long as there is no visible input. It is set by initInput().\n */", "this", ".", "input", "=", "null", ";", "/**\n * Array of items from which to select. If set, this will be an array of objects with 'id' and\n * 'text' properties.\n *\n * If given, all items are expected to be available locally and all selection operations operate\n * on this local array only. If null, items are not available locally, and a query function\n * should be provided to fetch remote data.\n */", "this", ".", "items", "=", "null", ";", "/**\n * Options passed to the Selectivity instance or set through setOptions().\n */", "this", ".", "options", "=", "{", "}", ";", "/**\n * Mapping of templates.\n *\n * Custom templates can be specified in the options object.\n */", "this", ".", "templates", "=", "assign", "(", "{", "}", ",", "Selectivity", ".", "Templates", ")", ";", "/**\n * The last used search term.\n */", "this", ".", "term", "=", "''", ";", "this", ".", "setOptions", "(", "options", ")", ";", "if", "(", "options", ".", "value", ")", "{", "this", ".", "setValue", "(", "options", ".", "value", ",", "{", "triggerChange", ":", "false", "}", ")", ";", "}", "else", "{", "this", ".", "setData", "(", "options", ".", "data", "||", "null", ",", "{", "triggerChange", ":", "false", "}", ")", ";", "}", "this", ".", "el", ".", "setAttribute", "(", "'tabindex'", ",", "options", ".", "tabIndex", "||", "0", ")", ";", "this", ".", "events", "=", "new", "EventListener", "(", "this", ".", "el", ",", "this", ")", ";", "this", ".", "events", ".", "on", "(", "{", "blur", ":", "this", ".", "_blur", ",", "mouseenter", ":", "this", ".", "_mouseenter", ",", "mouseleave", ":", "this", ".", "_mouseleave", ",", "'selectivity-close'", ":", "this", ".", "_closed", "}", ")", ";", "}" ]
Selectivity Base Constructor. You will never use this constructor directly. Instead, you use $(selector).selectivity(options) to create an instance of either MultipleSelectivity or SingleSelectivity. This class defines all functionality that is common between both. @param options Options object. Accepts the same options as the setOptions method(), in addition to the following ones: data - Initial selection data to set. This should be an array of objects with 'id' and 'text' properties. This option is mutually exclusive with 'value'. element - The DOM element to which to attach the Selectivity instance. This property is set by the API wrapper. value - Initial value to set. This should be an array of IDs. This property is mutually exclusive with 'data'.
[ "Selectivity", "Base", "Constructor", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L25-L94
16,002
arendjr/selectivity
src/selectivity.js
function() { this.events.destruct(); var el = this.el; while (el.firstChild) { el.removeChild(el.firstChild); } el.selectivity = null; }
javascript
function() { this.events.destruct(); var el = this.el; while (el.firstChild) { el.removeChild(el.firstChild); } el.selectivity = null; }
[ "function", "(", ")", "{", "this", ".", "events", ".", "destruct", "(", ")", ";", "var", "el", "=", "this", ".", "el", ";", "while", "(", "el", ".", "firstChild", ")", "{", "el", ".", "removeChild", "(", "el", ".", "firstChild", ")", ";", "}", "el", ".", "selectivity", "=", "null", ";", "}" ]
Destroys the Selectivity instance.
[ "Destroys", "the", "Selectivity", "instance", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L122-L130
16,003
arendjr/selectivity
src/selectivity.js
function(id) { var items = this.items; if (items) { return Selectivity.findNestedById(items, id); } else if (id === null) { return null; } else { return { id: id, text: '' + id }; } }
javascript
function(id) { var items = this.items; if (items) { return Selectivity.findNestedById(items, id); } else if (id === null) { return null; } else { return { id: id, text: '' + id }; } }
[ "function", "(", "id", ")", "{", "var", "items", "=", "this", ".", "items", ";", "if", "(", "items", ")", "{", "return", "Selectivity", ".", "findNestedById", "(", "items", ",", "id", ")", ";", "}", "else", "if", "(", "id", "===", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "{", "id", ":", "id", ",", "text", ":", "''", "+", "id", "}", ";", "}", "}" ]
Returns the correct item for a given ID. @param id The ID to get the item for. @return The corresponding item. Will be an object with 'id' and 'text' properties or null if the item cannot be found. Note that if no items are defined, this method assumes the text labels will be equal to the IDs.
[ "Returns", "the", "correct", "item", "for", "a", "given", "ID", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L177-L186
16,004
arendjr/selectivity
src/selectivity.js
function(elementOrEvent) { var el = elementOrEvent.target || elementOrEvent; while (el) { if (el.hasAttribute('data-item-id')) { break; } el = el.parentNode; } if (!el) { return null; } var id = el.getAttribute('data-item-id'); // IDs can be either numbers or strings, but attribute values are always strings, so we // will have to find out whether the item ID ought to be a number or string ourselves. if (Selectivity.findById(this._data || [], id)) { return id; } else { var dropdown = this.dropdown; while (dropdown) { if (Selectivity.findNestedById(dropdown.results, id)) { return id; } // FIXME: reference to submenu plugin doesn't belong in base dropdown = dropdown.submenu; } var number = parseInt(id, 10); return '' + number === id ? number : id; } }
javascript
function(elementOrEvent) { var el = elementOrEvent.target || elementOrEvent; while (el) { if (el.hasAttribute('data-item-id')) { break; } el = el.parentNode; } if (!el) { return null; } var id = el.getAttribute('data-item-id'); // IDs can be either numbers or strings, but attribute values are always strings, so we // will have to find out whether the item ID ought to be a number or string ourselves. if (Selectivity.findById(this._data || [], id)) { return id; } else { var dropdown = this.dropdown; while (dropdown) { if (Selectivity.findNestedById(dropdown.results, id)) { return id; } // FIXME: reference to submenu plugin doesn't belong in base dropdown = dropdown.submenu; } var number = parseInt(id, 10); return '' + number === id ? number : id; } }
[ "function", "(", "elementOrEvent", ")", "{", "var", "el", "=", "elementOrEvent", ".", "target", "||", "elementOrEvent", ";", "while", "(", "el", ")", "{", "if", "(", "el", ".", "hasAttribute", "(", "'data-item-id'", ")", ")", "{", "break", ";", "}", "el", "=", "el", ".", "parentNode", ";", "}", "if", "(", "!", "el", ")", "{", "return", "null", ";", "}", "var", "id", "=", "el", ".", "getAttribute", "(", "'data-item-id'", ")", ";", "// IDs can be either numbers or strings, but attribute values are always strings, so we", "// will have to find out whether the item ID ought to be a number or string ourselves.", "if", "(", "Selectivity", ".", "findById", "(", "this", ".", "_data", "||", "[", "]", ",", "id", ")", ")", "{", "return", "id", ";", "}", "else", "{", "var", "dropdown", "=", "this", ".", "dropdown", ";", "while", "(", "dropdown", ")", "{", "if", "(", "Selectivity", ".", "findNestedById", "(", "dropdown", ".", "results", ",", "id", ")", ")", "{", "return", "id", ";", "}", "// FIXME: reference to submenu plugin doesn't belong in base", "dropdown", "=", "dropdown", ".", "submenu", ";", "}", "var", "number", "=", "parseInt", "(", "id", ",", "10", ")", ";", "return", "''", "+", "number", "===", "id", "?", "number", ":", "id", ";", "}", "}" ]
Returns the item ID related to an element or event target. @param elementOrEvent The DOM element or event to get the item ID for. @return Item ID or null if no ID could be found.
[ "Returns", "the", "item", "ID", "related", "to", "an", "element", "or", "event", "target", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L195-L226
16,005
arendjr/selectivity
src/selectivity.js
function(input, options) { this.input = input; var selectivity = this; var inputListeners = this.options.inputListeners || Selectivity.InputListeners; inputListeners.forEach(function(listener) { listener(selectivity, input, options); }); if (!options || options.search !== false) { input.addEventListener('keyup', function(event) { if (!event.defaultPrevented) { selectivity.search(event.target.value); } }); } }
javascript
function(input, options) { this.input = input; var selectivity = this; var inputListeners = this.options.inputListeners || Selectivity.InputListeners; inputListeners.forEach(function(listener) { listener(selectivity, input, options); }); if (!options || options.search !== false) { input.addEventListener('keyup', function(event) { if (!event.defaultPrevented) { selectivity.search(event.target.value); } }); } }
[ "function", "(", "input", ",", "options", ")", "{", "this", ".", "input", "=", "input", ";", "var", "selectivity", "=", "this", ";", "var", "inputListeners", "=", "this", ".", "options", ".", "inputListeners", "||", "Selectivity", ".", "InputListeners", ";", "inputListeners", ".", "forEach", "(", "function", "(", "listener", ")", "{", "listener", "(", "selectivity", ",", "input", ",", "options", ")", ";", "}", ")", ";", "if", "(", "!", "options", "||", "options", ".", "search", "!==", "false", ")", "{", "input", ".", "addEventListener", "(", "'keyup'", ",", "function", "(", "event", ")", "{", "if", "(", "!", "event", ".", "defaultPrevented", ")", "{", "selectivity", ".", "search", "(", "event", ".", "target", ".", "value", ")", ";", "}", "}", ")", ";", "}", "}" ]
Initializes the input element. Sets the input property, invokes all input listeners and (by default) attaches the action of searching when something is typed. @param input Input element. @param options Optional options object. May contain the following property: search - If false, no event handlers are setup to initiate searching when the user types in the input field. This is useful if you want to use the input only to handle keyboard support.
[ "Initializes", "the", "input", "element", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L247-L263
16,006
arendjr/selectivity
src/selectivity.js
function(newData, options) { options = options || {}; newData = this.validateData(newData); this._data = newData; this._value = this.getValueForData(newData); if (options.triggerChange !== false) { this.triggerChange(); } }
javascript
function(newData, options) { options = options || {}; newData = this.validateData(newData); this._data = newData; this._value = this.getValueForData(newData); if (options.triggerChange !== false) { this.triggerChange(); } }
[ "function", "(", "newData", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "newData", "=", "this", ".", "validateData", "(", "newData", ")", ";", "this", ".", "_data", "=", "newData", ";", "this", ".", "_value", "=", "this", ".", "getValueForData", "(", "newData", ")", ";", "if", "(", "options", ".", "triggerChange", "!==", "false", ")", "{", "this", ".", "triggerChange", "(", ")", ";", "}", "}" ]
Sets the selection data. The selection data contains both IDs and text labels. If you only want to set or get the IDs, you should use the value() method. @param newData New data to set. For a MultipleSelectivity instance the data must be an array of objects with 'id' and 'text' properties, for a SingleSelectivity instance the data must be a single such object or null to indicate no item is selected. @param options Optional options object. May contain the following property: triggerChange - Set to false to suppress the "change" event being triggered. Note this will also cause the UI to not update automatically; so you may want to call rerenderSelection() manually when using this option.
[ "Sets", "the", "selection", "data", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L335-L346
16,007
arendjr/selectivity
src/selectivity.js
function(options) { options = options || {}; var selectivity = this; Selectivity.OptionListeners.forEach(function(listener) { listener(selectivity, options); }); if ('items' in options) { this.items = options.items ? Selectivity.processItems(options.items) : null; } if ('templates' in options) { assign(this.templates, options.templates); } assign(this.options, options); this.enabled = !this.options.readOnly && !this.options.removeOnly; }
javascript
function(options) { options = options || {}; var selectivity = this; Selectivity.OptionListeners.forEach(function(listener) { listener(selectivity, options); }); if ('items' in options) { this.items = options.items ? Selectivity.processItems(options.items) : null; } if ('templates' in options) { assign(this.templates, options.templates); } assign(this.options, options); this.enabled = !this.options.readOnly && !this.options.removeOnly; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "selectivity", "=", "this", ";", "Selectivity", ".", "OptionListeners", ".", "forEach", "(", "function", "(", "listener", ")", "{", "listener", "(", "selectivity", ",", "options", ")", ";", "}", ")", ";", "if", "(", "'items'", "in", "options", ")", "{", "this", ".", "items", "=", "options", ".", "items", "?", "Selectivity", ".", "processItems", "(", "options", ".", "items", ")", ":", "null", ";", "}", "if", "(", "'templates'", "in", "options", ")", "{", "assign", "(", "this", ".", "templates", ",", "options", ".", "templates", ")", ";", "}", "assign", "(", "this", ".", "options", ",", "options", ")", ";", "this", ".", "enabled", "=", "!", "this", ".", "options", ".", "readOnly", "&&", "!", "this", ".", "options", ".", "removeOnly", ";", "}" ]
Sets one or more options on this Selectivity instance. @param options Options object. May contain one or more of the following properties: closeOnSelect - Set to false to keep the dropdown open after the user has selected an item. This is useful if you want to allow the user to quickly select multiple items. The default value is true. dropdown - Custom dropdown implementation to use for this instance. initSelection - Function to map values by ID to selection data. This function receives two arguments, 'value' and 'callback'. The value is the current value of the selection, which is an ID or an array of IDs depending on the input type. The callback should be invoked with an object or array of objects, respectively, containing 'id' and 'text' properties. inputListeners - Array of search input listeners. By default, the global array Selectivity.InputListeners is used. items - Array of items from which to select. Should be an array of objects with 'id' and 'text' properties. As convenience, you may also pass an array of strings, in which case the same string is used for both the 'id' and 'text' properties. If items are given, all items are expected to be available locally and all selection operations operate on this local array only. If null, items are not available locally, and a query function should be provided to fetch remote data. matcher - Function to determine whether text matches a given search term. Note this function is only used if you have specified an array of items. Receives two arguments: item - The item that should match the search term. term - The search term. Note that for performance reasons, the term has always been already processed using Selectivity.transformText(). The method should return the item if it matches, and null otherwise. If the item has a children array, the matcher is expected to filter those itself (be sure to only return the filtered array of children in the returned item and not to modify the children of the item argument). placeholder - Placeholder text to display when the element has no focus and no selected items. positionDropdown - Function to position the dropdown. Receives two arguments: dropdownEl - The element to be positioned. selectEl - The element of the Selectivity instance, that you can position the dropdown to. The default implementation positions the dropdown element under the Selectivity's element and gives it the same width. query - Function to use for querying items. Receives a single object as argument with the following properties: callback - Callback to invoke when the results are available. This callback should be passed a single object as argument with the following properties: more - Boolean that can be set to true to indicate there are more results available. Additional results may be fetched by the user through pagination. results - Array of result items. The format for the result items is the same as for passing local items. offset - This property is only used for pagination and indicates how many results should be skipped when returning more results. selectivity - The Selectivity instance the query function is used on. term - The search term the user is searching for. Unlike with the matcher function, the term has not been processed using Selectivity.transformText(). readOnly - If true, disables any modification of the input. removeOnly - If true, disables any modification of the input except removing of selected items. shouldOpenSubmenu - Function to call that will decide whether a submenu should be opened. Receives two parameters: item - The currently highlighted result item. reason - The reason why the item is being highlighted. See Dropdown#highlight() for possible values. showDropdown - Set to false if you don't want to use any dropdown (you can still open it programmatically using open()). showSearchInputInDropdown - Set to false to remove the search input used in dropdowns. The default is true for single-value inputs. templates - Object with instance-specific templates to override the global templates assigned to Selectivity.Templates.
[ "Sets", "one", "or", "more", "options", "on", "this", "Selectivity", "instance", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L424-L442
16,008
arendjr/selectivity
src/selectivity.js
function(newValue, options) { options = options || {}; newValue = this.validateValue(newValue); this._value = newValue; if (this.options.initSelection) { this.options.initSelection( newValue, function(data) { if (this._value === newValue) { this._data = this.validateData(data); if (options.triggerChange !== false) { this.triggerChange(); } } }.bind(this) ); } else { this._data = this.getDataForValue(newValue); if (options.triggerChange !== false) { this.triggerChange(); } } }
javascript
function(newValue, options) { options = options || {}; newValue = this.validateValue(newValue); this._value = newValue; if (this.options.initSelection) { this.options.initSelection( newValue, function(data) { if (this._value === newValue) { this._data = this.validateData(data); if (options.triggerChange !== false) { this.triggerChange(); } } }.bind(this) ); } else { this._data = this.getDataForValue(newValue); if (options.triggerChange !== false) { this.triggerChange(); } } }
[ "function", "(", "newValue", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "newValue", "=", "this", ".", "validateValue", "(", "newValue", ")", ";", "this", ".", "_value", "=", "newValue", ";", "if", "(", "this", ".", "options", ".", "initSelection", ")", "{", "this", ".", "options", ".", "initSelection", "(", "newValue", ",", "function", "(", "data", ")", "{", "if", "(", "this", ".", "_value", "===", "newValue", ")", "{", "this", ".", "_data", "=", "this", ".", "validateData", "(", "data", ")", ";", "if", "(", "options", ".", "triggerChange", "!==", "false", ")", "{", "this", ".", "triggerChange", "(", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "this", ".", "_data", "=", "this", ".", "getDataForValue", "(", "newValue", ")", ";", "if", "(", "options", ".", "triggerChange", "!==", "false", ")", "{", "this", ".", "triggerChange", "(", ")", ";", "}", "}", "}" ]
Sets the value of the selection. The value of the selection only concerns the IDs of the selection items. If you are interested in the IDs and the text labels, you should use the data() method. Note that if neither the items option nor the initSelection option have been set, Selectivity will have no way to determine what text labels should be used with the given IDs in which case it will assume the text is equal to the ID. This is useful if you're working with tags, or selecting e-mail addresses for instance, but may not always be what you want. @param newValue New value to set. For a MultipleSelectivity instance the value must be an array of IDs, for a SingleSelectivity instance the value must be a single ID (a string or a number) or null to indicate no item is selected. @param options Optional options object. May contain the following property: triggerChange - Set to false to suppress the "change" event being triggered. Note this will also cause the UI to not update automatically; so you may want to call rerenderSelection() manually when using this option.
[ "Sets", "the", "value", "of", "the", "selection", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L464-L491
16,009
arendjr/selectivity
src/selectivity.js
function(templateName, options) { var template = this.templates[templateName]; if (!template) { throw new Error('Unknown template: ' + templateName); } if (typeof template === 'function') { var templateResult = template(options); return typeof templateResult === 'string' ? templateResult.trim() : templateResult; } else if (template.render) { return template.render(options).trim(); } else { return template.toString().trim(); } }
javascript
function(templateName, options) { var template = this.templates[templateName]; if (!template) { throw new Error('Unknown template: ' + templateName); } if (typeof template === 'function') { var templateResult = template(options); return typeof templateResult === 'string' ? templateResult.trim() : templateResult; } else if (template.render) { return template.render(options).trim(); } else { return template.toString().trim(); } }
[ "function", "(", "templateName", ",", "options", ")", "{", "var", "template", "=", "this", ".", "templates", "[", "templateName", "]", ";", "if", "(", "!", "template", ")", "{", "throw", "new", "Error", "(", "'Unknown template: '", "+", "templateName", ")", ";", "}", "if", "(", "typeof", "template", "===", "'function'", ")", "{", "var", "templateResult", "=", "template", "(", "options", ")", ";", "return", "typeof", "templateResult", "===", "'string'", "?", "templateResult", ".", "trim", "(", ")", ":", "templateResult", ";", "}", "else", "if", "(", "template", ".", "render", ")", "{", "return", "template", ".", "render", "(", "options", ")", ".", "trim", "(", ")", ";", "}", "else", "{", "return", "template", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}", "}" ]
Returns the result of the given template. @param templateName Name of the template to process. @param options Options to pass to the template. @return String containing HTML or ReactElement if template is a function returning ReactElement.
[ "Returns", "the", "result", "of", "the", "given", "template", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L502-L516
16,010
arendjr/selectivity
src/selectivity.js
function(options) { var data = assign({ data: this._data, value: this._value }, options); this.triggerEvent('change', data); this.triggerEvent('selectivity-change', data); }
javascript
function(options) { var data = assign({ data: this._data, value: this._value }, options); this.triggerEvent('change', data); this.triggerEvent('selectivity-change', data); }
[ "function", "(", "options", ")", "{", "var", "data", "=", "assign", "(", "{", "data", ":", "this", ".", "_data", ",", "value", ":", "this", ".", "_value", "}", ",", "options", ")", ";", "this", ".", "triggerEvent", "(", "'change'", ",", "data", ")", ";", "this", ".", "triggerEvent", "(", "'selectivity-change'", ",", "data", ")", ";", "}" ]
Triggers the change event. The event object at least contains the following properties: data - The new data of the Selectivity instance. value - The new value of the Selectivity instance. @param Optional additional options added to the event object. @see getData() @see getValue()
[ "Triggers", "the", "change", "event", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L530-L534
16,011
arendjr/selectivity
src/selectivity.js
function(eventName, data) { var event = document.createEvent('Event'); event.initEvent(eventName, /* bubbles: */ false, /* cancelable: */ true); assign(event, data); this.el.dispatchEvent(event); return !event.defaultPrevented; }
javascript
function(eventName, data) { var event = document.createEvent('Event'); event.initEvent(eventName, /* bubbles: */ false, /* cancelable: */ true); assign(event, data); this.el.dispatchEvent(event); return !event.defaultPrevented; }
[ "function", "(", "eventName", ",", "data", ")", "{", "var", "event", "=", "document", ".", "createEvent", "(", "'Event'", ")", ";", "event", ".", "initEvent", "(", "eventName", ",", "/* bubbles: */", "false", ",", "/* cancelable: */", "true", ")", ";", "assign", "(", "event", ",", "data", ")", ";", "this", ".", "el", ".", "dispatchEvent", "(", "event", ")", ";", "return", "!", "event", ".", "defaultPrevented", ";", "}" ]
Triggers an event on the instance's element. @param eventName Name of the event to trigger. @param data Optional event data to be added to the event object. @return Whether the default action of the event may be executed, ie. returns false if preventDefault() has been called.
[ "Triggers", "an", "event", "on", "the", "instance", "s", "element", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L545-L551
16,012
arendjr/selectivity
src/selectivity.js
function(item) { if (item && Selectivity.isValidId(item.id) && isString(item.text)) { return item; } else { throw new Error('Item should have id (number or string) and text (string) properties'); } }
javascript
function(item) { if (item && Selectivity.isValidId(item.id) && isString(item.text)) { return item; } else { throw new Error('Item should have id (number or string) and text (string) properties'); } }
[ "function", "(", "item", ")", "{", "if", "(", "item", "&&", "Selectivity", ".", "isValidId", "(", "item", ".", "id", ")", "&&", "isString", "(", "item", ".", "text", ")", ")", "{", "return", "item", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Item should have id (number or string) and text (string) properties'", ")", ";", "}", "}" ]
Validates a single item. Throws an exception if the item is invalid. @param item The item to validate. @return The validated item. May differ from the input item.
[ "Validates", "a", "single", "item", ".", "Throws", "an", "exception", "if", "the", "item", "is", "invalid", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/selectivity.js#L560-L566
16,013
arendjr/selectivity
src/inputs/email.js
EmailInput
function EmailInput(options) { MultipleInput.call( this, assign( { createTokenItem: createEmailItem, showDropdown: false, tokenizer: emailTokenizer }, options ) ); this.events.on('blur', function() { var input = this.input; if (input && isValidEmail(lastWord(input.value))) { this.add(createEmailItem(input.value)); } }); }
javascript
function EmailInput(options) { MultipleInput.call( this, assign( { createTokenItem: createEmailItem, showDropdown: false, tokenizer: emailTokenizer }, options ) ); this.events.on('blur', function() { var input = this.input; if (input && isValidEmail(lastWord(input.value))) { this.add(createEmailItem(input.value)); } }); }
[ "function", "EmailInput", "(", "options", ")", "{", "MultipleInput", ".", "call", "(", "this", ",", "assign", "(", "{", "createTokenItem", ":", "createEmailItem", ",", "showDropdown", ":", "false", ",", "tokenizer", ":", "emailTokenizer", "}", ",", "options", ")", ")", ";", "this", ".", "events", ".", "on", "(", "'blur'", ",", "function", "(", ")", "{", "var", "input", "=", "this", ".", "input", ";", "if", "(", "input", "&&", "isValidEmail", "(", "lastWord", "(", "input", ".", "value", ")", ")", ")", "{", "this", ".", "add", "(", "createEmailItem", "(", "input", ".", "value", ")", ")", ";", "}", "}", ")", ";", "}" ]
EmailInput Constructor. @param options Options object. Accepts all options from the MultipleInput Constructor.
[ "EmailInput", "Constructor", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/inputs/email.js#L126-L145
16,014
arendjr/selectivity
src/dropdown.js
SelectivityDropdown
function SelectivityDropdown(selectivity, options) { this.el = parseElement( selectivity.template('dropdown', { dropdownCssClass: selectivity.options.dropdownCssClass, searchInputPlaceholder: selectivity.options.searchInputPlaceholder, showSearchInput: options.showSearchInput }) ); /** * DOM element to add the results to. */ this.resultsContainer = this.$('.selectivity-results-container'); /** * Boolean indicating whether more results are available than currently displayed in the * dropdown. */ this.hasMore = false; /** * The currently highlighted result item. */ this.highlightedResult = null; /** * Boolean whether the load more link is currently highlighted. */ this.loadMoreHighlighted = false; /** * Options passed to the dropdown constructor. */ this.options = options; /** * The results displayed in the dropdown. */ this.results = []; /** * Selectivity instance. */ this.selectivity = selectivity; this._closed = false; this._lastMousePosition = {}; this.close = this.close.bind(this); this.position = this.position.bind(this); if (selectivity.options.closeOnSelect !== false) { selectivity.events.on('selectivity-selecting', this.close); } this.addToDom(); this.showLoading(); if (options.showSearchInput) { selectivity.initInput(this.$('.selectivity-search-input')); selectivity.focus(); } var events = {}; events['click ' + LOAD_MORE_SELECTOR] = this._loadMoreClicked; events['click ' + RESULT_ITEM_SELECTOR] = this._resultClicked; events['mouseenter ' + LOAD_MORE_SELECTOR] = this._loadMoreHovered; events['mouseenter ' + RESULT_ITEM_SELECTOR] = this._resultHovered; this.events = new EventListener(this.el, this); this.events.on(events); this._attachScrollListeners(); this._suppressWheel(); setTimeout(this.triggerOpen.bind(this), 1); }
javascript
function SelectivityDropdown(selectivity, options) { this.el = parseElement( selectivity.template('dropdown', { dropdownCssClass: selectivity.options.dropdownCssClass, searchInputPlaceholder: selectivity.options.searchInputPlaceholder, showSearchInput: options.showSearchInput }) ); /** * DOM element to add the results to. */ this.resultsContainer = this.$('.selectivity-results-container'); /** * Boolean indicating whether more results are available than currently displayed in the * dropdown. */ this.hasMore = false; /** * The currently highlighted result item. */ this.highlightedResult = null; /** * Boolean whether the load more link is currently highlighted. */ this.loadMoreHighlighted = false; /** * Options passed to the dropdown constructor. */ this.options = options; /** * The results displayed in the dropdown. */ this.results = []; /** * Selectivity instance. */ this.selectivity = selectivity; this._closed = false; this._lastMousePosition = {}; this.close = this.close.bind(this); this.position = this.position.bind(this); if (selectivity.options.closeOnSelect !== false) { selectivity.events.on('selectivity-selecting', this.close); } this.addToDom(); this.showLoading(); if (options.showSearchInput) { selectivity.initInput(this.$('.selectivity-search-input')); selectivity.focus(); } var events = {}; events['click ' + LOAD_MORE_SELECTOR] = this._loadMoreClicked; events['click ' + RESULT_ITEM_SELECTOR] = this._resultClicked; events['mouseenter ' + LOAD_MORE_SELECTOR] = this._loadMoreHovered; events['mouseenter ' + RESULT_ITEM_SELECTOR] = this._resultHovered; this.events = new EventListener(this.el, this); this.events.on(events); this._attachScrollListeners(); this._suppressWheel(); setTimeout(this.triggerOpen.bind(this), 1); }
[ "function", "SelectivityDropdown", "(", "selectivity", ",", "options", ")", "{", "this", ".", "el", "=", "parseElement", "(", "selectivity", ".", "template", "(", "'dropdown'", ",", "{", "dropdownCssClass", ":", "selectivity", ".", "options", ".", "dropdownCssClass", ",", "searchInputPlaceholder", ":", "selectivity", ".", "options", ".", "searchInputPlaceholder", ",", "showSearchInput", ":", "options", ".", "showSearchInput", "}", ")", ")", ";", "/**\n * DOM element to add the results to.\n */", "this", ".", "resultsContainer", "=", "this", ".", "$", "(", "'.selectivity-results-container'", ")", ";", "/**\n * Boolean indicating whether more results are available than currently displayed in the\n * dropdown.\n */", "this", ".", "hasMore", "=", "false", ";", "/**\n * The currently highlighted result item.\n */", "this", ".", "highlightedResult", "=", "null", ";", "/**\n * Boolean whether the load more link is currently highlighted.\n */", "this", ".", "loadMoreHighlighted", "=", "false", ";", "/**\n * Options passed to the dropdown constructor.\n */", "this", ".", "options", "=", "options", ";", "/**\n * The results displayed in the dropdown.\n */", "this", ".", "results", "=", "[", "]", ";", "/**\n * Selectivity instance.\n */", "this", ".", "selectivity", "=", "selectivity", ";", "this", ".", "_closed", "=", "false", ";", "this", ".", "_lastMousePosition", "=", "{", "}", ";", "this", ".", "close", "=", "this", ".", "close", ".", "bind", "(", "this", ")", ";", "this", ".", "position", "=", "this", ".", "position", ".", "bind", "(", "this", ")", ";", "if", "(", "selectivity", ".", "options", ".", "closeOnSelect", "!==", "false", ")", "{", "selectivity", ".", "events", ".", "on", "(", "'selectivity-selecting'", ",", "this", ".", "close", ")", ";", "}", "this", ".", "addToDom", "(", ")", ";", "this", ".", "showLoading", "(", ")", ";", "if", "(", "options", ".", "showSearchInput", ")", "{", "selectivity", ".", "initInput", "(", "this", ".", "$", "(", "'.selectivity-search-input'", ")", ")", ";", "selectivity", ".", "focus", "(", ")", ";", "}", "var", "events", "=", "{", "}", ";", "events", "[", "'click '", "+", "LOAD_MORE_SELECTOR", "]", "=", "this", ".", "_loadMoreClicked", ";", "events", "[", "'click '", "+", "RESULT_ITEM_SELECTOR", "]", "=", "this", ".", "_resultClicked", ";", "events", "[", "'mouseenter '", "+", "LOAD_MORE_SELECTOR", "]", "=", "this", ".", "_loadMoreHovered", ";", "events", "[", "'mouseenter '", "+", "RESULT_ITEM_SELECTOR", "]", "=", "this", ".", "_resultHovered", ";", "this", ".", "events", "=", "new", "EventListener", "(", "this", ".", "el", ",", "this", ")", ";", "this", ".", "events", ".", "on", "(", "events", ")", ";", "this", ".", "_attachScrollListeners", "(", ")", ";", "this", ".", "_suppressWheel", "(", ")", ";", "setTimeout", "(", "this", ".", "triggerOpen", ".", "bind", "(", "this", ")", ",", "1", ")", ";", "}" ]
Selectivity Dropdown Constructor. @param selectivity Selectivity instance to which the dropdown belongs. @param options Options object. Should have the following properties: highlightFirstItem - Set to false if you don't want the first item to be automatically highlighted (optional). items - Array of items to display. position - Callback for positioning the dropdown. query - Callback to fetch the items to display. showSearchInput - Boolean whether a search input should be shown.
[ "Selectivity", "Dropdown", "Constructor", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L41-L117
16,015
arendjr/selectivity
src/dropdown.js
function() { if (!this._closed) { this._closed = true; removeElement(this.el); this.selectivity.events.off('selectivity-selecting', this.close); this.triggerClose(); this._removeScrollListeners(); } }
javascript
function() { if (!this._closed) { this._closed = true; removeElement(this.el); this.selectivity.events.off('selectivity-selecting', this.close); this.triggerClose(); this._removeScrollListeners(); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "_closed", ")", "{", "this", ".", "_closed", "=", "true", ";", "removeElement", "(", "this", ".", "el", ")", ";", "this", ".", "selectivity", ".", "events", ".", "off", "(", "'selectivity-selecting'", ",", "this", ".", "close", ")", ";", "this", ".", "triggerClose", "(", ")", ";", "this", ".", "_removeScrollListeners", "(", ")", ";", "}", "}" ]
Closes the dropdown.
[ "Closes", "the", "dropdown", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L140-L152
16,016
arendjr/selectivity
src/dropdown.js
function(item, options) { toggleClass(this.$(HIGHLIGHT_SELECTOR), HIGHLIGHT_CLASS, false); toggleClass(this.$(getItemSelector(RESULT_ITEM_SELECTOR, item.id)), HIGHLIGHT_CLASS, true); this.highlightedResult = item; this.loadMoreHighlighted = false; this.selectivity.triggerEvent('selectivity-highlight', { item: item, id: item.id, reason: (options && options.reason) || 'unspecified' }); }
javascript
function(item, options) { toggleClass(this.$(HIGHLIGHT_SELECTOR), HIGHLIGHT_CLASS, false); toggleClass(this.$(getItemSelector(RESULT_ITEM_SELECTOR, item.id)), HIGHLIGHT_CLASS, true); this.highlightedResult = item; this.loadMoreHighlighted = false; this.selectivity.triggerEvent('selectivity-highlight', { item: item, id: item.id, reason: (options && options.reason) || 'unspecified' }); }
[ "function", "(", "item", ",", "options", ")", "{", "toggleClass", "(", "this", ".", "$", "(", "HIGHLIGHT_SELECTOR", ")", ",", "HIGHLIGHT_CLASS", ",", "false", ")", ";", "toggleClass", "(", "this", ".", "$", "(", "getItemSelector", "(", "RESULT_ITEM_SELECTOR", ",", "item", ".", "id", ")", ")", ",", "HIGHLIGHT_CLASS", ",", "true", ")", ";", "this", ".", "highlightedResult", "=", "item", ";", "this", ".", "loadMoreHighlighted", "=", "false", ";", "this", ".", "selectivity", ".", "triggerEvent", "(", "'selectivity-highlight'", ",", "{", "item", ":", "item", ",", "id", ":", "item", ".", "id", ",", "reason", ":", "(", "options", "&&", "options", ".", "reason", ")", "||", "'unspecified'", "}", ")", ";", "}" ]
Highlights a result item. @param item The item to highlight. @param options Optional options object that may contain the following property: reason - The reason why the result item is being highlighted. Possible values: 'current_value', 'first_result', 'hovered'.
[ "Highlights", "a", "result", "item", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L162-L174
16,017
arendjr/selectivity
src/dropdown.js
function() { toggleClass(this.$(HIGHLIGHT_SELECTOR), HIGHLIGHT_CLASS, false); toggleClass(this.$(LOAD_MORE_SELECTOR), HIGHLIGHT_CLASS, true); this.highlightedResult = null; this.loadMoreHighlighted = true; }
javascript
function() { toggleClass(this.$(HIGHLIGHT_SELECTOR), HIGHLIGHT_CLASS, false); toggleClass(this.$(LOAD_MORE_SELECTOR), HIGHLIGHT_CLASS, true); this.highlightedResult = null; this.loadMoreHighlighted = true; }
[ "function", "(", ")", "{", "toggleClass", "(", "this", ".", "$", "(", "HIGHLIGHT_SELECTOR", ")", ",", "HIGHLIGHT_CLASS", ",", "false", ")", ";", "toggleClass", "(", "this", ".", "$", "(", "LOAD_MORE_SELECTOR", ")", ",", "HIGHLIGHT_CLASS", ",", "true", ")", ";", "this", ".", "highlightedResult", "=", "null", ";", "this", ".", "loadMoreHighlighted", "=", "true", ";", "}" ]
Highlights the load more link. @param item The item to highlight.
[ "Highlights", "the", "load", "more", "link", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L181-L187
16,018
arendjr/selectivity
src/dropdown.js
function() { removeElement(this.$(LOAD_MORE_SELECTOR)); this.resultsContainer.innerHTML += this.selectivity.template('loading'); this.options.query({ callback: function(response) { if (response && response.results) { this._showResults(Selectivity.processItems(response.results), { add: true, hasMore: !!response.more }); } else { throw new Error('callback must be passed a response object'); } }.bind(this), error: this._showResults.bind(this, [], { add: true }), offset: this.results.length, selectivity: this.selectivity, term: this.term }); }
javascript
function() { removeElement(this.$(LOAD_MORE_SELECTOR)); this.resultsContainer.innerHTML += this.selectivity.template('loading'); this.options.query({ callback: function(response) { if (response && response.results) { this._showResults(Selectivity.processItems(response.results), { add: true, hasMore: !!response.more }); } else { throw new Error('callback must be passed a response object'); } }.bind(this), error: this._showResults.bind(this, [], { add: true }), offset: this.results.length, selectivity: this.selectivity, term: this.term }); }
[ "function", "(", ")", "{", "removeElement", "(", "this", ".", "$", "(", "LOAD_MORE_SELECTOR", ")", ")", ";", "this", ".", "resultsContainer", ".", "innerHTML", "+=", "this", ".", "selectivity", ".", "template", "(", "'loading'", ")", ";", "this", ".", "options", ".", "query", "(", "{", "callback", ":", "function", "(", "response", ")", "{", "if", "(", "response", "&&", "response", ".", "results", ")", "{", "this", ".", "_showResults", "(", "Selectivity", ".", "processItems", "(", "response", ".", "results", ")", ",", "{", "add", ":", "true", ",", "hasMore", ":", "!", "!", "response", ".", "more", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'callback must be passed a response object'", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ",", "error", ":", "this", ".", "_showResults", ".", "bind", "(", "this", ",", "[", "]", ",", "{", "add", ":", "true", "}", ")", ",", "offset", ":", "this", ".", "results", ".", "length", ",", "selectivity", ":", "this", ".", "selectivity", ",", "term", ":", "this", ".", "term", "}", ")", ";", "}" ]
Loads a follow-up page with results after a search. This method should only be called after a call to search() when the callback has indicated more results are available.
[ "Loads", "a", "follow", "-", "up", "page", "with", "results", "after", "a", "search", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L195-L215
16,019
arendjr/selectivity
src/dropdown.js
function(items) { var selectivity = this.selectivity; return items .map(function(item) { var result = selectivity.template(item.id ? 'resultItem' : 'resultLabel', item); if (item.children) { result += selectivity.template('resultChildren', { childrenHtml: this.renderItems(item.children) }); } return result; }, this) .join(''); }
javascript
function(items) { var selectivity = this.selectivity; return items .map(function(item) { var result = selectivity.template(item.id ? 'resultItem' : 'resultLabel', item); if (item.children) { result += selectivity.template('resultChildren', { childrenHtml: this.renderItems(item.children) }); } return result; }, this) .join(''); }
[ "function", "(", "items", ")", "{", "var", "selectivity", "=", "this", ".", "selectivity", ";", "return", "items", ".", "map", "(", "function", "(", "item", ")", "{", "var", "result", "=", "selectivity", ".", "template", "(", "item", ".", "id", "?", "'resultItem'", ":", "'resultLabel'", ",", "item", ")", ";", "if", "(", "item", ".", "children", ")", "{", "result", "+=", "selectivity", ".", "template", "(", "'resultChildren'", ",", "{", "childrenHtml", ":", "this", ".", "renderItems", "(", "item", ".", "children", ")", "}", ")", ";", "}", "return", "result", ";", "}", ",", "this", ")", ".", "join", "(", "''", ")", ";", "}" ]
Renders an array of result items. @param items Array of result items. @return HTML-formatted string to display the result items.
[ "Renders", "an", "array", "of", "result", "items", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L236-L249
16,020
arendjr/selectivity
src/dropdown.js
function(term) { this.term = term; if (this.options.items) { term = Selectivity.transformText(term); var matcher = this.selectivity.options.matcher || Selectivity.matcher; this._showResults( this.options.items .map(function(item) { return matcher(item, term); }) .filter(function(item) { return !!item; }), { term: term } ); } else if (this.options.query) { this.options.query({ callback: function(response) { if (response && response.results) { this._showResults(Selectivity.processItems(response.results), { hasMore: !!response.more, term: term }); } else { throw new Error('callback must be passed a response object'); } }.bind(this), error: this.showError.bind(this), offset: 0, selectivity: this.selectivity, term: term }); } }
javascript
function(term) { this.term = term; if (this.options.items) { term = Selectivity.transformText(term); var matcher = this.selectivity.options.matcher || Selectivity.matcher; this._showResults( this.options.items .map(function(item) { return matcher(item, term); }) .filter(function(item) { return !!item; }), { term: term } ); } else if (this.options.query) { this.options.query({ callback: function(response) { if (response && response.results) { this._showResults(Selectivity.processItems(response.results), { hasMore: !!response.more, term: term }); } else { throw new Error('callback must be passed a response object'); } }.bind(this), error: this.showError.bind(this), offset: 0, selectivity: this.selectivity, term: term }); } }
[ "function", "(", "term", ")", "{", "this", ".", "term", "=", "term", ";", "if", "(", "this", ".", "options", ".", "items", ")", "{", "term", "=", "Selectivity", ".", "transformText", "(", "term", ")", ";", "var", "matcher", "=", "this", ".", "selectivity", ".", "options", ".", "matcher", "||", "Selectivity", ".", "matcher", ";", "this", ".", "_showResults", "(", "this", ".", "options", ".", "items", ".", "map", "(", "function", "(", "item", ")", "{", "return", "matcher", "(", "item", ",", "term", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "!", "!", "item", ";", "}", ")", ",", "{", "term", ":", "term", "}", ")", ";", "}", "else", "if", "(", "this", ".", "options", ".", "query", ")", "{", "this", ".", "options", ".", "query", "(", "{", "callback", ":", "function", "(", "response", ")", "{", "if", "(", "response", "&&", "response", ".", "results", ")", "{", "this", ".", "_showResults", "(", "Selectivity", ".", "processItems", "(", "response", ".", "results", ")", ",", "{", "hasMore", ":", "!", "!", "response", ".", "more", ",", "term", ":", "term", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'callback must be passed a response object'", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ",", "error", ":", "this", ".", "showError", ".", "bind", "(", "this", ")", ",", "offset", ":", "0", ",", "selectivity", ":", "this", ".", "selectivity", ",", "term", ":", "term", "}", ")", ";", "}", "}" ]
Searches for results based on the term given. If an items array has been passed with the options to the Selectivity instance, a local search will be performed among those items. Otherwise, the query function specified in the options will be used to perform the search. If neither is defined, nothing happens. @param term Term to search for.
[ "Searches", "for", "results", "based", "on", "the", "term", "given", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L260-L294
16,021
arendjr/selectivity
src/dropdown.js
function(id) { var item = Selectivity.findNestedById(this.results, id); if (item && !item.disabled && item.selectable !== false) { var options = { id: id, item: item }; if (this.selectivity.triggerEvent('selectivity-selecting', options)) { this.selectivity.triggerEvent('selectivity-selected', options); } } }
javascript
function(id) { var item = Selectivity.findNestedById(this.results, id); if (item && !item.disabled && item.selectable !== false) { var options = { id: id, item: item }; if (this.selectivity.triggerEvent('selectivity-selecting', options)) { this.selectivity.triggerEvent('selectivity-selected', options); } } }
[ "function", "(", "id", ")", "{", "var", "item", "=", "Selectivity", ".", "findNestedById", "(", "this", ".", "results", ",", "id", ")", ";", "if", "(", "item", "&&", "!", "item", ".", "disabled", "&&", "item", ".", "selectable", "!==", "false", ")", "{", "var", "options", "=", "{", "id", ":", "id", ",", "item", ":", "item", "}", ";", "if", "(", "this", ".", "selectivity", ".", "triggerEvent", "(", "'selectivity-selecting'", ",", "options", ")", ")", "{", "this", ".", "selectivity", ".", "triggerEvent", "(", "'selectivity-selected'", ",", "options", ")", ";", "}", "}", "}" ]
Selects the item with the given ID. @param id ID of the item to select.
[ "Selects", "the", "item", "with", "the", "given", "ID", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L312-L320
16,022
arendjr/selectivity
src/dropdown.js
function(message, options) { this.resultsContainer.innerHTML = this.selectivity.template('error', { escape: !options || options.escape !== false, message: message }); this.hasMore = false; this.results = []; this.highlightedResult = null; this.loadMoreHighlighted = false; this.position(); }
javascript
function(message, options) { this.resultsContainer.innerHTML = this.selectivity.template('error', { escape: !options || options.escape !== false, message: message }); this.hasMore = false; this.results = []; this.highlightedResult = null; this.loadMoreHighlighted = false; this.position(); }
[ "function", "(", "message", ",", "options", ")", "{", "this", ".", "resultsContainer", ".", "innerHTML", "=", "this", ".", "selectivity", ".", "template", "(", "'error'", ",", "{", "escape", ":", "!", "options", "||", "options", ".", "escape", "!==", "false", ",", "message", ":", "message", "}", ")", ";", "this", ".", "hasMore", "=", "false", ";", "this", ".", "results", "=", "[", "]", ";", "this", ".", "highlightedResult", "=", "null", ";", "this", ".", "loadMoreHighlighted", "=", "false", ";", "this", ".", "position", "(", ")", ";", "}" ]
Shows an error message. @param message Error message to display. @param options Options object. May contain the following property: escape - Set to false to disable HTML-escaping of the message. Useful if you want to set raw HTML as the message, but may open you up to XSS attacks if you're not careful with escaping user input.
[ "Shows", "an", "error", "message", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L331-L344
16,023
arendjr/selectivity
src/dropdown.js
function() { this.resultsContainer.innerHTML = this.selectivity.template('loading'); this.hasMore = false; this.results = []; this.highlightedResult = null; this.loadMoreHighlighted = false; this.position(); }
javascript
function() { this.resultsContainer.innerHTML = this.selectivity.template('loading'); this.hasMore = false; this.results = []; this.highlightedResult = null; this.loadMoreHighlighted = false; this.position(); }
[ "function", "(", ")", "{", "this", ".", "resultsContainer", ".", "innerHTML", "=", "this", ".", "selectivity", ".", "template", "(", "'loading'", ")", ";", "this", ".", "hasMore", "=", "false", ";", "this", ".", "results", "=", "[", "]", ";", "this", ".", "highlightedResult", "=", "null", ";", "this", ".", "loadMoreHighlighted", "=", "false", ";", "this", ".", "position", "(", ")", ";", "}" ]
Shows a loading indicator in the dropdown.
[ "Shows", "a", "loading", "indicator", "in", "the", "dropdown", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L349-L359
16,024
arendjr/selectivity
src/dropdown.js
function(results, options) { if (options.add) { removeElement(this.$('.selectivity-loading')); } else { this.resultsContainer.innerHTML = ''; } var filteredResults = this.selectivity.filterResults(results); var resultsHtml = this.renderItems(filteredResults); if (options.hasMore) { resultsHtml += this.selectivity.template('loadMore'); } else if (!resultsHtml && !options.add) { resultsHtml = this.selectivity.template('noResults', { term: options.term }); } this.resultsContainer.innerHTML += resultsHtml; this.results = options.add ? this.results.concat(results) : results; this.hasMore = options.hasMore; var value = this.selectivity.getValue(); if (value && !Array.isArray(value)) { var item = Selectivity.findNestedById(results, value); if (item) { this.highlight(item, { reason: 'current_value' }); } } else if ( this.options.highlightFirstItem !== false && (!options.add || this.loadMoreHighlighted) ) { this._highlightFirstItem(filteredResults); } this.position(); }
javascript
function(results, options) { if (options.add) { removeElement(this.$('.selectivity-loading')); } else { this.resultsContainer.innerHTML = ''; } var filteredResults = this.selectivity.filterResults(results); var resultsHtml = this.renderItems(filteredResults); if (options.hasMore) { resultsHtml += this.selectivity.template('loadMore'); } else if (!resultsHtml && !options.add) { resultsHtml = this.selectivity.template('noResults', { term: options.term }); } this.resultsContainer.innerHTML += resultsHtml; this.results = options.add ? this.results.concat(results) : results; this.hasMore = options.hasMore; var value = this.selectivity.getValue(); if (value && !Array.isArray(value)) { var item = Selectivity.findNestedById(results, value); if (item) { this.highlight(item, { reason: 'current_value' }); } } else if ( this.options.highlightFirstItem !== false && (!options.add || this.loadMoreHighlighted) ) { this._highlightFirstItem(filteredResults); } this.position(); }
[ "function", "(", "results", ",", "options", ")", "{", "if", "(", "options", ".", "add", ")", "{", "removeElement", "(", "this", ".", "$", "(", "'.selectivity-loading'", ")", ")", ";", "}", "else", "{", "this", ".", "resultsContainer", ".", "innerHTML", "=", "''", ";", "}", "var", "filteredResults", "=", "this", ".", "selectivity", ".", "filterResults", "(", "results", ")", ";", "var", "resultsHtml", "=", "this", ".", "renderItems", "(", "filteredResults", ")", ";", "if", "(", "options", ".", "hasMore", ")", "{", "resultsHtml", "+=", "this", ".", "selectivity", ".", "template", "(", "'loadMore'", ")", ";", "}", "else", "if", "(", "!", "resultsHtml", "&&", "!", "options", ".", "add", ")", "{", "resultsHtml", "=", "this", ".", "selectivity", ".", "template", "(", "'noResults'", ",", "{", "term", ":", "options", ".", "term", "}", ")", ";", "}", "this", ".", "resultsContainer", ".", "innerHTML", "+=", "resultsHtml", ";", "this", ".", "results", "=", "options", ".", "add", "?", "this", ".", "results", ".", "concat", "(", "results", ")", ":", "results", ";", "this", ".", "hasMore", "=", "options", ".", "hasMore", ";", "var", "value", "=", "this", ".", "selectivity", ".", "getValue", "(", ")", ";", "if", "(", "value", "&&", "!", "Array", ".", "isArray", "(", "value", ")", ")", "{", "var", "item", "=", "Selectivity", ".", "findNestedById", "(", "results", ",", "value", ")", ";", "if", "(", "item", ")", "{", "this", ".", "highlight", "(", "item", ",", "{", "reason", ":", "'current_value'", "}", ")", ";", "}", "}", "else", "if", "(", "this", ".", "options", ".", "highlightFirstItem", "!==", "false", "&&", "(", "!", "options", ".", "add", "||", "this", ".", "loadMoreHighlighted", ")", ")", "{", "this", ".", "_highlightFirstItem", "(", "filteredResults", ")", ";", "}", "this", ".", "position", "(", ")", ";", "}" ]
Shows the results from a search query. @param results Array of result items. @param options Options object. May contain the following properties: add - True if the results should be added to any already shown results. dropdown - The dropdown instance for which the results are meant. hasMore - Boolean whether more results can be fetched using the query() function. term - The search term for which the results are displayed.
[ "Shows", "the", "results", "from", "a", "search", "query", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/dropdown.js#L372-L406
16,025
arendjr/selectivity
src/inputs/single.js
SingleInput
function SingleInput(options) { Selectivity.call( this, assign( { // Dropdowns for single-value inputs should open below the select box, unless there // is not enough space below, in which case the dropdown should be moved up just // enough so it fits in the window, but never so much that it reaches above the top. positionDropdown: function(el, selectEl) { var rect = selectEl.getBoundingClientRect(); var dropdownTop = rect.bottom; var deltaUp = Math.min( Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0), rect.top + rect.height ); assign(el.style, { left: rect.left + 'px', top: dropdownTop - deltaUp + 'px', width: rect.width + 'px' }); } }, options ) ); this.rerender(); if (options.showSearchInputInDropdown === false) { this.initInput(this.$('.selectivity-single-select-input'), { search: false }); } this.events.on({ change: this.rerenderSelection, click: this._clicked, 'click .selectivity-search-input': stopPropagation, 'click .selectivity-single-selected-item-remove': this._itemRemoveClicked, 'focus .selectivity-single-select-input': this._focused, 'selectivity-selected': this._resultSelected }); }
javascript
function SingleInput(options) { Selectivity.call( this, assign( { // Dropdowns for single-value inputs should open below the select box, unless there // is not enough space below, in which case the dropdown should be moved up just // enough so it fits in the window, but never so much that it reaches above the top. positionDropdown: function(el, selectEl) { var rect = selectEl.getBoundingClientRect(); var dropdownTop = rect.bottom; var deltaUp = Math.min( Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0), rect.top + rect.height ); assign(el.style, { left: rect.left + 'px', top: dropdownTop - deltaUp + 'px', width: rect.width + 'px' }); } }, options ) ); this.rerender(); if (options.showSearchInputInDropdown === false) { this.initInput(this.$('.selectivity-single-select-input'), { search: false }); } this.events.on({ change: this.rerenderSelection, click: this._clicked, 'click .selectivity-search-input': stopPropagation, 'click .selectivity-single-selected-item-remove': this._itemRemoveClicked, 'focus .selectivity-single-select-input': this._focused, 'selectivity-selected': this._resultSelected }); }
[ "function", "SingleInput", "(", "options", ")", "{", "Selectivity", ".", "call", "(", "this", ",", "assign", "(", "{", "// Dropdowns for single-value inputs should open below the select box, unless there", "// is not enough space below, in which case the dropdown should be moved up just", "// enough so it fits in the window, but never so much that it reaches above the top.", "positionDropdown", ":", "function", "(", "el", ",", "selectEl", ")", "{", "var", "rect", "=", "selectEl", ".", "getBoundingClientRect", "(", ")", ";", "var", "dropdownTop", "=", "rect", ".", "bottom", ";", "var", "deltaUp", "=", "Math", ".", "min", "(", "Math", ".", "max", "(", "dropdownTop", "+", "el", ".", "clientHeight", "-", "window", ".", "innerHeight", ",", "0", ")", ",", "rect", ".", "top", "+", "rect", ".", "height", ")", ";", "assign", "(", "el", ".", "style", ",", "{", "left", ":", "rect", ".", "left", "+", "'px'", ",", "top", ":", "dropdownTop", "-", "deltaUp", "+", "'px'", ",", "width", ":", "rect", ".", "width", "+", "'px'", "}", ")", ";", "}", "}", ",", "options", ")", ")", ";", "this", ".", "rerender", "(", ")", ";", "if", "(", "options", ".", "showSearchInputInDropdown", "===", "false", ")", "{", "this", ".", "initInput", "(", "this", ".", "$", "(", "'.selectivity-single-select-input'", ")", ",", "{", "search", ":", "false", "}", ")", ";", "}", "this", ".", "events", ".", "on", "(", "{", "change", ":", "this", ".", "rerenderSelection", ",", "click", ":", "this", ".", "_clicked", ",", "'click .selectivity-search-input'", ":", "stopPropagation", ",", "'click .selectivity-single-selected-item-remove'", ":", "this", ".", "_itemRemoveClicked", ",", "'focus .selectivity-single-select-input'", ":", "this", ".", "_focused", ",", "'selectivity-selected'", ":", "this", ".", "_resultSelected", "}", ")", ";", "}" ]
SingleInput Constructor.
[ "SingleInput", "Constructor", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/inputs/single.js#L11-L53
16,026
arendjr/selectivity
src/inputs/single.js
function(el, selectEl) { var rect = selectEl.getBoundingClientRect(); var dropdownTop = rect.bottom; var deltaUp = Math.min( Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0), rect.top + rect.height ); assign(el.style, { left: rect.left + 'px', top: dropdownTop - deltaUp + 'px', width: rect.width + 'px' }); }
javascript
function(el, selectEl) { var rect = selectEl.getBoundingClientRect(); var dropdownTop = rect.bottom; var deltaUp = Math.min( Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0), rect.top + rect.height ); assign(el.style, { left: rect.left + 'px', top: dropdownTop - deltaUp + 'px', width: rect.width + 'px' }); }
[ "function", "(", "el", ",", "selectEl", ")", "{", "var", "rect", "=", "selectEl", ".", "getBoundingClientRect", "(", ")", ";", "var", "dropdownTop", "=", "rect", ".", "bottom", ";", "var", "deltaUp", "=", "Math", ".", "min", "(", "Math", ".", "max", "(", "dropdownTop", "+", "el", ".", "clientHeight", "-", "window", ".", "innerHeight", ",", "0", ")", ",", "rect", ".", "top", "+", "rect", ".", "height", ")", ";", "assign", "(", "el", ".", "style", ",", "{", "left", ":", "rect", ".", "left", "+", "'px'", ",", "top", ":", "dropdownTop", "-", "deltaUp", "+", "'px'", ",", "width", ":", "rect", ".", "width", "+", "'px'", "}", ")", ";", "}" ]
Dropdowns for single-value inputs should open below the select box, unless there is not enough space below, in which case the dropdown should be moved up just enough so it fits in the window, but never so much that it reaches above the top.
[ "Dropdowns", "for", "single", "-", "value", "inputs", "should", "open", "below", "the", "select", "box", "unless", "there", "is", "not", "enough", "space", "below", "in", "which", "case", "the", "dropdown", "should", "be", "moved", "up", "just", "enough", "so", "it", "fits", "in", "the", "window", "but", "never", "so", "much", "that", "it", "reaches", "above", "the", "top", "." ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/inputs/single.js#L19-L33
16,027
arendjr/selectivity
src/apis/jquery.js
patchEvents
function patchEvents($el) { $.each(EVENT_PROPERTIES, function(eventName, properties) { $el.on(eventName, function(event) { if (event.originalEvent) { properties.forEach(function(propertyName) { event[propertyName] = event.originalEvent[propertyName]; }); } }); }); }
javascript
function patchEvents($el) { $.each(EVENT_PROPERTIES, function(eventName, properties) { $el.on(eventName, function(event) { if (event.originalEvent) { properties.forEach(function(propertyName) { event[propertyName] = event.originalEvent[propertyName]; }); } }); }); }
[ "function", "patchEvents", "(", "$el", ")", "{", "$", ".", "each", "(", "EVENT_PROPERTIES", ",", "function", "(", "eventName", ",", "properties", ")", "{", "$el", ".", "on", "(", "eventName", ",", "function", "(", "event", ")", "{", "if", "(", "event", ".", "originalEvent", ")", "{", "properties", ".", "forEach", "(", "function", "(", "propertyName", ")", "{", "event", "[", "propertyName", "]", "=", "event", ".", "originalEvent", "[", "propertyName", "]", ";", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
create event listeners that will copy the custom properties from the native events to the jQuery events, so jQuery users can use them seamlessly
[ "create", "event", "listeners", "that", "will", "copy", "the", "custom", "properties", "from", "the", "native", "events", "to", "the", "jQuery", "events", "so", "jQuery", "users", "can", "use", "them", "seamlessly" ]
00e0657aea491ea41547979b62e8f9fc48f36549
https://github.com/arendjr/selectivity/blob/00e0657aea491ea41547979b62e8f9fc48f36549/src/apis/jquery.js#L18-L28
16,028
pierrec/node-lz4
lib/encoder.js
LZ4_compress
function LZ4_compress (input, options) { var output = [] var encoder = new Encoder(options) encoder.on('data', function (chunk) { output.push(chunk) }) encoder.end(input) return Buffer.concat(output) }
javascript
function LZ4_compress (input, options) { var output = [] var encoder = new Encoder(options) encoder.on('data', function (chunk) { output.push(chunk) }) encoder.end(input) return Buffer.concat(output) }
[ "function", "LZ4_compress", "(", "input", ",", "options", ")", "{", "var", "output", "=", "[", "]", "var", "encoder", "=", "new", "Encoder", "(", "options", ")", "encoder", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "output", ".", "push", "(", "chunk", ")", "}", ")", "encoder", ".", "end", "(", "input", ")", "return", "Buffer", ".", "concat", "(", "output", ")", "}" ]
Encode an LZ4 stream
[ "Encode", "an", "LZ4", "stream" ]
631bedfbd632aba62cfcb8d94b523f001a7fb43c
https://github.com/pierrec/node-lz4/blob/631bedfbd632aba62cfcb8d94b523f001a7fb43c/lib/encoder.js#L6-L17
16,029
pierrec/node-lz4
lib/decoder.js
LZ4_uncompress
function LZ4_uncompress (input, options) { var output = [] var decoder = new Decoder(options) decoder.on('data', function (chunk) { output.push(chunk) }) decoder.end(input) return Buffer.concat(output) }
javascript
function LZ4_uncompress (input, options) { var output = [] var decoder = new Decoder(options) decoder.on('data', function (chunk) { output.push(chunk) }) decoder.end(input) return Buffer.concat(output) }
[ "function", "LZ4_uncompress", "(", "input", ",", "options", ")", "{", "var", "output", "=", "[", "]", "var", "decoder", "=", "new", "Decoder", "(", "options", ")", "decoder", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "output", ".", "push", "(", "chunk", ")", "}", ")", "decoder", ".", "end", "(", "input", ")", "return", "Buffer", ".", "concat", "(", "output", ")", "}" ]
Decode an LZ4 stream
[ "Decode", "an", "LZ4", "stream" ]
631bedfbd632aba62cfcb8d94b523f001a7fb43c
https://github.com/pierrec/node-lz4/blob/631bedfbd632aba62cfcb8d94b523f001a7fb43c/lib/decoder.js#L6-L17
16,030
mapbox/react-colorpickr
src/colorfunc.js
colorCoords
function colorCoords(channel, color) { let x, y, xmax, ymax; switch (channel) { case 'r': xmax = 255; ymax = 255; x = color.b; y = ymax - color.g; break; case 'g': xmax = 255; ymax = 255; x = color.b; y = ymax - color.r; break; case 'b': xmax = 255; ymax = 255; x = color.r; y = ymax - color.g; break; case 'h': xmax = 100; ymax = 100; x = color.s; y = ymax - color.l; break; case 's': xmax = 360; ymax = 100; x = color.h; y = ymax - color.l; break; case 'l': xmax = 360; ymax = 100; x = color.h; y = ymax - color.s; break; } return { xmax, ymax, x, y }; }
javascript
function colorCoords(channel, color) { let x, y, xmax, ymax; switch (channel) { case 'r': xmax = 255; ymax = 255; x = color.b; y = ymax - color.g; break; case 'g': xmax = 255; ymax = 255; x = color.b; y = ymax - color.r; break; case 'b': xmax = 255; ymax = 255; x = color.r; y = ymax - color.g; break; case 'h': xmax = 100; ymax = 100; x = color.s; y = ymax - color.l; break; case 's': xmax = 360; ymax = 100; x = color.h; y = ymax - color.l; break; case 'l': xmax = 360; ymax = 100; x = color.h; y = ymax - color.s; break; } return { xmax, ymax, x, y }; }
[ "function", "colorCoords", "(", "channel", ",", "color", ")", "{", "let", "x", ",", "y", ",", "xmax", ",", "ymax", ";", "switch", "(", "channel", ")", "{", "case", "'r'", ":", "xmax", "=", "255", ";", "ymax", "=", "255", ";", "x", "=", "color", ".", "b", ";", "y", "=", "ymax", "-", "color", ".", "g", ";", "break", ";", "case", "'g'", ":", "xmax", "=", "255", ";", "ymax", "=", "255", ";", "x", "=", "color", ".", "b", ";", "y", "=", "ymax", "-", "color", ".", "r", ";", "break", ";", "case", "'b'", ":", "xmax", "=", "255", ";", "ymax", "=", "255", ";", "x", "=", "color", ".", "r", ";", "y", "=", "ymax", "-", "color", ".", "g", ";", "break", ";", "case", "'h'", ":", "xmax", "=", "100", ";", "ymax", "=", "100", ";", "x", "=", "color", ".", "s", ";", "y", "=", "ymax", "-", "color", ".", "l", ";", "break", ";", "case", "'s'", ":", "xmax", "=", "360", ";", "ymax", "=", "100", ";", "x", "=", "color", ".", "h", ";", "y", "=", "ymax", "-", "color", ".", "l", ";", "break", ";", "case", "'l'", ":", "xmax", "=", "360", ";", "ymax", "=", "100", ";", "x", "=", "color", ".", "h", ";", "y", "=", "ymax", "-", "color", ".", "s", ";", "break", ";", "}", "return", "{", "xmax", ",", "ymax", ",", "x", ",", "y", "}", ";", "}" ]
Determine x y coordinates based on color channel. R: x = b, y = g G: x = b, y = r B: x = r, y = g H: x = s, y = l S: x = h, y = l L: x = h, y = s @param {string} channel one of `r`, `g`, `b`, `h`, `s`, or `l` @param {Object} color a color object of current values associated to key @return {Object} coordinates
[ "Determine", "x", "y", "coordinates", "based", "on", "color", "channel", "." ]
a44b549d30fd4e0826890a6bcfce0093cfcae839
https://github.com/mapbox/react-colorpickr/blob/a44b549d30fd4e0826890a6bcfce0093cfcae839/src/colorfunc.js#L84-L126
16,031
mapbox/react-colorpickr
src/colorfunc.js
colorCoordValue
function colorCoordValue(channel, pos) { const color = {}; pos.x = Math.round(pos.x); pos.y = Math.round(pos.y); switch (channel) { case 'r': color.b = pos.x; color.g = 255 - pos.y; break; case 'g': color.b = pos.x; color.r = 255 - pos.y; break; case 'b': color.r = pos.x; color.g = 255 - pos.y; break; case 'h': color.s = pos.x; color.l = 100 - pos.y; break; case 's': color.h = pos.x; color.l = 100 - pos.y; break; case 'l': color.h = pos.x; color.s = 100 - pos.y; break; } return color; }
javascript
function colorCoordValue(channel, pos) { const color = {}; pos.x = Math.round(pos.x); pos.y = Math.round(pos.y); switch (channel) { case 'r': color.b = pos.x; color.g = 255 - pos.y; break; case 'g': color.b = pos.x; color.r = 255 - pos.y; break; case 'b': color.r = pos.x; color.g = 255 - pos.y; break; case 'h': color.s = pos.x; color.l = 100 - pos.y; break; case 's': color.h = pos.x; color.l = 100 - pos.y; break; case 'l': color.h = pos.x; color.s = 100 - pos.y; break; } return color; }
[ "function", "colorCoordValue", "(", "channel", ",", "pos", ")", "{", "const", "color", "=", "{", "}", ";", "pos", ".", "x", "=", "Math", ".", "round", "(", "pos", ".", "x", ")", ";", "pos", ".", "y", "=", "Math", ".", "round", "(", "pos", ".", "y", ")", ";", "switch", "(", "channel", ")", "{", "case", "'r'", ":", "color", ".", "b", "=", "pos", ".", "x", ";", "color", ".", "g", "=", "255", "-", "pos", ".", "y", ";", "break", ";", "case", "'g'", ":", "color", ".", "b", "=", "pos", ".", "x", ";", "color", ".", "r", "=", "255", "-", "pos", ".", "y", ";", "break", ";", "case", "'b'", ":", "color", ".", "r", "=", "pos", ".", "x", ";", "color", ".", "g", "=", "255", "-", "pos", ".", "y", ";", "break", ";", "case", "'h'", ":", "color", ".", "s", "=", "pos", ".", "x", ";", "color", ".", "l", "=", "100", "-", "pos", ".", "y", ";", "break", ";", "case", "'s'", ":", "color", ".", "h", "=", "pos", ".", "x", ";", "color", ".", "l", "=", "100", "-", "pos", ".", "y", ";", "break", ";", "case", "'l'", ":", "color", ".", "h", "=", "pos", ".", "x", ";", "color", ".", "s", "=", "100", "-", "pos", ".", "y", ";", "break", ";", "}", "return", "color", ";", "}" ]
Takes a channel and returns its sibling values based on x,y positions R: x = b, y = g G: x = b, y = r B: x = r, y = g H: x = s, y = l S: x = h, y = l L: x = h, y = s @param {string} channel one of `r`, `g`, `b`, `h`, `s`, or `l` @param {Object} pos x, y coordinates @return {Object} Changed sibling values
[ "Takes", "a", "channel", "and", "returns", "its", "sibling", "values", "based", "on", "x", "y", "positions" ]
a44b549d30fd4e0826890a6bcfce0093cfcae839
https://github.com/mapbox/react-colorpickr/blob/a44b549d30fd4e0826890a6bcfce0093cfcae839/src/colorfunc.js#L143-L176
16,032
buttercup/buttercup-core
source/node/tools/export.js
function(archive) { return { type: "buttercup-archive", exported: Date.now(), format: archive.getFormat(), groups: archive.getGroups().map(group => group.toObject()) }; }
javascript
function(archive) { return { type: "buttercup-archive", exported: Date.now(), format: archive.getFormat(), groups: archive.getGroups().map(group => group.toObject()) }; }
[ "function", "(", "archive", ")", "{", "return", "{", "type", ":", "\"buttercup-archive\"", ",", "exported", ":", "Date", ".", "now", "(", ")", ",", "format", ":", "archive", ".", "getFormat", "(", ")", ",", "groups", ":", "archive", ".", "getGroups", "(", ")", ".", "map", "(", "group", "=>", "group", ".", "toObject", "(", ")", ")", "}", ";", "}" ]
Export an archive to Buttercup format @param {Archive} archive The archive to export @returns {Object} The exported object
[ "Export", "an", "archive", "to", "Buttercup", "format" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/export.js#L7-L14
16,033
buttercup/buttercup-core
source/node/Workspace.js
stripDestructiveCommands
function stripDestructiveCommands(history) { const destructiveSlugs = Object.keys(Inigo.Command) .map(key => Inigo.Command[key]) .filter(command => command.d) .map(command => command.s); return history.filter(command => { return destructiveSlugs.indexOf(getCommandType(command)) < 0; }); }
javascript
function stripDestructiveCommands(history) { const destructiveSlugs = Object.keys(Inigo.Command) .map(key => Inigo.Command[key]) .filter(command => command.d) .map(command => command.s); return history.filter(command => { return destructiveSlugs.indexOf(getCommandType(command)) < 0; }); }
[ "function", "stripDestructiveCommands", "(", "history", ")", "{", "const", "destructiveSlugs", "=", "Object", ".", "keys", "(", "Inigo", ".", "Command", ")", ".", "map", "(", "key", "=>", "Inigo", ".", "Command", "[", "key", "]", ")", ".", "filter", "(", "command", "=>", "command", ".", "d", ")", ".", "map", "(", "command", "=>", "command", ".", "s", ")", ";", "return", "history", ".", "filter", "(", "command", "=>", "{", "return", "destructiveSlugs", ".", "indexOf", "(", "getCommandType", "(", "command", ")", ")", "<", "0", ";", "}", ")", ";", "}" ]
Strip destructive commands from a history collection @param {Array.<String>} history The history @returns {Array.<String>} The history minus any destructive commands @private @static @memberof Workspace
[ "Strip", "destructive", "commands", "from", "a", "history", "collection" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/Workspace.js#L27-L35
16,034
buttercup/buttercup-core
source/node/archiveManagement/ArchiveSource.js
rehydrate
function rehydrate(dehydratedString) { const { name, id, sourceCredentials, archiveCredentials, type, colour, order } = JSON.parse(dehydratedString); const source = new ArchiveSource(name, sourceCredentials, archiveCredentials, { id, type }); source.type = type; if (colour) { source._colour = colour; } if (order >= 0) { source.order = order; } return source; }
javascript
function rehydrate(dehydratedString) { const { name, id, sourceCredentials, archiveCredentials, type, colour, order } = JSON.parse(dehydratedString); const source = new ArchiveSource(name, sourceCredentials, archiveCredentials, { id, type }); source.type = type; if (colour) { source._colour = colour; } if (order >= 0) { source.order = order; } return source; }
[ "function", "rehydrate", "(", "dehydratedString", ")", "{", "const", "{", "name", ",", "id", ",", "sourceCredentials", ",", "archiveCredentials", ",", "type", ",", "colour", ",", "order", "}", "=", "JSON", ".", "parse", "(", "dehydratedString", ")", ";", "const", "source", "=", "new", "ArchiveSource", "(", "name", ",", "sourceCredentials", ",", "archiveCredentials", ",", "{", "id", ",", "type", "}", ")", ";", "source", ".", "type", "=", "type", ";", "if", "(", "colour", ")", "{", "source", ".", "_colour", "=", "colour", ";", "}", "if", "(", "order", ">=", "0", ")", "{", "source", ".", "order", "=", "order", ";", "}", "return", "source", ";", "}" ]
Rehydrate a dehydrated archive source @param {String} dehydratedString A dehydrated archive source @returns {ArchiveSource} The rehydrated source @memberof ArchiveSource @static
[ "Rehydrate", "a", "dehydrated", "archive", "source" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/archiveManagement/ArchiveSource.js#L32-L43
16,035
buttercup/buttercup-core
source/node/tools/compare.js
dedupe
function dedupe(arr) { return arr.filter(function(item, pos) { return arr.indexOf(item) === pos; }); }
javascript
function dedupe(arr) { return arr.filter(function(item, pos) { return arr.indexOf(item) === pos; }); }
[ "function", "dedupe", "(", "arr", ")", "{", "return", "arr", ".", "filter", "(", "function", "(", "item", ",", "pos", ")", "{", "return", "arr", ".", "indexOf", "(", "item", ")", "===", "pos", ";", "}", ")", ";", "}" ]
De-dupe an array @param {Array} arr The array @returns {Array} The de-duped array
[ "De", "-", "dupe", "an", "array" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/compare.js#L8-L12
16,036
buttercup/buttercup-core
source/node/EntryFinder.js
flattenEntries
function flattenEntries(archives) { return archives.reduce(function _reduceArchiveEntries(items, archive) { return [ ...items, ...getAllEntries(archive.getGroups()).map(function _expandEntry(entry) { return { entry, archive }; }) ]; }, []); }
javascript
function flattenEntries(archives) { return archives.reduce(function _reduceArchiveEntries(items, archive) { return [ ...items, ...getAllEntries(archive.getGroups()).map(function _expandEntry(entry) { return { entry, archive }; }) ]; }, []); }
[ "function", "flattenEntries", "(", "archives", ")", "{", "return", "archives", ".", "reduce", "(", "function", "_reduceArchiveEntries", "(", "items", ",", "archive", ")", "{", "return", "[", "...", "items", ",", "...", "getAllEntries", "(", "archive", ".", "getGroups", "(", ")", ")", ".", "map", "(", "function", "_expandEntry", "(", "entry", ")", "{", "return", "{", "entry", ",", "archive", "}", ";", "}", ")", "]", ";", "}", ",", "[", "]", ")", ";", "}" ]
Flatten entries into a searchable structure @param {Array.<Archive>} archives An array of archives @returns {Array.<EntrySearchInfo>} An array of searchable objects
[ "Flatten", "entries", "into", "a", "searchable", "structure" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/EntryFinder.js#L9-L21
16,037
buttercup/buttercup-core
source/node/tools/sharing.js
function(movingGroup, target) { let targetArchive, groupDesc; if (target.type === "Archive") { // destination is an archive targetArchive = target; groupDesc = describe(movingGroup._getRemoteObject(), "0"); } else if (target.type === "Group") { // destination is a group targetArchive = target._getArchive(); groupDesc = describe(movingGroup._getRemoteObject(), target.getID()); } else { throw new Error(`Unknown remote type: ${target.type}`); } // execute each command in the destination archive groupDesc.forEach(function(command) { targetArchive ._getWestley() .execute(command) .pad(); }); // delete movingGroup.delete(/* skip trash */ true); }
javascript
function(movingGroup, target) { let targetArchive, groupDesc; if (target.type === "Archive") { // destination is an archive targetArchive = target; groupDesc = describe(movingGroup._getRemoteObject(), "0"); } else if (target.type === "Group") { // destination is a group targetArchive = target._getArchive(); groupDesc = describe(movingGroup._getRemoteObject(), target.getID()); } else { throw new Error(`Unknown remote type: ${target.type}`); } // execute each command in the destination archive groupDesc.forEach(function(command) { targetArchive ._getWestley() .execute(command) .pad(); }); // delete movingGroup.delete(/* skip trash */ true); }
[ "function", "(", "movingGroup", ",", "target", ")", "{", "let", "targetArchive", ",", "groupDesc", ";", "if", "(", "target", ".", "type", "===", "\"Archive\"", ")", "{", "// destination is an archive", "targetArchive", "=", "target", ";", "groupDesc", "=", "describe", "(", "movingGroup", ".", "_getRemoteObject", "(", ")", ",", "\"0\"", ")", ";", "}", "else", "if", "(", "target", ".", "type", "===", "\"Group\"", ")", "{", "// destination is a group", "targetArchive", "=", "target", ".", "_getArchive", "(", ")", ";", "groupDesc", "=", "describe", "(", "movingGroup", ".", "_getRemoteObject", "(", ")", ",", "target", ".", "getID", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "`", "${", "target", ".", "type", "}", "`", ")", ";", "}", "// execute each command in the destination archive", "groupDesc", ".", "forEach", "(", "function", "(", "command", ")", "{", "targetArchive", ".", "_getWestley", "(", ")", ".", "execute", "(", "command", ")", ".", "pad", "(", ")", ";", "}", ")", ";", "// delete", "movingGroup", ".", "delete", "(", "/* skip trash */", "true", ")", ";", "}" ]
Move a group between archives @param {Group} movingGroup The group to move @param {Group|Archive} target The group to move to @throws {Error} Throws if the remote type is not recognised
[ "Move", "a", "group", "between", "archives" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/sharing.js#L10-L32
16,038
buttercup/buttercup-core
source/web/HashingTools.js
deriveKeyFromPassword
function deriveKeyFromPassword(password, salt, rounds, bits) { checkBrowserSupport(); const subtleCrypto = window.crypto.subtle; let params = { name: "PBKDF2", hash: "SHA-256", salt: stringToArrayBuffer(salt), iterations: rounds }, bytes = bits / 8, keysLen = bytes / 2; return subtleCrypto .importKey( "raw", stringToArrayBuffer(password), { name: "PBKDF2" }, false, // not extractable ["deriveBits"] ) .then(keyData => subtleCrypto.deriveBits(params, keyData, bits)) .then(derivedData => Promise.all([ subtleCrypto.importKey("raw", derivedData.slice(0, keysLen), "AES-CBC", true, ["encrypt", "decrypt"]), subtleCrypto.importKey("raw", derivedData.slice(keysLen, keysLen * 2), "AES-CBC", true, [ "encrypt", "decrypt" ]) ]) ) .then(aesKeys => Promise.all([subtleCrypto.exportKey("raw", aesKeys[0]), subtleCrypto.exportKey("raw", aesKeys[1])]) ) .then(rawKeys => joinBuffers(rawKeys[0], rawKeys[1])) .then(arrBuff => addHexSupportToArrayBuffer(arrBuff)); // HAXOR }
javascript
function deriveKeyFromPassword(password, salt, rounds, bits) { checkBrowserSupport(); const subtleCrypto = window.crypto.subtle; let params = { name: "PBKDF2", hash: "SHA-256", salt: stringToArrayBuffer(salt), iterations: rounds }, bytes = bits / 8, keysLen = bytes / 2; return subtleCrypto .importKey( "raw", stringToArrayBuffer(password), { name: "PBKDF2" }, false, // not extractable ["deriveBits"] ) .then(keyData => subtleCrypto.deriveBits(params, keyData, bits)) .then(derivedData => Promise.all([ subtleCrypto.importKey("raw", derivedData.slice(0, keysLen), "AES-CBC", true, ["encrypt", "decrypt"]), subtleCrypto.importKey("raw", derivedData.slice(keysLen, keysLen * 2), "AES-CBC", true, [ "encrypt", "decrypt" ]) ]) ) .then(aesKeys => Promise.all([subtleCrypto.exportKey("raw", aesKeys[0]), subtleCrypto.exportKey("raw", aesKeys[1])]) ) .then(rawKeys => joinBuffers(rawKeys[0], rawKeys[1])) .then(arrBuff => addHexSupportToArrayBuffer(arrBuff)); // HAXOR }
[ "function", "deriveKeyFromPassword", "(", "password", ",", "salt", ",", "rounds", ",", "bits", ")", "{", "checkBrowserSupport", "(", ")", ";", "const", "subtleCrypto", "=", "window", ".", "crypto", ".", "subtle", ";", "let", "params", "=", "{", "name", ":", "\"PBKDF2\"", ",", "hash", ":", "\"SHA-256\"", ",", "salt", ":", "stringToArrayBuffer", "(", "salt", ")", ",", "iterations", ":", "rounds", "}", ",", "bytes", "=", "bits", "/", "8", ",", "keysLen", "=", "bytes", "/", "2", ";", "return", "subtleCrypto", ".", "importKey", "(", "\"raw\"", ",", "stringToArrayBuffer", "(", "password", ")", ",", "{", "name", ":", "\"PBKDF2\"", "}", ",", "false", ",", "// not extractable", "[", "\"deriveBits\"", "]", ")", ".", "then", "(", "keyData", "=>", "subtleCrypto", ".", "deriveBits", "(", "params", ",", "keyData", ",", "bits", ")", ")", ".", "then", "(", "derivedData", "=>", "Promise", ".", "all", "(", "[", "subtleCrypto", ".", "importKey", "(", "\"raw\"", ",", "derivedData", ".", "slice", "(", "0", ",", "keysLen", ")", ",", "\"AES-CBC\"", ",", "true", ",", "[", "\"encrypt\"", ",", "\"decrypt\"", "]", ")", ",", "subtleCrypto", ".", "importKey", "(", "\"raw\"", ",", "derivedData", ".", "slice", "(", "keysLen", ",", "keysLen", "*", "2", ")", ",", "\"AES-CBC\"", ",", "true", ",", "[", "\"encrypt\"", ",", "\"decrypt\"", "]", ")", "]", ")", ")", ".", "then", "(", "aesKeys", "=>", "Promise", ".", "all", "(", "[", "subtleCrypto", ".", "exportKey", "(", "\"raw\"", ",", "aesKeys", "[", "0", "]", ")", ",", "subtleCrypto", ".", "exportKey", "(", "\"raw\"", ",", "aesKeys", "[", "1", "]", ")", "]", ")", ")", ".", "then", "(", "rawKeys", "=>", "joinBuffers", "(", "rawKeys", "[", "0", "]", ",", "rawKeys", "[", "1", "]", ")", ")", ".", "then", "(", "arrBuff", "=>", "addHexSupportToArrayBuffer", "(", "arrBuff", ")", ")", ";", "// HAXOR", "}" ]
Derive a key from a password @param {String} password The password @param {String} salt The salt @param {Number} rounds The number of derivation rounds @param {Number} bits The number of bits for the key @see checkBrowserSupport @returns {Promise.<ArrayBuffer>} A promise that resolves with an ArrayBuffer
[ "Derive", "a", "key", "from", "a", "password" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/web/HashingTools.js#L42-L76
16,039
buttercup/buttercup-core
source/node/archiveManagement/marshalling.js
credentialsToDatasource
function credentialsToDatasource(sourceCredentials) { return Promise.resolve() .then(function() { const datasourceDescriptionRaw = sourceCredentials.getValueOrFail("datasource"); const datasourceDescription = typeof datasourceDescriptionRaw === "string" ? JSON.parse(datasourceDescriptionRaw) : datasourceDescriptionRaw; if (typeof datasourceDescription.type !== "string") { throw new VError("Invalid or missing type"); } const datasource = objectToDatasource(datasourceDescription, sourceCredentials); return { datasource, credentials: sourceCredentials }; }) .catch(function __handleCreationError(err) { throw new VError(err, "Failed creating datasources"); }); }
javascript
function credentialsToDatasource(sourceCredentials) { return Promise.resolve() .then(function() { const datasourceDescriptionRaw = sourceCredentials.getValueOrFail("datasource"); const datasourceDescription = typeof datasourceDescriptionRaw === "string" ? JSON.parse(datasourceDescriptionRaw) : datasourceDescriptionRaw; if (typeof datasourceDescription.type !== "string") { throw new VError("Invalid or missing type"); } const datasource = objectToDatasource(datasourceDescription, sourceCredentials); return { datasource, credentials: sourceCredentials }; }) .catch(function __handleCreationError(err) { throw new VError(err, "Failed creating datasources"); }); }
[ "function", "credentialsToDatasource", "(", "sourceCredentials", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "(", ")", "{", "const", "datasourceDescriptionRaw", "=", "sourceCredentials", ".", "getValueOrFail", "(", "\"datasource\"", ")", ";", "const", "datasourceDescription", "=", "typeof", "datasourceDescriptionRaw", "===", "\"string\"", "?", "JSON", ".", "parse", "(", "datasourceDescriptionRaw", ")", ":", "datasourceDescriptionRaw", ";", "if", "(", "typeof", "datasourceDescription", ".", "type", "!==", "\"string\"", ")", "{", "throw", "new", "VError", "(", "\"Invalid or missing type\"", ")", ";", "}", "const", "datasource", "=", "objectToDatasource", "(", "datasourceDescription", ",", "sourceCredentials", ")", ";", "return", "{", "datasource", ",", "credentials", ":", "sourceCredentials", "}", ";", "}", ")", ".", "catch", "(", "function", "__handleCreationError", "(", "err", ")", "{", "throw", "new", "VError", "(", "err", ",", "\"Failed creating datasources\"", ")", ";", "}", ")", ";", "}" ]
Convert credentials of a remote archive to a datasource @param {Credentials} sourceCredentials The remote credentials. The credentials must have a type field and datasource information field @returns {Promise.<{datasource, credentials}>} A promise that resolves with the datasource and source credentials
[ "Convert", "credentials", "of", "a", "remote", "archive", "to", "a", "datasource" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/archiveManagement/marshalling.js#L14-L34
16,040
buttercup/buttercup-core
source/node/archiveManagement/marshalling.js
credentialsToSource
function credentialsToSource(sourceCredentials, archiveCredentials, initialise = false, contentOverride = null) { let updated = false; const onUpdate = () => { updated = true; }; return credentialsToDatasource(sourceCredentials) .then(function __handleInitialisation(result) { const datasource = result.datasource; const defaultArchive = Archive.createWithDefaults(); if (typeof contentOverride === "string") { datasource.setContent(contentOverride); } datasource.once("updated", onUpdate); return initialise ? datasource.save(defaultArchive.getHistory(), archiveCredentials).then(() => Object.assign( { archive: defaultArchive }, result ) ) : datasource .load(archiveCredentials) .then(history => Archive.createFromHistory(history)) .then(archive => Object.assign( { archive }, result ) ); }) .then(function __datasourceToSource(result) { const workspace = new Workspace(); if (typeof contentOverride === "string") { // Content is overridden, so it cannot be modified: // Setting to readOnly is a safety measure const westley = result.archive._getWestley(); westley.readOnly = true; } result.datasource.removeListener("updated", onUpdate); workspace.setArchive(result.archive, result.datasource, archiveCredentials); return { workspace, sourceCredentials, archiveCredentials, updated }; }); }
javascript
function credentialsToSource(sourceCredentials, archiveCredentials, initialise = false, contentOverride = null) { let updated = false; const onUpdate = () => { updated = true; }; return credentialsToDatasource(sourceCredentials) .then(function __handleInitialisation(result) { const datasource = result.datasource; const defaultArchive = Archive.createWithDefaults(); if (typeof contentOverride === "string") { datasource.setContent(contentOverride); } datasource.once("updated", onUpdate); return initialise ? datasource.save(defaultArchive.getHistory(), archiveCredentials).then(() => Object.assign( { archive: defaultArchive }, result ) ) : datasource .load(archiveCredentials) .then(history => Archive.createFromHistory(history)) .then(archive => Object.assign( { archive }, result ) ); }) .then(function __datasourceToSource(result) { const workspace = new Workspace(); if (typeof contentOverride === "string") { // Content is overridden, so it cannot be modified: // Setting to readOnly is a safety measure const westley = result.archive._getWestley(); westley.readOnly = true; } result.datasource.removeListener("updated", onUpdate); workspace.setArchive(result.archive, result.datasource, archiveCredentials); return { workspace, sourceCredentials, archiveCredentials, updated }; }); }
[ "function", "credentialsToSource", "(", "sourceCredentials", ",", "archiveCredentials", ",", "initialise", "=", "false", ",", "contentOverride", "=", "null", ")", "{", "let", "updated", "=", "false", ";", "const", "onUpdate", "=", "(", ")", "=>", "{", "updated", "=", "true", ";", "}", ";", "return", "credentialsToDatasource", "(", "sourceCredentials", ")", ".", "then", "(", "function", "__handleInitialisation", "(", "result", ")", "{", "const", "datasource", "=", "result", ".", "datasource", ";", "const", "defaultArchive", "=", "Archive", ".", "createWithDefaults", "(", ")", ";", "if", "(", "typeof", "contentOverride", "===", "\"string\"", ")", "{", "datasource", ".", "setContent", "(", "contentOverride", ")", ";", "}", "datasource", ".", "once", "(", "\"updated\"", ",", "onUpdate", ")", ";", "return", "initialise", "?", "datasource", ".", "save", "(", "defaultArchive", ".", "getHistory", "(", ")", ",", "archiveCredentials", ")", ".", "then", "(", "(", ")", "=>", "Object", ".", "assign", "(", "{", "archive", ":", "defaultArchive", "}", ",", "result", ")", ")", ":", "datasource", ".", "load", "(", "archiveCredentials", ")", ".", "then", "(", "history", "=>", "Archive", ".", "createFromHistory", "(", "history", ")", ")", ".", "then", "(", "archive", "=>", "Object", ".", "assign", "(", "{", "archive", "}", ",", "result", ")", ")", ";", "}", ")", ".", "then", "(", "function", "__datasourceToSource", "(", "result", ")", "{", "const", "workspace", "=", "new", "Workspace", "(", ")", ";", "if", "(", "typeof", "contentOverride", "===", "\"string\"", ")", "{", "// Content is overridden, so it cannot be modified:", "// Setting to readOnly is a safety measure", "const", "westley", "=", "result", ".", "archive", ".", "_getWestley", "(", ")", ";", "westley", ".", "readOnly", "=", "true", ";", "}", "result", ".", "datasource", ".", "removeListener", "(", "\"updated\"", ",", "onUpdate", ")", ";", "workspace", ".", "setArchive", "(", "result", ".", "archive", ",", "result", ".", "datasource", ",", "archiveCredentials", ")", ";", "return", "{", "workspace", ",", "sourceCredentials", ",", "archiveCredentials", ",", "updated", "}", ";", "}", ")", ";", "}" ]
Convert credentials to a source for the ArchiveManager @param {Credentials} sourceCredentials The remote archive credentials @param {Credentials} archiveCredentials Credentials for unlocking the archive @param {Boolean=} initialise Whether or not to initialise a new archive (defaults to false) @param {String=} contentOverride Content for overriding the fetch operation in the datasource, for loading offline content @returns {Promise.<Object>} A promise that resolves with an object containing a workspace, the source credentials and archive credentials
[ "Convert", "credentials", "to", "a", "source", "for", "the", "ArchiveManager" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/archiveManagement/marshalling.js#L46-L97
16,041
buttercup/buttercup-core
source/node/entryFacade.js
applyFieldDescriptor
function applyFieldDescriptor(entry, descriptor) { setEntryValue(entry, descriptor.field, descriptor.property, descriptor.value); }
javascript
function applyFieldDescriptor(entry, descriptor) { setEntryValue(entry, descriptor.field, descriptor.property, descriptor.value); }
[ "function", "applyFieldDescriptor", "(", "entry", ",", "descriptor", ")", "{", "setEntryValue", "(", "entry", ",", "descriptor", ".", "field", ",", "descriptor", ".", "property", ",", "descriptor", ".", "value", ")", ";", "}" ]
Entry facade for data input @typedef {Object} EntryFacade @property {String} type - The type of the facade @property {Array.<EntryFacadeField>} fields - An array of fields Apply a facade field descriptor to an entry Takes data from the descriptor and writes it to the entry. @param {Entry} entry The entry to apply to @param {EntryFacadeField} descriptor The descriptor object
[ "Entry", "facade", "for", "data", "input" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/entryFacade.js#L46-L48
16,042
buttercup/buttercup-core
source/node/entryFacade.js
consumeEntryFacade
function consumeEntryFacade(entry, facade) { const facadeType = getEntryFacadeType(entry); if (facade && facade.type) { const properties = entry.getProperty(); const attributes = entry.getAttribute(); if (facade.type !== facadeType) { throw new Error(`Failed consuming entry data: Expected type "${facadeType}" but received "${facade.type}"`); } // update data (facade.fields || []).forEach(field => applyFieldDescriptor(entry, field)); // remove missing properties Object.keys(properties).forEach(propKey => { const correspondingField = facade.fields.find( ({ field, property }) => field === "property" && property === propKey ); if (typeof correspondingField === "undefined") { entry.deleteProperty(propKey); } }); // remove missing attributes Object.keys(attributes).forEach(attrKey => { const correspondingField = facade.fields.find( ({ field, property }) => field === "attribute" && property === attrKey ); if (typeof correspondingField === "undefined") { entry.deleteAttribute(attrKey); } }); } else { throw new Error("Failed consuming entry data: Invalid item passed as a facade"); } }
javascript
function consumeEntryFacade(entry, facade) { const facadeType = getEntryFacadeType(entry); if (facade && facade.type) { const properties = entry.getProperty(); const attributes = entry.getAttribute(); if (facade.type !== facadeType) { throw new Error(`Failed consuming entry data: Expected type "${facadeType}" but received "${facade.type}"`); } // update data (facade.fields || []).forEach(field => applyFieldDescriptor(entry, field)); // remove missing properties Object.keys(properties).forEach(propKey => { const correspondingField = facade.fields.find( ({ field, property }) => field === "property" && property === propKey ); if (typeof correspondingField === "undefined") { entry.deleteProperty(propKey); } }); // remove missing attributes Object.keys(attributes).forEach(attrKey => { const correspondingField = facade.fields.find( ({ field, property }) => field === "attribute" && property === attrKey ); if (typeof correspondingField === "undefined") { entry.deleteAttribute(attrKey); } }); } else { throw new Error("Failed consuming entry data: Invalid item passed as a facade"); } }
[ "function", "consumeEntryFacade", "(", "entry", ",", "facade", ")", "{", "const", "facadeType", "=", "getEntryFacadeType", "(", "entry", ")", ";", "if", "(", "facade", "&&", "facade", ".", "type", ")", "{", "const", "properties", "=", "entry", ".", "getProperty", "(", ")", ";", "const", "attributes", "=", "entry", ".", "getAttribute", "(", ")", ";", "if", "(", "facade", ".", "type", "!==", "facadeType", ")", "{", "throw", "new", "Error", "(", "`", "${", "facadeType", "}", "${", "facade", ".", "type", "}", "`", ")", ";", "}", "// update data", "(", "facade", ".", "fields", "||", "[", "]", ")", ".", "forEach", "(", "field", "=>", "applyFieldDescriptor", "(", "entry", ",", "field", ")", ")", ";", "// remove missing properties", "Object", ".", "keys", "(", "properties", ")", ".", "forEach", "(", "propKey", "=>", "{", "const", "correspondingField", "=", "facade", ".", "fields", ".", "find", "(", "(", "{", "field", ",", "property", "}", ")", "=>", "field", "===", "\"property\"", "&&", "property", "===", "propKey", ")", ";", "if", "(", "typeof", "correspondingField", "===", "\"undefined\"", ")", "{", "entry", ".", "deleteProperty", "(", "propKey", ")", ";", "}", "}", ")", ";", "// remove missing attributes", "Object", ".", "keys", "(", "attributes", ")", ".", "forEach", "(", "attrKey", "=>", "{", "const", "correspondingField", "=", "facade", ".", "fields", ".", "find", "(", "(", "{", "field", ",", "property", "}", ")", "=>", "field", "===", "\"attribute\"", "&&", "property", "===", "attrKey", ")", ";", "if", "(", "typeof", "correspondingField", "===", "\"undefined\"", ")", "{", "entry", ".", "deleteAttribute", "(", "attrKey", ")", ";", "}", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Failed consuming entry data: Invalid item passed as a facade\"", ")", ";", "}", "}" ]
Process a modified entry facade @param {Entry} entry The entry to apply processed data on @param {EntryFacade} facade The facade object
[ "Process", "a", "modified", "entry", "facade" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/entryFacade.js#L55-L86
16,043
buttercup/buttercup-core
source/node/entryFacade.js
setEntryValue
function setEntryValue(entry, property, name, value) { switch (property) { case "property": return entry.setProperty(name, value); case "attribute": return entry.setAttribute(name, value); default: throw new Error(`Cannot set value: Unknown property type: ${property}`); } }
javascript
function setEntryValue(entry, property, name, value) { switch (property) { case "property": return entry.setProperty(name, value); case "attribute": return entry.setAttribute(name, value); default: throw new Error(`Cannot set value: Unknown property type: ${property}`); } }
[ "function", "setEntryValue", "(", "entry", ",", "property", ",", "name", ",", "value", ")", "{", "switch", "(", "property", ")", "{", "case", "\"property\"", ":", "return", "entry", ".", "setProperty", "(", "name", ",", "value", ")", ";", "case", "\"attribute\"", ":", "return", "entry", ".", "setAttribute", "(", "name", ",", "value", ")", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "property", "}", "`", ")", ";", "}", "}" ]
Set a value on an entry @param {Entry} entry The entry instance @param {String} property Type of property ("property"/"meta"/"attribute") @param {String} name The property name @param {String} value The value to set @throws {Error} Throws if the property type is not recognised
[ "Set", "a", "value", "on", "an", "entry" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/entryFacade.js#L126-L135
16,044
buttercup/buttercup-core
source/node/tools/command.js
function(command) { var patt = /("[^"]*")/, quotedStringPlaceholder = "__QUOTEDSTR__", escapedQuotePlaceholder = "__ESCAPED_QUOTE__", matches = [], match; command = command.replace(/\\\"/g, escapedQuotePlaceholder); while ((match = patt.exec(command))) { var matched = match[0]; command = command.substr(0, match.index) + quotedStringPlaceholder + command.substr(match.index + matched.length); matches.push(matched.substring(1, matched.length - 1)); } var parts = command.split(" "); parts = parts.map(function(part) { var item = part.trim(); if (item === quotedStringPlaceholder) { item = matches.shift(); } item = item.replace(new RegExp(escapedQuotePlaceholder, "g"), '"'); return item; }); return parts; }
javascript
function(command) { var patt = /("[^"]*")/, quotedStringPlaceholder = "__QUOTEDSTR__", escapedQuotePlaceholder = "__ESCAPED_QUOTE__", matches = [], match; command = command.replace(/\\\"/g, escapedQuotePlaceholder); while ((match = patt.exec(command))) { var matched = match[0]; command = command.substr(0, match.index) + quotedStringPlaceholder + command.substr(match.index + matched.length); matches.push(matched.substring(1, matched.length - 1)); } var parts = command.split(" "); parts = parts.map(function(part) { var item = part.trim(); if (item === quotedStringPlaceholder) { item = matches.shift(); } item = item.replace(new RegExp(escapedQuotePlaceholder, "g"), '"'); return item; }); return parts; }
[ "function", "(", "command", ")", "{", "var", "patt", "=", "/", "(\"[^\"]*\")", "/", ",", "quotedStringPlaceholder", "=", "\"__QUOTEDSTR__\"", ",", "escapedQuotePlaceholder", "=", "\"__ESCAPED_QUOTE__\"", ",", "matches", "=", "[", "]", ",", "match", ";", "command", "=", "command", ".", "replace", "(", "/", "\\\\\\\"", "/", "g", ",", "escapedQuotePlaceholder", ")", ";", "while", "(", "(", "match", "=", "patt", ".", "exec", "(", "command", ")", ")", ")", "{", "var", "matched", "=", "match", "[", "0", "]", ";", "command", "=", "command", ".", "substr", "(", "0", ",", "match", ".", "index", ")", "+", "quotedStringPlaceholder", "+", "command", ".", "substr", "(", "match", ".", "index", "+", "matched", ".", "length", ")", ";", "matches", ".", "push", "(", "matched", ".", "substring", "(", "1", ",", "matched", ".", "length", "-", "1", ")", ")", ";", "}", "var", "parts", "=", "command", ".", "split", "(", "\" \"", ")", ";", "parts", "=", "parts", ".", "map", "(", "function", "(", "part", ")", "{", "var", "item", "=", "part", ".", "trim", "(", ")", ";", "if", "(", "item", "===", "quotedStringPlaceholder", ")", "{", "item", "=", "matches", ".", "shift", "(", ")", ";", "}", "item", "=", "item", ".", "replace", "(", "new", "RegExp", "(", "escapedQuotePlaceholder", ",", "\"g\"", ")", ",", "'\"'", ")", ";", "return", "item", ";", "}", ")", ";", "return", "parts", ";", "}" ]
Extract command components from a string @param {String} command The command to extract from @returns {String[]} The separated parts
[ "Extract", "command", "components", "from", "a", "string" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/command.js#L11-L38
16,045
buttercup/buttercup-core
source/node/tools/searching-instance.js
findEntriesByCheck
function findEntriesByCheck(groups, compareFn) { var foundEntries = [], newEntries; groups.forEach(function(group) { newEntries = group.getEntries().filter(compareFn); if (newEntries.length > 0) { foundEntries = foundEntries.concat(newEntries); } newEntries = findEntriesByCheck(group.getGroups(), compareFn); if (newEntries.length > 0) { foundEntries = foundEntries.concat(newEntries); } }); return foundEntries; }
javascript
function findEntriesByCheck(groups, compareFn) { var foundEntries = [], newEntries; groups.forEach(function(group) { newEntries = group.getEntries().filter(compareFn); if (newEntries.length > 0) { foundEntries = foundEntries.concat(newEntries); } newEntries = findEntriesByCheck(group.getGroups(), compareFn); if (newEntries.length > 0) { foundEntries = foundEntries.concat(newEntries); } }); return foundEntries; }
[ "function", "findEntriesByCheck", "(", "groups", ",", "compareFn", ")", "{", "var", "foundEntries", "=", "[", "]", ",", "newEntries", ";", "groups", ".", "forEach", "(", "function", "(", "group", ")", "{", "newEntries", "=", "group", ".", "getEntries", "(", ")", ".", "filter", "(", "compareFn", ")", ";", "if", "(", "newEntries", ".", "length", ">", "0", ")", "{", "foundEntries", "=", "foundEntries", ".", "concat", "(", "newEntries", ")", ";", "}", "newEntries", "=", "findEntriesByCheck", "(", "group", ".", "getGroups", "(", ")", ",", "compareFn", ")", ";", "if", "(", "newEntries", ".", "length", ">", "0", ")", "{", "foundEntries", "=", "foundEntries", ".", "concat", "(", "newEntries", ")", ";", "}", "}", ")", ";", "return", "foundEntries", ";", "}" ]
Find entry instances by filtering with a compare function @param {Array.<Group>} groups The groups to check in @param {Function} compareFn The callback comparison function, return true to keep and false to strip @returns {Array.<Entry>} An array of found entries
[ "Find", "entry", "instances", "by", "filtering", "with", "a", "compare", "function" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/searching-instance.js#L8-L22
16,046
buttercup/buttercup-core
source/node/tools/searching-instance.js
findGroupsByCheck
function findGroupsByCheck(groups, compareFn) { var foundGroups = groups.filter(compareFn); groups.forEach(function(group) { var subFound = findGroupsByCheck(group.getGroups(), compareFn); if (subFound.length > 0) { foundGroups = foundGroups.concat(subFound); } }); return foundGroups; }
javascript
function findGroupsByCheck(groups, compareFn) { var foundGroups = groups.filter(compareFn); groups.forEach(function(group) { var subFound = findGroupsByCheck(group.getGroups(), compareFn); if (subFound.length > 0) { foundGroups = foundGroups.concat(subFound); } }); return foundGroups; }
[ "function", "findGroupsByCheck", "(", "groups", ",", "compareFn", ")", "{", "var", "foundGroups", "=", "groups", ".", "filter", "(", "compareFn", ")", ";", "groups", ".", "forEach", "(", "function", "(", "group", ")", "{", "var", "subFound", "=", "findGroupsByCheck", "(", "group", ".", "getGroups", "(", ")", ",", "compareFn", ")", ";", "if", "(", "subFound", ".", "length", ">", "0", ")", "{", "foundGroups", "=", "foundGroups", ".", "concat", "(", "subFound", ")", ";", "}", "}", ")", ";", "return", "foundGroups", ";", "}" ]
Find group instances within groups that satisfy some check @param {Array.<Group>} groups The groups to check within @param {Function} compareFn A comparision function - return true to keep, false to strip @returns {Array.<Group>} An array of found groups
[ "Find", "group", "instances", "within", "groups", "that", "satisfy", "some", "check" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/searching-instance.js#L30-L39
16,047
buttercup/buttercup-core
source/node/tools/searching-instance.js
getAllEntries
function getAllEntries(groups) { return groups.reduce(function(current, group) { const theseEntries = group.getEntries(); const subEntries = getAllEntries(group.getGroups()); if (theseEntries.length > 0) { current = current.concat(theseEntries); } if (subEntries.length > 0) { current = current.concat(subEntries); } return current; }, []); }
javascript
function getAllEntries(groups) { return groups.reduce(function(current, group) { const theseEntries = group.getEntries(); const subEntries = getAllEntries(group.getGroups()); if (theseEntries.length > 0) { current = current.concat(theseEntries); } if (subEntries.length > 0) { current = current.concat(subEntries); } return current; }, []); }
[ "function", "getAllEntries", "(", "groups", ")", "{", "return", "groups", ".", "reduce", "(", "function", "(", "current", ",", "group", ")", "{", "const", "theseEntries", "=", "group", ".", "getEntries", "(", ")", ";", "const", "subEntries", "=", "getAllEntries", "(", "group", ".", "getGroups", "(", ")", ")", ";", "if", "(", "theseEntries", ".", "length", ">", "0", ")", "{", "current", "=", "current", ".", "concat", "(", "theseEntries", ")", ";", "}", "if", "(", "subEntries", ".", "length", ">", "0", ")", "{", "current", "=", "current", ".", "concat", "(", "subEntries", ")", ";", "}", "return", "current", ";", "}", ",", "[", "]", ")", ";", "}" ]
Get all entries within a collection of groups @param {Array.<Group>} groups An array of groups @returns {Array.<Entry>} An array of entries
[ "Get", "all", "entries", "within", "a", "collection", "of", "groups" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/searching-instance.js#L46-L58
16,048
buttercup/buttercup-core
source/node/ArchiveComparator.js
calculateCommonRecentCommand
function calculateCommonRecentCommand(archiveA, archiveB) { var historyA = archiveA._getWestley().getHistory(), historyB = archiveB._getWestley().getHistory(), aLen = historyA.length, bLen = historyB.length, a, b; for (a = aLen - 1; a >= 0; a -= 1) { if (getCommandType(historyA[a]) === "pad") { var paddingA = getPaddingID(historyA[a]); for (b = bLen - 1; b >= 0; b -= 1) { if (getCommandType(historyB[b]) === "pad" && getPaddingID(historyB[b]) === paddingA) { return { a: a, b: b, historyA: historyA, historyB: historyB }; } } } } return false; }
javascript
function calculateCommonRecentCommand(archiveA, archiveB) { var historyA = archiveA._getWestley().getHistory(), historyB = archiveB._getWestley().getHistory(), aLen = historyA.length, bLen = historyB.length, a, b; for (a = aLen - 1; a >= 0; a -= 1) { if (getCommandType(historyA[a]) === "pad") { var paddingA = getPaddingID(historyA[a]); for (b = bLen - 1; b >= 0; b -= 1) { if (getCommandType(historyB[b]) === "pad" && getPaddingID(historyB[b]) === paddingA) { return { a: a, b: b, historyA: historyA, historyB: historyB }; } } } } return false; }
[ "function", "calculateCommonRecentCommand", "(", "archiveA", ",", "archiveB", ")", "{", "var", "historyA", "=", "archiveA", ".", "_getWestley", "(", ")", ".", "getHistory", "(", ")", ",", "historyB", "=", "archiveB", ".", "_getWestley", "(", ")", ".", "getHistory", "(", ")", ",", "aLen", "=", "historyA", ".", "length", ",", "bLen", "=", "historyB", ".", "length", ",", "a", ",", "b", ";", "for", "(", "a", "=", "aLen", "-", "1", ";", "a", ">=", "0", ";", "a", "-=", "1", ")", "{", "if", "(", "getCommandType", "(", "historyA", "[", "a", "]", ")", "===", "\"pad\"", ")", "{", "var", "paddingA", "=", "getPaddingID", "(", "historyA", "[", "a", "]", ")", ";", "for", "(", "b", "=", "bLen", "-", "1", ";", "b", ">=", "0", ";", "b", "-=", "1", ")", "{", "if", "(", "getCommandType", "(", "historyB", "[", "b", "]", ")", "===", "\"pad\"", "&&", "getPaddingID", "(", "historyB", "[", "b", "]", ")", "===", "paddingA", ")", "{", "return", "{", "a", ":", "a", ",", "b", ":", "b", ",", "historyA", ":", "historyA", ",", "historyB", ":", "historyB", "}", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Calculate the common command indexes between 2 archives. The common index is where a padding ID matches that of the other archive, at some point. If we assume one archive may have been flattened, we cannot assume that the entire past history of the archives will be the same, but we can assume that at that point, the archives produce the same structure. Because the archives may be different in the future, we use the newest matching pad ID to create a common link between the 2 histories. @param {Archive} archiveA The original archive @param {Archive} archiveB The secondary archive @returns {Boolean|{ a: Number, b: Number, historyA: Array, historyB: Array }} Returns false if no common point, or an object with the common information. `a` and `b` are the indexes where the common padding occurs, and historyA and historyB are the history arrays for the archives. @private @static @memberof ArchiveComparator
[ "Calculate", "the", "common", "command", "indexes", "between", "2", "archives", ".", "The", "common", "index", "is", "where", "a", "padding", "ID", "matches", "that", "of", "the", "other", "archive", "at", "some", "point", ".", "If", "we", "assume", "one", "archive", "may", "have", "been", "flattened", "we", "cannot", "assume", "that", "the", "entire", "past", "history", "of", "the", "archives", "will", "be", "the", "same", "but", "we", "can", "assume", "that", "at", "that", "point", "the", "archives", "produce", "the", "same", "structure", ".", "Because", "the", "archives", "may", "be", "different", "in", "the", "future", "we", "use", "the", "newest", "matching", "pad", "ID", "to", "create", "a", "common", "link", "between", "the", "2", "histories", "." ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/ArchiveComparator.js#L22-L45
16,049
buttercup/buttercup-core
source/node/tools/entry.js
createFieldDescriptor
function createFieldDescriptor( entry, title, entryPropertyType, entryPropertyName, { multiline = false, secret = false, formatting = false, removeable = false } = {} ) { const value = getEntryValue(entry, entryPropertyType, entryPropertyName); return { title, field: entryPropertyType, property: entryPropertyName, value, secret, multiline, formatting, removeable }; }
javascript
function createFieldDescriptor( entry, title, entryPropertyType, entryPropertyName, { multiline = false, secret = false, formatting = false, removeable = false } = {} ) { const value = getEntryValue(entry, entryPropertyType, entryPropertyName); return { title, field: entryPropertyType, property: entryPropertyName, value, secret, multiline, formatting, removeable }; }
[ "function", "createFieldDescriptor", "(", "entry", ",", "title", ",", "entryPropertyType", ",", "entryPropertyName", ",", "{", "multiline", "=", "false", ",", "secret", "=", "false", ",", "formatting", "=", "false", ",", "removeable", "=", "false", "}", "=", "{", "}", ")", "{", "const", "value", "=", "getEntryValue", "(", "entry", ",", "entryPropertyType", ",", "entryPropertyName", ")", ";", "return", "{", "title", ",", "field", ":", "entryPropertyType", ",", "property", ":", "entryPropertyName", ",", "value", ",", "secret", ",", "multiline", ",", "formatting", ",", "removeable", "}", ";", "}" ]
Entry facade data field @typedef {Object} EntryFacadeField @property {String} title - The user-friendly title of the field @property {String} field - The type of data to map back to on the Entry instance (property/attribute) @property {String} property - The property name within the field type of the Entry instance @property {String} value - The value of the property (read/write) @property {Boolean} secret - Wether or not the value should be hidden while viewing (masked) @property {Boolean} multiline - Whether the value should be edited as a multiline value or not @property {Object|Boolean} formatting - Vendor formatting options object, or false if no formatting necessary @property {Number} maxLength - Maximum recommended length of the value (defaults to -1) Create a descriptor for a field to be used within a facade @param {Entry} entry The entry instance to process @param {String} title The field title @param {String} entryPropertyType The type of entry property (property/attribute) @param {String} entryPropertyName The name of the property @param {Object} options The options for the field @returns {EntryFacadeField} The field descriptor
[ "Entry", "facade", "data", "field" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/entry.js#L33-L51
16,050
buttercup/buttercup-core
source/node/tools/entry.js
getEntryURLs
function getEntryURLs(properties, preference = ENTRY_URL_TYPE_ANY) { const urlRef = Object.keys(properties) .filter(key => URL_PROP.test(key)) .reduce( (output, nextKey) => Object.assign(output, { [nextKey]: properties[nextKey] }), {} ); if (preference === ENTRY_URL_TYPE_GENERAL || preference === ENTRY_URL_TYPE_LOGIN) { return Object.keys(urlRef) .sort((a, b) => { if (preference === ENTRY_URL_TYPE_GENERAL) { const general = /^ur[li]$/i; const aVal = general.test(a) ? 1 : 0; const bVal = general.test(b) ? 1 : 0; return bVal - aVal; } else if (preference === ENTRY_URL_TYPE_LOGIN) { const login = /login/i; const aVal = login.test(a) ? 1 : 0; const bVal = login.test(b) ? 1 : 0; return bVal - aVal; } return 0; }) .map(key => urlRef[key]); } else if (preference === ENTRY_URL_TYPE_ICON) { const iconProp = Object.keys(urlRef).find(key => URL_PROP_ICON.test(key)); return iconProp ? [urlRef[iconProp]] : []; } // Default is "any" URLs return objectValues(urlRef); }
javascript
function getEntryURLs(properties, preference = ENTRY_URL_TYPE_ANY) { const urlRef = Object.keys(properties) .filter(key => URL_PROP.test(key)) .reduce( (output, nextKey) => Object.assign(output, { [nextKey]: properties[nextKey] }), {} ); if (preference === ENTRY_URL_TYPE_GENERAL || preference === ENTRY_URL_TYPE_LOGIN) { return Object.keys(urlRef) .sort((a, b) => { if (preference === ENTRY_URL_TYPE_GENERAL) { const general = /^ur[li]$/i; const aVal = general.test(a) ? 1 : 0; const bVal = general.test(b) ? 1 : 0; return bVal - aVal; } else if (preference === ENTRY_URL_TYPE_LOGIN) { const login = /login/i; const aVal = login.test(a) ? 1 : 0; const bVal = login.test(b) ? 1 : 0; return bVal - aVal; } return 0; }) .map(key => urlRef[key]); } else if (preference === ENTRY_URL_TYPE_ICON) { const iconProp = Object.keys(urlRef).find(key => URL_PROP_ICON.test(key)); return iconProp ? [urlRef[iconProp]] : []; } // Default is "any" URLs return objectValues(urlRef); }
[ "function", "getEntryURLs", "(", "properties", ",", "preference", "=", "ENTRY_URL_TYPE_ANY", ")", "{", "const", "urlRef", "=", "Object", ".", "keys", "(", "properties", ")", ".", "filter", "(", "key", "=>", "URL_PROP", ".", "test", "(", "key", ")", ")", ".", "reduce", "(", "(", "output", ",", "nextKey", ")", "=>", "Object", ".", "assign", "(", "output", ",", "{", "[", "nextKey", "]", ":", "properties", "[", "nextKey", "]", "}", ")", ",", "{", "}", ")", ";", "if", "(", "preference", "===", "ENTRY_URL_TYPE_GENERAL", "||", "preference", "===", "ENTRY_URL_TYPE_LOGIN", ")", "{", "return", "Object", ".", "keys", "(", "urlRef", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "preference", "===", "ENTRY_URL_TYPE_GENERAL", ")", "{", "const", "general", "=", "/", "^ur[li]$", "/", "i", ";", "const", "aVal", "=", "general", ".", "test", "(", "a", ")", "?", "1", ":", "0", ";", "const", "bVal", "=", "general", ".", "test", "(", "b", ")", "?", "1", ":", "0", ";", "return", "bVal", "-", "aVal", ";", "}", "else", "if", "(", "preference", "===", "ENTRY_URL_TYPE_LOGIN", ")", "{", "const", "login", "=", "/", "login", "/", "i", ";", "const", "aVal", "=", "login", ".", "test", "(", "a", ")", "?", "1", ":", "0", ";", "const", "bVal", "=", "login", ".", "test", "(", "b", ")", "?", "1", ":", "0", ";", "return", "bVal", "-", "aVal", ";", "}", "return", "0", ";", "}", ")", ".", "map", "(", "key", "=>", "urlRef", "[", "key", "]", ")", ";", "}", "else", "if", "(", "preference", "===", "ENTRY_URL_TYPE_ICON", ")", "{", "const", "iconProp", "=", "Object", ".", "keys", "(", "urlRef", ")", ".", "find", "(", "key", "=>", "URL_PROP_ICON", ".", "test", "(", "key", ")", ")", ";", "return", "iconProp", "?", "[", "urlRef", "[", "iconProp", "]", "]", ":", "[", "]", ";", "}", "// Default is \"any\" URLs", "return", "objectValues", "(", "urlRef", ")", ";", "}" ]
Get URLs from an entry's properties Allows for preferential sorting @param {Object} properties The entry properties @param {*} preference
[ "Get", "URLs", "from", "an", "entry", "s", "properties", "Allows", "for", "preferential", "sorting" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/entry.js#L59-L92
16,051
buttercup/buttercup-core
source/node/tools/entry.js
getEntryValue
function getEntryValue(entry, property, name) { switch (property) { case "property": return entry.getProperty(name); case "meta": return entry.getMeta(name); case "attribute": return entry.getAttribute(name); default: throw new Error(`Cannot retrieve value: Unknown property type: ${property}`); } }
javascript
function getEntryValue(entry, property, name) { switch (property) { case "property": return entry.getProperty(name); case "meta": return entry.getMeta(name); case "attribute": return entry.getAttribute(name); default: throw new Error(`Cannot retrieve value: Unknown property type: ${property}`); } }
[ "function", "getEntryValue", "(", "entry", ",", "property", ",", "name", ")", "{", "switch", "(", "property", ")", "{", "case", "\"property\"", ":", "return", "entry", ".", "getProperty", "(", "name", ")", ";", "case", "\"meta\"", ":", "return", "entry", ".", "getMeta", "(", "name", ")", ";", "case", "\"attribute\"", ":", "return", "entry", ".", "getAttribute", "(", "name", ")", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "property", "}", "`", ")", ";", "}", "}" ]
Get a value on an entry for a specific property type @param {Entry} entry The entry instance @param {String} property The type of entry property (property/meta/attribute) @param {String} name The property name @returns {String} The property value @throws {Error} Throws for unknown property types @deprecated Not in use - To be removed
[ "Get", "a", "value", "on", "an", "entry", "for", "a", "specific", "property", "type" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/entry.js#L116-L127
16,052
buttercup/buttercup-core
source/node/tools/entry.js
isValidProperty
function isValidProperty(name) { for (var keyName in EntryProperty) { if (EntryProperty.hasOwnProperty(keyName)) { if (EntryProperty[keyName] === name) { return true; } } } return false; }
javascript
function isValidProperty(name) { for (var keyName in EntryProperty) { if (EntryProperty.hasOwnProperty(keyName)) { if (EntryProperty[keyName] === name) { return true; } } } return false; }
[ "function", "isValidProperty", "(", "name", ")", "{", "for", "(", "var", "keyName", "in", "EntryProperty", ")", "{", "if", "(", "EntryProperty", ".", "hasOwnProperty", "(", "keyName", ")", ")", "{", "if", "(", "EntryProperty", "[", "keyName", "]", "===", "name", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check if a property name is valid @param {String} name The name to check @returns {Boolean} True if the name is valid
[ "Check", "if", "a", "property", "name", "is", "valid" ]
0da03ab57a68b686312799af435287d8ce8f8490
https://github.com/buttercup/buttercup-core/blob/0da03ab57a68b686312799af435287d8ce8f8490/source/node/tools/entry.js#L134-L143
16,053
ausi/cq-prolyfill
cq-prolyfill.js
scheduleExecution
function scheduleExecution(step, clearContainerCache, contexts) { if (!scheduledCall) { scheduledCall = { _step: step, _clearContainerCache: clearContainerCache, _contexts: contexts, }; requestAnimationFrame(executeScheduledCall); return; } scheduledCall._step = Math.min(scheduledCall._step, step); // Merge parameters for reevaluate if (scheduledCall._step === 3) { scheduledCall._clearContainerCache = scheduledCall._clearContainerCache || clearContainerCache; if (scheduledCall._contexts && contexts) { scheduledCall._contexts = scheduledCall._contexts.concat(contexts); } } }
javascript
function scheduleExecution(step, clearContainerCache, contexts) { if (!scheduledCall) { scheduledCall = { _step: step, _clearContainerCache: clearContainerCache, _contexts: contexts, }; requestAnimationFrame(executeScheduledCall); return; } scheduledCall._step = Math.min(scheduledCall._step, step); // Merge parameters for reevaluate if (scheduledCall._step === 3) { scheduledCall._clearContainerCache = scheduledCall._clearContainerCache || clearContainerCache; if (scheduledCall._contexts && contexts) { scheduledCall._contexts = scheduledCall._contexts.concat(contexts); } } }
[ "function", "scheduleExecution", "(", "step", ",", "clearContainerCache", ",", "contexts", ")", "{", "if", "(", "!", "scheduledCall", ")", "{", "scheduledCall", "=", "{", "_step", ":", "step", ",", "_clearContainerCache", ":", "clearContainerCache", ",", "_contexts", ":", "contexts", ",", "}", ";", "requestAnimationFrame", "(", "executeScheduledCall", ")", ";", "return", ";", "}", "scheduledCall", ".", "_step", "=", "Math", ".", "min", "(", "scheduledCall", ".", "_step", ",", "step", ")", ";", "// Merge parameters for reevaluate", "if", "(", "scheduledCall", ".", "_step", "===", "3", ")", "{", "scheduledCall", ".", "_clearContainerCache", "=", "scheduledCall", ".", "_clearContainerCache", "||", "clearContainerCache", ";", "if", "(", "scheduledCall", ".", "_contexts", "&&", "contexts", ")", "{", "scheduledCall", ".", "_contexts", "=", "scheduledCall", ".", "_contexts", ".", "concat", "(", "contexts", ")", ";", "}", "}", "}" ]
Schedule the execution of step 1, 2 or 3 for the next animation frame @param {number} step 1: reprocess, 2: reparse, 3: reevaluate @param {boolean} clearContainerCache @param {Array.<Element>} contexts
[ "Schedule", "the", "execution", "of", "step", "1", "2", "or", "3", "for", "the", "next", "animation", "frame" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L134-L156
16,054
ausi/cq-prolyfill
cq-prolyfill.js
startObserving
function startObserving() { if (config.skipObserving) { return; } // Reprocess now scheduleExecution(1); window.addEventListener('DOMContentLoaded', scheduleExecution.bind(undefined, 1, undefined, undefined)); window.addEventListener('load', scheduleExecution.bind(undefined, 1, undefined, undefined)); window.addEventListener('resize', scheduleExecution.bind(undefined, 3, true, undefined)); var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; if (MutationObserver) { observer = new MutationObserver(checkMutations); observer.observe(document.documentElement, { childList: true, subtree: true, }); } else { window.addEventListener('DOMNodeInserted', onDomMutate); window.addEventListener('DOMNodeRemoved', onDomMutate); } }
javascript
function startObserving() { if (config.skipObserving) { return; } // Reprocess now scheduleExecution(1); window.addEventListener('DOMContentLoaded', scheduleExecution.bind(undefined, 1, undefined, undefined)); window.addEventListener('load', scheduleExecution.bind(undefined, 1, undefined, undefined)); window.addEventListener('resize', scheduleExecution.bind(undefined, 3, true, undefined)); var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; if (MutationObserver) { observer = new MutationObserver(checkMutations); observer.observe(document.documentElement, { childList: true, subtree: true, }); } else { window.addEventListener('DOMNodeInserted', onDomMutate); window.addEventListener('DOMNodeRemoved', onDomMutate); } }
[ "function", "startObserving", "(", ")", "{", "if", "(", "config", ".", "skipObserving", ")", "{", "return", ";", "}", "// Reprocess now", "scheduleExecution", "(", "1", ")", ";", "window", ".", "addEventListener", "(", "'DOMContentLoaded'", ",", "scheduleExecution", ".", "bind", "(", "undefined", ",", "1", ",", "undefined", ",", "undefined", ")", ")", ";", "window", ".", "addEventListener", "(", "'load'", ",", "scheduleExecution", ".", "bind", "(", "undefined", ",", "1", ",", "undefined", ",", "undefined", ")", ")", ";", "window", ".", "addEventListener", "(", "'resize'", ",", "scheduleExecution", ".", "bind", "(", "undefined", ",", "3", ",", "true", ",", "undefined", ")", ")", ";", "var", "MutationObserver", "=", "window", ".", "MutationObserver", "||", "window", ".", "WebKitMutationObserver", ";", "if", "(", "MutationObserver", ")", "{", "observer", "=", "new", "MutationObserver", "(", "checkMutations", ")", ";", "observer", ".", "observe", "(", "document", ".", "documentElement", ",", "{", "childList", ":", "true", ",", "subtree", ":", "true", ",", "}", ")", ";", "}", "else", "{", "window", ".", "addEventListener", "(", "'DOMNodeInserted'", ",", "onDomMutate", ")", ";", "window", ".", "addEventListener", "(", "'DOMNodeRemoved'", ",", "onDomMutate", ")", ";", "}", "}" ]
Starts observing DOM events and mutations
[ "Starts", "observing", "DOM", "events", "and", "mutations" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L181-L207
16,055
ausi/cq-prolyfill
cq-prolyfill.js
checkMutations
function checkMutations(mutations) { // Skip iterating the nodes, if a run is already scheduled, to improve performance if (scheduledCall && (scheduledCall._level < 3 || !scheduledCall._contexts)) { return; } var addedNodes = []; var stylesChanged = false; var replacedSheets = []; processedSheets.forEach(function(newNode) { replacedSheets.push(newNode); }); arrayFrom(mutations).forEach(function(mutation) { addedNodes.push.apply(addedNodes, arrayFrom(mutation.addedNodes).filter(function(node) { return node.nodeType === 1; })); arrayFrom(mutation.removedNodes).forEach(function(node) { var index = addedNodes.indexOf(node); if (index !== -1) { addedNodes.splice(index, 1); } else if ( (node.tagName === 'LINK' || node.tagName === 'STYLE') && replacedSheets.indexOf(node) === -1 ) { stylesChanged = true; } }); }); addedNodes.forEach(function(node) { if (node.sheet && replacedSheets.indexOf(node) === -1) { stylesChanged = true; } }); if (stylesChanged) { scheduleExecution(1); } else if (addedNodes.length) { scheduleExecution(3, false, addedNodes); } }
javascript
function checkMutations(mutations) { // Skip iterating the nodes, if a run is already scheduled, to improve performance if (scheduledCall && (scheduledCall._level < 3 || !scheduledCall._contexts)) { return; } var addedNodes = []; var stylesChanged = false; var replacedSheets = []; processedSheets.forEach(function(newNode) { replacedSheets.push(newNode); }); arrayFrom(mutations).forEach(function(mutation) { addedNodes.push.apply(addedNodes, arrayFrom(mutation.addedNodes).filter(function(node) { return node.nodeType === 1; })); arrayFrom(mutation.removedNodes).forEach(function(node) { var index = addedNodes.indexOf(node); if (index !== -1) { addedNodes.splice(index, 1); } else if ( (node.tagName === 'LINK' || node.tagName === 'STYLE') && replacedSheets.indexOf(node) === -1 ) { stylesChanged = true; } }); }); addedNodes.forEach(function(node) { if (node.sheet && replacedSheets.indexOf(node) === -1) { stylesChanged = true; } }); if (stylesChanged) { scheduleExecution(1); } else if (addedNodes.length) { scheduleExecution(3, false, addedNodes); } }
[ "function", "checkMutations", "(", "mutations", ")", "{", "// Skip iterating the nodes, if a run is already scheduled, to improve performance", "if", "(", "scheduledCall", "&&", "(", "scheduledCall", ".", "_level", "<", "3", "||", "!", "scheduledCall", ".", "_contexts", ")", ")", "{", "return", ";", "}", "var", "addedNodes", "=", "[", "]", ";", "var", "stylesChanged", "=", "false", ";", "var", "replacedSheets", "=", "[", "]", ";", "processedSheets", ".", "forEach", "(", "function", "(", "newNode", ")", "{", "replacedSheets", ".", "push", "(", "newNode", ")", ";", "}", ")", ";", "arrayFrom", "(", "mutations", ")", ".", "forEach", "(", "function", "(", "mutation", ")", "{", "addedNodes", ".", "push", ".", "apply", "(", "addedNodes", ",", "arrayFrom", "(", "mutation", ".", "addedNodes", ")", ".", "filter", "(", "function", "(", "node", ")", "{", "return", "node", ".", "nodeType", "===", "1", ";", "}", ")", ")", ";", "arrayFrom", "(", "mutation", ".", "removedNodes", ")", ".", "forEach", "(", "function", "(", "node", ")", "{", "var", "index", "=", "addedNodes", ".", "indexOf", "(", "node", ")", ";", "if", "(", "index", "!==", "-", "1", ")", "{", "addedNodes", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "else", "if", "(", "(", "node", ".", "tagName", "===", "'LINK'", "||", "node", ".", "tagName", "===", "'STYLE'", ")", "&&", "replacedSheets", ".", "indexOf", "(", "node", ")", "===", "-", "1", ")", "{", "stylesChanged", "=", "true", ";", "}", "}", ")", ";", "}", ")", ";", "addedNodes", ".", "forEach", "(", "function", "(", "node", ")", "{", "if", "(", "node", ".", "sheet", "&&", "replacedSheets", ".", "indexOf", "(", "node", ")", "===", "-", "1", ")", "{", "stylesChanged", "=", "true", ";", "}", "}", ")", ";", "if", "(", "stylesChanged", ")", "{", "scheduleExecution", "(", "1", ")", ";", "}", "else", "if", "(", "addedNodes", ".", "length", ")", "{", "scheduleExecution", "(", "3", ",", "false", ",", "addedNodes", ")", ";", "}", "}" ]
Check DOM mutations and reprocess or reevaluate @param {Array.<MutationRecord>} mutations
[ "Check", "DOM", "mutations", "and", "reprocess", "or", "reevaluate" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L214-L263
16,056
ausi/cq-prolyfill
cq-prolyfill.js
onDomMutate
function onDomMutate(event) { var mutation = { addedNodes: [], removedNodes: [], }; mutation[ (event.type === 'DOMNodeInserted' ? 'added' : 'removed') + 'Nodes' ] = [event.target]; domMutations.push(mutation); // Delay the call to checkMutations() setTimeout(function() { checkMutations(domMutations); domMutations = []; }); }
javascript
function onDomMutate(event) { var mutation = { addedNodes: [], removedNodes: [], }; mutation[ (event.type === 'DOMNodeInserted' ? 'added' : 'removed') + 'Nodes' ] = [event.target]; domMutations.push(mutation); // Delay the call to checkMutations() setTimeout(function() { checkMutations(domMutations); domMutations = []; }); }
[ "function", "onDomMutate", "(", "event", ")", "{", "var", "mutation", "=", "{", "addedNodes", ":", "[", "]", ",", "removedNodes", ":", "[", "]", ",", "}", ";", "mutation", "[", "(", "event", ".", "type", "===", "'DOMNodeInserted'", "?", "'added'", ":", "'removed'", ")", "+", "'Nodes'", "]", "=", "[", "event", ".", "target", "]", ";", "domMutations", ".", "push", "(", "mutation", ")", ";", "// Delay the call to checkMutations()", "setTimeout", "(", "function", "(", ")", "{", "checkMutations", "(", "domMutations", ")", ";", "domMutations", "=", "[", "]", ";", "}", ")", ";", "}" ]
Event handler for DOMNodeInserted and DOMNodeRemoved @param {MutationEvent} event
[ "Event", "handler", "for", "DOMNodeInserted", "and", "DOMNodeRemoved" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L270-L288
16,057
ausi/cq-prolyfill
cq-prolyfill.js
loadExternal
function loadExternal(href, callback) { var cacheEntryType = typeof requestCache[href]; if (cacheEntryType === 'string') { callback(requestCache[href]); return; } else if (cacheEntryType === 'object') { requestCache[href].push(callback); return; } requestCache[href] = [callback] var isDone = false; var done = function(response) { if (!isDone) { response = response || ''; requestCache[href].forEach(function(cachedCallback) { setTimeout(function() { cachedCallback(response); }); }); requestCache[href] = response; } isDone = true; }; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } done(xhr.status === 200 && xhr.responseText); }; try { xhr.open('GET', href); xhr.send(); } catch(e) { if (window.XDomainRequest) { xhr = new XDomainRequest(); xhr.onprogress = /* istanbul ignore next: fix for a rare IE9 bug */ function() {}; xhr.onload = xhr.onerror = xhr.ontimeout = function() { done(xhr.responseText); }; try { xhr.open('GET', href); xhr.send(); } catch(e2) { done(); } } else { done(); } } }
javascript
function loadExternal(href, callback) { var cacheEntryType = typeof requestCache[href]; if (cacheEntryType === 'string') { callback(requestCache[href]); return; } else if (cacheEntryType === 'object') { requestCache[href].push(callback); return; } requestCache[href] = [callback] var isDone = false; var done = function(response) { if (!isDone) { response = response || ''; requestCache[href].forEach(function(cachedCallback) { setTimeout(function() { cachedCallback(response); }); }); requestCache[href] = response; } isDone = true; }; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } done(xhr.status === 200 && xhr.responseText); }; try { xhr.open('GET', href); xhr.send(); } catch(e) { if (window.XDomainRequest) { xhr = new XDomainRequest(); xhr.onprogress = /* istanbul ignore next: fix for a rare IE9 bug */ function() {}; xhr.onload = xhr.onerror = xhr.ontimeout = function() { done(xhr.responseText); }; try { xhr.open('GET', href); xhr.send(); } catch(e2) { done(); } } else { done(); } } }
[ "function", "loadExternal", "(", "href", ",", "callback", ")", "{", "var", "cacheEntryType", "=", "typeof", "requestCache", "[", "href", "]", ";", "if", "(", "cacheEntryType", "===", "'string'", ")", "{", "callback", "(", "requestCache", "[", "href", "]", ")", ";", "return", ";", "}", "else", "if", "(", "cacheEntryType", "===", "'object'", ")", "{", "requestCache", "[", "href", "]", ".", "push", "(", "callback", ")", ";", "return", ";", "}", "requestCache", "[", "href", "]", "=", "[", "callback", "]", "var", "isDone", "=", "false", ";", "var", "done", "=", "function", "(", "response", ")", "{", "if", "(", "!", "isDone", ")", "{", "response", "=", "response", "||", "''", ";", "requestCache", "[", "href", "]", ".", "forEach", "(", "function", "(", "cachedCallback", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "cachedCallback", "(", "response", ")", ";", "}", ")", ";", "}", ")", ";", "requestCache", "[", "href", "]", "=", "response", ";", "}", "isDone", "=", "true", ";", "}", ";", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "!==", "4", ")", "{", "return", ";", "}", "done", "(", "xhr", ".", "status", "===", "200", "&&", "xhr", ".", "responseText", ")", ";", "}", ";", "try", "{", "xhr", ".", "open", "(", "'GET'", ",", "href", ")", ";", "xhr", ".", "send", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "window", ".", "XDomainRequest", ")", "{", "xhr", "=", "new", "XDomainRequest", "(", ")", ";", "xhr", ".", "onprogress", "=", "/* istanbul ignore next: fix for a rare IE9 bug */", "function", "(", ")", "{", "}", ";", "xhr", ".", "onload", "=", "xhr", ".", "onerror", "=", "xhr", ".", "ontimeout", "=", "function", "(", ")", "{", "done", "(", "xhr", ".", "responseText", ")", ";", "}", ";", "try", "{", "xhr", ".", "open", "(", "'GET'", ",", "href", ")", ";", "xhr", ".", "send", "(", ")", ";", "}", "catch", "(", "e2", ")", "{", "done", "(", ")", ";", "}", "}", "else", "{", "done", "(", ")", ";", "}", "}", "}" ]
Load external file via AJAX @param {string} href @param {function(string)} callback Gets called with the response text on success or empty string on failure
[ "Load", "external", "file", "via", "AJAX" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L381-L437
16,058
ausi/cq-prolyfill
cq-prolyfill.js
fixRelativeUrls
function fixRelativeUrls(cssText, href) { var base = resolveRelativeUrl(href, document.baseURI); return cssText.replace(URL_VALUE_REGEXP, function(match, quote, url1, url2) { var url = url1 || url2; if (!url) { return match; } return 'url(' + (quote || '"') + resolveRelativeUrl(url, base) + (quote || '"') + ')'; }); }
javascript
function fixRelativeUrls(cssText, href) { var base = resolveRelativeUrl(href, document.baseURI); return cssText.replace(URL_VALUE_REGEXP, function(match, quote, url1, url2) { var url = url1 || url2; if (!url) { return match; } return 'url(' + (quote || '"') + resolveRelativeUrl(url, base) + (quote || '"') + ')'; }); }
[ "function", "fixRelativeUrls", "(", "cssText", ",", "href", ")", "{", "var", "base", "=", "resolveRelativeUrl", "(", "href", ",", "document", ".", "baseURI", ")", ";", "return", "cssText", ".", "replace", "(", "URL_VALUE_REGEXP", ",", "function", "(", "match", ",", "quote", ",", "url1", ",", "url2", ")", "{", "var", "url", "=", "url1", "||", "url2", ";", "if", "(", "!", "url", ")", "{", "return", "match", ";", "}", "return", "'url('", "+", "(", "quote", "||", "'\"'", ")", "+", "resolveRelativeUrl", "(", "url", ",", "base", ")", "+", "(", "quote", "||", "'\"'", ")", "+", "')'", ";", "}", ")", ";", "}" ]
Replace relative CSS URLs with their absolute counterpart @param {string} cssText @param {string} href URL of the stylesheet @return {string}
[ "Replace", "relative", "CSS", "URLs", "with", "their", "absolute", "counterpart" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L446-L455
16,059
ausi/cq-prolyfill
cq-prolyfill.js
buildStyleCache
function buildStyleCache() { styleCache = { width: {}, height: {}, }; var rules; for (var i = 0; i < styleSheets.length; i++) { if (styleSheets[i].disabled) { continue; } try { rules = styleSheets[i].cssRules; if (!rules || !rules.length) { continue; } } catch(e) { continue; } buildStyleCacheFromRules(rules); } }
javascript
function buildStyleCache() { styleCache = { width: {}, height: {}, }; var rules; for (var i = 0; i < styleSheets.length; i++) { if (styleSheets[i].disabled) { continue; } try { rules = styleSheets[i].cssRules; if (!rules || !rules.length) { continue; } } catch(e) { continue; } buildStyleCacheFromRules(rules); } }
[ "function", "buildStyleCache", "(", ")", "{", "styleCache", "=", "{", "width", ":", "{", "}", ",", "height", ":", "{", "}", ",", "}", ";", "var", "rules", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "styleSheets", ".", "length", ";", "i", "++", ")", "{", "if", "(", "styleSheets", "[", "i", "]", ".", "disabled", ")", "{", "continue", ";", "}", "try", "{", "rules", "=", "styleSheets", "[", "i", "]", ".", "cssRules", ";", "if", "(", "!", "rules", "||", "!", "rules", ".", "length", ")", "{", "continue", ";", "}", "}", "catch", "(", "e", ")", "{", "continue", ";", "}", "buildStyleCacheFromRules", "(", "rules", ")", ";", "}", "}" ]
Builds the styleCache needed by getOriginalStyle
[ "Builds", "the", "styleCache", "needed", "by", "getOriginalStyle" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L666-L687
16,060
ausi/cq-prolyfill
cq-prolyfill.js
updateClassesRead
function updateClassesRead(treeNodes, dontMarkAsDone) { var hasChanges = false; var i, node, j, query; for (i = 0; i < treeNodes.length; i++) { node = treeNodes[i]; if (!node._done) { for (j = 0; j < node._queries.length; j++) { query = node._queries[j]; var queryMatches = evaluateQuery(node._element.parentNode, query); if (queryMatches !== hasQuery(node._element, query)) { node._changes.push([queryMatches, query]); } } node._done = !dontMarkAsDone; } hasChanges = updateClassesRead(node._children, dontMarkAsDone || node._changes.length) || node._changes.length || hasChanges; } return hasChanges; }
javascript
function updateClassesRead(treeNodes, dontMarkAsDone) { var hasChanges = false; var i, node, j, query; for (i = 0; i < treeNodes.length; i++) { node = treeNodes[i]; if (!node._done) { for (j = 0; j < node._queries.length; j++) { query = node._queries[j]; var queryMatches = evaluateQuery(node._element.parentNode, query); if (queryMatches !== hasQuery(node._element, query)) { node._changes.push([queryMatches, query]); } } node._done = !dontMarkAsDone; } hasChanges = updateClassesRead(node._children, dontMarkAsDone || node._changes.length) || node._changes.length || hasChanges; } return hasChanges; }
[ "function", "updateClassesRead", "(", "treeNodes", ",", "dontMarkAsDone", ")", "{", "var", "hasChanges", "=", "false", ";", "var", "i", ",", "node", ",", "j", ",", "query", ";", "for", "(", "i", "=", "0", ";", "i", "<", "treeNodes", ".", "length", ";", "i", "++", ")", "{", "node", "=", "treeNodes", "[", "i", "]", ";", "if", "(", "!", "node", ".", "_done", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<", "node", ".", "_queries", ".", "length", ";", "j", "++", ")", "{", "query", "=", "node", ".", "_queries", "[", "j", "]", ";", "var", "queryMatches", "=", "evaluateQuery", "(", "node", ".", "_element", ".", "parentNode", ",", "query", ")", ";", "if", "(", "queryMatches", "!==", "hasQuery", "(", "node", ".", "_element", ",", "query", ")", ")", "{", "node", ".", "_changes", ".", "push", "(", "[", "queryMatches", ",", "query", "]", ")", ";", "}", "}", "node", ".", "_done", "=", "!", "dontMarkAsDone", ";", "}", "hasChanges", "=", "updateClassesRead", "(", "node", ".", "_children", ",", "dontMarkAsDone", "||", "node", ".", "_changes", ".", "length", ")", "||", "node", ".", "_changes", ".", "length", "||", "hasChanges", ";", "}", "return", "hasChanges", ";", "}" ]
Update classes read step @param {Array.<{_element: Element, _children: array, _queries: array, _changes: array, _done: boolean}>} treeNodes @param {boolean} dontMarkAsDone @return {boolean} True if changes were found
[ "Update", "classes", "read", "step" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L781-L801
16,061
ausi/cq-prolyfill
cq-prolyfill.js
updateClassesWrite
function updateClassesWrite(treeNodes) { var node, j; for (var i = 0; i < treeNodes.length; i++) { node = treeNodes[i]; for (j = 0; j < node._changes.length; j++) { (node._changes[j][0] ? addQuery : removeQuery)(node._element, node._changes[j][1]); } node._changes = []; updateClassesWrite(node._children); } }
javascript
function updateClassesWrite(treeNodes) { var node, j; for (var i = 0; i < treeNodes.length; i++) { node = treeNodes[i]; for (j = 0; j < node._changes.length; j++) { (node._changes[j][0] ? addQuery : removeQuery)(node._element, node._changes[j][1]); } node._changes = []; updateClassesWrite(node._children); } }
[ "function", "updateClassesWrite", "(", "treeNodes", ")", "{", "var", "node", ",", "j", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "treeNodes", ".", "length", ";", "i", "++", ")", "{", "node", "=", "treeNodes", "[", "i", "]", ";", "for", "(", "j", "=", "0", ";", "j", "<", "node", ".", "_changes", ".", "length", ";", "j", "++", ")", "{", "(", "node", ".", "_changes", "[", "j", "]", "[", "0", "]", "?", "addQuery", ":", "removeQuery", ")", "(", "node", ".", "_element", ",", "node", ".", "_changes", "[", "j", "]", "[", "1", "]", ")", ";", "}", "node", ".", "_changes", "=", "[", "]", ";", "updateClassesWrite", "(", "node", ".", "_children", ")", ";", "}", "}" ]
Update classes write step @param {Array.<{_element: Element, _children: array, _queries: array, _changes: array, _done: boolean}>} treeNodes
[ "Update", "classes", "write", "step" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L808-L818
16,062
ausi/cq-prolyfill
cq-prolyfill.js
buildElementsTree
function buildElementsTree(contexts) { contexts = contexts || [document]; var queriesArray = Object.keys(queries).map(function(key) { return queries[key]; }); var selector = queriesArray.map(function(query) { return query._selector; }).join(','); var elements = []; contexts.forEach(function(context) { for (var node = context.parentNode; node; node = node.parentNode) { // Skip nested contexts if (contexts.indexOf(node) !== -1) { return; } } if (context !== document && elementMatchesSelector(context, selector)) { elements.push(context); } elements.push.apply(elements, arrayFrom(context.querySelectorAll(selector))); }); var tree = []; var treeCache = createCacheMap(); elements.forEach(function(element) { if (element === documentElement) { return; } var treeNode = { _element: element, _children: [], _queries: [], _changes: [], _done: false, }; var children = tree; for (var node = element.parentNode; node; node = node.parentNode) { if (treeCache.get(node)) { children = treeCache.get(node)._children; break; } } treeCache.set(element, treeNode); children.push(treeNode); queriesArray.forEach(function(query) { if (elementMatchesSelector(element, query._selector)) { treeNode._queries.push(query); } }); }); return tree; }
javascript
function buildElementsTree(contexts) { contexts = contexts || [document]; var queriesArray = Object.keys(queries).map(function(key) { return queries[key]; }); var selector = queriesArray.map(function(query) { return query._selector; }).join(','); var elements = []; contexts.forEach(function(context) { for (var node = context.parentNode; node; node = node.parentNode) { // Skip nested contexts if (contexts.indexOf(node) !== -1) { return; } } if (context !== document && elementMatchesSelector(context, selector)) { elements.push(context); } elements.push.apply(elements, arrayFrom(context.querySelectorAll(selector))); }); var tree = []; var treeCache = createCacheMap(); elements.forEach(function(element) { if (element === documentElement) { return; } var treeNode = { _element: element, _children: [], _queries: [], _changes: [], _done: false, }; var children = tree; for (var node = element.parentNode; node; node = node.parentNode) { if (treeCache.get(node)) { children = treeCache.get(node)._children; break; } } treeCache.set(element, treeNode); children.push(treeNode); queriesArray.forEach(function(query) { if (elementMatchesSelector(element, query._selector)) { treeNode._queries.push(query); } }); }); return tree; }
[ "function", "buildElementsTree", "(", "contexts", ")", "{", "contexts", "=", "contexts", "||", "[", "document", "]", ";", "var", "queriesArray", "=", "Object", ".", "keys", "(", "queries", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "queries", "[", "key", "]", ";", "}", ")", ";", "var", "selector", "=", "queriesArray", ".", "map", "(", "function", "(", "query", ")", "{", "return", "query", ".", "_selector", ";", "}", ")", ".", "join", "(", "','", ")", ";", "var", "elements", "=", "[", "]", ";", "contexts", ".", "forEach", "(", "function", "(", "context", ")", "{", "for", "(", "var", "node", "=", "context", ".", "parentNode", ";", "node", ";", "node", "=", "node", ".", "parentNode", ")", "{", "// Skip nested contexts", "if", "(", "contexts", ".", "indexOf", "(", "node", ")", "!==", "-", "1", ")", "{", "return", ";", "}", "}", "if", "(", "context", "!==", "document", "&&", "elementMatchesSelector", "(", "context", ",", "selector", ")", ")", "{", "elements", ".", "push", "(", "context", ")", ";", "}", "elements", ".", "push", ".", "apply", "(", "elements", ",", "arrayFrom", "(", "context", ".", "querySelectorAll", "(", "selector", ")", ")", ")", ";", "}", ")", ";", "var", "tree", "=", "[", "]", ";", "var", "treeCache", "=", "createCacheMap", "(", ")", ";", "elements", ".", "forEach", "(", "function", "(", "element", ")", "{", "if", "(", "element", "===", "documentElement", ")", "{", "return", ";", "}", "var", "treeNode", "=", "{", "_element", ":", "element", ",", "_children", ":", "[", "]", ",", "_queries", ":", "[", "]", ",", "_changes", ":", "[", "]", ",", "_done", ":", "false", ",", "}", ";", "var", "children", "=", "tree", ";", "for", "(", "var", "node", "=", "element", ".", "parentNode", ";", "node", ";", "node", "=", "node", ".", "parentNode", ")", "{", "if", "(", "treeCache", ".", "get", "(", "node", ")", ")", "{", "children", "=", "treeCache", ".", "get", "(", "node", ")", ".", "_children", ";", "break", ";", "}", "}", "treeCache", ".", "set", "(", "element", ",", "treeNode", ")", ";", "children", ".", "push", "(", "treeNode", ")", ";", "queriesArray", ".", "forEach", "(", "function", "(", "query", ")", "{", "if", "(", "elementMatchesSelector", "(", "element", ",", "query", ".", "_selector", ")", ")", "{", "treeNode", ".", "_queries", ".", "push", "(", "query", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "tree", ";", "}" ]
Build tree of all query elements @param {Array.<Element>} contexts @return {Array.<{_element: Element, _children: array, _queries: array, _changes: array, _done: boolean}>}
[ "Build", "tree", "of", "all", "query", "elements" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L826-L891
16,063
ausi/cq-prolyfill
cq-prolyfill.js
evaluateQuery
function evaluateQuery(parent, query) { var container = getContainer(parent, query._prop); var qValues = query._values.slice(0); var i; var cValue; if (query._prop === 'width' || query._prop === 'height') { cValue = getSize(container, query._prop); } else { cValue = getComputedStyle(container).getPropertyValue(query._prop); } if (query._filter) { var color = parseColor(cValue); if (query._filter[0] === 'h') { cValue = color[0]; } else if (query._filter[0] === 's') { cValue = color[1]; } else if (query._filter[0] === 'l') { cValue = color[2]; } else if (query._filter[0] === 'a') { cValue = color[3]; } else { return false; } } else if (query._valueType === 'c') { cValue = parseColor(cValue).join(','); } else if (query._valueType === 'l') { for (i = 0; i < qValues.length; i++) { qValues[i] = getComputedLength(qValues[i], parent); } if (typeof cValue === 'string') { cValue = getComputedLength(cValue, parent); } } else if (query._valueType === 'n') { cValue = parseFloat(cValue); } else if (typeof cValue === 'string') { cValue = cValue.trim(); } if (( query._types[0][0] === '>' || query._types[0][0] === '<' ) && ( typeof cValue !== 'number' || typeof qValues[0] !== 'number' )) { return false; } for (i = 0; i < qValues.length; i++) { if (!( (query._types[i] === '>=' && cValue >= qValues[i]) || (query._types[i] === '<=' && cValue <= qValues[i]) || (query._types[i] === '>' && cValue > qValues[i]) || (query._types[i] === '<' && cValue < qValues[i]) || (query._types[i] === '=' && cValue === qValues[i]) )) { return false; } } return true; }
javascript
function evaluateQuery(parent, query) { var container = getContainer(parent, query._prop); var qValues = query._values.slice(0); var i; var cValue; if (query._prop === 'width' || query._prop === 'height') { cValue = getSize(container, query._prop); } else { cValue = getComputedStyle(container).getPropertyValue(query._prop); } if (query._filter) { var color = parseColor(cValue); if (query._filter[0] === 'h') { cValue = color[0]; } else if (query._filter[0] === 's') { cValue = color[1]; } else if (query._filter[0] === 'l') { cValue = color[2]; } else if (query._filter[0] === 'a') { cValue = color[3]; } else { return false; } } else if (query._valueType === 'c') { cValue = parseColor(cValue).join(','); } else if (query._valueType === 'l') { for (i = 0; i < qValues.length; i++) { qValues[i] = getComputedLength(qValues[i], parent); } if (typeof cValue === 'string') { cValue = getComputedLength(cValue, parent); } } else if (query._valueType === 'n') { cValue = parseFloat(cValue); } else if (typeof cValue === 'string') { cValue = cValue.trim(); } if (( query._types[0][0] === '>' || query._types[0][0] === '<' ) && ( typeof cValue !== 'number' || typeof qValues[0] !== 'number' )) { return false; } for (i = 0; i < qValues.length; i++) { if (!( (query._types[i] === '>=' && cValue >= qValues[i]) || (query._types[i] === '<=' && cValue <= qValues[i]) || (query._types[i] === '>' && cValue > qValues[i]) || (query._types[i] === '<' && cValue < qValues[i]) || (query._types[i] === '=' && cValue === qValues[i]) )) { return false; } } return true; }
[ "function", "evaluateQuery", "(", "parent", ",", "query", ")", "{", "var", "container", "=", "getContainer", "(", "parent", ",", "query", ".", "_prop", ")", ";", "var", "qValues", "=", "query", ".", "_values", ".", "slice", "(", "0", ")", ";", "var", "i", ";", "var", "cValue", ";", "if", "(", "query", ".", "_prop", "===", "'width'", "||", "query", ".", "_prop", "===", "'height'", ")", "{", "cValue", "=", "getSize", "(", "container", ",", "query", ".", "_prop", ")", ";", "}", "else", "{", "cValue", "=", "getComputedStyle", "(", "container", ")", ".", "getPropertyValue", "(", "query", ".", "_prop", ")", ";", "}", "if", "(", "query", ".", "_filter", ")", "{", "var", "color", "=", "parseColor", "(", "cValue", ")", ";", "if", "(", "query", ".", "_filter", "[", "0", "]", "===", "'h'", ")", "{", "cValue", "=", "color", "[", "0", "]", ";", "}", "else", "if", "(", "query", ".", "_filter", "[", "0", "]", "===", "'s'", ")", "{", "cValue", "=", "color", "[", "1", "]", ";", "}", "else", "if", "(", "query", ".", "_filter", "[", "0", "]", "===", "'l'", ")", "{", "cValue", "=", "color", "[", "2", "]", ";", "}", "else", "if", "(", "query", ".", "_filter", "[", "0", "]", "===", "'a'", ")", "{", "cValue", "=", "color", "[", "3", "]", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "if", "(", "query", ".", "_valueType", "===", "'c'", ")", "{", "cValue", "=", "parseColor", "(", "cValue", ")", ".", "join", "(", "','", ")", ";", "}", "else", "if", "(", "query", ".", "_valueType", "===", "'l'", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "qValues", ".", "length", ";", "i", "++", ")", "{", "qValues", "[", "i", "]", "=", "getComputedLength", "(", "qValues", "[", "i", "]", ",", "parent", ")", ";", "}", "if", "(", "typeof", "cValue", "===", "'string'", ")", "{", "cValue", "=", "getComputedLength", "(", "cValue", ",", "parent", ")", ";", "}", "}", "else", "if", "(", "query", ".", "_valueType", "===", "'n'", ")", "{", "cValue", "=", "parseFloat", "(", "cValue", ")", ";", "}", "else", "if", "(", "typeof", "cValue", "===", "'string'", ")", "{", "cValue", "=", "cValue", ".", "trim", "(", ")", ";", "}", "if", "(", "(", "query", ".", "_types", "[", "0", "]", "[", "0", "]", "===", "'>'", "||", "query", ".", "_types", "[", "0", "]", "[", "0", "]", "===", "'<'", ")", "&&", "(", "typeof", "cValue", "!==", "'number'", "||", "typeof", "qValues", "[", "0", "]", "!==", "'number'", ")", ")", "{", "return", "false", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "qValues", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "(", "(", "query", ".", "_types", "[", "i", "]", "===", "'>='", "&&", "cValue", ">=", "qValues", "[", "i", "]", ")", "||", "(", "query", ".", "_types", "[", "i", "]", "===", "'<='", "&&", "cValue", "<=", "qValues", "[", "i", "]", ")", "||", "(", "query", ".", "_types", "[", "i", "]", "===", "'>'", "&&", "cValue", ">", "qValues", "[", "i", "]", ")", "||", "(", "query", ".", "_types", "[", "i", "]", "===", "'<'", "&&", "cValue", "<", "qValues", "[", "i", "]", ")", "||", "(", "query", ".", "_types", "[", "i", "]", "===", "'='", "&&", "cValue", "===", "qValues", "[", "i", "]", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
True if the query matches otherwise false @param {Element} parent @param {object} query @return {boolean}
[ "True", "if", "the", "query", "matches", "otherwise", "false" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L900-L974
16,064
ausi/cq-prolyfill
cq-prolyfill.js
getContainer
function getContainer(element, prop) { var cache; if (containerCache.has(element)) { cache = containerCache.get(element); if (cache[prop]) { return cache[prop]; } } else { cache = {}; containerCache.set(element, cache); } if (element === documentElement) { cache[prop] = element; } else if (prop !== 'width' && prop !== 'height') { // Skip transparent background colors if (prop === 'background-color' && !parseColor(getComputedStyle(element).getPropertyValue(prop))[3]) { cache[prop] = getContainer(element.parentNode, prop); } else { cache[prop] = element; } } // Skip inline elements else if (getComputedStyle(element).display === 'inline') { cache[prop] = getContainer(element.parentNode, prop); } else if (isFixedSize(element, prop)) { cache[prop] = element; } else { var parentNode = element.parentNode; // Skip to next positioned ancestor for absolute positioned elements if (getComputedStyle(element).position === 'absolute') { while ( parentNode.parentNode && parentNode.parentNode.nodeType === 1 && ['relative', 'absolute'].indexOf(getComputedStyle(parentNode).position) === -1 ) { parentNode = parentNode.parentNode; } } // Skip to next ancestor with a transform applied for fixed positioned elements if (getComputedStyle(element).position === 'fixed') { while ( parentNode.parentNode && parentNode.parentNode.nodeType === 1 && [undefined, 'none'].indexOf( getComputedStyle(parentNode).transform || getComputedStyle(parentNode).MsTransform || getComputedStyle(parentNode).WebkitTransform ) !== -1 ) { parentNode = parentNode.parentNode; } } var parentContainer = getContainer(parentNode, prop); while (getComputedStyle(parentNode).display === 'inline') { parentNode = parentNode.parentNode; } if (parentNode === parentContainer && !isIntrinsicSize(element, prop)) { cache[prop] = element; } else { cache[prop] = parentContainer; } } return cache[prop]; }
javascript
function getContainer(element, prop) { var cache; if (containerCache.has(element)) { cache = containerCache.get(element); if (cache[prop]) { return cache[prop]; } } else { cache = {}; containerCache.set(element, cache); } if (element === documentElement) { cache[prop] = element; } else if (prop !== 'width' && prop !== 'height') { // Skip transparent background colors if (prop === 'background-color' && !parseColor(getComputedStyle(element).getPropertyValue(prop))[3]) { cache[prop] = getContainer(element.parentNode, prop); } else { cache[prop] = element; } } // Skip inline elements else if (getComputedStyle(element).display === 'inline') { cache[prop] = getContainer(element.parentNode, prop); } else if (isFixedSize(element, prop)) { cache[prop] = element; } else { var parentNode = element.parentNode; // Skip to next positioned ancestor for absolute positioned elements if (getComputedStyle(element).position === 'absolute') { while ( parentNode.parentNode && parentNode.parentNode.nodeType === 1 && ['relative', 'absolute'].indexOf(getComputedStyle(parentNode).position) === -1 ) { parentNode = parentNode.parentNode; } } // Skip to next ancestor with a transform applied for fixed positioned elements if (getComputedStyle(element).position === 'fixed') { while ( parentNode.parentNode && parentNode.parentNode.nodeType === 1 && [undefined, 'none'].indexOf( getComputedStyle(parentNode).transform || getComputedStyle(parentNode).MsTransform || getComputedStyle(parentNode).WebkitTransform ) !== -1 ) { parentNode = parentNode.parentNode; } } var parentContainer = getContainer(parentNode, prop); while (getComputedStyle(parentNode).display === 'inline') { parentNode = parentNode.parentNode; } if (parentNode === parentContainer && !isIntrinsicSize(element, prop)) { cache[prop] = element; } else { cache[prop] = parentContainer; } } return cache[prop]; }
[ "function", "getContainer", "(", "element", ",", "prop", ")", "{", "var", "cache", ";", "if", "(", "containerCache", ".", "has", "(", "element", ")", ")", "{", "cache", "=", "containerCache", ".", "get", "(", "element", ")", ";", "if", "(", "cache", "[", "prop", "]", ")", "{", "return", "cache", "[", "prop", "]", ";", "}", "}", "else", "{", "cache", "=", "{", "}", ";", "containerCache", ".", "set", "(", "element", ",", "cache", ")", ";", "}", "if", "(", "element", "===", "documentElement", ")", "{", "cache", "[", "prop", "]", "=", "element", ";", "}", "else", "if", "(", "prop", "!==", "'width'", "&&", "prop", "!==", "'height'", ")", "{", "// Skip transparent background colors", "if", "(", "prop", "===", "'background-color'", "&&", "!", "parseColor", "(", "getComputedStyle", "(", "element", ")", ".", "getPropertyValue", "(", "prop", ")", ")", "[", "3", "]", ")", "{", "cache", "[", "prop", "]", "=", "getContainer", "(", "element", ".", "parentNode", ",", "prop", ")", ";", "}", "else", "{", "cache", "[", "prop", "]", "=", "element", ";", "}", "}", "// Skip inline elements", "else", "if", "(", "getComputedStyle", "(", "element", ")", ".", "display", "===", "'inline'", ")", "{", "cache", "[", "prop", "]", "=", "getContainer", "(", "element", ".", "parentNode", ",", "prop", ")", ";", "}", "else", "if", "(", "isFixedSize", "(", "element", ",", "prop", ")", ")", "{", "cache", "[", "prop", "]", "=", "element", ";", "}", "else", "{", "var", "parentNode", "=", "element", ".", "parentNode", ";", "// Skip to next positioned ancestor for absolute positioned elements", "if", "(", "getComputedStyle", "(", "element", ")", ".", "position", "===", "'absolute'", ")", "{", "while", "(", "parentNode", ".", "parentNode", "&&", "parentNode", ".", "parentNode", ".", "nodeType", "===", "1", "&&", "[", "'relative'", ",", "'absolute'", "]", ".", "indexOf", "(", "getComputedStyle", "(", "parentNode", ")", ".", "position", ")", "===", "-", "1", ")", "{", "parentNode", "=", "parentNode", ".", "parentNode", ";", "}", "}", "// Skip to next ancestor with a transform applied for fixed positioned elements", "if", "(", "getComputedStyle", "(", "element", ")", ".", "position", "===", "'fixed'", ")", "{", "while", "(", "parentNode", ".", "parentNode", "&&", "parentNode", ".", "parentNode", ".", "nodeType", "===", "1", "&&", "[", "undefined", ",", "'none'", "]", ".", "indexOf", "(", "getComputedStyle", "(", "parentNode", ")", ".", "transform", "||", "getComputedStyle", "(", "parentNode", ")", ".", "MsTransform", "||", "getComputedStyle", "(", "parentNode", ")", ".", "WebkitTransform", ")", "!==", "-", "1", ")", "{", "parentNode", "=", "parentNode", ".", "parentNode", ";", "}", "}", "var", "parentContainer", "=", "getContainer", "(", "parentNode", ",", "prop", ")", ";", "while", "(", "getComputedStyle", "(", "parentNode", ")", ".", "display", "===", "'inline'", ")", "{", "parentNode", "=", "parentNode", ".", "parentNode", ";", "}", "if", "(", "parentNode", "===", "parentContainer", "&&", "!", "isIntrinsicSize", "(", "element", ",", "prop", ")", ")", "{", "cache", "[", "prop", "]", "=", "element", ";", "}", "else", "{", "cache", "[", "prop", "]", "=", "parentContainer", ";", "}", "}", "return", "cache", "[", "prop", "]", ";", "}" ]
Get the nearest qualified container element starting by the element itself @param {Element} element @param {string} prop CSS property @return {Element}
[ "Get", "the", "nearest", "qualified", "container", "element", "starting", "by", "the", "element", "itself" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L983-L1064
16,065
ausi/cq-prolyfill
cq-prolyfill.js
isIntrinsicSize
function isIntrinsicSize(element, prop) { var computedStyle = getComputedStyle(element); if (computedStyle.display === 'none') { return false; } if (computedStyle.display === 'inline') { return true; } // Non-floating non-absolute block elements (only width) if ( prop === 'width' && ['block', 'list-item', 'flex', 'grid'].indexOf(computedStyle.display) !== -1 && computedStyle.cssFloat === 'none' && computedStyle.position !== 'absolute' && computedStyle.position !== 'fixed' ) { return false; } var originalStyle = getOriginalStyle(element, prop); // Fixed size if (originalStyle && originalStyle.match(LENGTH_REGEXP)) { return false; } // Percentage size if (originalStyle && originalStyle.substr(-1) === '%') { return false; } // Calc expression if (originalStyle && originalStyle.substr(0, 5) === 'calc(') { return false; } // Elements without a defined size return true; }
javascript
function isIntrinsicSize(element, prop) { var computedStyle = getComputedStyle(element); if (computedStyle.display === 'none') { return false; } if (computedStyle.display === 'inline') { return true; } // Non-floating non-absolute block elements (only width) if ( prop === 'width' && ['block', 'list-item', 'flex', 'grid'].indexOf(computedStyle.display) !== -1 && computedStyle.cssFloat === 'none' && computedStyle.position !== 'absolute' && computedStyle.position !== 'fixed' ) { return false; } var originalStyle = getOriginalStyle(element, prop); // Fixed size if (originalStyle && originalStyle.match(LENGTH_REGEXP)) { return false; } // Percentage size if (originalStyle && originalStyle.substr(-1) === '%') { return false; } // Calc expression if (originalStyle && originalStyle.substr(0, 5) === 'calc(') { return false; } // Elements without a defined size return true; }
[ "function", "isIntrinsicSize", "(", "element", ",", "prop", ")", "{", "var", "computedStyle", "=", "getComputedStyle", "(", "element", ")", ";", "if", "(", "computedStyle", ".", "display", "===", "'none'", ")", "{", "return", "false", ";", "}", "if", "(", "computedStyle", ".", "display", "===", "'inline'", ")", "{", "return", "true", ";", "}", "// Non-floating non-absolute block elements (only width)", "if", "(", "prop", "===", "'width'", "&&", "[", "'block'", ",", "'list-item'", ",", "'flex'", ",", "'grid'", "]", ".", "indexOf", "(", "computedStyle", ".", "display", ")", "!==", "-", "1", "&&", "computedStyle", ".", "cssFloat", "===", "'none'", "&&", "computedStyle", ".", "position", "!==", "'absolute'", "&&", "computedStyle", ".", "position", "!==", "'fixed'", ")", "{", "return", "false", ";", "}", "var", "originalStyle", "=", "getOriginalStyle", "(", "element", ",", "prop", ")", ";", "// Fixed size", "if", "(", "originalStyle", "&&", "originalStyle", ".", "match", "(", "LENGTH_REGEXP", ")", ")", "{", "return", "false", ";", "}", "// Percentage size", "if", "(", "originalStyle", "&&", "originalStyle", ".", "substr", "(", "-", "1", ")", "===", "'%'", ")", "{", "return", "false", ";", "}", "// Calc expression", "if", "(", "originalStyle", "&&", "originalStyle", ".", "substr", "(", "0", ",", "5", ")", "===", "'calc('", ")", "{", "return", "false", ";", "}", "// Elements without a defined size", "return", "true", ";", "}" ]
Is the size of the element depending on its descendants? @param {Element} element @param {string} prop `width` or `height` @return {boolean}
[ "Is", "the", "size", "of", "the", "element", "depending", "on", "its", "descendants?" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1091-L1134
16,066
ausi/cq-prolyfill
cq-prolyfill.js
getSize
function getSize(element, prop) { var style = getComputedStyle(element); if (prop === 'width') { return element.offsetWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.paddingLeft) - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight); } else { return element.offsetHeight - parseFloat(style.borderTopWidth) - parseFloat(style.paddingTop) - parseFloat(style.borderBottomWidth) - parseFloat(style.paddingBottom); } }
javascript
function getSize(element, prop) { var style = getComputedStyle(element); if (prop === 'width') { return element.offsetWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.paddingLeft) - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight); } else { return element.offsetHeight - parseFloat(style.borderTopWidth) - parseFloat(style.paddingTop) - parseFloat(style.borderBottomWidth) - parseFloat(style.paddingBottom); } }
[ "function", "getSize", "(", "element", ",", "prop", ")", "{", "var", "style", "=", "getComputedStyle", "(", "element", ")", ";", "if", "(", "prop", "===", "'width'", ")", "{", "return", "element", ".", "offsetWidth", "-", "parseFloat", "(", "style", ".", "borderLeftWidth", ")", "-", "parseFloat", "(", "style", ".", "paddingLeft", ")", "-", "parseFloat", "(", "style", ".", "borderRightWidth", ")", "-", "parseFloat", "(", "style", ".", "paddingRight", ")", ";", "}", "else", "{", "return", "element", ".", "offsetHeight", "-", "parseFloat", "(", "style", ".", "borderTopWidth", ")", "-", "parseFloat", "(", "style", ".", "paddingTop", ")", "-", "parseFloat", "(", "style", ".", "borderBottomWidth", ")", "-", "parseFloat", "(", "style", ".", "paddingBottom", ")", ";", "}", "}" ]
Get the computed content-box size @param {Element} element @param {string} prop `width` or `height` @return {number}
[ "Get", "the", "computed", "content", "-", "box", "size" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1143-L1159
16,067
ausi/cq-prolyfill
cq-prolyfill.js
getComputedLength
function getComputedLength(value, element) { var length = value.match(LENGTH_REGEXP); if (!length) { return parseFloat(value); } value = parseFloat(length[1]); var unit = length[2].toLowerCase(); if (FIXED_UNIT_MAP[unit]) { return value * FIXED_UNIT_MAP[unit]; } if (unit === 'vw') { return value * window.innerWidth / 100; } if (unit === 'vh') { return value * window.innerHeight / 100; } if (unit === 'vmin') { return value * Math.min(window.innerWidth, window.innerHeight) / 100; } if (unit === 'vmax') { return value * Math.max(window.innerWidth, window.innerHeight) / 100; } // em units if (unit === 'rem') { element = documentElement; } if (unit === 'ex') { value /= 2; } return parseFloat(getComputedStyle(element).fontSize) * value; }
javascript
function getComputedLength(value, element) { var length = value.match(LENGTH_REGEXP); if (!length) { return parseFloat(value); } value = parseFloat(length[1]); var unit = length[2].toLowerCase(); if (FIXED_UNIT_MAP[unit]) { return value * FIXED_UNIT_MAP[unit]; } if (unit === 'vw') { return value * window.innerWidth / 100; } if (unit === 'vh') { return value * window.innerHeight / 100; } if (unit === 'vmin') { return value * Math.min(window.innerWidth, window.innerHeight) / 100; } if (unit === 'vmax') { return value * Math.max(window.innerWidth, window.innerHeight) / 100; } // em units if (unit === 'rem') { element = documentElement; } if (unit === 'ex') { value /= 2; } return parseFloat(getComputedStyle(element).fontSize) * value; }
[ "function", "getComputedLength", "(", "value", ",", "element", ")", "{", "var", "length", "=", "value", ".", "match", "(", "LENGTH_REGEXP", ")", ";", "if", "(", "!", "length", ")", "{", "return", "parseFloat", "(", "value", ")", ";", "}", "value", "=", "parseFloat", "(", "length", "[", "1", "]", ")", ";", "var", "unit", "=", "length", "[", "2", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "FIXED_UNIT_MAP", "[", "unit", "]", ")", "{", "return", "value", "*", "FIXED_UNIT_MAP", "[", "unit", "]", ";", "}", "if", "(", "unit", "===", "'vw'", ")", "{", "return", "value", "*", "window", ".", "innerWidth", "/", "100", ";", "}", "if", "(", "unit", "===", "'vh'", ")", "{", "return", "value", "*", "window", ".", "innerHeight", "/", "100", ";", "}", "if", "(", "unit", "===", "'vmin'", ")", "{", "return", "value", "*", "Math", ".", "min", "(", "window", ".", "innerWidth", ",", "window", ".", "innerHeight", ")", "/", "100", ";", "}", "if", "(", "unit", "===", "'vmax'", ")", "{", "return", "value", "*", "Math", ".", "max", "(", "window", ".", "innerWidth", ",", "window", ".", "innerHeight", ")", "/", "100", ";", "}", "// em units", "if", "(", "unit", "===", "'rem'", ")", "{", "element", "=", "documentElement", ";", "}", "if", "(", "unit", "===", "'ex'", ")", "{", "value", "/=", "2", ";", "}", "return", "parseFloat", "(", "getComputedStyle", "(", "element", ")", ".", "fontSize", ")", "*", "value", ";", "}" ]
Get the computed length in pixel of a CSS length value @param {string} value @param {Element} element @return {number}
[ "Get", "the", "computed", "length", "in", "pixel", "of", "a", "CSS", "length", "value" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1168-L1198
16,068
ausi/cq-prolyfill
cq-prolyfill.js
getOriginalStyle
function getOriginalStyle(element, prop) { var matchedRules = []; var value; var j; matchedRules = sortRulesBySpecificity( filterRulesByElementAndProp(styleCache[prop], element, prop) ); // Add style attribute matchedRules.unshift({ _rule: { style: element.style, }, }); // Loop through all important styles for (j = 0; j < matchedRules.length; j++) { if ( (value = matchedRules[j]._rule.style.getPropertyValue(prop)) && matchedRules[j]._rule.style.getPropertyPriority(prop) === 'important' ) { return value; } } // Loop through all non-important styles for (j = 0; j < matchedRules.length; j++) { if ( (value = matchedRules[j]._rule.style.getPropertyValue(prop)) && matchedRules[j]._rule.style.getPropertyPriority(prop) !== 'important' ) { return value; } } return undefined; }
javascript
function getOriginalStyle(element, prop) { var matchedRules = []; var value; var j; matchedRules = sortRulesBySpecificity( filterRulesByElementAndProp(styleCache[prop], element, prop) ); // Add style attribute matchedRules.unshift({ _rule: { style: element.style, }, }); // Loop through all important styles for (j = 0; j < matchedRules.length; j++) { if ( (value = matchedRules[j]._rule.style.getPropertyValue(prop)) && matchedRules[j]._rule.style.getPropertyPriority(prop) === 'important' ) { return value; } } // Loop through all non-important styles for (j = 0; j < matchedRules.length; j++) { if ( (value = matchedRules[j]._rule.style.getPropertyValue(prop)) && matchedRules[j]._rule.style.getPropertyPriority(prop) !== 'important' ) { return value; } } return undefined; }
[ "function", "getOriginalStyle", "(", "element", ",", "prop", ")", "{", "var", "matchedRules", "=", "[", "]", ";", "var", "value", ";", "var", "j", ";", "matchedRules", "=", "sortRulesBySpecificity", "(", "filterRulesByElementAndProp", "(", "styleCache", "[", "prop", "]", ",", "element", ",", "prop", ")", ")", ";", "// Add style attribute", "matchedRules", ".", "unshift", "(", "{", "_rule", ":", "{", "style", ":", "element", ".", "style", ",", "}", ",", "}", ")", ";", "// Loop through all important styles", "for", "(", "j", "=", "0", ";", "j", "<", "matchedRules", ".", "length", ";", "j", "++", ")", "{", "if", "(", "(", "value", "=", "matchedRules", "[", "j", "]", ".", "_rule", ".", "style", ".", "getPropertyValue", "(", "prop", ")", ")", "&&", "matchedRules", "[", "j", "]", ".", "_rule", ".", "style", ".", "getPropertyPriority", "(", "prop", ")", "===", "'important'", ")", "{", "return", "value", ";", "}", "}", "// Loop through all non-important styles", "for", "(", "j", "=", "0", ";", "j", "<", "matchedRules", ".", "length", ";", "j", "++", ")", "{", "if", "(", "(", "value", "=", "matchedRules", "[", "j", "]", ".", "_rule", ".", "style", ".", "getPropertyValue", "(", "prop", ")", ")", "&&", "matchedRules", "[", "j", "]", ".", "_rule", ".", "style", ".", "getPropertyPriority", "(", "prop", ")", "!==", "'important'", ")", "{", "return", "value", ";", "}", "}", "return", "undefined", ";", "}" ]
Get the original style of an element as it was specified in CSS @param {Element} element @param {string} prop Property to return, e.g. `width` or `height` @return {string}
[ "Get", "the", "original", "style", "of", "an", "element", "as", "it", "was", "specified", "in", "CSS" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1240-L1279
16,069
ausi/cq-prolyfill
cq-prolyfill.js
parseColor
function parseColor(color) { // Let the browser round the RGBA values for consistency parseColorStyle.cssText = 'color:' + color; color = parseColorStyle.color; if (!color || !color.split || !color.split('(')[1]) { return [0, 0, 0, 0]; } color = color.split('(')[1].split(',').map(parseFloat); if (color[3] === undefined) { color[3] = 1; } else if (!color[3]) { color[0] = color[1] = color[2] = 0; } color[3] = Math.round(color[3] * 255); return rgbaToHsla(color); }
javascript
function parseColor(color) { // Let the browser round the RGBA values for consistency parseColorStyle.cssText = 'color:' + color; color = parseColorStyle.color; if (!color || !color.split || !color.split('(')[1]) { return [0, 0, 0, 0]; } color = color.split('(')[1].split(',').map(parseFloat); if (color[3] === undefined) { color[3] = 1; } else if (!color[3]) { color[0] = color[1] = color[2] = 0; } color[3] = Math.round(color[3] * 255); return rgbaToHsla(color); }
[ "function", "parseColor", "(", "color", ")", "{", "// Let the browser round the RGBA values for consistency", "parseColorStyle", ".", "cssText", "=", "'color:'", "+", "color", ";", "color", "=", "parseColorStyle", ".", "color", ";", "if", "(", "!", "color", "||", "!", "color", ".", "split", "||", "!", "color", ".", "split", "(", "'('", ")", "[", "1", "]", ")", "{", "return", "[", "0", ",", "0", ",", "0", ",", "0", "]", ";", "}", "color", "=", "color", ".", "split", "(", "'('", ")", "[", "1", "]", ".", "split", "(", "','", ")", ".", "map", "(", "parseFloat", ")", ";", "if", "(", "color", "[", "3", "]", "===", "undefined", ")", "{", "color", "[", "3", "]", "=", "1", ";", "}", "else", "if", "(", "!", "color", "[", "3", "]", ")", "{", "color", "[", "0", "]", "=", "color", "[", "1", "]", "=", "color", "[", "2", "]", "=", "0", ";", "}", "color", "[", "3", "]", "=", "Math", ".", "round", "(", "color", "[", "3", "]", "*", "255", ")", ";", "return", "rgbaToHsla", "(", "color", ")", ";", "}" ]
Parse CSS color and return as HSLA array @param {string} color @return {Array.<number>}
[ "Parse", "CSS", "color", "and", "return", "as", "HSLA", "array" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1292-L1315
16,070
ausi/cq-prolyfill
cq-prolyfill.js
filterRulesByElementAndProp
function filterRulesByElementAndProp(rules, element, prop) { var foundRules = []; if (element.id) { foundRules = foundRules.concat(rules['#' + element.id] || []); } (element.getAttribute('class') || '').split(/\s+/).forEach(function(className) { foundRules = foundRules.concat(rules['.' + className] || []); }); foundRules = foundRules .concat(rules[element.tagName.toLowerCase()] || []) .concat(rules['*'] || []); return foundRules.filter(function(rule) { return rule._rule.style.getPropertyValue(prop) && ( !rule._rule.parentRule || rule._rule.parentRule.type !== 4 // @media rule || matchesMedia(rule._rule.parentRule.media.mediaText) ) && elementMatchesSelector(element, rule._selector); }); }
javascript
function filterRulesByElementAndProp(rules, element, prop) { var foundRules = []; if (element.id) { foundRules = foundRules.concat(rules['#' + element.id] || []); } (element.getAttribute('class') || '').split(/\s+/).forEach(function(className) { foundRules = foundRules.concat(rules['.' + className] || []); }); foundRules = foundRules .concat(rules[element.tagName.toLowerCase()] || []) .concat(rules['*'] || []); return foundRules.filter(function(rule) { return rule._rule.style.getPropertyValue(prop) && ( !rule._rule.parentRule || rule._rule.parentRule.type !== 4 // @media rule || matchesMedia(rule._rule.parentRule.media.mediaText) ) && elementMatchesSelector(element, rule._selector); }); }
[ "function", "filterRulesByElementAndProp", "(", "rules", ",", "element", ",", "prop", ")", "{", "var", "foundRules", "=", "[", "]", ";", "if", "(", "element", ".", "id", ")", "{", "foundRules", "=", "foundRules", ".", "concat", "(", "rules", "[", "'#'", "+", "element", ".", "id", "]", "||", "[", "]", ")", ";", "}", "(", "element", ".", "getAttribute", "(", "'class'", ")", "||", "''", ")", ".", "split", "(", "/", "\\s+", "/", ")", ".", "forEach", "(", "function", "(", "className", ")", "{", "foundRules", "=", "foundRules", ".", "concat", "(", "rules", "[", "'.'", "+", "className", "]", "||", "[", "]", ")", ";", "}", ")", ";", "foundRules", "=", "foundRules", ".", "concat", "(", "rules", "[", "element", ".", "tagName", ".", "toLowerCase", "(", ")", "]", "||", "[", "]", ")", ".", "concat", "(", "rules", "[", "'*'", "]", "||", "[", "]", ")", ";", "return", "foundRules", ".", "filter", "(", "function", "(", "rule", ")", "{", "return", "rule", ".", "_rule", ".", "style", ".", "getPropertyValue", "(", "prop", ")", "&&", "(", "!", "rule", ".", "_rule", ".", "parentRule", "||", "rule", ".", "_rule", ".", "parentRule", ".", "type", "!==", "4", "// @media rule", "||", "matchesMedia", "(", "rule", ".", "_rule", ".", "parentRule", ".", "media", ".", "mediaText", ")", ")", "&&", "elementMatchesSelector", "(", "element", ",", "rule", ".", "_selector", ")", ";", "}", ")", ";", "}" ]
Filter rules by matching the element and at least one property @param {{<string>: Array.<{_selector: string, _rule: CSSRule}>}} rules @param {Element} element @param {string} prop @return {Array.<{_selector: string, _rule: CSSRule}>}
[ "Filter", "rules", "by", "matching", "the", "element", "and", "at", "least", "one", "property" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1362-L1382
16,071
ausi/cq-prolyfill
cq-prolyfill.js
createCacheMap
function createCacheMap() { if (typeof Map === 'function') { return new Map(); } var keys = []; var values = []; function getIndex(key) { return keys.indexOf(key); } function get(key) { return values[getIndex(key)]; } function has(key) { return getIndex(key) !== -1; } function set(key, value) { var index = getIndex(key); if (index === -1) { index = keys.push(key) - 1; } values[index] = value; } function deleteFunc(key) { var index = getIndex(key); if (index === -1) { return false; } delete keys[index]; delete values[index]; return true; } function forEach(callback) { keys.forEach(function(key, index) { if (key !== undefined) { callback(values[index], key); } }); } return { set: set, get: get, has: has, delete: deleteFunc, forEach: forEach, }; }
javascript
function createCacheMap() { if (typeof Map === 'function') { return new Map(); } var keys = []; var values = []; function getIndex(key) { return keys.indexOf(key); } function get(key) { return values[getIndex(key)]; } function has(key) { return getIndex(key) !== -1; } function set(key, value) { var index = getIndex(key); if (index === -1) { index = keys.push(key) - 1; } values[index] = value; } function deleteFunc(key) { var index = getIndex(key); if (index === -1) { return false; } delete keys[index]; delete values[index]; return true; } function forEach(callback) { keys.forEach(function(key, index) { if (key !== undefined) { callback(values[index], key); } }); } return { set: set, get: get, has: has, delete: deleteFunc, forEach: forEach, }; }
[ "function", "createCacheMap", "(", ")", "{", "if", "(", "typeof", "Map", "===", "'function'", ")", "{", "return", "new", "Map", "(", ")", ";", "}", "var", "keys", "=", "[", "]", ";", "var", "values", "=", "[", "]", ";", "function", "getIndex", "(", "key", ")", "{", "return", "keys", ".", "indexOf", "(", "key", ")", ";", "}", "function", "get", "(", "key", ")", "{", "return", "values", "[", "getIndex", "(", "key", ")", "]", ";", "}", "function", "has", "(", "key", ")", "{", "return", "getIndex", "(", "key", ")", "!==", "-", "1", ";", "}", "function", "set", "(", "key", ",", "value", ")", "{", "var", "index", "=", "getIndex", "(", "key", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "index", "=", "keys", ".", "push", "(", "key", ")", "-", "1", ";", "}", "values", "[", "index", "]", "=", "value", ";", "}", "function", "deleteFunc", "(", "key", ")", "{", "var", "index", "=", "getIndex", "(", "key", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "return", "false", ";", "}", "delete", "keys", "[", "index", "]", ";", "delete", "values", "[", "index", "]", ";", "return", "true", ";", "}", "function", "forEach", "(", "callback", ")", "{", "keys", ".", "forEach", "(", "function", "(", "key", ",", "index", ")", "{", "if", "(", "key", "!==", "undefined", ")", "{", "callback", "(", "values", "[", "index", "]", ",", "key", ")", ";", "}", "}", ")", ";", "}", "return", "{", "set", ":", "set", ",", "get", ":", "get", ",", "has", ":", "has", ",", "delete", ":", "deleteFunc", ",", "forEach", ":", "forEach", ",", "}", ";", "}" ]
Create a new Map or a simple shim of it in non-supporting browsers @return {Map}
[ "Create", "a", "new", "Map", "or", "a", "simple", "shim", "of", "it", "in", "non", "-", "supporting", "browsers" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1478-L1532
16,072
ausi/cq-prolyfill
cq-prolyfill.js
arrayFrom
function arrayFrom(arrayLike) { if (Array.from) { return Array.from(arrayLike); } var array = []; for (var i = 0; i < arrayLike.length; i++) { array[i] = arrayLike[i]; } return array; }
javascript
function arrayFrom(arrayLike) { if (Array.from) { return Array.from(arrayLike); } var array = []; for (var i = 0; i < arrayLike.length; i++) { array[i] = arrayLike[i]; } return array; }
[ "function", "arrayFrom", "(", "arrayLike", ")", "{", "if", "(", "Array", ".", "from", ")", "{", "return", "Array", ".", "from", "(", "arrayLike", ")", ";", "}", "var", "array", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arrayLike", ".", "length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "arrayLike", "[", "i", "]", ";", "}", "return", "array", ";", "}" ]
Array.from or a simple shim for non-supporting browsers @param {{length: number}} arrayLike @return {array}
[ "Array", ".", "from", "or", "a", "simple", "shim", "for", "non", "-", "supporting", "browsers" ]
cc459daadb99a7a47377ca695d943100e3420b0a
https://github.com/ausi/cq-prolyfill/blob/cc459daadb99a7a47377ca695d943100e3420b0a/cq-prolyfill.js#L1667-L1676
16,073
anvaka/ngraph.graph
index.js
indexOfElementInArray
function indexOfElementInArray(element, array) { if (!array) return -1; if (array.indexOf) { return array.indexOf(element); } var len = array.length, i; for (i = 0; i < len; i += 1) { if (array[i] === element) { return i; } } return -1; }
javascript
function indexOfElementInArray(element, array) { if (!array) return -1; if (array.indexOf) { return array.indexOf(element); } var len = array.length, i; for (i = 0; i < len; i += 1) { if (array[i] === element) { return i; } } return -1; }
[ "function", "indexOfElementInArray", "(", "element", ",", "array", ")", "{", "if", "(", "!", "array", ")", "return", "-", "1", ";", "if", "(", "array", ".", "indexOf", ")", "{", "return", "array", ".", "indexOf", "(", "element", ")", ";", "}", "var", "len", "=", "array", ".", "length", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "if", "(", "array", "[", "i", "]", "===", "element", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
need this for old browsers. Should this be a separate module?
[ "need", "this", "for", "old", "browsers", ".", "Should", "this", "be", "a", "separate", "module?" ]
22f34d2624cbffd70660bc40a9629809ecc5d573
https://github.com/anvaka/ngraph.graph/blob/22f34d2624cbffd70660bc40a9629809ecc5d573/index.js#L542-L559
16,074
anvaka/ngraph.graph
index.js
Link
function Link(fromId, toId, data, id) { this.fromId = fromId; this.toId = toId; this.data = data; this.id = id; }
javascript
function Link(fromId, toId, data, id) { this.fromId = fromId; this.toId = toId; this.data = data; this.id = id; }
[ "function", "Link", "(", "fromId", ",", "toId", ",", "data", ",", "id", ")", "{", "this", ".", "fromId", "=", "fromId", ";", "this", ".", "toId", "=", "toId", ";", "this", ".", "data", "=", "data", ";", "this", ".", "id", "=", "id", ";", "}" ]
Internal structure to represent links;
[ "Internal", "structure", "to", "represent", "links", ";" ]
22f34d2624cbffd70660bc40a9629809ecc5d573
https://github.com/anvaka/ngraph.graph/blob/22f34d2624cbffd70660bc40a9629809ecc5d573/index.js#L581-L586
16,075
cscott/compressjs
lib/Bzip2.js
function(freq, alphabetSize) { // As in BZip2HuffmanStageEncoder.java (from jbzip2): // The Huffman allocator needs its input symbol frequencies to be // sorted, but we need to return code lengths in the same order as // the corresponding frequencies are passed in. // The symbol frequency and index are merged into a single array of // integers - frequency in the high 23 bits, index in the low 9 // bits. // 2^23 = 8,388,608 which is higher than the maximum possible // frequency for one symbol in a block // 2^9 = 512 which is higher than the maximum possible // alphabet size (== 258) // Sorting this array simultaneously sorts the frequencies and // leaves a lookup that can be used to cheaply invert the sort var i, mergedFreq = []; for (i=0; i<alphabetSize; i++) { mergedFreq[i] = (freq[i] << 9) | i; } mergedFreq.sort(function(a,b) { return a-b; }); var sortedFreq = mergedFreq.map(function(v) { return v>>>9; }); // allocate code lengths in place. (result in sortedFreq array) HuffmanAllocator.allocateHuffmanCodeLengths(sortedFreq, MAX_HUFCODE_BITS); // reverse the sort to put codes & code lengths in order of input symbols this.codeLengths = Util.makeU8Buffer(alphabetSize); for (i=0; i<alphabetSize; i++) { var sym = mergedFreq[i] & 0x1FF; this.codeLengths[sym] = sortedFreq[i]; } }
javascript
function(freq, alphabetSize) { // As in BZip2HuffmanStageEncoder.java (from jbzip2): // The Huffman allocator needs its input symbol frequencies to be // sorted, but we need to return code lengths in the same order as // the corresponding frequencies are passed in. // The symbol frequency and index are merged into a single array of // integers - frequency in the high 23 bits, index in the low 9 // bits. // 2^23 = 8,388,608 which is higher than the maximum possible // frequency for one symbol in a block // 2^9 = 512 which is higher than the maximum possible // alphabet size (== 258) // Sorting this array simultaneously sorts the frequencies and // leaves a lookup that can be used to cheaply invert the sort var i, mergedFreq = []; for (i=0; i<alphabetSize; i++) { mergedFreq[i] = (freq[i] << 9) | i; } mergedFreq.sort(function(a,b) { return a-b; }); var sortedFreq = mergedFreq.map(function(v) { return v>>>9; }); // allocate code lengths in place. (result in sortedFreq array) HuffmanAllocator.allocateHuffmanCodeLengths(sortedFreq, MAX_HUFCODE_BITS); // reverse the sort to put codes & code lengths in order of input symbols this.codeLengths = Util.makeU8Buffer(alphabetSize); for (i=0; i<alphabetSize; i++) { var sym = mergedFreq[i] & 0x1FF; this.codeLengths[sym] = sortedFreq[i]; } }
[ "function", "(", "freq", ",", "alphabetSize", ")", "{", "// As in BZip2HuffmanStageEncoder.java (from jbzip2):", "// The Huffman allocator needs its input symbol frequencies to be", "// sorted, but we need to return code lengths in the same order as", "// the corresponding frequencies are passed in.", "// The symbol frequency and index are merged into a single array of", "// integers - frequency in the high 23 bits, index in the low 9", "// bits.", "// 2^23 = 8,388,608 which is higher than the maximum possible", "// frequency for one symbol in a block", "// 2^9 = 512 which is higher than the maximum possible", "// alphabet size (== 258)", "// Sorting this array simultaneously sorts the frequencies and", "// leaves a lookup that can be used to cheaply invert the sort", "var", "i", ",", "mergedFreq", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "alphabetSize", ";", "i", "++", ")", "{", "mergedFreq", "[", "i", "]", "=", "(", "freq", "[", "i", "]", "<<", "9", ")", "|", "i", ";", "}", "mergedFreq", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "var", "sortedFreq", "=", "mergedFreq", ".", "map", "(", "function", "(", "v", ")", "{", "return", "v", ">>>", "9", ";", "}", ")", ";", "// allocate code lengths in place. (result in sortedFreq array)", "HuffmanAllocator", ".", "allocateHuffmanCodeLengths", "(", "sortedFreq", ",", "MAX_HUFCODE_BITS", ")", ";", "// reverse the sort to put codes & code lengths in order of input symbols", "this", ".", "codeLengths", "=", "Util", ".", "makeU8Buffer", "(", "alphabetSize", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "alphabetSize", ";", "i", "++", ")", "{", "var", "sym", "=", "mergedFreq", "[", "i", "]", "&", "0x1FF", ";", "this", ".", "codeLengths", "[", "sym", "]", "=", "sortedFreq", "[", "i", "]", ";", "}", "}" ]
create a Huffman tree from the table of frequencies
[ "create", "a", "Huffman", "tree", "from", "the", "table", "of", "frequencies" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/Bzip2.js#L551-L579
16,076
cscott/compressjs
lib/Bzip2.js
function(inStream, block, length, crc) { var pos = 0; var lastChar = -1; var runLength = 0; while (pos < length) { if (runLength===4) { block[pos++] = 0; if (pos >= length) { break; } } var ch = inStream.readByte(); if (ch === EOF) { break; } crc.updateCRC(ch); if (ch !== lastChar) { lastChar = ch; runLength = 1; } else { runLength++; if (runLength > 4) { if (runLength < 256) { block[pos-1]++; continue; } else { runLength = 1; } } } block[pos++] = ch; } return pos; }
javascript
function(inStream, block, length, crc) { var pos = 0; var lastChar = -1; var runLength = 0; while (pos < length) { if (runLength===4) { block[pos++] = 0; if (pos >= length) { break; } } var ch = inStream.readByte(); if (ch === EOF) { break; } crc.updateCRC(ch); if (ch !== lastChar) { lastChar = ch; runLength = 1; } else { runLength++; if (runLength > 4) { if (runLength < 256) { block[pos-1]++; continue; } else { runLength = 1; } } } block[pos++] = ch; } return pos; }
[ "function", "(", "inStream", ",", "block", ",", "length", ",", "crc", ")", "{", "var", "pos", "=", "0", ";", "var", "lastChar", "=", "-", "1", ";", "var", "runLength", "=", "0", ";", "while", "(", "pos", "<", "length", ")", "{", "if", "(", "runLength", "===", "4", ")", "{", "block", "[", "pos", "++", "]", "=", "0", ";", "if", "(", "pos", ">=", "length", ")", "{", "break", ";", "}", "}", "var", "ch", "=", "inStream", ".", "readByte", "(", ")", ";", "if", "(", "ch", "===", "EOF", ")", "{", "break", ";", "}", "crc", ".", "updateCRC", "(", "ch", ")", ";", "if", "(", "ch", "!==", "lastChar", ")", "{", "lastChar", "=", "ch", ";", "runLength", "=", "1", ";", "}", "else", "{", "runLength", "++", ";", "if", "(", "runLength", ">", "4", ")", "{", "if", "(", "runLength", "<", "256", ")", "{", "block", "[", "pos", "-", "1", "]", "++", ";", "continue", ";", "}", "else", "{", "runLength", "=", "1", ";", "}", "}", "}", "block", "[", "pos", "++", "]", "=", "ch", ";", "}", "return", "pos", ";", "}" ]
read a block for bzip2 compression.
[ "read", "a", "block", "for", "bzip2", "compression", "." ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/Bzip2.js#L636-L667
16,077
cscott/compressjs
lib/Bzip2.js
function(selectors, groups, input) { var i, j, k; for (i=0, k=0; i<input.length; i+=GROUP_SIZE) { var groupSize = Math.min(GROUP_SIZE, input.length - i); var best = 0, bestCost = groups[0].cost(input, i, groupSize); for (j=1; j<groups.length; j++) { var groupCost = groups[j].cost(input, i, groupSize); if (groupCost < bestCost) { best = j; bestCost = groupCost; } } selectors[k++] = best; } }
javascript
function(selectors, groups, input) { var i, j, k; for (i=0, k=0; i<input.length; i+=GROUP_SIZE) { var groupSize = Math.min(GROUP_SIZE, input.length - i); var best = 0, bestCost = groups[0].cost(input, i, groupSize); for (j=1; j<groups.length; j++) { var groupCost = groups[j].cost(input, i, groupSize); if (groupCost < bestCost) { best = j; bestCost = groupCost; } } selectors[k++] = best; } }
[ "function", "(", "selectors", ",", "groups", ",", "input", ")", "{", "var", "i", ",", "j", ",", "k", ";", "for", "(", "i", "=", "0", ",", "k", "=", "0", ";", "i", "<", "input", ".", "length", ";", "i", "+=", "GROUP_SIZE", ")", "{", "var", "groupSize", "=", "Math", ".", "min", "(", "GROUP_SIZE", ",", "input", ".", "length", "-", "i", ")", ";", "var", "best", "=", "0", ",", "bestCost", "=", "groups", "[", "0", "]", ".", "cost", "(", "input", ",", "i", ",", "groupSize", ")", ";", "for", "(", "j", "=", "1", ";", "j", "<", "groups", ".", "length", ";", "j", "++", ")", "{", "var", "groupCost", "=", "groups", "[", "j", "]", ".", "cost", "(", "input", ",", "i", ",", "groupSize", ")", ";", "if", "(", "groupCost", "<", "bestCost", ")", "{", "best", "=", "j", ";", "bestCost", "=", "groupCost", ";", "}", "}", "selectors", "[", "k", "++", "]", "=", "best", ";", "}", "}" ]
divide the input into groups at most GROUP_SIZE symbols long. assign each group to the Huffman table which compresses it best.
[ "divide", "the", "input", "into", "groups", "at", "most", "GROUP_SIZE", "symbols", "long", ".", "assign", "each", "group", "to", "the", "Huffman", "table", "which", "compresses", "it", "best", "." ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/Bzip2.js#L671-L684
16,078
cscott/compressjs
lib/HuffmanAllocator.js
function(array) { var length = array.length; array[0] += array[1]; var headNode, tailNode, topNode, temp; for (headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) { if ((topNode >= length) || (array[headNode] < array[topNode])) { temp = array[headNode]; array[headNode++] = tailNode; } else { temp = array[topNode++]; } if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) { temp += array[headNode]; array[headNode++] = tailNode + length; } else { temp += array[topNode++]; } array[tailNode] = temp; } }
javascript
function(array) { var length = array.length; array[0] += array[1]; var headNode, tailNode, topNode, temp; for (headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) { if ((topNode >= length) || (array[headNode] < array[topNode])) { temp = array[headNode]; array[headNode++] = tailNode; } else { temp = array[topNode++]; } if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) { temp += array[headNode]; array[headNode++] = tailNode + length; } else { temp += array[topNode++]; } array[tailNode] = temp; } }
[ "function", "(", "array", ")", "{", "var", "length", "=", "array", ".", "length", ";", "array", "[", "0", "]", "+=", "array", "[", "1", "]", ";", "var", "headNode", ",", "tailNode", ",", "topNode", ",", "temp", ";", "for", "(", "headNode", "=", "0", ",", "tailNode", "=", "1", ",", "topNode", "=", "2", ";", "tailNode", "<", "(", "length", "-", "1", ")", ";", "tailNode", "++", ")", "{", "if", "(", "(", "topNode", ">=", "length", ")", "||", "(", "array", "[", "headNode", "]", "<", "array", "[", "topNode", "]", ")", ")", "{", "temp", "=", "array", "[", "headNode", "]", ";", "array", "[", "headNode", "++", "]", "=", "tailNode", ";", "}", "else", "{", "temp", "=", "array", "[", "topNode", "++", "]", ";", "}", "if", "(", "(", "topNode", ">=", "length", ")", "||", "(", "(", "headNode", "<", "tailNode", ")", "&&", "(", "array", "[", "headNode", "]", "<", "array", "[", "topNode", "]", ")", ")", ")", "{", "temp", "+=", "array", "[", "headNode", "]", ";", "array", "[", "headNode", "++", "]", "=", "tailNode", "+", "length", ";", "}", "else", "{", "temp", "+=", "array", "[", "topNode", "++", "]", ";", "}", "array", "[", "tailNode", "]", "=", "temp", ";", "}", "}" ]
Fills the code array with extended parent pointers @param array The code length array
[ "Fills", "the", "code", "array", "with", "extended", "parent", "pointers" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/HuffmanAllocator.js#L79-L105
16,079
cscott/compressjs
lib/HuffmanAllocator.js
function(array, maximumLength) { var currentNode = array.length - 2; var currentDepth; for (currentDepth = 1; (currentDepth < (maximumLength - 1)) && (currentNode > 1); currentDepth++) { currentNode = first (array, currentNode - 1, 0); } return currentNode; }
javascript
function(array, maximumLength) { var currentNode = array.length - 2; var currentDepth; for (currentDepth = 1; (currentDepth < (maximumLength - 1)) && (currentNode > 1); currentDepth++) { currentNode = first (array, currentNode - 1, 0); } return currentNode; }
[ "function", "(", "array", ",", "maximumLength", ")", "{", "var", "currentNode", "=", "array", ".", "length", "-", "2", ";", "var", "currentDepth", ";", "for", "(", "currentDepth", "=", "1", ";", "(", "currentDepth", "<", "(", "maximumLength", "-", "1", ")", ")", "&&", "(", "currentNode", ">", "1", ")", ";", "currentDepth", "++", ")", "{", "currentNode", "=", "first", "(", "array", ",", "currentNode", "-", "1", ",", "0", ")", ";", "}", "return", "currentNode", ";", "}" ]
Finds the number of nodes to relocate in order to achieve a given code length limit @param array The code length array @param maximumLength The maximum bit length for the generated codes @return The number of nodes to relocate
[ "Finds", "the", "number", "of", "nodes", "to", "relocate", "in", "order", "to", "achieve", "a", "given", "code", "length", "limit" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/HuffmanAllocator.js#L114-L124
16,080
cscott/compressjs
lib/HuffmanAllocator.js
function(array) { var firstNode = array.length - 2; var nextNode = array.length - 1; var currentDepth, availableNodes, lastNode, i; for (currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) { lastNode = firstNode; firstNode = first (array, lastNode - 1, 0); for (i = availableNodes - (lastNode - firstNode); i > 0; i--) { array[nextNode--] = currentDepth; } availableNodes = (lastNode - firstNode) << 1; } }
javascript
function(array) { var firstNode = array.length - 2; var nextNode = array.length - 1; var currentDepth, availableNodes, lastNode, i; for (currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) { lastNode = firstNode; firstNode = first (array, lastNode - 1, 0); for (i = availableNodes - (lastNode - firstNode); i > 0; i--) { array[nextNode--] = currentDepth; } availableNodes = (lastNode - firstNode) << 1; } }
[ "function", "(", "array", ")", "{", "var", "firstNode", "=", "array", ".", "length", "-", "2", ";", "var", "nextNode", "=", "array", ".", "length", "-", "1", ";", "var", "currentDepth", ",", "availableNodes", ",", "lastNode", ",", "i", ";", "for", "(", "currentDepth", "=", "1", ",", "availableNodes", "=", "2", ";", "availableNodes", ">", "0", ";", "currentDepth", "++", ")", "{", "lastNode", "=", "firstNode", ";", "firstNode", "=", "first", "(", "array", ",", "lastNode", "-", "1", ",", "0", ")", ";", "for", "(", "i", "=", "availableNodes", "-", "(", "lastNode", "-", "firstNode", ")", ";", "i", ">", "0", ";", "i", "--", ")", "{", "array", "[", "nextNode", "--", "]", "=", "currentDepth", ";", "}", "availableNodes", "=", "(", "lastNode", "-", "firstNode", ")", "<<", "1", ";", "}", "}" ]
A final allocation pass with no code length limit @param array The code length array
[ "A", "final", "allocation", "pass", "with", "no", "code", "length", "limit" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/HuffmanAllocator.js#L131-L148
16,081
cscott/compressjs
lib/HuffmanAllocator.js
function(array, nodesToMove, insertDepth) { var firstNode = array.length - 2; var nextNode = array.length - 1; var currentDepth = (insertDepth == 1) ? 2 : 1; var nodesLeftToMove = (insertDepth == 1) ? nodesToMove - 2 : nodesToMove; var availableNodes, lastNode, offset, i; for (availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) { lastNode = firstNode; firstNode = (firstNode <= nodesToMove) ? firstNode : first (array, lastNode - 1, nodesToMove); offset = 0; if (currentDepth >= insertDepth) { offset = Math.min (nodesLeftToMove, 1 << (currentDepth - insertDepth)); } else if (currentDepth == (insertDepth - 1)) { offset = 1; if ((array[firstNode]) == lastNode) { firstNode++; } } for (i = availableNodes - (lastNode - firstNode + offset); i > 0; i--) { array[nextNode--] = currentDepth; } nodesLeftToMove -= offset; availableNodes = (lastNode - firstNode + offset) << 1; } }
javascript
function(array, nodesToMove, insertDepth) { var firstNode = array.length - 2; var nextNode = array.length - 1; var currentDepth = (insertDepth == 1) ? 2 : 1; var nodesLeftToMove = (insertDepth == 1) ? nodesToMove - 2 : nodesToMove; var availableNodes, lastNode, offset, i; for (availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) { lastNode = firstNode; firstNode = (firstNode <= nodesToMove) ? firstNode : first (array, lastNode - 1, nodesToMove); offset = 0; if (currentDepth >= insertDepth) { offset = Math.min (nodesLeftToMove, 1 << (currentDepth - insertDepth)); } else if (currentDepth == (insertDepth - 1)) { offset = 1; if ((array[firstNode]) == lastNode) { firstNode++; } } for (i = availableNodes - (lastNode - firstNode + offset); i > 0; i--) { array[nextNode--] = currentDepth; } nodesLeftToMove -= offset; availableNodes = (lastNode - firstNode + offset) << 1; } }
[ "function", "(", "array", ",", "nodesToMove", ",", "insertDepth", ")", "{", "var", "firstNode", "=", "array", ".", "length", "-", "2", ";", "var", "nextNode", "=", "array", ".", "length", "-", "1", ";", "var", "currentDepth", "=", "(", "insertDepth", "==", "1", ")", "?", "2", ":", "1", ";", "var", "nodesLeftToMove", "=", "(", "insertDepth", "==", "1", ")", "?", "nodesToMove", "-", "2", ":", "nodesToMove", ";", "var", "availableNodes", ",", "lastNode", ",", "offset", ",", "i", ";", "for", "(", "availableNodes", "=", "currentDepth", "<<", "1", ";", "availableNodes", ">", "0", ";", "currentDepth", "++", ")", "{", "lastNode", "=", "firstNode", ";", "firstNode", "=", "(", "firstNode", "<=", "nodesToMove", ")", "?", "firstNode", ":", "first", "(", "array", ",", "lastNode", "-", "1", ",", "nodesToMove", ")", ";", "offset", "=", "0", ";", "if", "(", "currentDepth", ">=", "insertDepth", ")", "{", "offset", "=", "Math", ".", "min", "(", "nodesLeftToMove", ",", "1", "<<", "(", "currentDepth", "-", "insertDepth", ")", ")", ";", "}", "else", "if", "(", "currentDepth", "==", "(", "insertDepth", "-", "1", ")", ")", "{", "offset", "=", "1", ";", "if", "(", "(", "array", "[", "firstNode", "]", ")", "==", "lastNode", ")", "{", "firstNode", "++", ";", "}", "}", "for", "(", "i", "=", "availableNodes", "-", "(", "lastNode", "-", "firstNode", "+", "offset", ")", ";", "i", ">", "0", ";", "i", "--", ")", "{", "array", "[", "nextNode", "--", "]", "=", "currentDepth", ";", "}", "nodesLeftToMove", "-=", "offset", ";", "availableNodes", "=", "(", "lastNode", "-", "firstNode", "+", "offset", ")", "<<", "1", ";", "}", "}" ]
A final allocation pass that relocates nodes in order to achieve a maximum code length limit @param array The code length array @param nodesToMove The number of internal nodes to be relocated @param insertDepth The depth at which to insert relocated nodes
[ "A", "final", "allocation", "pass", "that", "relocates", "nodes", "in", "order", "to", "achieve", "a", "maximum", "code", "length", "limit" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/HuffmanAllocator.js#L157-L188
16,082
cscott/compressjs
lib/HuffmanAllocator.js
function(array, maximumLength) { switch (array.length) { case 2: array[1] = 1; case 1: array[0] = 1; return; } /* Pass 1 : Set extended parent pointers */ setExtendedParentPointers (array); /* Pass 2 : Find number of nodes to relocate in order to achieve * maximum code length */ var nodesToRelocate = findNodesToRelocate (array, maximumLength); /* Pass 3 : Generate code lengths */ if ((array[0] % array.length) >= nodesToRelocate) { allocateNodeLengths (array); } else { var insertDepth = maximumLength - (Util.fls(nodesToRelocate - 1)); allocateNodeLengthsWithRelocation (array, nodesToRelocate, insertDepth); } }
javascript
function(array, maximumLength) { switch (array.length) { case 2: array[1] = 1; case 1: array[0] = 1; return; } /* Pass 1 : Set extended parent pointers */ setExtendedParentPointers (array); /* Pass 2 : Find number of nodes to relocate in order to achieve * maximum code length */ var nodesToRelocate = findNodesToRelocate (array, maximumLength); /* Pass 3 : Generate code lengths */ if ((array[0] % array.length) >= nodesToRelocate) { allocateNodeLengths (array); } else { var insertDepth = maximumLength - (Util.fls(nodesToRelocate - 1)); allocateNodeLengthsWithRelocation (array, nodesToRelocate, insertDepth); } }
[ "function", "(", "array", ",", "maximumLength", ")", "{", "switch", "(", "array", ".", "length", ")", "{", "case", "2", ":", "array", "[", "1", "]", "=", "1", ";", "case", "1", ":", "array", "[", "0", "]", "=", "1", ";", "return", ";", "}", "/* Pass 1 : Set extended parent pointers */", "setExtendedParentPointers", "(", "array", ")", ";", "/* Pass 2 : Find number of nodes to relocate in order to achieve\n * maximum code length */", "var", "nodesToRelocate", "=", "findNodesToRelocate", "(", "array", ",", "maximumLength", ")", ";", "/* Pass 3 : Generate code lengths */", "if", "(", "(", "array", "[", "0", "]", "%", "array", ".", "length", ")", ">=", "nodesToRelocate", ")", "{", "allocateNodeLengths", "(", "array", ")", ";", "}", "else", "{", "var", "insertDepth", "=", "maximumLength", "-", "(", "Util", ".", "fls", "(", "nodesToRelocate", "-", "1", ")", ")", ";", "allocateNodeLengthsWithRelocation", "(", "array", ",", "nodesToRelocate", ",", "insertDepth", ")", ";", "}", "}" ]
Allocates Canonical Huffman code lengths in place based on a sorted frequency array @param array On input, a sorted array of symbol frequencies; On output, an array of Canonical Huffman code lengths @param maximumLength The maximum code length. Must be at least {@code ceil(log2(array.length))} public
[ "Allocates", "Canonical", "Huffman", "code", "lengths", "in", "place", "based", "on", "a", "sorted", "frequency", "array" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/HuffmanAllocator.js#L199-L222
16,083
cscott/compressjs
lib/DeflateDistanceModel.js
function(size, extraStates, lgDistanceModelFactory, lengthBitsModelFactory) { var i; var bits = Util.fls(size-1); this.extraStates = +extraStates || 0; this.lgDistanceModel = lgDistanceModelFactory(2*bits + extraStates); // this.distanceModel[n] used for distances which are n-bits long, // but only n-2 bits are encoded: the top bit is known to be one, // and the next bit is encoded by the lgDistanceModel. this.distanceModel = []; for (i=3 ; i <= bits; i++) { var numBits = i - 2; this.distanceModel[i] = lengthBitsModelFactory(1<<numBits); } }
javascript
function(size, extraStates, lgDistanceModelFactory, lengthBitsModelFactory) { var i; var bits = Util.fls(size-1); this.extraStates = +extraStates || 0; this.lgDistanceModel = lgDistanceModelFactory(2*bits + extraStates); // this.distanceModel[n] used for distances which are n-bits long, // but only n-2 bits are encoded: the top bit is known to be one, // and the next bit is encoded by the lgDistanceModel. this.distanceModel = []; for (i=3 ; i <= bits; i++) { var numBits = i - 2; this.distanceModel[i] = lengthBitsModelFactory(1<<numBits); } }
[ "function", "(", "size", ",", "extraStates", ",", "lgDistanceModelFactory", ",", "lengthBitsModelFactory", ")", "{", "var", "i", ";", "var", "bits", "=", "Util", ".", "fls", "(", "size", "-", "1", ")", ";", "this", ".", "extraStates", "=", "+", "extraStates", "||", "0", ";", "this", ".", "lgDistanceModel", "=", "lgDistanceModelFactory", "(", "2", "*", "bits", "+", "extraStates", ")", ";", "// this.distanceModel[n] used for distances which are n-bits long,", "// but only n-2 bits are encoded: the top bit is known to be one,", "// and the next bit is encoded by the lgDistanceModel.", "this", ".", "distanceModel", "=", "[", "]", ";", "for", "(", "i", "=", "3", ";", "i", "<=", "bits", ";", "i", "++", ")", "{", "var", "numBits", "=", "i", "-", "2", ";", "this", ".", "distanceModel", "[", "i", "]", "=", "lengthBitsModelFactory", "(", "1", "<<", "numBits", ")", ";", "}", "}" ]
lengthBitsModelFactory will be called with arguments 2, 4, 8, 16, etc and must return an appropriate model or coder.
[ "lengthBitsModelFactory", "will", "be", "called", "with", "arguments", "2", "4", "8", "16", "etc", "and", "must", "return", "an", "appropriate", "model", "or", "coder", "." ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/DeflateDistanceModel.js#L11-L26
16,084
cscott/compressjs
lib/BWT.js
function(T, C, n, k) { var i; for (i = 0; i < k; i++) { C[i] = 0; } for (i = 0; i < n; i++) { C[T[i]]++; } }
javascript
function(T, C, n, k) { var i; for (i = 0; i < k; i++) { C[i] = 0; } for (i = 0; i < n; i++) { C[T[i]]++; } }
[ "function", "(", "T", ",", "C", ",", "n", ",", "k", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "k", ";", "i", "++", ")", "{", "C", "[", "i", "]", "=", "0", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "C", "[", "T", "[", "i", "]", "]", "++", ";", "}", "}" ]
we're dispensing with the "arbitrary alphabet" stuff of the source and just using Uint8Arrays. Find the start or end of each bucket.
[ "we", "re", "dispensing", "with", "the", "arbitrary", "alphabet", "stuff", "of", "the", "source", "and", "just", "using", "Uint8Arrays", ".", "Find", "the", "start", "or", "end", "of", "each", "bucket", "." ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/BWT.js#L21-L25
16,085
cscott/compressjs
lib/BWT.js
function(T, SA, C, B, n, k) { var b, i, j; var c0, c1; /* compute SAl */ if (C === B) { getCounts(T, C, n, k); } getBuckets(C, B, k, false); /* find starts of buckets */ j = n - 1; b = B[c1 = T[j]]; j--; SA[b++] = (T[j] < c1) ? ~j : j; for (i = 0; i < n; i++) { if ((j = SA[i]) > 0) { ASSERT(T[j] >= T[j+1]); if ((c0 = T[j]) !== c1) { B[c1] = b; b = B[c1 = c0]; } ASSERT(i < b); j--; SA[b++] = (T[j] < c1) ? ~j : j; SA[i] = 0; } else if (j < 0) { SA[i] = ~j; } } /* compute SAs */ if (C === B) { getCounts(T, C, n, k); } getBuckets(C, B, k, 1); /* find ends of buckets */ for (i = n-1, b = B[c1 = 0]; i >= 0; i--) { if ((j = SA[i]) > 0) { ASSERT(T[j] <= T[j+1]); if ((c0 = T[j]) !== c1) { B[c1] = b; b = B[c1 = c0]; } ASSERT(b <= i); j--; SA[--b] = (T[j] > c1) ? ~(j+1) : j; SA[i] = 0; } } }
javascript
function(T, SA, C, B, n, k) { var b, i, j; var c0, c1; /* compute SAl */ if (C === B) { getCounts(T, C, n, k); } getBuckets(C, B, k, false); /* find starts of buckets */ j = n - 1; b = B[c1 = T[j]]; j--; SA[b++] = (T[j] < c1) ? ~j : j; for (i = 0; i < n; i++) { if ((j = SA[i]) > 0) { ASSERT(T[j] >= T[j+1]); if ((c0 = T[j]) !== c1) { B[c1] = b; b = B[c1 = c0]; } ASSERT(i < b); j--; SA[b++] = (T[j] < c1) ? ~j : j; SA[i] = 0; } else if (j < 0) { SA[i] = ~j; } } /* compute SAs */ if (C === B) { getCounts(T, C, n, k); } getBuckets(C, B, k, 1); /* find ends of buckets */ for (i = n-1, b = B[c1 = 0]; i >= 0; i--) { if ((j = SA[i]) > 0) { ASSERT(T[j] <= T[j+1]); if ((c0 = T[j]) !== c1) { B[c1] = b; b = B[c1 = c0]; } ASSERT(b <= i); j--; SA[--b] = (T[j] > c1) ? ~(j+1) : j; SA[i] = 0; } } }
[ "function", "(", "T", ",", "SA", ",", "C", ",", "B", ",", "n", ",", "k", ")", "{", "var", "b", ",", "i", ",", "j", ";", "var", "c0", ",", "c1", ";", "/* compute SAl */", "if", "(", "C", "===", "B", ")", "{", "getCounts", "(", "T", ",", "C", ",", "n", ",", "k", ")", ";", "}", "getBuckets", "(", "C", ",", "B", ",", "k", ",", "false", ")", ";", "/* find starts of buckets */", "j", "=", "n", "-", "1", ";", "b", "=", "B", "[", "c1", "=", "T", "[", "j", "]", "]", ";", "j", "--", ";", "SA", "[", "b", "++", "]", "=", "(", "T", "[", "j", "]", "<", "c1", ")", "?", "~", "j", ":", "j", ";", "for", "(", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "(", "j", "=", "SA", "[", "i", "]", ")", ">", "0", ")", "{", "ASSERT", "(", "T", "[", "j", "]", ">=", "T", "[", "j", "+", "1", "]", ")", ";", "if", "(", "(", "c0", "=", "T", "[", "j", "]", ")", "!==", "c1", ")", "{", "B", "[", "c1", "]", "=", "b", ";", "b", "=", "B", "[", "c1", "=", "c0", "]", ";", "}", "ASSERT", "(", "i", "<", "b", ")", ";", "j", "--", ";", "SA", "[", "b", "++", "]", "=", "(", "T", "[", "j", "]", "<", "c1", ")", "?", "~", "j", ":", "j", ";", "SA", "[", "i", "]", "=", "0", ";", "}", "else", "if", "(", "j", "<", "0", ")", "{", "SA", "[", "i", "]", "=", "~", "j", ";", "}", "}", "/* compute SAs */", "if", "(", "C", "===", "B", ")", "{", "getCounts", "(", "T", ",", "C", ",", "n", ",", "k", ")", ";", "}", "getBuckets", "(", "C", ",", "B", ",", "k", ",", "1", ")", ";", "/* find ends of buckets */", "for", "(", "i", "=", "n", "-", "1", ",", "b", "=", "B", "[", "c1", "=", "0", "]", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "(", "j", "=", "SA", "[", "i", "]", ")", ">", "0", ")", "{", "ASSERT", "(", "T", "[", "j", "]", "<=", "T", "[", "j", "+", "1", "]", ")", ";", "if", "(", "(", "c0", "=", "T", "[", "j", "]", ")", "!==", "c1", ")", "{", "B", "[", "c1", "]", "=", "b", ";", "b", "=", "B", "[", "c1", "=", "c0", "]", ";", "}", "ASSERT", "(", "b", "<=", "i", ")", ";", "j", "--", ";", "SA", "[", "--", "b", "]", "=", "(", "T", "[", "j", "]", ">", "c1", ")", "?", "~", "(", "j", "+", "1", ")", ":", "j", ";", "SA", "[", "i", "]", "=", "0", ";", "}", "}", "}" ]
Sort all type LMS suffixes
[ "Sort", "all", "type", "LMS", "suffixes" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/BWT.js#L36-L71
16,086
cscott/compressjs
lib/Huffman.js
function(size, root, bitstream, max_weight) { var i; // default: all alphabet symbols are used console.assert(size && typeof(size)==='number'); if( !root || root > size ) root = size; // create the initial escape node // at the tree root if ( root <<= 1 ) { root--; } // create root+1 htables (coding table) // XXX this could be views on a backing Uint32 array? this.table = []; for (i=0; i<=root; i++) { this.table[i] = new HTable(0,0,0,0); } // this.map => mapping for symbols to nodes this.map = []; // this.size => the alphabet size if( this.size = size ) { for (i=0; i<size; i++) { this.map[i] = 0; } } // this.esc => the current tree height // this.root => the root of the tree this.esc = this.root = root; if (bitstream) { this.readBit = bitstream.readBit.bind(bitstream); this.writeBit = bitstream.writeBit.bind(bitstream); } this.max_weight = max_weight; // may be null or undefined }
javascript
function(size, root, bitstream, max_weight) { var i; // default: all alphabet symbols are used console.assert(size && typeof(size)==='number'); if( !root || root > size ) root = size; // create the initial escape node // at the tree root if ( root <<= 1 ) { root--; } // create root+1 htables (coding table) // XXX this could be views on a backing Uint32 array? this.table = []; for (i=0; i<=root; i++) { this.table[i] = new HTable(0,0,0,0); } // this.map => mapping for symbols to nodes this.map = []; // this.size => the alphabet size if( this.size = size ) { for (i=0; i<size; i++) { this.map[i] = 0; } } // this.esc => the current tree height // this.root => the root of the tree this.esc = this.root = root; if (bitstream) { this.readBit = bitstream.readBit.bind(bitstream); this.writeBit = bitstream.writeBit.bind(bitstream); } this.max_weight = max_weight; // may be null or undefined }
[ "function", "(", "size", ",", "root", ",", "bitstream", ",", "max_weight", ")", "{", "var", "i", ";", "// default: all alphabet symbols are used", "console", ".", "assert", "(", "size", "&&", "typeof", "(", "size", ")", "===", "'number'", ")", ";", "if", "(", "!", "root", "||", "root", ">", "size", ")", "root", "=", "size", ";", "// create the initial escape node", "// at the tree root", "if", "(", "root", "<<=", "1", ")", "{", "root", "--", ";", "}", "// create root+1 htables (coding table)", "// XXX this could be views on a backing Uint32 array?", "this", ".", "table", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<=", "root", ";", "i", "++", ")", "{", "this", ".", "table", "[", "i", "]", "=", "new", "HTable", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "}", "// this.map => mapping for symbols to nodes", "this", ".", "map", "=", "[", "]", ";", "// this.size => the alphabet size", "if", "(", "this", ".", "size", "=", "size", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "this", ".", "map", "[", "i", "]", "=", "0", ";", "}", "}", "// this.esc => the current tree height", "// this.root => the root of the tree", "this", ".", "esc", "=", "this", ".", "root", "=", "root", ";", "if", "(", "bitstream", ")", "{", "this", ".", "readBit", "=", "bitstream", ".", "readBit", ".", "bind", "(", "bitstream", ")", ";", "this", ".", "writeBit", "=", "bitstream", ".", "writeBit", ".", "bind", "(", "bitstream", ")", ";", "}", "this", ".", "max_weight", "=", "max_weight", ";", "// may be null or undefined", "}" ]
initialize an adaptive coder for alphabet size, and count of nodes to be used
[ "initialize", "an", "adaptive", "coder", "for", "alphabet", "size", "and", "count", "of", "nodes", "to", "be", "used" ]
f2377885d433b4de566f412f3d1089303abbd114
https://github.com/cscott/compressjs/blob/f2377885d433b4de566f412f3d1089303abbd114/lib/Huffman.js#L80-L120
16,087
joshmarinacci/node-pureimage
src/context.js
pathToLines
function pathToLines(path) { var lines = []; var curr = null; path.forEach(function(cmd) { if(cmd[0] == PATH_COMMAND.MOVE) { curr = cmd[1]; } if(cmd[0] == PATH_COMMAND.LINE) { var pt = cmd[1]; lines.push(new Line(curr, pt)); curr = pt; } if(cmd[0] == PATH_COMMAND.QUADRATIC_CURVE) { var pts = [curr, cmd[1], cmd[2]]; for(var t=0; t<1; t+=0.1) { var pt = calcQuadraticAtT(pts,t); lines.push(new Line(curr, pt)); curr = pt; } } if(cmd[0] === PATH_COMMAND.BEZIER_CURVE) { var pts = [curr, cmd[1], cmd[2], cmd[3]]; bezierToLines(pts,10).forEach(pt => { lines.push(new Line(curr,pt)) curr = pt }) } }); return lines; }
javascript
function pathToLines(path) { var lines = []; var curr = null; path.forEach(function(cmd) { if(cmd[0] == PATH_COMMAND.MOVE) { curr = cmd[1]; } if(cmd[0] == PATH_COMMAND.LINE) { var pt = cmd[1]; lines.push(new Line(curr, pt)); curr = pt; } if(cmd[0] == PATH_COMMAND.QUADRATIC_CURVE) { var pts = [curr, cmd[1], cmd[2]]; for(var t=0; t<1; t+=0.1) { var pt = calcQuadraticAtT(pts,t); lines.push(new Line(curr, pt)); curr = pt; } } if(cmd[0] === PATH_COMMAND.BEZIER_CURVE) { var pts = [curr, cmd[1], cmd[2], cmd[3]]; bezierToLines(pts,10).forEach(pt => { lines.push(new Line(curr,pt)) curr = pt }) } }); return lines; }
[ "function", "pathToLines", "(", "path", ")", "{", "var", "lines", "=", "[", "]", ";", "var", "curr", "=", "null", ";", "path", ".", "forEach", "(", "function", "(", "cmd", ")", "{", "if", "(", "cmd", "[", "0", "]", "==", "PATH_COMMAND", ".", "MOVE", ")", "{", "curr", "=", "cmd", "[", "1", "]", ";", "}", "if", "(", "cmd", "[", "0", "]", "==", "PATH_COMMAND", ".", "LINE", ")", "{", "var", "pt", "=", "cmd", "[", "1", "]", ";", "lines", ".", "push", "(", "new", "Line", "(", "curr", ",", "pt", ")", ")", ";", "curr", "=", "pt", ";", "}", "if", "(", "cmd", "[", "0", "]", "==", "PATH_COMMAND", ".", "QUADRATIC_CURVE", ")", "{", "var", "pts", "=", "[", "curr", ",", "cmd", "[", "1", "]", ",", "cmd", "[", "2", "]", "]", ";", "for", "(", "var", "t", "=", "0", ";", "t", "<", "1", ";", "t", "+=", "0.1", ")", "{", "var", "pt", "=", "calcQuadraticAtT", "(", "pts", ",", "t", ")", ";", "lines", ".", "push", "(", "new", "Line", "(", "curr", ",", "pt", ")", ")", ";", "curr", "=", "pt", ";", "}", "}", "if", "(", "cmd", "[", "0", "]", "===", "PATH_COMMAND", ".", "BEZIER_CURVE", ")", "{", "var", "pts", "=", "[", "curr", ",", "cmd", "[", "1", "]", ",", "cmd", "[", "2", "]", ",", "cmd", "[", "3", "]", "]", ";", "bezierToLines", "(", "pts", ",", "10", ")", ".", "forEach", "(", "pt", "=>", "{", "lines", ".", "push", "(", "new", "Line", "(", "curr", ",", "pt", ")", ")", "curr", "=", "pt", "}", ")", "}", "}", ")", ";", "return", "lines", ";", "}" ]
Convert a path of points to an array of lines @param {Array} path List of sub-paths @returns {Array<Line>}
[ "Convert", "a", "path", "of", "points", "to", "an", "array", "of", "lines" ]
1853e12c86685b768a1f264d025a469178255f2f
https://github.com/joshmarinacci/node-pureimage/blob/1853e12c86685b768a1f264d025a469178255f2f/src/context.js#L1168-L1198
16,088
joshmarinacci/node-pureimage
src/context.js
calcBezierAtT
function calcBezierAtT(p, t) { var x = (1-t)*(1-t)*(1-t)*p[0].x + 3*(1-t)*(1-t)*t*p[1].x + 3*(1-t)*t*t*p[2].x + t*t*t*p[3].x; var y = (1-t)*(1-t)*(1-t)*p[0].y + 3*(1-t)*(1-t)*t*p[1].y + 3*(1-t)*t*t*p[2].y + t*t*t*p[3].y; return new Point(x, y); }
javascript
function calcBezierAtT(p, t) { var x = (1-t)*(1-t)*(1-t)*p[0].x + 3*(1-t)*(1-t)*t*p[1].x + 3*(1-t)*t*t*p[2].x + t*t*t*p[3].x; var y = (1-t)*(1-t)*(1-t)*p[0].y + 3*(1-t)*(1-t)*t*p[1].y + 3*(1-t)*t*t*p[2].y + t*t*t*p[3].y; return new Point(x, y); }
[ "function", "calcBezierAtT", "(", "p", ",", "t", ")", "{", "var", "x", "=", "(", "1", "-", "t", ")", "*", "(", "1", "-", "t", ")", "*", "(", "1", "-", "t", ")", "*", "p", "[", "0", "]", ".", "x", "+", "3", "*", "(", "1", "-", "t", ")", "*", "(", "1", "-", "t", ")", "*", "t", "*", "p", "[", "1", "]", ".", "x", "+", "3", "*", "(", "1", "-", "t", ")", "*", "t", "*", "t", "*", "p", "[", "2", "]", ".", "x", "+", "t", "*", "t", "*", "t", "*", "p", "[", "3", "]", ".", "x", ";", "var", "y", "=", "(", "1", "-", "t", ")", "*", "(", "1", "-", "t", ")", "*", "(", "1", "-", "t", ")", "*", "p", "[", "0", "]", ".", "y", "+", "3", "*", "(", "1", "-", "t", ")", "*", "(", "1", "-", "t", ")", "*", "t", "*", "p", "[", "1", "]", ".", "y", "+", "3", "*", "(", "1", "-", "t", ")", "*", "t", "*", "t", "*", "p", "[", "2", "]", ".", "y", "+", "t", "*", "t", "*", "t", "*", "p", "[", "3", "]", ".", "y", ";", "return", "new", "Point", "(", "x", ",", "y", ")", ";", "}" ]
Calculate Bezier at T @param {number} p @param {number} t @returns {void}
[ "Calculate", "Bezier", "at", "T" ]
1853e12c86685b768a1f264d025a469178255f2f
https://github.com/joshmarinacci/node-pureimage/blob/1853e12c86685b768a1f264d025a469178255f2f/src/context.js#L1224-L1228
16,089
joshmarinacci/node-pureimage
src/context.js
calcMinimumBounds
function calcMinimumBounds(lines) { var bounds = { x: Number.MAX_VALUE, y: Number.MAX_VALUE, x2: Number.MIN_VALUE, y2: Number.MIN_VALUE } function checkPoint(pt) { bounds.x = Math.min(bounds.x,pt.x); bounds.y = Math.min(bounds.y,pt.y); bounds.x2 = Math.max(bounds.x2,pt.x); bounds.y2 = Math.max(bounds.y2,pt.y); } lines.forEach(function(line) { checkPoint(line.start); checkPoint(line.end); }) return bounds; }
javascript
function calcMinimumBounds(lines) { var bounds = { x: Number.MAX_VALUE, y: Number.MAX_VALUE, x2: Number.MIN_VALUE, y2: Number.MIN_VALUE } function checkPoint(pt) { bounds.x = Math.min(bounds.x,pt.x); bounds.y = Math.min(bounds.y,pt.y); bounds.x2 = Math.max(bounds.x2,pt.x); bounds.y2 = Math.max(bounds.y2,pt.y); } lines.forEach(function(line) { checkPoint(line.start); checkPoint(line.end); }) return bounds; }
[ "function", "calcMinimumBounds", "(", "lines", ")", "{", "var", "bounds", "=", "{", "x", ":", "Number", ".", "MAX_VALUE", ",", "y", ":", "Number", ".", "MAX_VALUE", ",", "x2", ":", "Number", ".", "MIN_VALUE", ",", "y2", ":", "Number", ".", "MIN_VALUE", "}", "function", "checkPoint", "(", "pt", ")", "{", "bounds", ".", "x", "=", "Math", ".", "min", "(", "bounds", ".", "x", ",", "pt", ".", "x", ")", ";", "bounds", ".", "y", "=", "Math", ".", "min", "(", "bounds", ".", "y", ",", "pt", ".", "y", ")", ";", "bounds", ".", "x2", "=", "Math", ".", "max", "(", "bounds", ".", "x2", ",", "pt", ".", "x", ")", ";", "bounds", ".", "y2", "=", "Math", ".", "max", "(", "bounds", ".", "y2", ",", "pt", ".", "y", ")", ";", "}", "lines", ".", "forEach", "(", "function", "(", "line", ")", "{", "checkPoint", "(", "line", ".", "start", ")", ";", "checkPoint", "(", "line", ".", "end", ")", ";", "}", ")", "return", "bounds", ";", "}" ]
Calculate Minimum Bounds @param {Array} lines @ignore @returns {{x: Number.MAX_VALUE, y: Number.MAX_VALUE, x2: Number.MIN_VALUE, y2: Number.MIN_VALUE}}
[ "Calculate", "Minimum", "Bounds" ]
1853e12c86685b768a1f264d025a469178255f2f
https://github.com/joshmarinacci/node-pureimage/blob/1853e12c86685b768a1f264d025a469178255f2f/src/context.js#L1286-L1299
16,090
joshmarinacci/node-pureimage
src/context.js
calcSortedIntersections
function calcSortedIntersections(lines,y) { var xlist = []; for(var i=0; i<lines.length; i++) { var A = lines[i].start; var B = lines[i].end; if(A.y<y && B.y>=y || B.y<y && A.y>=y) { var xval = A.x + (y-A.y) / (B.y-A.y) * (B.x-A.x); xlist.push(xval); } } return xlist.sort(function(a,b) { return a-b; }); }
javascript
function calcSortedIntersections(lines,y) { var xlist = []; for(var i=0; i<lines.length; i++) { var A = lines[i].start; var B = lines[i].end; if(A.y<y && B.y>=y || B.y<y && A.y>=y) { var xval = A.x + (y-A.y) / (B.y-A.y) * (B.x-A.x); xlist.push(xval); } } return xlist.sort(function(a,b) { return a-b; }); }
[ "function", "calcSortedIntersections", "(", "lines", ",", "y", ")", "{", "var", "xlist", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "var", "A", "=", "lines", "[", "i", "]", ".", "start", ";", "var", "B", "=", "lines", "[", "i", "]", ".", "end", ";", "if", "(", "A", ".", "y", "<", "y", "&&", "B", ".", "y", ">=", "y", "||", "B", ".", "y", "<", "y", "&&", "A", ".", "y", ">=", "y", ")", "{", "var", "xval", "=", "A", ".", "x", "+", "(", "y", "-", "A", ".", "y", ")", "/", "(", "B", ".", "y", "-", "A", ".", "y", ")", "*", "(", "B", ".", "x", "-", "A", ".", "x", ")", ";", "xlist", ".", "push", "(", "xval", ")", ";", "}", "}", "return", "xlist", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "}" ]
Calculate Sorted Intersections Adopted from http://alienryderflex.com/polygon @see http://alienryderflex.com/polygon @param {Array} lines An {@link Array} of Lines @param {number} y @ignore @returns {Array}
[ "Calculate", "Sorted", "Intersections" ]
1853e12c86685b768a1f264d025a469178255f2f
https://github.com/joshmarinacci/node-pureimage/blob/1853e12c86685b768a1f264d025a469178255f2f/src/context.js#L1316-L1327
16,091
tcorral/JSONC
versions/jsonc.js
contains
function contains(arr, v) { var nIndex, nLen = arr.length; for (nIndex = 0; nIndex < nLen; nIndex++) { if (arr[nIndex][1] === v) { return true; } } return false; }
javascript
function contains(arr, v) { var nIndex, nLen = arr.length; for (nIndex = 0; nIndex < nLen; nIndex++) { if (arr[nIndex][1] === v) { return true; } } return false; }
[ "function", "contains", "(", "arr", ",", "v", ")", "{", "var", "nIndex", ",", "nLen", "=", "arr", ".", "length", ";", "for", "(", "nIndex", "=", "0", ";", "nIndex", "<", "nLen", ";", "nIndex", "++", ")", "{", "if", "(", "arr", "[", "nIndex", "]", "[", "1", "]", "===", "v", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the value exist in the array. @param arr @param v @returns {boolean}
[ "Checks", "if", "the", "value", "exist", "in", "the", "array", "." ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3067-L3076
16,092
tcorral/JSONC
versions/jsonc.js
unique
function unique(oldArray) { var nIndex, nLen = oldArray.length, aArr = []; for (nIndex = 0; nIndex < nLen; nIndex++) { if (!contains(aArr, oldArray[nIndex][1])) { aArr.push(oldArray[nIndex]); } } return aArr; }
javascript
function unique(oldArray) { var nIndex, nLen = oldArray.length, aArr = []; for (nIndex = 0; nIndex < nLen; nIndex++) { if (!contains(aArr, oldArray[nIndex][1])) { aArr.push(oldArray[nIndex]); } } return aArr; }
[ "function", "unique", "(", "oldArray", ")", "{", "var", "nIndex", ",", "nLen", "=", "oldArray", ".", "length", ",", "aArr", "=", "[", "]", ";", "for", "(", "nIndex", "=", "0", ";", "nIndex", "<", "nLen", ";", "nIndex", "++", ")", "{", "if", "(", "!", "contains", "(", "aArr", ",", "oldArray", "[", "nIndex", "]", "[", "1", "]", ")", ")", "{", "aArr", ".", "push", "(", "oldArray", "[", "nIndex", "]", ")", ";", "}", "}", "return", "aArr", ";", "}" ]
Removes duplicated values in an array @param oldArray @returns {Array}
[ "Removes", "duplicated", "values", "in", "an", "array" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3083-L3093
16,093
tcorral/JSONC
versions/jsonc.js
_biDimensionalArrayToObject
function _biDimensionalArrayToObject(aArr) { var obj = {}, nIndex, nLen = aArr.length, oItem; for (nIndex = 0; nIndex < nLen; nIndex++) { oItem = aArr[nIndex]; obj[oItem[0]] = oItem[1]; } return obj; }
javascript
function _biDimensionalArrayToObject(aArr) { var obj = {}, nIndex, nLen = aArr.length, oItem; for (nIndex = 0; nIndex < nLen; nIndex++) { oItem = aArr[nIndex]; obj[oItem[0]] = oItem[1]; } return obj; }
[ "function", "_biDimensionalArrayToObject", "(", "aArr", ")", "{", "var", "obj", "=", "{", "}", ",", "nIndex", ",", "nLen", "=", "aArr", ".", "length", ",", "oItem", ";", "for", "(", "nIndex", "=", "0", ";", "nIndex", "<", "nLen", ";", "nIndex", "++", ")", "{", "oItem", "=", "aArr", "[", "nIndex", "]", ";", "obj", "[", "oItem", "[", "0", "]", "]", "=", "oItem", "[", "1", "]", ";", "}", "return", "obj", ";", "}" ]
Converts a bidimensional array to object @param aArr @returns {{}} @private
[ "Converts", "a", "bidimensional", "array", "to", "object" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3130-L3140
16,094
tcorral/JSONC
versions/jsonc.js
_getKeys
function _getKeys(json, aKeys) { var aKey, sKey, oItem; for (sKey in json) { if (json.hasOwnProperty(sKey)) { oItem = json[sKey]; if (_isObject(oItem) || _isArray(oItem)) { aKeys = aKeys.concat(unique(_getKeys(oItem, aKeys))); } if (isNaN(Number(sKey))) { if (!contains(aKeys, sKey)) { _nCode += 1; aKey = []; aKey.push(_getSpecialKey(_numberToKey(_nCode)), sKey); aKeys.push(aKey); } } } } return aKeys; }
javascript
function _getKeys(json, aKeys) { var aKey, sKey, oItem; for (sKey in json) { if (json.hasOwnProperty(sKey)) { oItem = json[sKey]; if (_isObject(oItem) || _isArray(oItem)) { aKeys = aKeys.concat(unique(_getKeys(oItem, aKeys))); } if (isNaN(Number(sKey))) { if (!contains(aKeys, sKey)) { _nCode += 1; aKey = []; aKey.push(_getSpecialKey(_numberToKey(_nCode)), sKey); aKeys.push(aKey); } } } } return aKeys; }
[ "function", "_getKeys", "(", "json", ",", "aKeys", ")", "{", "var", "aKey", ",", "sKey", ",", "oItem", ";", "for", "(", "sKey", "in", "json", ")", "{", "if", "(", "json", ".", "hasOwnProperty", "(", "sKey", ")", ")", "{", "oItem", "=", "json", "[", "sKey", "]", ";", "if", "(", "_isObject", "(", "oItem", ")", "||", "_isArray", "(", "oItem", ")", ")", "{", "aKeys", "=", "aKeys", ".", "concat", "(", "unique", "(", "_getKeys", "(", "oItem", ",", "aKeys", ")", ")", ")", ";", "}", "if", "(", "isNaN", "(", "Number", "(", "sKey", ")", ")", ")", "{", "if", "(", "!", "contains", "(", "aKeys", ",", "sKey", ")", ")", "{", "_nCode", "+=", "1", ";", "aKey", "=", "[", "]", ";", "aKey", ".", "push", "(", "_getSpecialKey", "(", "_numberToKey", "(", "_nCode", ")", ")", ",", "sKey", ")", ";", "aKeys", ".", "push", "(", "aKey", ")", ";", "}", "}", "}", "}", "return", "aKeys", ";", "}" ]
Traverse all the objects looking for keys and set an array with the new keys @param json @param aKeys @returns {*} @private
[ "Traverse", "all", "the", "objects", "looking", "for", "keys", "and", "set", "an", "array", "with", "the", "new", "keys" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3181-L3204
16,095
tcorral/JSONC
versions/jsonc.js
_compressArray
function _compressArray(json, aKeys) { var nIndex, nLenKeys; for (nIndex = 0, nLenKeys = json.length; nIndex < nLenKeys; nIndex++) { json[nIndex] = JSONC.compress(json[nIndex], aKeys); } }
javascript
function _compressArray(json, aKeys) { var nIndex, nLenKeys; for (nIndex = 0, nLenKeys = json.length; nIndex < nLenKeys; nIndex++) { json[nIndex] = JSONC.compress(json[nIndex], aKeys); } }
[ "function", "_compressArray", "(", "json", ",", "aKeys", ")", "{", "var", "nIndex", ",", "nLenKeys", ";", "for", "(", "nIndex", "=", "0", ",", "nLenKeys", "=", "json", ".", "length", ";", "nIndex", "<", "nLenKeys", ";", "nIndex", "++", ")", "{", "json", "[", "nIndex", "]", "=", "JSONC", ".", "compress", "(", "json", "[", "nIndex", "]", ",", "aKeys", ")", ";", "}", "}" ]
Method to compress array objects @private @param json @param aKeys
[ "Method", "to", "compress", "array", "objects" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3212-L3219
16,096
tcorral/JSONC
versions/jsonc.js
_compressOther
function _compressOther(json, aKeys) { var oKeys, aKey, str, nLenKeys, nIndex, obj; aKeys = _getKeys(json, aKeys); aKeys = unique(aKeys); oKeys = _biDimensionalArrayToObject(aKeys); str = JSON.stringify(json); nLenKeys = aKeys.length; for (nIndex = 0; nIndex < nLenKeys; nIndex++) { aKey = aKeys[nIndex]; str = str.replace(new RegExp(escapeRegExp('"' + aKey[1] + '"'), 'g'), '"' + aKey[0] + '"'); } obj = JSON.parse(str); obj._ = oKeys; return obj; }
javascript
function _compressOther(json, aKeys) { var oKeys, aKey, str, nLenKeys, nIndex, obj; aKeys = _getKeys(json, aKeys); aKeys = unique(aKeys); oKeys = _biDimensionalArrayToObject(aKeys); str = JSON.stringify(json); nLenKeys = aKeys.length; for (nIndex = 0; nIndex < nLenKeys; nIndex++) { aKey = aKeys[nIndex]; str = str.replace(new RegExp(escapeRegExp('"' + aKey[1] + '"'), 'g'), '"' + aKey[0] + '"'); } obj = JSON.parse(str); obj._ = oKeys; return obj; }
[ "function", "_compressOther", "(", "json", ",", "aKeys", ")", "{", "var", "oKeys", ",", "aKey", ",", "str", ",", "nLenKeys", ",", "nIndex", ",", "obj", ";", "aKeys", "=", "_getKeys", "(", "json", ",", "aKeys", ")", ";", "aKeys", "=", "unique", "(", "aKeys", ")", ";", "oKeys", "=", "_biDimensionalArrayToObject", "(", "aKeys", ")", ";", "str", "=", "JSON", ".", "stringify", "(", "json", ")", ";", "nLenKeys", "=", "aKeys", ".", "length", ";", "for", "(", "nIndex", "=", "0", ";", "nIndex", "<", "nLenKeys", ";", "nIndex", "++", ")", "{", "aKey", "=", "aKeys", "[", "nIndex", "]", ";", "str", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "escapeRegExp", "(", "'\"'", "+", "aKey", "[", "1", "]", "+", "'\"'", ")", ",", "'g'", ")", ",", "'\"'", "+", "aKey", "[", "0", "]", "+", "'\"'", ")", ";", "}", "obj", "=", "JSON", ".", "parse", "(", "str", ")", ";", "obj", ".", "_", "=", "oKeys", ";", "return", "obj", ";", "}" ]
Method to compress anything but array @private @param json @param aKeys @returns {*}
[ "Method", "to", "compress", "anything", "but", "array" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3228-L3249
16,097
tcorral/JSONC
versions/jsonc.js
_decompressArray
function _decompressArray(json) { var nIndex, nLenKeys; for (nIndex = 0, nLenKeys = json.length; nIndex < nLenKeys; nIndex++) { json[nIndex] = JSONC.decompress(json[nIndex]); } }
javascript
function _decompressArray(json) { var nIndex, nLenKeys; for (nIndex = 0, nLenKeys = json.length; nIndex < nLenKeys; nIndex++) { json[nIndex] = JSONC.decompress(json[nIndex]); } }
[ "function", "_decompressArray", "(", "json", ")", "{", "var", "nIndex", ",", "nLenKeys", ";", "for", "(", "nIndex", "=", "0", ",", "nLenKeys", "=", "json", ".", "length", ";", "nIndex", "<", "nLenKeys", ";", "nIndex", "++", ")", "{", "json", "[", "nIndex", "]", "=", "JSONC", ".", "decompress", "(", "json", "[", "nIndex", "]", ")", ";", "}", "}" ]
Method to decompress array objects @private @param json
[ "Method", "to", "decompress", "array", "objects" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3256-L3262
16,098
tcorral/JSONC
versions/jsonc.js
_decompressOther
function _decompressOther(jsonCopy) { var oKeys, str, sKey; oKeys = JSON.parse(JSON.stringify(jsonCopy._)); delete jsonCopy._; str = JSON.stringify(jsonCopy); for (sKey in oKeys) { if (oKeys.hasOwnProperty(sKey)) { str = str.replace(new RegExp('"' + sKey + '"', 'g'), '"' + oKeys[sKey] + '"'); } } return str; }
javascript
function _decompressOther(jsonCopy) { var oKeys, str, sKey; oKeys = JSON.parse(JSON.stringify(jsonCopy._)); delete jsonCopy._; str = JSON.stringify(jsonCopy); for (sKey in oKeys) { if (oKeys.hasOwnProperty(sKey)) { str = str.replace(new RegExp('"' + sKey + '"', 'g'), '"' + oKeys[sKey] + '"'); } } return str; }
[ "function", "_decompressOther", "(", "jsonCopy", ")", "{", "var", "oKeys", ",", "str", ",", "sKey", ";", "oKeys", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "jsonCopy", ".", "_", ")", ")", ";", "delete", "jsonCopy", ".", "_", ";", "str", "=", "JSON", ".", "stringify", "(", "jsonCopy", ")", ";", "for", "(", "sKey", "in", "oKeys", ")", "{", "if", "(", "oKeys", ".", "hasOwnProperty", "(", "sKey", ")", ")", "{", "str", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "'\"'", "+", "sKey", "+", "'\"'", ",", "'g'", ")", ",", "'\"'", "+", "oKeys", "[", "sKey", "]", "+", "'\"'", ")", ";", "}", "}", "return", "str", ";", "}" ]
Method to decompress anything but array @private @param jsonCopy @returns {*}
[ "Method", "to", "decompress", "anything", "but", "array" ]
128d17ebcd4e12fa861a0d085a8ce7a29a02d84f
https://github.com/tcorral/JSONC/blob/128d17ebcd4e12fa861a0d085a8ce7a29a02d84f/versions/jsonc.js#L3270-L3282
16,099
antonmedv/monkberry
src/compiler/attribute.js
attr
function attr(loc, reference, attrName, value) { if (plainAttributes.indexOf(attrName) != -1) { return sourceNode(loc, [reference, '.', attrName, ' = ', value, ';']); } else { return sourceNode(loc, [reference, '.setAttribute(', esc(attrName), ', ', value, ');']); } }
javascript
function attr(loc, reference, attrName, value) { if (plainAttributes.indexOf(attrName) != -1) { return sourceNode(loc, [reference, '.', attrName, ' = ', value, ';']); } else { return sourceNode(loc, [reference, '.setAttribute(', esc(attrName), ', ', value, ');']); } }
[ "function", "attr", "(", "loc", ",", "reference", ",", "attrName", ",", "value", ")", "{", "if", "(", "plainAttributes", ".", "indexOf", "(", "attrName", ")", "!=", "-", "1", ")", "{", "return", "sourceNode", "(", "loc", ",", "[", "reference", ",", "'.'", ",", "attrName", ",", "' = '", ",", "value", ",", "';'", "]", ")", ";", "}", "else", "{", "return", "sourceNode", "(", "loc", ",", "[", "reference", ",", "'.setAttribute('", ",", "esc", "(", "attrName", ")", ",", "', '", ",", "value", ",", "');'", "]", ")", ";", "}", "}" ]
Generate source nodes for attribute. @param {Object} loc @param {string} reference @param {string} attrName @param {string} value @returns {SourceNode}
[ "Generate", "source", "nodes", "for", "attribute", "." ]
f9590fe6cd31a1395f12bb3f4f8af50ab7e70e3e
https://github.com/antonmedv/monkberry/blob/f9590fe6cd31a1395f12bb3f4f8af50ab7e70e3e/src/compiler/attribute.js#L176-L182