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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
1,200
openlayers/openlayers
examples/measure.js
createHelpTooltip
function createHelpTooltip() { if (helpTooltipElement) { helpTooltipElement.parentNode.removeChild(helpTooltipElement); } helpTooltipElement = document.createElement('div'); helpTooltipElement.className = 'ol-tooltip hidden'; helpTooltip = new Overlay({ element: helpTooltipElement, offset: [15, 0], positioning: 'center-left' }); map.addOverlay(helpTooltip); }
javascript
function createHelpTooltip() { if (helpTooltipElement) { helpTooltipElement.parentNode.removeChild(helpTooltipElement); } helpTooltipElement = document.createElement('div'); helpTooltipElement.className = 'ol-tooltip hidden'; helpTooltip = new Overlay({ element: helpTooltipElement, offset: [15, 0], positioning: 'center-left' }); map.addOverlay(helpTooltip); }
[ "function", "createHelpTooltip", "(", ")", "{", "if", "(", "helpTooltipElement", ")", "{", "helpTooltipElement", ".", "parentNode", ".", "removeChild", "(", "helpTooltipElement", ")", ";", "}", "helpTooltipElement", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "helpTooltipElement", ".", "className", "=", "'ol-tooltip hidden'", ";", "helpTooltip", "=", "new", "Overlay", "(", "{", "element", ":", "helpTooltipElement", ",", "offset", ":", "[", "15", ",", "0", "]", ",", "positioning", ":", "'center-left'", "}", ")", ";", "map", ".", "addOverlay", "(", "helpTooltip", ")", ";", "}" ]
Creates a new help tooltip
[ "Creates", "a", "new", "help", "tooltip" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L243-L255
1,201
openlayers/openlayers
examples/measure.js
createMeasureTooltip
function createMeasureTooltip() { if (measureTooltipElement) { measureTooltipElement.parentNode.removeChild(measureTooltipElement); } measureTooltipElement = document.createElement('div'); measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure'; measureTooltip = new Overlay({ element: measureTooltipElement, offset: [0, -15], positioning: 'bottom-center' }); map.addOverlay(measureTooltip); }
javascript
function createMeasureTooltip() { if (measureTooltipElement) { measureTooltipElement.parentNode.removeChild(measureTooltipElement); } measureTooltipElement = document.createElement('div'); measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure'; measureTooltip = new Overlay({ element: measureTooltipElement, offset: [0, -15], positioning: 'bottom-center' }); map.addOverlay(measureTooltip); }
[ "function", "createMeasureTooltip", "(", ")", "{", "if", "(", "measureTooltipElement", ")", "{", "measureTooltipElement", ".", "parentNode", ".", "removeChild", "(", "measureTooltipElement", ")", ";", "}", "measureTooltipElement", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "measureTooltipElement", ".", "className", "=", "'ol-tooltip ol-tooltip-measure'", ";", "measureTooltip", "=", "new", "Overlay", "(", "{", "element", ":", "measureTooltipElement", ",", "offset", ":", "[", "0", ",", "-", "15", "]", ",", "positioning", ":", "'bottom-center'", "}", ")", ";", "map", ".", "addOverlay", "(", "measureTooltip", ")", ";", "}" ]
Creates a new measure tooltip
[ "Creates", "a", "new", "measure", "tooltip" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/measure.js#L261-L273
1,202
openlayers/openlayers
src/ol/sphere.js
getAreaInternal
function getAreaInternal(coordinates, radius) { let area = 0; const len = coordinates.length; let x1 = coordinates[len - 1][0]; let y1 = coordinates[len - 1][1]; for (let i = 0; i < len; i++) { const x2 = coordinates[i][0]; const y2 = coordinates[i][1]; area += toRadians(x2 - x1) * (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2))); x1 = x2; y1 = y2; } return area * radius * radius / 2.0; }
javascript
function getAreaInternal(coordinates, radius) { let area = 0; const len = coordinates.length; let x1 = coordinates[len - 1][0]; let y1 = coordinates[len - 1][1]; for (let i = 0; i < len; i++) { const x2 = coordinates[i][0]; const y2 = coordinates[i][1]; area += toRadians(x2 - x1) * (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2))); x1 = x2; y1 = y2; } return area * radius * radius / 2.0; }
[ "function", "getAreaInternal", "(", "coordinates", ",", "radius", ")", "{", "let", "area", "=", "0", ";", "const", "len", "=", "coordinates", ".", "length", ";", "let", "x1", "=", "coordinates", "[", "len", "-", "1", "]", "[", "0", "]", ";", "let", "y1", "=", "coordinates", "[", "len", "-", "1", "]", "[", "1", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "const", "x2", "=", "coordinates", "[", "i", "]", "[", "0", "]", ";", "const", "y2", "=", "coordinates", "[", "i", "]", "[", "1", "]", ";", "area", "+=", "toRadians", "(", "x2", "-", "x1", ")", "*", "(", "2", "+", "Math", ".", "sin", "(", "toRadians", "(", "y1", ")", ")", "+", "Math", ".", "sin", "(", "toRadians", "(", "y2", ")", ")", ")", ";", "x1", "=", "x2", ";", "y1", "=", "y2", ";", "}", "return", "area", "*", "radius", "*", "radius", "/", "2.0", ";", "}" ]
Returns the spherical area for a list of coordinates. [Reference](https://trs-new.jpl.nasa.gov/handle/2014/40409) Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion Laboratory, Pasadena, CA, June 2007 @param {Array<import("./coordinate.js").Coordinate>} coordinates List of coordinates of a linear ring. If the ring is oriented clockwise, the area will be positive, otherwise it will be negative. @param {number} radius The sphere radius. @return {number} Area (in square meters).
[ "Returns", "the", "spherical", "area", "for", "a", "list", "of", "coordinates", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/sphere.js#L153-L168
1,203
openlayers/openlayers
examples/wms-custom-proj.js
DECtoSEX
function DECtoSEX(angle) { // Extract DMS const deg = parseInt(angle, 10); const min = parseInt((angle - deg) * 60, 10); const sec = (((angle - deg) * 60) - min) * 60; // Result in degrees sex (dd.mmss) return deg + min / 100 + sec / 10000; }
javascript
function DECtoSEX(angle) { // Extract DMS const deg = parseInt(angle, 10); const min = parseInt((angle - deg) * 60, 10); const sec = (((angle - deg) * 60) - min) * 60; // Result in degrees sex (dd.mmss) return deg + min / 100 + sec / 10000; }
[ "function", "DECtoSEX", "(", "angle", ")", "{", "// Extract DMS", "const", "deg", "=", "parseInt", "(", "angle", ",", "10", ")", ";", "const", "min", "=", "parseInt", "(", "(", "angle", "-", "deg", ")", "*", "60", ",", "10", ")", ";", "const", "sec", "=", "(", "(", "(", "angle", "-", "deg", ")", "*", "60", ")", "-", "min", ")", "*", "60", ";", "// Result in degrees sex (dd.mmss)", "return", "deg", "+", "min", "/", "100", "+", "sec", "/", "10000", ";", "}" ]
Convert DEC angle to SEX DMS
[ "Convert", "DEC", "angle", "to", "SEX", "DMS" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/wms-custom-proj.js#L193-L203
1,204
openlayers/openlayers
examples/wms-custom-proj.js
DEGtoSEC
function DEGtoSEC(angle) { // Extract DMS const deg = parseInt(angle, 10); let min = parseInt((angle - deg) * 100, 10); let sec = (((angle - deg) * 100) - min) * 100; // Avoid rounding problems with seconds=0 const parts = String(angle).split('.'); if (parts.length == 2 && parts[1].length == 2) { min = Number(parts[1]); sec = 0; } // Result in degrees sex (dd.mmss) return sec + min * 60 + deg * 3600; }
javascript
function DEGtoSEC(angle) { // Extract DMS const deg = parseInt(angle, 10); let min = parseInt((angle - deg) * 100, 10); let sec = (((angle - deg) * 100) - min) * 100; // Avoid rounding problems with seconds=0 const parts = String(angle).split('.'); if (parts.length == 2 && parts[1].length == 2) { min = Number(parts[1]); sec = 0; } // Result in degrees sex (dd.mmss) return sec + min * 60 + deg * 3600; }
[ "function", "DEGtoSEC", "(", "angle", ")", "{", "// Extract DMS", "const", "deg", "=", "parseInt", "(", "angle", ",", "10", ")", ";", "let", "min", "=", "parseInt", "(", "(", "angle", "-", "deg", ")", "*", "100", ",", "10", ")", ";", "let", "sec", "=", "(", "(", "(", "angle", "-", "deg", ")", "*", "100", ")", "-", "min", ")", "*", "100", ";", "// Avoid rounding problems with seconds=0", "const", "parts", "=", "String", "(", "angle", ")", ".", "split", "(", "'.'", ")", ";", "if", "(", "parts", ".", "length", "==", "2", "&&", "parts", "[", "1", "]", ".", "length", "==", "2", ")", "{", "min", "=", "Number", "(", "parts", "[", "1", "]", ")", ";", "sec", "=", "0", ";", "}", "// Result in degrees sex (dd.mmss)", "return", "sec", "+", "min", "*", "60", "+", "deg", "*", "3600", ";", "}" ]
Convert Degrees angle to seconds
[ "Convert", "Degrees", "angle", "to", "seconds" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/wms-custom-proj.js#L206-L223
1,205
openlayers/openlayers
src/ol/events.js
getListenerMap
function getListenerMap(target, opt_create) { let listenerMap = target.ol_lm; if (!listenerMap && opt_create) { listenerMap = target.ol_lm = {}; } return listenerMap; }
javascript
function getListenerMap(target, opt_create) { let listenerMap = target.ol_lm; if (!listenerMap && opt_create) { listenerMap = target.ol_lm = {}; } return listenerMap; }
[ "function", "getListenerMap", "(", "target", ",", "opt_create", ")", "{", "let", "listenerMap", "=", "target", ".", "ol_lm", ";", "if", "(", "!", "listenerMap", "&&", "opt_create", ")", "{", "listenerMap", "=", "target", ".", "ol_lm", "=", "{", "}", ";", "}", "return", "listenerMap", ";", "}" ]
Get the lookup of listeners. @param {Object} target Target. @param {boolean=} opt_create If a map should be created if it doesn't exist. @return {!Object<string, Array<EventsKey>>} Map of listeners by event type.
[ "Get", "the", "lookup", "of", "listeners", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/events.js#L93-L99
1,206
openlayers/openlayers
src/ol/events.js
removeListeners
function removeListeners(target, type) { const listeners = getListeners(target, type); if (listeners) { for (let i = 0, ii = listeners.length; i < ii; ++i) { /** @type {import("./events/Target.js").default} */ (target). removeEventListener(type, listeners[i].boundListener); clear(listeners[i]); } listeners.length = 0; const listenerMap = getListenerMap(target); if (listenerMap) { delete listenerMap[type]; if (Object.keys(listenerMap).length === 0) { removeListenerMap(target); } } } }
javascript
function removeListeners(target, type) { const listeners = getListeners(target, type); if (listeners) { for (let i = 0, ii = listeners.length; i < ii; ++i) { /** @type {import("./events/Target.js").default} */ (target). removeEventListener(type, listeners[i].boundListener); clear(listeners[i]); } listeners.length = 0; const listenerMap = getListenerMap(target); if (listenerMap) { delete listenerMap[type]; if (Object.keys(listenerMap).length === 0) { removeListenerMap(target); } } } }
[ "function", "removeListeners", "(", "target", ",", "type", ")", "{", "const", "listeners", "=", "getListeners", "(", "target", ",", "type", ")", ";", "if", "(", "listeners", ")", "{", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "listeners", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "/** @type {import(\"./events/Target.js\").default} */", "(", "target", ")", ".", "removeEventListener", "(", "type", ",", "listeners", "[", "i", "]", ".", "boundListener", ")", ";", "clear", "(", "listeners", "[", "i", "]", ")", ";", "}", "listeners", ".", "length", "=", "0", ";", "const", "listenerMap", "=", "getListenerMap", "(", "target", ")", ";", "if", "(", "listenerMap", ")", "{", "delete", "listenerMap", "[", "type", "]", ";", "if", "(", "Object", ".", "keys", "(", "listenerMap", ")", ".", "length", "===", "0", ")", "{", "removeListenerMap", "(", "target", ")", ";", "}", "}", "}", "}" ]
Clean up all listener objects of the given type. All properties on the listener objects will be removed, and if no listeners remain in the listener map, it will be removed from the target. @param {import("./events/Target.js").EventTargetLike} target Target. @param {string} type Type.
[ "Clean", "up", "all", "listener", "objects", "of", "the", "given", "type", ".", "All", "properties", "on", "the", "listener", "objects", "will", "be", "removed", "and", "if", "no", "listeners", "remain", "in", "the", "listener", "map", "it", "will", "be", "removed", "from", "the", "target", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/events.js#L118-L135
1,207
openlayers/openlayers
src/ol/source/Raster.js
getImageData
function getImageData(layer, frameState, layerState) { const renderer = layer.getRenderer(); if (!renderer) { throw new Error('Unsupported layer type: ' + layer); } if (!renderer.prepareFrame(frameState, layerState)) { return null; } const width = frameState.size[0]; const height = frameState.size[1]; const element = renderer.renderFrame(frameState, layerState); if (!(element instanceof HTMLCanvasElement)) { throw new Error('Unsupported rendered element: ' + element); } if (element.width === width && element.height === height) { const context = element.getContext('2d'); return context.getImageData(0, 0, width, height); } if (!sharedContext) { sharedContext = createCanvasContext2D(width, height); } else { const canvas = sharedContext.canvas; if (canvas.width !== width || canvas.height !== height) { sharedContext = createCanvasContext2D(width, height); } else { sharedContext.clearRect(0, 0, width, height); } } sharedContext.drawImage(element, 0, 0, width, height); return sharedContext.getImageData(0, 0, width, height); }
javascript
function getImageData(layer, frameState, layerState) { const renderer = layer.getRenderer(); if (!renderer) { throw new Error('Unsupported layer type: ' + layer); } if (!renderer.prepareFrame(frameState, layerState)) { return null; } const width = frameState.size[0]; const height = frameState.size[1]; const element = renderer.renderFrame(frameState, layerState); if (!(element instanceof HTMLCanvasElement)) { throw new Error('Unsupported rendered element: ' + element); } if (element.width === width && element.height === height) { const context = element.getContext('2d'); return context.getImageData(0, 0, width, height); } if (!sharedContext) { sharedContext = createCanvasContext2D(width, height); } else { const canvas = sharedContext.canvas; if (canvas.width !== width || canvas.height !== height) { sharedContext = createCanvasContext2D(width, height); } else { sharedContext.clearRect(0, 0, width, height); } } sharedContext.drawImage(element, 0, 0, width, height); return sharedContext.getImageData(0, 0, width, height); }
[ "function", "getImageData", "(", "layer", ",", "frameState", ",", "layerState", ")", "{", "const", "renderer", "=", "layer", ".", "getRenderer", "(", ")", ";", "if", "(", "!", "renderer", ")", "{", "throw", "new", "Error", "(", "'Unsupported layer type: '", "+", "layer", ")", ";", "}", "if", "(", "!", "renderer", ".", "prepareFrame", "(", "frameState", ",", "layerState", ")", ")", "{", "return", "null", ";", "}", "const", "width", "=", "frameState", ".", "size", "[", "0", "]", ";", "const", "height", "=", "frameState", ".", "size", "[", "1", "]", ";", "const", "element", "=", "renderer", ".", "renderFrame", "(", "frameState", ",", "layerState", ")", ";", "if", "(", "!", "(", "element", "instanceof", "HTMLCanvasElement", ")", ")", "{", "throw", "new", "Error", "(", "'Unsupported rendered element: '", "+", "element", ")", ";", "}", "if", "(", "element", ".", "width", "===", "width", "&&", "element", ".", "height", "===", "height", ")", "{", "const", "context", "=", "element", ".", "getContext", "(", "'2d'", ")", ";", "return", "context", ".", "getImageData", "(", "0", ",", "0", ",", "width", ",", "height", ")", ";", "}", "if", "(", "!", "sharedContext", ")", "{", "sharedContext", "=", "createCanvasContext2D", "(", "width", ",", "height", ")", ";", "}", "else", "{", "const", "canvas", "=", "sharedContext", ".", "canvas", ";", "if", "(", "canvas", ".", "width", "!==", "width", "||", "canvas", ".", "height", "!==", "height", ")", "{", "sharedContext", "=", "createCanvasContext2D", "(", "width", ",", "height", ")", ";", "}", "else", "{", "sharedContext", ".", "clearRect", "(", "0", ",", "0", ",", "width", ",", "height", ")", ";", "}", "}", "sharedContext", ".", "drawImage", "(", "element", ",", "0", ",", "0", ",", "width", ",", "height", ")", ";", "return", "sharedContext", ".", "getImageData", "(", "0", ",", "0", ",", "width", ",", "height", ")", ";", "}" ]
Get image data from a layer. @param {import("../layer/Layer.js").default} layer Layer to render. @param {import("../PluggableMap.js").FrameState} frameState The frame state. @param {import("../layer/Layer.js").State} layerState The layer state. @return {ImageData} The image data.
[ "Get", "image", "data", "from", "a", "layer", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Raster.js#L436-L468
1,208
openlayers/openlayers
src/ol/source/Raster.js
createLayers
function createLayers(sources) { const len = sources.length; const layers = new Array(len); for (let i = 0; i < len; ++i) { layers[i] = createLayer(sources[i]); } return layers; }
javascript
function createLayers(sources) { const len = sources.length; const layers = new Array(len); for (let i = 0; i < len; ++i) { layers[i] = createLayer(sources[i]); } return layers; }
[ "function", "createLayers", "(", "sources", ")", "{", "const", "len", "=", "sources", ".", "length", ";", "const", "layers", "=", "new", "Array", "(", "len", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "++", "i", ")", "{", "layers", "[", "i", "]", "=", "createLayer", "(", "sources", "[", "i", "]", ")", ";", "}", "return", "layers", ";", "}" ]
Create layers for all sources. @param {Array<import("./Source.js").default|import("../layer/Layer.js").default>} sources The sources. @return {Array<import("../layer/Layer.js").default>} Array of layers.
[ "Create", "layers", "for", "all", "sources", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Raster.js#L488-L495
1,209
openlayers/openlayers
src/ol/source/Raster.js
createLayer
function createLayer(layerOrSource) { // @type {import("../layer/Layer.js").default} let layer; if (layerOrSource instanceof Source) { if (layerOrSource instanceof TileSource) { layer = new TileLayer({source: layerOrSource}); } else if (layerOrSource instanceof ImageSource) { layer = new ImageLayer({source: layerOrSource}); } } else { layer = layerOrSource; } return layer; }
javascript
function createLayer(layerOrSource) { // @type {import("../layer/Layer.js").default} let layer; if (layerOrSource instanceof Source) { if (layerOrSource instanceof TileSource) { layer = new TileLayer({source: layerOrSource}); } else if (layerOrSource instanceof ImageSource) { layer = new ImageLayer({source: layerOrSource}); } } else { layer = layerOrSource; } return layer; }
[ "function", "createLayer", "(", "layerOrSource", ")", "{", "// @type {import(\"../layer/Layer.js\").default}", "let", "layer", ";", "if", "(", "layerOrSource", "instanceof", "Source", ")", "{", "if", "(", "layerOrSource", "instanceof", "TileSource", ")", "{", "layer", "=", "new", "TileLayer", "(", "{", "source", ":", "layerOrSource", "}", ")", ";", "}", "else", "if", "(", "layerOrSource", "instanceof", "ImageSource", ")", "{", "layer", "=", "new", "ImageLayer", "(", "{", "source", ":", "layerOrSource", "}", ")", ";", "}", "}", "else", "{", "layer", "=", "layerOrSource", ";", "}", "return", "layer", ";", "}" ]
Create a layer for the provided source. @param {import("./Source.js").default|import("../layer/Layer.js").default} layerOrSource The layer or source. @return {import("../layer/Layer.js").default} The layer.
[ "Create", "a", "layer", "for", "the", "provided", "source", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/source/Raster.js#L503-L516
1,210
openlayers/openlayers
src/ol/render/canvas/ExecutorGroup.js
fillCircleArrayRowToMiddle
function fillCircleArrayRowToMiddle(array, x, y) { let i; const radius = Math.floor(array.length / 2); if (x >= radius) { for (i = radius; i < x; i++) { array[i][y] = true; } } else if (x < radius) { for (i = x + 1; i < radius; i++) { array[i][y] = true; } } }
javascript
function fillCircleArrayRowToMiddle(array, x, y) { let i; const radius = Math.floor(array.length / 2); if (x >= radius) { for (i = radius; i < x; i++) { array[i][y] = true; } } else if (x < radius) { for (i = x + 1; i < radius; i++) { array[i][y] = true; } } }
[ "function", "fillCircleArrayRowToMiddle", "(", "array", ",", "x", ",", "y", ")", "{", "let", "i", ";", "const", "radius", "=", "Math", ".", "floor", "(", "array", ".", "length", "/", "2", ")", ";", "if", "(", "x", ">=", "radius", ")", "{", "for", "(", "i", "=", "radius", ";", "i", "<", "x", ";", "i", "++", ")", "{", "array", "[", "i", "]", "[", "y", "]", "=", "true", ";", "}", "}", "else", "if", "(", "x", "<", "radius", ")", "{", "for", "(", "i", "=", "x", "+", "1", ";", "i", "<", "radius", ";", "i", "++", ")", "{", "array", "[", "i", "]", "[", "y", "]", "=", "true", ";", "}", "}", "}" ]
This method fills a row in the array from the given coordinate to the middle with `true`. @param {Array<Array<(boolean|undefined)>>} array The array that will be altered. @param {number} x X coordinate. @param {number} y Y coordinate.
[ "This", "method", "fills", "a", "row", "in", "the", "array", "from", "the", "given", "coordinate", "to", "the", "middle", "with", "true", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/render/canvas/ExecutorGroup.js#L361-L373
1,211
openlayers/openlayers
src/ol/format/TopoJSON.js
concatenateArcs
function concatenateArcs(indices, arcs) { /** @type {Array<import("../coordinate.js").Coordinate>} */ const coordinates = []; let index, arc; for (let i = 0, ii = indices.length; i < ii; ++i) { index = indices[i]; if (i > 0) { // splicing together arcs, discard last point coordinates.pop(); } if (index >= 0) { // forward arc arc = arcs[index]; } else { // reverse arc arc = arcs[~index].slice().reverse(); } coordinates.push.apply(coordinates, arc); } // provide fresh copies of coordinate arrays for (let j = 0, jj = coordinates.length; j < jj; ++j) { coordinates[j] = coordinates[j].slice(); } return coordinates; }
javascript
function concatenateArcs(indices, arcs) { /** @type {Array<import("../coordinate.js").Coordinate>} */ const coordinates = []; let index, arc; for (let i = 0, ii = indices.length; i < ii; ++i) { index = indices[i]; if (i > 0) { // splicing together arcs, discard last point coordinates.pop(); } if (index >= 0) { // forward arc arc = arcs[index]; } else { // reverse arc arc = arcs[~index].slice().reverse(); } coordinates.push.apply(coordinates, arc); } // provide fresh copies of coordinate arrays for (let j = 0, jj = coordinates.length; j < jj; ++j) { coordinates[j] = coordinates[j].slice(); } return coordinates; }
[ "function", "concatenateArcs", "(", "indices", ",", "arcs", ")", "{", "/** @type {Array<import(\"../coordinate.js\").Coordinate>} */", "const", "coordinates", "=", "[", "]", ";", "let", "index", ",", "arc", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "indices", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "index", "=", "indices", "[", "i", "]", ";", "if", "(", "i", ">", "0", ")", "{", "// splicing together arcs, discard last point", "coordinates", ".", "pop", "(", ")", ";", "}", "if", "(", "index", ">=", "0", ")", "{", "// forward arc", "arc", "=", "arcs", "[", "index", "]", ";", "}", "else", "{", "// reverse arc", "arc", "=", "arcs", "[", "~", "index", "]", ".", "slice", "(", ")", ".", "reverse", "(", ")", ";", "}", "coordinates", ".", "push", ".", "apply", "(", "coordinates", ",", "arc", ")", ";", "}", "// provide fresh copies of coordinate arrays", "for", "(", "let", "j", "=", "0", ",", "jj", "=", "coordinates", ".", "length", ";", "j", "<", "jj", ";", "++", "j", ")", "{", "coordinates", "[", "j", "]", "=", "coordinates", "[", "j", "]", ".", "slice", "(", ")", ";", "}", "return", "coordinates", ";", "}" ]
Concatenate arcs into a coordinate array. @param {Array<number>} indices Indices of arcs to concatenate. Negative values indicate arcs need to be reversed. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs (already transformed). @return {Array<import("../coordinate.js").Coordinate>} Coordinates array.
[ "Concatenate", "arcs", "into", "a", "coordinate", "array", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L162-L186
1,212
openlayers/openlayers
src/ol/format/TopoJSON.js
readPointGeometry
function readPointGeometry(object, scale, translate) { const coordinates = object['coordinates']; if (scale && translate) { transformVertex(coordinates, scale, translate); } return new Point(coordinates); }
javascript
function readPointGeometry(object, scale, translate) { const coordinates = object['coordinates']; if (scale && translate) { transformVertex(coordinates, scale, translate); } return new Point(coordinates); }
[ "function", "readPointGeometry", "(", "object", ",", "scale", ",", "translate", ")", "{", "const", "coordinates", "=", "object", "[", "'coordinates'", "]", ";", "if", "(", "scale", "&&", "translate", ")", "{", "transformVertex", "(", "coordinates", ",", "scale", ",", "translate", ")", ";", "}", "return", "new", "Point", "(", "coordinates", ")", ";", "}" ]
Create a point from a TopoJSON geometry object. @param {TopoJSONPoint} object TopoJSON object. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension. @return {Point} Geometry.
[ "Create", "a", "point", "from", "a", "TopoJSON", "geometry", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L197-L203
1,213
openlayers/openlayers
src/ol/format/TopoJSON.js
readMultiPointGeometry
function readMultiPointGeometry(object, scale, translate) { const coordinates = object['coordinates']; if (scale && translate) { for (let i = 0, ii = coordinates.length; i < ii; ++i) { transformVertex(coordinates[i], scale, translate); } } return new MultiPoint(coordinates); }
javascript
function readMultiPointGeometry(object, scale, translate) { const coordinates = object['coordinates']; if (scale && translate) { for (let i = 0, ii = coordinates.length; i < ii; ++i) { transformVertex(coordinates[i], scale, translate); } } return new MultiPoint(coordinates); }
[ "function", "readMultiPointGeometry", "(", "object", ",", "scale", ",", "translate", ")", "{", "const", "coordinates", "=", "object", "[", "'coordinates'", "]", ";", "if", "(", "scale", "&&", "translate", ")", "{", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "coordinates", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "transformVertex", "(", "coordinates", "[", "i", "]", ",", "scale", ",", "translate", ")", ";", "}", "}", "return", "new", "MultiPoint", "(", "coordinates", ")", ";", "}" ]
Create a multi-point from a TopoJSON geometry object. @param {TopoJSONMultiPoint} object TopoJSON object. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension. @return {MultiPoint} Geometry.
[ "Create", "a", "multi", "-", "point", "from", "a", "TopoJSON", "geometry", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L214-L222
1,214
openlayers/openlayers
src/ol/format/TopoJSON.js
readMultiLineStringGeometry
function readMultiLineStringGeometry(object, arcs) { const coordinates = []; for (let i = 0, ii = object['arcs'].length; i < ii; ++i) { coordinates[i] = concatenateArcs(object['arcs'][i], arcs); } return new MultiLineString(coordinates); }
javascript
function readMultiLineStringGeometry(object, arcs) { const coordinates = []; for (let i = 0, ii = object['arcs'].length; i < ii; ++i) { coordinates[i] = concatenateArcs(object['arcs'][i], arcs); } return new MultiLineString(coordinates); }
[ "function", "readMultiLineStringGeometry", "(", "object", ",", "arcs", ")", "{", "const", "coordinates", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "object", "[", "'arcs'", "]", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "coordinates", "[", "i", "]", "=", "concatenateArcs", "(", "object", "[", "'arcs'", "]", "[", "i", "]", ",", "arcs", ")", ";", "}", "return", "new", "MultiLineString", "(", "coordinates", ")", ";", "}" ]
Create a multi-linestring from a TopoJSON geometry object. @param {TopoJSONMultiLineString} object TopoJSON object. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs. @return {MultiLineString} Geometry.
[ "Create", "a", "multi", "-", "linestring", "from", "a", "TopoJSON", "geometry", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L245-L251
1,215
openlayers/openlayers
src/ol/format/TopoJSON.js
readPolygonGeometry
function readPolygonGeometry(object, arcs) { const coordinates = []; for (let i = 0, ii = object['arcs'].length; i < ii; ++i) { coordinates[i] = concatenateArcs(object['arcs'][i], arcs); } return new Polygon(coordinates); }
javascript
function readPolygonGeometry(object, arcs) { const coordinates = []; for (let i = 0, ii = object['arcs'].length; i < ii; ++i) { coordinates[i] = concatenateArcs(object['arcs'][i], arcs); } return new Polygon(coordinates); }
[ "function", "readPolygonGeometry", "(", "object", ",", "arcs", ")", "{", "const", "coordinates", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "object", "[", "'arcs'", "]", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "coordinates", "[", "i", "]", "=", "concatenateArcs", "(", "object", "[", "'arcs'", "]", "[", "i", "]", ",", "arcs", ")", ";", "}", "return", "new", "Polygon", "(", "coordinates", ")", ";", "}" ]
Create a polygon from a TopoJSON geometry object. @param {TopoJSONPolygon} object TopoJSON object. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs. @return {Polygon} Geometry.
[ "Create", "a", "polygon", "from", "a", "TopoJSON", "geometry", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L261-L267
1,216
openlayers/openlayers
src/ol/format/TopoJSON.js
readMultiPolygonGeometry
function readMultiPolygonGeometry(object, arcs) { const coordinates = []; for (let i = 0, ii = object['arcs'].length; i < ii; ++i) { // for each polygon const polyArray = object['arcs'][i]; const ringCoords = []; for (let j = 0, jj = polyArray.length; j < jj; ++j) { // for each ring ringCoords[j] = concatenateArcs(polyArray[j], arcs); } coordinates[i] = ringCoords; } return new MultiPolygon(coordinates); }
javascript
function readMultiPolygonGeometry(object, arcs) { const coordinates = []; for (let i = 0, ii = object['arcs'].length; i < ii; ++i) { // for each polygon const polyArray = object['arcs'][i]; const ringCoords = []; for (let j = 0, jj = polyArray.length; j < jj; ++j) { // for each ring ringCoords[j] = concatenateArcs(polyArray[j], arcs); } coordinates[i] = ringCoords; } return new MultiPolygon(coordinates); }
[ "function", "readMultiPolygonGeometry", "(", "object", ",", "arcs", ")", "{", "const", "coordinates", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "object", "[", "'arcs'", "]", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "// for each polygon", "const", "polyArray", "=", "object", "[", "'arcs'", "]", "[", "i", "]", ";", "const", "ringCoords", "=", "[", "]", ";", "for", "(", "let", "j", "=", "0", ",", "jj", "=", "polyArray", ".", "length", ";", "j", "<", "jj", ";", "++", "j", ")", "{", "// for each ring", "ringCoords", "[", "j", "]", "=", "concatenateArcs", "(", "polyArray", "[", "j", "]", ",", "arcs", ")", ";", "}", "coordinates", "[", "i", "]", "=", "ringCoords", ";", "}", "return", "new", "MultiPolygon", "(", "coordinates", ")", ";", "}" ]
Create a multi-polygon from a TopoJSON geometry object. @param {TopoJSONMultiPolygon} object TopoJSON object. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs. @return {MultiPolygon} Geometry.
[ "Create", "a", "multi", "-", "polygon", "from", "a", "TopoJSON", "geometry", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L277-L290
1,217
openlayers/openlayers
src/ol/format/TopoJSON.js
readFeaturesFromGeometryCollection
function readFeaturesFromGeometryCollection(collection, arcs, scale, translate, property, name, opt_options) { const geometries = collection['geometries']; const features = []; for (let i = 0, ii = geometries.length; i < ii; ++i) { features[i] = readFeatureFromGeometry( geometries[i], arcs, scale, translate, property, name, opt_options); } return features; }
javascript
function readFeaturesFromGeometryCollection(collection, arcs, scale, translate, property, name, opt_options) { const geometries = collection['geometries']; const features = []; for (let i = 0, ii = geometries.length; i < ii; ++i) { features[i] = readFeatureFromGeometry( geometries[i], arcs, scale, translate, property, name, opt_options); } return features; }
[ "function", "readFeaturesFromGeometryCollection", "(", "collection", ",", "arcs", ",", "scale", ",", "translate", ",", "property", ",", "name", ",", "opt_options", ")", "{", "const", "geometries", "=", "collection", "[", "'geometries'", "]", ";", "const", "features", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "geometries", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "features", "[", "i", "]", "=", "readFeatureFromGeometry", "(", "geometries", "[", "i", "]", ",", "arcs", ",", "scale", ",", "translate", ",", "property", ",", "name", ",", "opt_options", ")", ";", "}", "return", "features", ";", "}" ]
Create features from a TopoJSON GeometryCollection object. @param {TopoJSONGeometryCollection} collection TopoJSON Geometry object. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension. @param {string|undefined} property Property to set the `GeometryCollection`'s parent object to. @param {string} name Name of the `Topology`'s child object. @param {import("./Feature.js").ReadOptions=} opt_options Read options. @return {Array<Feature>} Array of features.
[ "Create", "features", "from", "a", "TopoJSON", "GeometryCollection", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L307-L315
1,218
openlayers/openlayers
src/ol/format/TopoJSON.js
readFeatureFromGeometry
function readFeatureFromGeometry(object, arcs, scale, translate, property, name, opt_options) { let geometry; const type = object.type; const geometryReader = GEOMETRY_READERS[type]; if ((type === 'Point') || (type === 'MultiPoint')) { geometry = geometryReader(object, scale, translate); } else { geometry = geometryReader(object, arcs); } const feature = new Feature(); feature.setGeometry(transformGeometryWithOptions(geometry, false, opt_options)); if (object.id !== undefined) { feature.setId(object.id); } let properties = object.properties; if (property) { if (!properties) { properties = {}; } properties[property] = name; } if (properties) { feature.setProperties(properties, true); } return feature; }
javascript
function readFeatureFromGeometry(object, arcs, scale, translate, property, name, opt_options) { let geometry; const type = object.type; const geometryReader = GEOMETRY_READERS[type]; if ((type === 'Point') || (type === 'MultiPoint')) { geometry = geometryReader(object, scale, translate); } else { geometry = geometryReader(object, arcs); } const feature = new Feature(); feature.setGeometry(transformGeometryWithOptions(geometry, false, opt_options)); if (object.id !== undefined) { feature.setId(object.id); } let properties = object.properties; if (property) { if (!properties) { properties = {}; } properties[property] = name; } if (properties) { feature.setProperties(properties, true); } return feature; }
[ "function", "readFeatureFromGeometry", "(", "object", ",", "arcs", ",", "scale", ",", "translate", ",", "property", ",", "name", ",", "opt_options", ")", "{", "let", "geometry", ";", "const", "type", "=", "object", ".", "type", ";", "const", "geometryReader", "=", "GEOMETRY_READERS", "[", "type", "]", ";", "if", "(", "(", "type", "===", "'Point'", ")", "||", "(", "type", "===", "'MultiPoint'", ")", ")", "{", "geometry", "=", "geometryReader", "(", "object", ",", "scale", ",", "translate", ")", ";", "}", "else", "{", "geometry", "=", "geometryReader", "(", "object", ",", "arcs", ")", ";", "}", "const", "feature", "=", "new", "Feature", "(", ")", ";", "feature", ".", "setGeometry", "(", "transformGeometryWithOptions", "(", "geometry", ",", "false", ",", "opt_options", ")", ")", ";", "if", "(", "object", ".", "id", "!==", "undefined", ")", "{", "feature", ".", "setId", "(", "object", ".", "id", ")", ";", "}", "let", "properties", "=", "object", ".", "properties", ";", "if", "(", "property", ")", "{", "if", "(", "!", "properties", ")", "{", "properties", "=", "{", "}", ";", "}", "properties", "[", "property", "]", "=", "name", ";", "}", "if", "(", "properties", ")", "{", "feature", ".", "setProperties", "(", "properties", ",", "true", ")", ";", "}", "return", "feature", ";", "}" ]
Create a feature from a TopoJSON geometry object. @param {TopoJSONGeometry} object TopoJSON geometry object. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension. @param {string|undefined} property Property to set the `GeometryCollection`'s parent object to. @param {string} name Name of the `Topology`'s child object. @param {import("./Feature.js").ReadOptions=} opt_options Read options. @return {Feature} Feature.
[ "Create", "a", "feature", "from", "a", "TopoJSON", "geometry", "object", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L331-L356
1,219
openlayers/openlayers
src/ol/format/TopoJSON.js
transformArcs
function transformArcs(arcs, scale, translate) { for (let i = 0, ii = arcs.length; i < ii; ++i) { transformArc(arcs[i], scale, translate); } }
javascript
function transformArcs(arcs, scale, translate) { for (let i = 0, ii = arcs.length; i < ii; ++i) { transformArc(arcs[i], scale, translate); } }
[ "function", "transformArcs", "(", "arcs", ",", "scale", ",", "translate", ")", "{", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "arcs", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "transformArc", "(", "arcs", "[", "i", "]", ",", "scale", ",", "translate", ")", ";", "}", "}" ]
Apply a linear transform to array of arcs. The provided array of arcs is modified in place. @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension.
[ "Apply", "a", "linear", "transform", "to", "array", "of", "arcs", ".", "The", "provided", "array", "of", "arcs", "is", "modified", "in", "place", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L367-L371
1,220
openlayers/openlayers
src/ol/format/TopoJSON.js
transformArc
function transformArc(arc, scale, translate) { let x = 0; let y = 0; for (let i = 0, ii = arc.length; i < ii; ++i) { const vertex = arc[i]; x += vertex[0]; y += vertex[1]; vertex[0] = x; vertex[1] = y; transformVertex(vertex, scale, translate); } }
javascript
function transformArc(arc, scale, translate) { let x = 0; let y = 0; for (let i = 0, ii = arc.length; i < ii; ++i) { const vertex = arc[i]; x += vertex[0]; y += vertex[1]; vertex[0] = x; vertex[1] = y; transformVertex(vertex, scale, translate); } }
[ "function", "transformArc", "(", "arc", ",", "scale", ",", "translate", ")", "{", "let", "x", "=", "0", ";", "let", "y", "=", "0", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "arc", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "const", "vertex", "=", "arc", "[", "i", "]", ";", "x", "+=", "vertex", "[", "0", "]", ";", "y", "+=", "vertex", "[", "1", "]", ";", "vertex", "[", "0", "]", "=", "x", ";", "vertex", "[", "1", "]", "=", "y", ";", "transformVertex", "(", "vertex", ",", "scale", ",", "translate", ")", ";", "}", "}" ]
Apply a linear transform to an arc. The provided arc is modified in place. @param {Array<import("../coordinate.js").Coordinate>} arc Arc. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension.
[ "Apply", "a", "linear", "transform", "to", "an", "arc", ".", "The", "provided", "arc", "is", "modified", "in", "place", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L381-L392
1,221
openlayers/openlayers
src/ol/format/TopoJSON.js
transformVertex
function transformVertex(vertex, scale, translate) { vertex[0] = vertex[0] * scale[0] + translate[0]; vertex[1] = vertex[1] * scale[1] + translate[1]; }
javascript
function transformVertex(vertex, scale, translate) { vertex[0] = vertex[0] * scale[0] + translate[0]; vertex[1] = vertex[1] * scale[1] + translate[1]; }
[ "function", "transformVertex", "(", "vertex", ",", "scale", ",", "translate", ")", "{", "vertex", "[", "0", "]", "=", "vertex", "[", "0", "]", "*", "scale", "[", "0", "]", "+", "translate", "[", "0", "]", ";", "vertex", "[", "1", "]", "=", "vertex", "[", "1", "]", "*", "scale", "[", "1", "]", "+", "translate", "[", "1", "]", ";", "}" ]
Apply a linear transform to a vertex. The provided vertex is modified in place. @param {import("../coordinate.js").Coordinate} vertex Vertex. @param {Array<number>} scale Scale for each dimension. @param {Array<number>} translate Translation for each dimension.
[ "Apply", "a", "linear", "transform", "to", "a", "vertex", ".", "The", "provided", "vertex", "is", "modified", "in", "place", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/TopoJSON.js#L403-L406
1,222
openlayers/openlayers
src/ol/pointer/TouchSource.js
touchstart
function touchstart(inEvent) { this.vacuumTouches_(inEvent); this.setPrimaryTouch_(inEvent.changedTouches[0]); this.dedupSynthMouse_(inEvent); this.clickCount_++; this.processTouches_(inEvent, this.overDown_); }
javascript
function touchstart(inEvent) { this.vacuumTouches_(inEvent); this.setPrimaryTouch_(inEvent.changedTouches[0]); this.dedupSynthMouse_(inEvent); this.clickCount_++; this.processTouches_(inEvent, this.overDown_); }
[ "function", "touchstart", "(", "inEvent", ")", "{", "this", ".", "vacuumTouches_", "(", "inEvent", ")", ";", "this", ".", "setPrimaryTouch_", "(", "inEvent", ".", "changedTouches", "[", "0", "]", ")", ";", "this", ".", "dedupSynthMouse_", "(", "inEvent", ")", ";", "this", ".", "clickCount_", "++", ";", "this", ".", "processTouches_", "(", "inEvent", ",", "this", ".", "overDown_", ")", ";", "}" ]
Handler for `touchstart`, triggers `pointerover`, `pointerenter` and `pointerdown` events. @this {TouchSource} @param {TouchEvent} inEvent The in event.
[ "Handler", "for", "touchstart", "triggers", "pointerover", "pointerenter", "and", "pointerdown", "events", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/TouchSource.js#L57-L63
1,223
openlayers/openlayers
examples/mapbox-vector-tiles-advanced.js
tileUrlFunction
function tileUrlFunction(tileCoord) { return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' + '{z}/{x}/{y}.vector.pbf?access_token=' + key) .replace('{z}', String(tileCoord[0] * 2 - 1)) .replace('{x}', String(tileCoord[1])) .replace('{y}', String(tileCoord[2])) .replace('{a-d}', 'abcd'.substr( ((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)); }
javascript
function tileUrlFunction(tileCoord) { return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' + '{z}/{x}/{y}.vector.pbf?access_token=' + key) .replace('{z}', String(tileCoord[0] * 2 - 1)) .replace('{x}', String(tileCoord[1])) .replace('{y}', String(tileCoord[2])) .replace('{a-d}', 'abcd'.substr( ((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)); }
[ "function", "tileUrlFunction", "(", "tileCoord", ")", "{", "return", "(", "'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/'", "+", "'{z}/{x}/{y}.vector.pbf?access_token='", "+", "key", ")", ".", "replace", "(", "'{z}'", ",", "String", "(", "tileCoord", "[", "0", "]", "*", "2", "-", "1", ")", ")", ".", "replace", "(", "'{x}'", ",", "String", "(", "tileCoord", "[", "1", "]", ")", ")", ".", "replace", "(", "'{y}'", ",", "String", "(", "tileCoord", "[", "2", "]", ")", ")", ".", "replace", "(", "'{a-d}'", ",", "'abcd'", ".", "substr", "(", "(", "(", "tileCoord", "[", "1", "]", "<<", "tileCoord", "[", "0", "]", ")", "+", "tileCoord", "[", "2", "]", ")", "%", "4", ",", "1", ")", ")", ";", "}" ]
Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15.
[ "Calculation", "of", "tile", "urls", "for", "zoom", "levels", "1", "3", "5", "7", "9", "11", "13", "15", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/mapbox-vector-tiles-advanced.js#L19-L27
1,224
openlayers/openlayers
config/jsdoc/api/plugins/inline-options.js
function(e) { if (e.doclet.kind == 'typedef' && e.doclet.properties) { properties[e.doclet.longname] = e.doclet.properties; } }
javascript
function(e) { if (e.doclet.kind == 'typedef' && e.doclet.properties) { properties[e.doclet.longname] = e.doclet.properties; } }
[ "function", "(", "e", ")", "{", "if", "(", "e", ".", "doclet", ".", "kind", "==", "'typedef'", "&&", "e", ".", "doclet", ".", "properties", ")", "{", "properties", "[", "e", ".", "doclet", ".", "longname", "]", "=", "e", ".", "doclet", ".", "properties", ";", "}", "}" ]
Collects all typedefs, keyed by longname @param {Object} e Event object.
[ "Collects", "all", "typedefs", "keyed", "by", "longname" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/config/jsdoc/api/plugins/inline-options.js#L14-L18
1,225
openlayers/openlayers
tasks/generate-info.js
getBinaryPath
function getBinaryPath(binaryName) { if (isWindows) { binaryName += '.cmd'; } const jsdocResolved = require.resolve('jsdoc/jsdoc.js'); const expectedPaths = [ path.join(__dirname, '..', 'node_modules', '.bin', binaryName), path.resolve(path.join(path.dirname(jsdocResolved), '..', '.bin', binaryName)) ]; for (let i = 0; i < expectedPaths.length; i++) { const expectedPath = expectedPaths[i]; if (fse.existsSync(expectedPath)) { return expectedPath; } } throw Error('JsDoc binary was not found in any of the expected paths: ' + expectedPaths); }
javascript
function getBinaryPath(binaryName) { if (isWindows) { binaryName += '.cmd'; } const jsdocResolved = require.resolve('jsdoc/jsdoc.js'); const expectedPaths = [ path.join(__dirname, '..', 'node_modules', '.bin', binaryName), path.resolve(path.join(path.dirname(jsdocResolved), '..', '.bin', binaryName)) ]; for (let i = 0; i < expectedPaths.length; i++) { const expectedPath = expectedPaths[i]; if (fse.existsSync(expectedPath)) { return expectedPath; } } throw Error('JsDoc binary was not found in any of the expected paths: ' + expectedPaths); }
[ "function", "getBinaryPath", "(", "binaryName", ")", "{", "if", "(", "isWindows", ")", "{", "binaryName", "+=", "'.cmd'", ";", "}", "const", "jsdocResolved", "=", "require", ".", "resolve", "(", "'jsdoc/jsdoc.js'", ")", ";", "const", "expectedPaths", "=", "[", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'node_modules'", ",", "'.bin'", ",", "binaryName", ")", ",", "path", ".", "resolve", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "jsdocResolved", ")", ",", "'..'", ",", "'.bin'", ",", "binaryName", ")", ")", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "expectedPaths", ".", "length", ";", "i", "++", ")", "{", "const", "expectedPath", "=", "expectedPaths", "[", "i", "]", ";", "if", "(", "fse", ".", "existsSync", "(", "expectedPath", ")", ")", "{", "return", "expectedPath", ";", "}", "}", "throw", "Error", "(", "'JsDoc binary was not found in any of the expected paths: '", "+", "expectedPaths", ")", ";", "}" ]
Get checked path of a binary. @param {string} binaryName Binary name of the binary path to find. @return {string} Path.
[ "Get", "checked", "path", "of", "a", "binary", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-info.js#L15-L34
1,226
openlayers/openlayers
tasks/generate-info.js
getPaths
function getPaths() { return new Promise((resolve, reject) => { let paths = []; const walker = walk(sourceDir); walker.on('file', (root, stats, next) => { const sourcePath = path.join(root, stats.name); if (/\.js$/.test(sourcePath)) { paths.push(sourcePath); } next(); }); walker.on('errors', () => { reject(new Error(`Trouble walking ${sourceDir}`)); }); walker.on('end', () => { /** * Windows has restrictions on length of command line, so passing all the * changed paths to a task will fail if this limit is exceeded. * To get round this, if this is Windows and there are newer files, just * pass the sourceDir to the task so it can do the walking. */ if (isWindows) { paths = [sourceDir]; } resolve(paths); }); }); }
javascript
function getPaths() { return new Promise((resolve, reject) => { let paths = []; const walker = walk(sourceDir); walker.on('file', (root, stats, next) => { const sourcePath = path.join(root, stats.name); if (/\.js$/.test(sourcePath)) { paths.push(sourcePath); } next(); }); walker.on('errors', () => { reject(new Error(`Trouble walking ${sourceDir}`)); }); walker.on('end', () => { /** * Windows has restrictions on length of command line, so passing all the * changed paths to a task will fail if this limit is exceeded. * To get round this, if this is Windows and there are newer files, just * pass the sourceDir to the task so it can do the walking. */ if (isWindows) { paths = [sourceDir]; } resolve(paths); }); }); }
[ "function", "getPaths", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "paths", "=", "[", "]", ";", "const", "walker", "=", "walk", "(", "sourceDir", ")", ";", "walker", ".", "on", "(", "'file'", ",", "(", "root", ",", "stats", ",", "next", ")", "=>", "{", "const", "sourcePath", "=", "path", ".", "join", "(", "root", ",", "stats", ".", "name", ")", ";", "if", "(", "/", "\\.js$", "/", ".", "test", "(", "sourcePath", ")", ")", "{", "paths", ".", "push", "(", "sourcePath", ")", ";", "}", "next", "(", ")", ";", "}", ")", ";", "walker", ".", "on", "(", "'errors'", ",", "(", ")", "=>", "{", "reject", "(", "new", "Error", "(", "`", "${", "sourceDir", "}", "`", ")", ")", ";", "}", ")", ";", "walker", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "/**\n * Windows has restrictions on length of command line, so passing all the\n * changed paths to a task will fail if this limit is exceeded.\n * To get round this, if this is Windows and there are newer files, just\n * pass the sourceDir to the task so it can do the walking.\n */", "if", "(", "isWindows", ")", "{", "paths", "=", "[", "sourceDir", "]", ";", "}", "resolve", "(", "paths", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Generate a list of all .js paths in the source directory. @return {Promise<Array>} Resolves to an array of source paths.
[ "Generate", "a", "list", "of", "all", ".", "js", "paths", "in", "the", "source", "directory", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-info.js#L46-L76
1,227
openlayers/openlayers
tasks/generate-info.js
parseOutput
function parseOutput(output) { if (!output) { throw new Error('Expected JSON output'); } let info; try { info = JSON.parse(String(output)); } catch (err) { throw new Error('Failed to parse output as JSON: ' + output); } if (!Array.isArray(info.symbols)) { throw new Error('Expected symbols array: ' + output); } if (!Array.isArray(info.defines)) { throw new Error('Expected defines array: ' + output); } return info; }
javascript
function parseOutput(output) { if (!output) { throw new Error('Expected JSON output'); } let info; try { info = JSON.parse(String(output)); } catch (err) { throw new Error('Failed to parse output as JSON: ' + output); } if (!Array.isArray(info.symbols)) { throw new Error('Expected symbols array: ' + output); } if (!Array.isArray(info.defines)) { throw new Error('Expected defines array: ' + output); } return info; }
[ "function", "parseOutput", "(", "output", ")", "{", "if", "(", "!", "output", ")", "{", "throw", "new", "Error", "(", "'Expected JSON output'", ")", ";", "}", "let", "info", ";", "try", "{", "info", "=", "JSON", ".", "parse", "(", "String", "(", "output", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "'Failed to parse output as JSON: '", "+", "output", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "info", ".", "symbols", ")", ")", "{", "throw", "new", "Error", "(", "'Expected symbols array: '", "+", "output", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "info", ".", "defines", ")", ")", "{", "throw", "new", "Error", "(", "'Expected defines array: '", "+", "output", ")", ";", "}", "return", "info", ";", "}" ]
Parse the JSDoc output. @param {string} output JSDoc output @return {Object} Symbol and define info.
[ "Parse", "the", "JSDoc", "output", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-info.js#L84-L103
1,228
openlayers/openlayers
tasks/generate-info.js
spawnJSDoc
function spawnJSDoc(paths) { return new Promise((resolve, reject) => { let output = ''; let errors = ''; const cwd = path.join(__dirname, '..'); const child = spawn(jsdoc, ['-c', jsdocConfig].concat(paths), {cwd: cwd}); child.stdout.on('data', data => { output += String(data); }); child.stderr.on('data', data => { errors += String(data); }); child.on('exit', code => { if (code) { reject(new Error(errors || 'JSDoc failed with no output')); return; } let info; try { info = parseOutput(output); } catch (err) { reject(err); return; } resolve(info); }); }); }
javascript
function spawnJSDoc(paths) { return new Promise((resolve, reject) => { let output = ''; let errors = ''; const cwd = path.join(__dirname, '..'); const child = spawn(jsdoc, ['-c', jsdocConfig].concat(paths), {cwd: cwd}); child.stdout.on('data', data => { output += String(data); }); child.stderr.on('data', data => { errors += String(data); }); child.on('exit', code => { if (code) { reject(new Error(errors || 'JSDoc failed with no output')); return; } let info; try { info = parseOutput(output); } catch (err) { reject(err); return; } resolve(info); }); }); }
[ "function", "spawnJSDoc", "(", "paths", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "output", "=", "''", ";", "let", "errors", "=", "''", ";", "const", "cwd", "=", "path", ".", "join", "(", "__dirname", ",", "'..'", ")", ";", "const", "child", "=", "spawn", "(", "jsdoc", ",", "[", "'-c'", ",", "jsdocConfig", "]", ".", "concat", "(", "paths", ")", ",", "{", "cwd", ":", "cwd", "}", ")", ";", "child", ".", "stdout", ".", "on", "(", "'data'", ",", "data", "=>", "{", "output", "+=", "String", "(", "data", ")", ";", "}", ")", ";", "child", ".", "stderr", ".", "on", "(", "'data'", ",", "data", "=>", "{", "errors", "+=", "String", "(", "data", ")", ";", "}", ")", ";", "child", ".", "on", "(", "'exit'", ",", "code", "=>", "{", "if", "(", "code", ")", "{", "reject", "(", "new", "Error", "(", "errors", "||", "'JSDoc failed with no output'", ")", ")", ";", "return", ";", "}", "let", "info", ";", "try", "{", "info", "=", "parseOutput", "(", "output", ")", ";", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "resolve", "(", "info", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Spawn JSDoc. @param {Array<string>} paths Paths to source files. @return {Promise<string>} Resolves with the JSDoc output (new metadata). If provided with an empty list of paths, resolves with null.
[ "Spawn", "JSDoc", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-info.js#L112-L143
1,229
openlayers/openlayers
src/ol/pointer/MouseSource.js
mousedown
function mousedown(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { // TODO(dfreedman) workaround for some elements not sending mouseup // http://crbug/149091 if (POINTER_ID.toString() in this.pointerMap) { this.cancel(inEvent); } const e = prepareEvent(inEvent, this.dispatcher); this.pointerMap[POINTER_ID.toString()] = inEvent; this.dispatcher.down(e, inEvent); } }
javascript
function mousedown(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { // TODO(dfreedman) workaround for some elements not sending mouseup // http://crbug/149091 if (POINTER_ID.toString() in this.pointerMap) { this.cancel(inEvent); } const e = prepareEvent(inEvent, this.dispatcher); this.pointerMap[POINTER_ID.toString()] = inEvent; this.dispatcher.down(e, inEvent); } }
[ "function", "mousedown", "(", "inEvent", ")", "{", "if", "(", "!", "this", ".", "isEventSimulatedFromTouch_", "(", "inEvent", ")", ")", "{", "// TODO(dfreedman) workaround for some elements not sending mouseup", "// http://crbug/149091", "if", "(", "POINTER_ID", ".", "toString", "(", ")", "in", "this", ".", "pointerMap", ")", "{", "this", ".", "cancel", "(", "inEvent", ")", ";", "}", "const", "e", "=", "prepareEvent", "(", "inEvent", ",", "this", ".", "dispatcher", ")", ";", "this", ".", "pointerMap", "[", "POINTER_ID", ".", "toString", "(", ")", "]", "=", "inEvent", ";", "this", ".", "dispatcher", ".", "down", "(", "e", ",", "inEvent", ")", ";", "}", "}" ]
Handler for `mousedown`. @this {MouseSource} @param {MouseEvent} inEvent The in event.
[ "Handler", "for", "mousedown", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MouseSource.js#L63-L74
1,230
openlayers/openlayers
src/ol/pointer/MouseSource.js
mousemove
function mousemove(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.move(e, inEvent); } }
javascript
function mousemove(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.move(e, inEvent); } }
[ "function", "mousemove", "(", "inEvent", ")", "{", "if", "(", "!", "this", ".", "isEventSimulatedFromTouch_", "(", "inEvent", ")", ")", "{", "const", "e", "=", "prepareEvent", "(", "inEvent", ",", "this", ".", "dispatcher", ")", ";", "this", ".", "dispatcher", ".", "move", "(", "e", ",", "inEvent", ")", ";", "}", "}" ]
Handler for `mousemove`. @this {MouseSource} @param {MouseEvent} inEvent The in event.
[ "Handler", "for", "mousemove", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MouseSource.js#L82-L87
1,231
openlayers/openlayers
src/ol/pointer/MouseSource.js
mouseup
function mouseup(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const p = this.pointerMap[POINTER_ID.toString()]; if (p && p.button === inEvent.button) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.up(e, inEvent); this.cleanupMouse(); } } }
javascript
function mouseup(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const p = this.pointerMap[POINTER_ID.toString()]; if (p && p.button === inEvent.button) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.up(e, inEvent); this.cleanupMouse(); } } }
[ "function", "mouseup", "(", "inEvent", ")", "{", "if", "(", "!", "this", ".", "isEventSimulatedFromTouch_", "(", "inEvent", ")", ")", "{", "const", "p", "=", "this", ".", "pointerMap", "[", "POINTER_ID", ".", "toString", "(", ")", "]", ";", "if", "(", "p", "&&", "p", ".", "button", "===", "inEvent", ".", "button", ")", "{", "const", "e", "=", "prepareEvent", "(", "inEvent", ",", "this", ".", "dispatcher", ")", ";", "this", ".", "dispatcher", ".", "up", "(", "e", ",", "inEvent", ")", ";", "this", ".", "cleanupMouse", "(", ")", ";", "}", "}", "}" ]
Handler for `mouseup`. @this {MouseSource} @param {MouseEvent} inEvent The in event.
[ "Handler", "for", "mouseup", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MouseSource.js#L95-L105
1,232
openlayers/openlayers
src/ol/pointer/MouseSource.js
mouseover
function mouseover(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.enterOver(e, inEvent); } }
javascript
function mouseover(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.enterOver(e, inEvent); } }
[ "function", "mouseover", "(", "inEvent", ")", "{", "if", "(", "!", "this", ".", "isEventSimulatedFromTouch_", "(", "inEvent", ")", ")", "{", "const", "e", "=", "prepareEvent", "(", "inEvent", ",", "this", ".", "dispatcher", ")", ";", "this", ".", "dispatcher", ".", "enterOver", "(", "e", ",", "inEvent", ")", ";", "}", "}" ]
Handler for `mouseover`. @this {MouseSource} @param {MouseEvent} inEvent The in event.
[ "Handler", "for", "mouseover", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MouseSource.js#L113-L118
1,233
openlayers/openlayers
src/ol/pointer/MouseSource.js
mouseout
function mouseout(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.leaveOut(e, inEvent); } }
javascript
function mouseout(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { const e = prepareEvent(inEvent, this.dispatcher); this.dispatcher.leaveOut(e, inEvent); } }
[ "function", "mouseout", "(", "inEvent", ")", "{", "if", "(", "!", "this", ".", "isEventSimulatedFromTouch_", "(", "inEvent", ")", ")", "{", "const", "e", "=", "prepareEvent", "(", "inEvent", ",", "this", ".", "dispatcher", ")", ";", "this", ".", "dispatcher", ".", "leaveOut", "(", "e", ",", "inEvent", ")", ";", "}", "}" ]
Handler for `mouseout`. @this {MouseSource} @param {MouseEvent} inEvent The in event.
[ "Handler", "for", "mouseout", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/pointer/MouseSource.js#L126-L131
1,234
openlayers/openlayers
src/ol/interaction/Extent.js
function(point) { let x_ = null; let y_ = null; if (point[0] == extent[0]) { x_ = extent[2]; } else if (point[0] == extent[2]) { x_ = extent[0]; } if (point[1] == extent[1]) { y_ = extent[3]; } else if (point[1] == extent[3]) { y_ = extent[1]; } if (x_ !== null && y_ !== null) { return [x_, y_]; } return null; }
javascript
function(point) { let x_ = null; let y_ = null; if (point[0] == extent[0]) { x_ = extent[2]; } else if (point[0] == extent[2]) { x_ = extent[0]; } if (point[1] == extent[1]) { y_ = extent[3]; } else if (point[1] == extent[3]) { y_ = extent[1]; } if (x_ !== null && y_ !== null) { return [x_, y_]; } return null; }
[ "function", "(", "point", ")", "{", "let", "x_", "=", "null", ";", "let", "y_", "=", "null", ";", "if", "(", "point", "[", "0", "]", "==", "extent", "[", "0", "]", ")", "{", "x_", "=", "extent", "[", "2", "]", ";", "}", "else", "if", "(", "point", "[", "0", "]", "==", "extent", "[", "2", "]", ")", "{", "x_", "=", "extent", "[", "0", "]", ";", "}", "if", "(", "point", "[", "1", "]", "==", "extent", "[", "1", "]", ")", "{", "y_", "=", "extent", "[", "3", "]", ";", "}", "else", "if", "(", "point", "[", "1", "]", "==", "extent", "[", "3", "]", ")", "{", "y_", "=", "extent", "[", "1", "]", ";", "}", "if", "(", "x_", "!==", "null", "&&", "y_", "!==", "null", ")", "{", "return", "[", "x_", ",", "y_", "]", ";", "}", "return", "null", ";", "}" ]
find the extent corner opposite the passed corner
[ "find", "the", "extent", "corner", "opposite", "the", "passed", "corner" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/interaction/Extent.js#L302-L319
1,235
openlayers/openlayers
src/ol/color.js
fromNamed
function fromNamed(color) { const el = document.createElement('div'); el.style.color = color; if (el.style.color !== '') { document.body.appendChild(el); const rgb = getComputedStyle(el).color; document.body.removeChild(el); return rgb; } else { return ''; } }
javascript
function fromNamed(color) { const el = document.createElement('div'); el.style.color = color; if (el.style.color !== '') { document.body.appendChild(el); const rgb = getComputedStyle(el).color; document.body.removeChild(el); return rgb; } else { return ''; } }
[ "function", "fromNamed", "(", "color", ")", "{", "const", "el", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "el", ".", "style", ".", "color", "=", "color", ";", "if", "(", "el", ".", "style", ".", "color", "!==", "''", ")", "{", "document", ".", "body", ".", "appendChild", "(", "el", ")", ";", "const", "rgb", "=", "getComputedStyle", "(", "el", ")", ".", "color", ";", "document", ".", "body", ".", "removeChild", "(", "el", ")", ";", "return", "rgb", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Return named color as an rgba string. @param {string} color Named color. @return {string} Rgb string.
[ "Return", "named", "color", "as", "an", "rgba", "string", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/color.js#L55-L66
1,236
openlayers/openlayers
tasks/generate-index.js
getSymbols
async function getSymbols() { const info = await generateInfo(); return info.symbols.filter(symbol => symbol.kind != 'member'); }
javascript
async function getSymbols() { const info = await generateInfo(); return info.symbols.filter(symbol => symbol.kind != 'member'); }
[ "async", "function", "getSymbols", "(", ")", "{", "const", "info", "=", "await", "generateInfo", "(", ")", ";", "return", "info", ".", "symbols", ".", "filter", "(", "symbol", "=>", "symbol", ".", "kind", "!=", "'member'", ")", ";", "}" ]
Read the symbols from info file. @return {Promise<Array>} Resolves with an array of symbol objects.
[ "Read", "the", "symbols", "from", "info", "file", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-index.js#L10-L13
1,237
openlayers/openlayers
tasks/generate-index.js
getImport
function getImport(symbol, member) { const defaultExport = symbol.name.split('~'); const namedExport = symbol.name.split('.'); if (defaultExport.length > 1) { const from = defaultExport[0].replace(/^module\:/, './'); const importName = from.replace(/[.\/]+/g, '$'); return `import ${importName} from '${from}';`; } else if (namedExport.length > 1 && member) { const from = namedExport[0].replace(/^module\:/, './'); const importName = from.replace(/[.\/]+/g, '_'); return `import {${member} as ${importName}$${member}} from '${from}';`; } }
javascript
function getImport(symbol, member) { const defaultExport = symbol.name.split('~'); const namedExport = symbol.name.split('.'); if (defaultExport.length > 1) { const from = defaultExport[0].replace(/^module\:/, './'); const importName = from.replace(/[.\/]+/g, '$'); return `import ${importName} from '${from}';`; } else if (namedExport.length > 1 && member) { const from = namedExport[0].replace(/^module\:/, './'); const importName = from.replace(/[.\/]+/g, '_'); return `import {${member} as ${importName}$${member}} from '${from}';`; } }
[ "function", "getImport", "(", "symbol", ",", "member", ")", "{", "const", "defaultExport", "=", "symbol", ".", "name", ".", "split", "(", "'~'", ")", ";", "const", "namedExport", "=", "symbol", ".", "name", ".", "split", "(", "'.'", ")", ";", "if", "(", "defaultExport", ".", "length", ">", "1", ")", "{", "const", "from", "=", "defaultExport", "[", "0", "]", ".", "replace", "(", "/", "^module\\:", "/", ",", "'./'", ")", ";", "const", "importName", "=", "from", ".", "replace", "(", "/", "[.\\/]+", "/", "g", ",", "'$'", ")", ";", "return", "`", "${", "importName", "}", "${", "from", "}", "`", ";", "}", "else", "if", "(", "namedExport", ".", "length", ">", "1", "&&", "member", ")", "{", "const", "from", "=", "namedExport", "[", "0", "]", ".", "replace", "(", "/", "^module\\:", "/", ",", "'./'", ")", ";", "const", "importName", "=", "from", ".", "replace", "(", "/", "[.\\/]+", "/", "g", ",", "'_'", ")", ";", "return", "`", "${", "member", "}", "${", "importName", "}", "${", "member", "}", "${", "from", "}", "`", ";", "}", "}" ]
Generate an import statement. @param {Object} symbol Symbol. @param {string} member Member. @return {string} An import statement.
[ "Generate", "an", "import", "statement", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-index.js#L21-L33
1,238
openlayers/openlayers
tasks/generate-index.js
formatSymbolExport
function formatSymbolExport(symbol, namespaces, imports) { const name = symbol.name; const parts = name.split('~'); const isNamed = parts[0].indexOf('.') !== -1; const nsParts = parts[0].replace(/^module\:/, '').split(/[\/\.]/); const last = nsParts.length - 1; const importName = isNamed ? '_' + nsParts.slice(0, last).join('_') + '$' + nsParts[last] : '$' + nsParts.join('$'); let line = nsParts[0]; for (let i = 1, ii = nsParts.length; i < ii; ++i) { line += `.${nsParts[i]}`; namespaces[line] = (line in namespaces ? namespaces[line] : true) && i < ii - 1; } line += ` = ${importName};`; imports[getImport(symbol, nsParts.pop())] = true; return line; }
javascript
function formatSymbolExport(symbol, namespaces, imports) { const name = symbol.name; const parts = name.split('~'); const isNamed = parts[0].indexOf('.') !== -1; const nsParts = parts[0].replace(/^module\:/, '').split(/[\/\.]/); const last = nsParts.length - 1; const importName = isNamed ? '_' + nsParts.slice(0, last).join('_') + '$' + nsParts[last] : '$' + nsParts.join('$'); let line = nsParts[0]; for (let i = 1, ii = nsParts.length; i < ii; ++i) { line += `.${nsParts[i]}`; namespaces[line] = (line in namespaces ? namespaces[line] : true) && i < ii - 1; } line += ` = ${importName};`; imports[getImport(symbol, nsParts.pop())] = true; return line; }
[ "function", "formatSymbolExport", "(", "symbol", ",", "namespaces", ",", "imports", ")", "{", "const", "name", "=", "symbol", ".", "name", ";", "const", "parts", "=", "name", ".", "split", "(", "'~'", ")", ";", "const", "isNamed", "=", "parts", "[", "0", "]", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ";", "const", "nsParts", "=", "parts", "[", "0", "]", ".", "replace", "(", "/", "^module\\:", "/", ",", "''", ")", ".", "split", "(", "/", "[\\/\\.]", "/", ")", ";", "const", "last", "=", "nsParts", ".", "length", "-", "1", ";", "const", "importName", "=", "isNamed", "?", "'_'", "+", "nsParts", ".", "slice", "(", "0", ",", "last", ")", ".", "join", "(", "'_'", ")", "+", "'$'", "+", "nsParts", "[", "last", "]", ":", "'$'", "+", "nsParts", ".", "join", "(", "'$'", ")", ";", "let", "line", "=", "nsParts", "[", "0", "]", ";", "for", "(", "let", "i", "=", "1", ",", "ii", "=", "nsParts", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "line", "+=", "`", "${", "nsParts", "[", "i", "]", "}", "`", ";", "namespaces", "[", "line", "]", "=", "(", "line", "in", "namespaces", "?", "namespaces", "[", "line", "]", ":", "true", ")", "&&", "i", "<", "ii", "-", "1", ";", "}", "line", "+=", "`", "${", "importName", "}", "`", ";", "imports", "[", "getImport", "(", "symbol", ",", "nsParts", ".", "pop", "(", ")", ")", "]", "=", "true", ";", "return", "line", ";", "}" ]
Generate code to export a named symbol. @param {Object} symbol Symbol. @param {Object<string, string>} namespaces Already defined namespaces. @param {Object} imports Imports. @return {string} Export code.
[ "Generate", "code", "to", "export", "a", "named", "symbol", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-index.js#L43-L60
1,239
openlayers/openlayers
tasks/generate-index.js
generateExports
function generateExports(symbols) { const namespaces = {}; const imports = []; let blocks = []; symbols.forEach(function(symbol) { const name = symbol.name; if (name.indexOf('#') == -1) { const imp = getImport(symbol); if (imp) { imports[getImport(symbol)] = true; } const block = formatSymbolExport(symbol, namespaces, imports); if (block !== blocks[blocks.length - 1]) { blocks.push(block); } } }); const nsdefs = []; const ns = Object.keys(namespaces).sort(); for (let i = 0, ii = ns.length; i < ii; ++i) { if (namespaces[ns[i]]) { nsdefs.push(`${ns[i]} = {};`); } } blocks = Object.keys(imports).concat('\nvar ol = {};\n', nsdefs.sort()).concat(blocks.sort()); blocks.push('', 'export default ol;'); return blocks.join('\n'); }
javascript
function generateExports(symbols) { const namespaces = {}; const imports = []; let blocks = []; symbols.forEach(function(symbol) { const name = symbol.name; if (name.indexOf('#') == -1) { const imp = getImport(symbol); if (imp) { imports[getImport(symbol)] = true; } const block = formatSymbolExport(symbol, namespaces, imports); if (block !== blocks[blocks.length - 1]) { blocks.push(block); } } }); const nsdefs = []; const ns = Object.keys(namespaces).sort(); for (let i = 0, ii = ns.length; i < ii; ++i) { if (namespaces[ns[i]]) { nsdefs.push(`${ns[i]} = {};`); } } blocks = Object.keys(imports).concat('\nvar ol = {};\n', nsdefs.sort()).concat(blocks.sort()); blocks.push('', 'export default ol;'); return blocks.join('\n'); }
[ "function", "generateExports", "(", "symbols", ")", "{", "const", "namespaces", "=", "{", "}", ";", "const", "imports", "=", "[", "]", ";", "let", "blocks", "=", "[", "]", ";", "symbols", ".", "forEach", "(", "function", "(", "symbol", ")", "{", "const", "name", "=", "symbol", ".", "name", ";", "if", "(", "name", ".", "indexOf", "(", "'#'", ")", "==", "-", "1", ")", "{", "const", "imp", "=", "getImport", "(", "symbol", ")", ";", "if", "(", "imp", ")", "{", "imports", "[", "getImport", "(", "symbol", ")", "]", "=", "true", ";", "}", "const", "block", "=", "formatSymbolExport", "(", "symbol", ",", "namespaces", ",", "imports", ")", ";", "if", "(", "block", "!==", "blocks", "[", "blocks", ".", "length", "-", "1", "]", ")", "{", "blocks", ".", "push", "(", "block", ")", ";", "}", "}", "}", ")", ";", "const", "nsdefs", "=", "[", "]", ";", "const", "ns", "=", "Object", ".", "keys", "(", "namespaces", ")", ".", "sort", "(", ")", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "ns", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "if", "(", "namespaces", "[", "ns", "[", "i", "]", "]", ")", "{", "nsdefs", ".", "push", "(", "`", "${", "ns", "[", "i", "]", "}", "`", ")", ";", "}", "}", "blocks", "=", "Object", ".", "keys", "(", "imports", ")", ".", "concat", "(", "'\\nvar ol = {};\\n'", ",", "nsdefs", ".", "sort", "(", ")", ")", ".", "concat", "(", "blocks", ".", "sort", "(", ")", ")", ";", "blocks", ".", "push", "(", "''", ",", "'export default ol;'", ")", ";", "return", "blocks", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Generate export code given a list symbol names. @param {Array<Object>} symbols List of symbols. @param {Object<string, string>} namespaces Already defined namespaces. @param {Array<string>} imports List of all imports. @return {string} Export code.
[ "Generate", "export", "code", "given", "a", "list", "symbol", "names", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/tasks/generate-index.js#L70-L97
1,240
openlayers/openlayers
src/ol/control/FullScreen.js
requestFullScreen
function requestFullScreen(element) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } }
javascript
function requestFullScreen(element) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } }
[ "function", "requestFullScreen", "(", "element", ")", "{", "if", "(", "element", ".", "requestFullscreen", ")", "{", "element", ".", "requestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "msRequestFullscreen", ")", "{", "element", ".", "msRequestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "webkitRequestFullscreen", ")", "{", "element", ".", "webkitRequestFullscreen", "(", ")", ";", "}", "}" ]
Request to fullscreen an element. @param {HTMLElement} element Element to request fullscreen
[ "Request", "to", "fullscreen", "an", "element", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/control/FullScreen.js#L230-L238
1,241
openlayers/openlayers
src/ol/control/FullScreen.js
exitFullScreen
function exitFullScreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } }
javascript
function exitFullScreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } }
[ "function", "exitFullScreen", "(", ")", "{", "if", "(", "document", ".", "exitFullscreen", ")", "{", "document", ".", "exitFullscreen", "(", ")", ";", "}", "else", "if", "(", "document", ".", "msExitFullscreen", ")", "{", "document", ".", "msExitFullscreen", "(", ")", ";", "}", "else", "if", "(", "document", ".", "webkitExitFullscreen", ")", "{", "document", ".", "webkitExitFullscreen", "(", ")", ";", "}", "}" ]
Exit fullscreen.
[ "Exit", "fullscreen", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/control/FullScreen.js#L255-L263
1,242
openlayers/openlayers
src/ol/format/MVT.js
layersPBFReader
function layersPBFReader(tag, layers, pbf) { if (tag === 3) { const layer = { keys: [], values: [], features: [] }; const end = pbf.readVarint() + pbf.pos; pbf.readFields(layerPBFReader, layer, end); layer.length = layer.features.length; if (layer.length) { layers[layer.name] = layer; } } }
javascript
function layersPBFReader(tag, layers, pbf) { if (tag === 3) { const layer = { keys: [], values: [], features: [] }; const end = pbf.readVarint() + pbf.pos; pbf.readFields(layerPBFReader, layer, end); layer.length = layer.features.length; if (layer.length) { layers[layer.name] = layer; } } }
[ "function", "layersPBFReader", "(", "tag", ",", "layers", ",", "pbf", ")", "{", "if", "(", "tag", "===", "3", ")", "{", "const", "layer", "=", "{", "keys", ":", "[", "]", ",", "values", ":", "[", "]", ",", "features", ":", "[", "]", "}", ";", "const", "end", "=", "pbf", ".", "readVarint", "(", ")", "+", "pbf", ".", "pos", ";", "pbf", ".", "readFields", "(", "layerPBFReader", ",", "layer", ",", "end", ")", ";", "layer", ".", "length", "=", "layer", ".", "features", ".", "length", ";", "if", "(", "layer", ".", "length", ")", "{", "layers", "[", "layer", ".", "name", "]", "=", "layer", ";", "}", "}", "}" ]
Reader callback for parsing layers. @param {number} tag The tag. @param {Object} layers The layers object. @param {PBF} pbf The PBF.
[ "Reader", "callback", "for", "parsing", "layers", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/MVT.js#L290-L304
1,243
openlayers/openlayers
src/ol/format/MVT.js
layerPBFReader
function layerPBFReader(tag, layer, pbf) { if (tag === 15) { layer.version = pbf.readVarint(); } else if (tag === 1) { layer.name = pbf.readString(); } else if (tag === 5) { layer.extent = pbf.readVarint(); } else if (tag === 2) { layer.features.push(pbf.pos); } else if (tag === 3) { layer.keys.push(pbf.readString()); } else if (tag === 4) { let value = null; const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { tag = pbf.readVarint() >> 3; value = tag === 1 ? pbf.readString() : tag === 2 ? pbf.readFloat() : tag === 3 ? pbf.readDouble() : tag === 4 ? pbf.readVarint64() : tag === 5 ? pbf.readVarint() : tag === 6 ? pbf.readSVarint() : tag === 7 ? pbf.readBoolean() : null; } layer.values.push(value); } }
javascript
function layerPBFReader(tag, layer, pbf) { if (tag === 15) { layer.version = pbf.readVarint(); } else if (tag === 1) { layer.name = pbf.readString(); } else if (tag === 5) { layer.extent = pbf.readVarint(); } else if (tag === 2) { layer.features.push(pbf.pos); } else if (tag === 3) { layer.keys.push(pbf.readString()); } else if (tag === 4) { let value = null; const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { tag = pbf.readVarint() >> 3; value = tag === 1 ? pbf.readString() : tag === 2 ? pbf.readFloat() : tag === 3 ? pbf.readDouble() : tag === 4 ? pbf.readVarint64() : tag === 5 ? pbf.readVarint() : tag === 6 ? pbf.readSVarint() : tag === 7 ? pbf.readBoolean() : null; } layer.values.push(value); } }
[ "function", "layerPBFReader", "(", "tag", ",", "layer", ",", "pbf", ")", "{", "if", "(", "tag", "===", "15", ")", "{", "layer", ".", "version", "=", "pbf", ".", "readVarint", "(", ")", ";", "}", "else", "if", "(", "tag", "===", "1", ")", "{", "layer", ".", "name", "=", "pbf", ".", "readString", "(", ")", ";", "}", "else", "if", "(", "tag", "===", "5", ")", "{", "layer", ".", "extent", "=", "pbf", ".", "readVarint", "(", ")", ";", "}", "else", "if", "(", "tag", "===", "2", ")", "{", "layer", ".", "features", ".", "push", "(", "pbf", ".", "pos", ")", ";", "}", "else", "if", "(", "tag", "===", "3", ")", "{", "layer", ".", "keys", ".", "push", "(", "pbf", ".", "readString", "(", ")", ")", ";", "}", "else", "if", "(", "tag", "===", "4", ")", "{", "let", "value", "=", "null", ";", "const", "end", "=", "pbf", ".", "readVarint", "(", ")", "+", "pbf", ".", "pos", ";", "while", "(", "pbf", ".", "pos", "<", "end", ")", "{", "tag", "=", "pbf", ".", "readVarint", "(", ")", ">>", "3", ";", "value", "=", "tag", "===", "1", "?", "pbf", ".", "readString", "(", ")", ":", "tag", "===", "2", "?", "pbf", ".", "readFloat", "(", ")", ":", "tag", "===", "3", "?", "pbf", ".", "readDouble", "(", ")", ":", "tag", "===", "4", "?", "pbf", ".", "readVarint64", "(", ")", ":", "tag", "===", "5", "?", "pbf", ".", "readVarint", "(", ")", ":", "tag", "===", "6", "?", "pbf", ".", "readSVarint", "(", ")", ":", "tag", "===", "7", "?", "pbf", ".", "readBoolean", "(", ")", ":", "null", ";", "}", "layer", ".", "values", ".", "push", "(", "value", ")", ";", "}", "}" ]
Reader callback for parsing layer. @param {number} tag The tag. @param {Object} layer The layer object. @param {PBF} pbf The PBF.
[ "Reader", "callback", "for", "parsing", "layer", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/MVT.js#L312-L338
1,244
openlayers/openlayers
src/ol/format/MVT.js
featurePBFReader
function featurePBFReader(tag, feature, pbf) { if (tag == 1) { feature.id = pbf.readVarint(); } else if (tag == 2) { const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { const key = feature.layer.keys[pbf.readVarint()]; const value = feature.layer.values[pbf.readVarint()]; feature.properties[key] = value; } } else if (tag == 3) { feature.type = pbf.readVarint(); } else if (tag == 4) { feature.geometry = pbf.pos; } }
javascript
function featurePBFReader(tag, feature, pbf) { if (tag == 1) { feature.id = pbf.readVarint(); } else if (tag == 2) { const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { const key = feature.layer.keys[pbf.readVarint()]; const value = feature.layer.values[pbf.readVarint()]; feature.properties[key] = value; } } else if (tag == 3) { feature.type = pbf.readVarint(); } else if (tag == 4) { feature.geometry = pbf.pos; } }
[ "function", "featurePBFReader", "(", "tag", ",", "feature", ",", "pbf", ")", "{", "if", "(", "tag", "==", "1", ")", "{", "feature", ".", "id", "=", "pbf", ".", "readVarint", "(", ")", ";", "}", "else", "if", "(", "tag", "==", "2", ")", "{", "const", "end", "=", "pbf", ".", "readVarint", "(", ")", "+", "pbf", ".", "pos", ";", "while", "(", "pbf", ".", "pos", "<", "end", ")", "{", "const", "key", "=", "feature", ".", "layer", ".", "keys", "[", "pbf", ".", "readVarint", "(", ")", "]", ";", "const", "value", "=", "feature", ".", "layer", ".", "values", "[", "pbf", ".", "readVarint", "(", ")", "]", ";", "feature", ".", "properties", "[", "key", "]", "=", "value", ";", "}", "}", "else", "if", "(", "tag", "==", "3", ")", "{", "feature", ".", "type", "=", "pbf", ".", "readVarint", "(", ")", ";", "}", "else", "if", "(", "tag", "==", "4", ")", "{", "feature", ".", "geometry", "=", "pbf", ".", "pos", ";", "}", "}" ]
Reader callback for parsing feature. @param {number} tag The tag. @param {Object} feature The feature object. @param {PBF} pbf The PBF.
[ "Reader", "callback", "for", "parsing", "feature", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/MVT.js#L346-L361
1,245
openlayers/openlayers
src/ol/format/MVT.js
readRawFeature
function readRawFeature(pbf, layer, i) { pbf.pos = layer.features[i]; const end = pbf.readVarint() + pbf.pos; const feature = { layer: layer, type: 0, properties: {} }; pbf.readFields(featurePBFReader, feature, end); return feature; }
javascript
function readRawFeature(pbf, layer, i) { pbf.pos = layer.features[i]; const end = pbf.readVarint() + pbf.pos; const feature = { layer: layer, type: 0, properties: {} }; pbf.readFields(featurePBFReader, feature, end); return feature; }
[ "function", "readRawFeature", "(", "pbf", ",", "layer", ",", "i", ")", "{", "pbf", ".", "pos", "=", "layer", ".", "features", "[", "i", "]", ";", "const", "end", "=", "pbf", ".", "readVarint", "(", ")", "+", "pbf", ".", "pos", ";", "const", "feature", "=", "{", "layer", ":", "layer", ",", "type", ":", "0", ",", "properties", ":", "{", "}", "}", ";", "pbf", ".", "readFields", "(", "featurePBFReader", ",", "feature", ",", "end", ")", ";", "return", "feature", ";", "}" ]
Read a raw feature from the pbf offset stored at index `i` in the raw layer. @param {PBF} pbf PBF. @param {Object} layer Raw layer. @param {number} i Index of the feature in the raw layer's `features` array. @return {Object} Raw feature.
[ "Read", "a", "raw", "feature", "from", "the", "pbf", "offset", "stored", "at", "index", "i", "in", "the", "raw", "layer", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/MVT.js#L371-L382
1,246
openlayers/openlayers
examples/raster.js
summarize
function summarize(value, counts) { const min = counts.min; const max = counts.max; const num = counts.values.length; if (value < min) { // do nothing } else if (value >= max) { counts.values[num - 1] += 1; } else { const index = Math.floor((value - min) / counts.delta); counts.values[index] += 1; } }
javascript
function summarize(value, counts) { const min = counts.min; const max = counts.max; const num = counts.values.length; if (value < min) { // do nothing } else if (value >= max) { counts.values[num - 1] += 1; } else { const index = Math.floor((value - min) / counts.delta); counts.values[index] += 1; } }
[ "function", "summarize", "(", "value", ",", "counts", ")", "{", "const", "min", "=", "counts", ".", "min", ";", "const", "max", "=", "counts", ".", "max", ";", "const", "num", "=", "counts", ".", "values", ".", "length", ";", "if", "(", "value", "<", "min", ")", "{", "// do nothing", "}", "else", "if", "(", "value", ">=", "max", ")", "{", "counts", ".", "values", "[", "num", "-", "1", "]", "+=", "1", ";", "}", "else", "{", "const", "index", "=", "Math", ".", "floor", "(", "(", "value", "-", "min", ")", "/", "counts", ".", "delta", ")", ";", "counts", ".", "values", "[", "index", "]", "+=", "1", ";", "}", "}" ]
Summarize values for a histogram. @param {numver} value A VGI value. @param {Object} counts An object for keeping track of VGI counts.
[ "Summarize", "values", "for", "a", "histogram", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/raster.js#L31-L43
1,247
openlayers/openlayers
examples/raster.js
function(pixels, data) { const pixel = pixels[0]; const value = vgi(pixel); summarize(value, data.counts); if (value >= data.threshold) { pixel[0] = 0; pixel[1] = 255; pixel[2] = 0; pixel[3] = 128; } else { pixel[3] = 0; } return pixel; }
javascript
function(pixels, data) { const pixel = pixels[0]; const value = vgi(pixel); summarize(value, data.counts); if (value >= data.threshold) { pixel[0] = 0; pixel[1] = 255; pixel[2] = 0; pixel[3] = 128; } else { pixel[3] = 0; } return pixel; }
[ "function", "(", "pixels", ",", "data", ")", "{", "const", "pixel", "=", "pixels", "[", "0", "]", ";", "const", "value", "=", "vgi", "(", "pixel", ")", ";", "summarize", "(", "value", ",", "data", ".", "counts", ")", ";", "if", "(", "value", ">=", "data", ".", "threshold", ")", "{", "pixel", "[", "0", "]", "=", "0", ";", "pixel", "[", "1", "]", "=", "255", ";", "pixel", "[", "2", "]", "=", "0", ";", "pixel", "[", "3", "]", "=", "128", ";", "}", "else", "{", "pixel", "[", "3", "]", "=", "0", ";", "}", "return", "pixel", ";", "}" ]
Run calculations on pixel data. @param {Array} pixels List of pixels (one per source). @param {Object} data User data object. @return {Array} The output pixel.
[ "Run", "calculations", "on", "pixel", "data", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/raster.js#L67-L80
1,248
openlayers/openlayers
src/ol/interaction/Draw.js
getMode
function getMode(type) { let mode; if (type === GeometryType.POINT || type === GeometryType.MULTI_POINT) { mode = Mode.POINT; } else if (type === GeometryType.LINE_STRING || type === GeometryType.MULTI_LINE_STRING) { mode = Mode.LINE_STRING; } else if (type === GeometryType.POLYGON || type === GeometryType.MULTI_POLYGON) { mode = Mode.POLYGON; } else if (type === GeometryType.CIRCLE) { mode = Mode.CIRCLE; } return ( /** @type {!Mode} */ (mode) ); }
javascript
function getMode(type) { let mode; if (type === GeometryType.POINT || type === GeometryType.MULTI_POINT) { mode = Mode.POINT; } else if (type === GeometryType.LINE_STRING || type === GeometryType.MULTI_LINE_STRING) { mode = Mode.LINE_STRING; } else if (type === GeometryType.POLYGON || type === GeometryType.MULTI_POLYGON) { mode = Mode.POLYGON; } else if (type === GeometryType.CIRCLE) { mode = Mode.CIRCLE; } return ( /** @type {!Mode} */ (mode) ); }
[ "function", "getMode", "(", "type", ")", "{", "let", "mode", ";", "if", "(", "type", "===", "GeometryType", ".", "POINT", "||", "type", "===", "GeometryType", ".", "MULTI_POINT", ")", "{", "mode", "=", "Mode", ".", "POINT", ";", "}", "else", "if", "(", "type", "===", "GeometryType", ".", "LINE_STRING", "||", "type", "===", "GeometryType", ".", "MULTI_LINE_STRING", ")", "{", "mode", "=", "Mode", ".", "LINE_STRING", ";", "}", "else", "if", "(", "type", "===", "GeometryType", ".", "POLYGON", "||", "type", "===", "GeometryType", ".", "MULTI_POLYGON", ")", "{", "mode", "=", "Mode", ".", "POLYGON", ";", "}", "else", "if", "(", "type", "===", "GeometryType", ".", "CIRCLE", ")", "{", "mode", "=", "Mode", ".", "CIRCLE", ";", "}", "return", "(", "/** @type {!Mode} */", "(", "mode", ")", ")", ";", "}" ]
Get the drawing mode. The mode for mult-part geometries is the same as for their single-part cousins. @param {GeometryType} type Geometry type. @return {Mode} Drawing mode.
[ "Get", "the", "drawing", "mode", ".", "The", "mode", "for", "mult", "-", "part", "geometries", "is", "the", "same", "as", "for", "their", "single", "-", "part", "cousins", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/interaction/Draw.js#L1032-L1049
1,249
openlayers/openlayers
src/ol/tilegrid.js
resolutionsFromExtent
function resolutionsFromExtent(extent, opt_maxZoom, opt_tileSize) { const maxZoom = opt_maxZoom !== undefined ? opt_maxZoom : DEFAULT_MAX_ZOOM; const height = getHeight(extent); const width = getWidth(extent); const tileSize = toSize(opt_tileSize !== undefined ? opt_tileSize : DEFAULT_TILE_SIZE); const maxResolution = Math.max( width / tileSize[0], height / tileSize[1]); const length = maxZoom + 1; const resolutions = new Array(length); for (let z = 0; z < length; ++z) { resolutions[z] = maxResolution / Math.pow(2, z); } return resolutions; }
javascript
function resolutionsFromExtent(extent, opt_maxZoom, opt_tileSize) { const maxZoom = opt_maxZoom !== undefined ? opt_maxZoom : DEFAULT_MAX_ZOOM; const height = getHeight(extent); const width = getWidth(extent); const tileSize = toSize(opt_tileSize !== undefined ? opt_tileSize : DEFAULT_TILE_SIZE); const maxResolution = Math.max( width / tileSize[0], height / tileSize[1]); const length = maxZoom + 1; const resolutions = new Array(length); for (let z = 0; z < length; ++z) { resolutions[z] = maxResolution / Math.pow(2, z); } return resolutions; }
[ "function", "resolutionsFromExtent", "(", "extent", ",", "opt_maxZoom", ",", "opt_tileSize", ")", "{", "const", "maxZoom", "=", "opt_maxZoom", "!==", "undefined", "?", "opt_maxZoom", ":", "DEFAULT_MAX_ZOOM", ";", "const", "height", "=", "getHeight", "(", "extent", ")", ";", "const", "width", "=", "getWidth", "(", "extent", ")", ";", "const", "tileSize", "=", "toSize", "(", "opt_tileSize", "!==", "undefined", "?", "opt_tileSize", ":", "DEFAULT_TILE_SIZE", ")", ";", "const", "maxResolution", "=", "Math", ".", "max", "(", "width", "/", "tileSize", "[", "0", "]", ",", "height", "/", "tileSize", "[", "1", "]", ")", ";", "const", "length", "=", "maxZoom", "+", "1", ";", "const", "resolutions", "=", "new", "Array", "(", "length", ")", ";", "for", "(", "let", "z", "=", "0", ";", "z", "<", "length", ";", "++", "z", ")", "{", "resolutions", "[", "z", "]", "=", "maxResolution", "/", "Math", ".", "pow", "(", "2", ",", "z", ")", ";", "}", "return", "resolutions", ";", "}" ]
Create a resolutions array from an extent. A zoom factor of 2 is assumed. @param {import("./extent.js").Extent} extent Extent. @param {number=} opt_maxZoom Maximum zoom level (default is DEFAULT_MAX_ZOOM). @param {number|import("./size.js").Size=} opt_tileSize Tile size (default uses DEFAULT_TILE_SIZE). @return {!Array<number>} Resolutions array.
[ "Create", "a", "resolutions", "array", "from", "an", "extent", ".", "A", "zoom", "factor", "of", "2", "is", "assumed", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/tilegrid.js#L120-L138
1,250
openlayers/openlayers
src/ol/format/WKT.js
encode
function encode(geom) { let type = geom.getType(); const geometryEncoder = GeometryEncoder[type]; const enc = geometryEncoder(geom); type = type.toUpperCase(); if (typeof /** @type {?} */ (geom).getFlatCoordinates === 'function') { const dimInfo = encodeGeometryLayout(/** @type {import("../geom/SimpleGeometry.js").default} */ (geom)); if (dimInfo.length > 0) { type += ' ' + dimInfo; } } if (enc.length === 0) { return type + ' ' + EMPTY; } return type + '(' + enc + ')'; }
javascript
function encode(geom) { let type = geom.getType(); const geometryEncoder = GeometryEncoder[type]; const enc = geometryEncoder(geom); type = type.toUpperCase(); if (typeof /** @type {?} */ (geom).getFlatCoordinates === 'function') { const dimInfo = encodeGeometryLayout(/** @type {import("../geom/SimpleGeometry.js").default} */ (geom)); if (dimInfo.length > 0) { type += ' ' + dimInfo; } } if (enc.length === 0) { return type + ' ' + EMPTY; } return type + '(' + enc + ')'; }
[ "function", "encode", "(", "geom", ")", "{", "let", "type", "=", "geom", ".", "getType", "(", ")", ";", "const", "geometryEncoder", "=", "GeometryEncoder", "[", "type", "]", ";", "const", "enc", "=", "geometryEncoder", "(", "geom", ")", ";", "type", "=", "type", ".", "toUpperCase", "(", ")", ";", "if", "(", "typeof", "/** @type {?} */", "(", "geom", ")", ".", "getFlatCoordinates", "===", "'function'", ")", "{", "const", "dimInfo", "=", "encodeGeometryLayout", "(", "/** @type {import(\"../geom/SimpleGeometry.js\").default} */", "(", "geom", ")", ")", ";", "if", "(", "dimInfo", ".", "length", ">", "0", ")", "{", "type", "+=", "' '", "+", "dimInfo", ";", "}", "}", "if", "(", "enc", ".", "length", "===", "0", ")", "{", "return", "type", "+", "' '", "+", "EMPTY", ";", "}", "return", "type", "+", "'('", "+", "enc", "+", "')'", ";", "}" ]
Encode a geometry as WKT. @param {!import("../geom/Geometry.js").default} geom The geometry to encode. @return {string} WKT string for the geometry.
[ "Encode", "a", "geometry", "as", "WKT", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/format/WKT.js#L859-L874
1,251
openlayers/openlayers
src/ol/reproj.js
enlargeClipPoint
function enlargeClipPoint(centroidX, centroidY, x, y) { const dX = x - centroidX; const dY = y - centroidY; const distance = Math.sqrt(dX * dX + dY * dY); return [Math.round(x + dX / distance), Math.round(y + dY / distance)]; }
javascript
function enlargeClipPoint(centroidX, centroidY, x, y) { const dX = x - centroidX; const dY = y - centroidY; const distance = Math.sqrt(dX * dX + dY * dY); return [Math.round(x + dX / distance), Math.round(y + dY / distance)]; }
[ "function", "enlargeClipPoint", "(", "centroidX", ",", "centroidY", ",", "x", ",", "y", ")", "{", "const", "dX", "=", "x", "-", "centroidX", ";", "const", "dY", "=", "y", "-", "centroidY", ";", "const", "distance", "=", "Math", ".", "sqrt", "(", "dX", "*", "dX", "+", "dY", "*", "dY", ")", ";", "return", "[", "Math", ".", "round", "(", "x", "+", "dX", "/", "distance", ")", ",", "Math", ".", "round", "(", "y", "+", "dY", "/", "distance", ")", "]", ";", "}" ]
Enlarge the clipping triangle point by 1 pixel to ensure the edges overlap in order to mask gaps caused by antialiasing. @param {number} centroidX Centroid of the triangle (x coordinate in pixels). @param {number} centroidY Centroid of the triangle (y coordinate in pixels). @param {number} x X coordinate of the point (in pixels). @param {number} y Y coordinate of the point (in pixels). @return {import("./coordinate.js").Coordinate} New point 1 px farther from the centroid.
[ "Enlarge", "the", "clipping", "triangle", "point", "by", "1", "pixel", "to", "ensure", "the", "edges", "overlap", "in", "order", "to", "mask", "gaps", "caused", "by", "antialiasing", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/reproj.js#L66-L71
1,252
openlayers/openlayers
src/ol/interaction/Modify.js
pointDistanceToSegmentDataSquared
function pointDistanceToSegmentDataSquared(pointCoordinates, segmentData) { const geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE) { const circleGeometry = /** @type {import("../geom/Circle.js").default} */ (geometry); if (segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) { const distanceToCenterSquared = squaredCoordinateDistance(circleGeometry.getCenter(), pointCoordinates); const distanceToCircumference = Math.sqrt(distanceToCenterSquared) - circleGeometry.getRadius(); return distanceToCircumference * distanceToCircumference; } } return squaredDistanceToSegment(pointCoordinates, segmentData.segment); }
javascript
function pointDistanceToSegmentDataSquared(pointCoordinates, segmentData) { const geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE) { const circleGeometry = /** @type {import("../geom/Circle.js").default} */ (geometry); if (segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) { const distanceToCenterSquared = squaredCoordinateDistance(circleGeometry.getCenter(), pointCoordinates); const distanceToCircumference = Math.sqrt(distanceToCenterSquared) - circleGeometry.getRadius(); return distanceToCircumference * distanceToCircumference; } } return squaredDistanceToSegment(pointCoordinates, segmentData.segment); }
[ "function", "pointDistanceToSegmentDataSquared", "(", "pointCoordinates", ",", "segmentData", ")", "{", "const", "geometry", "=", "segmentData", ".", "geometry", ";", "if", "(", "geometry", ".", "getType", "(", ")", "===", "GeometryType", ".", "CIRCLE", ")", "{", "const", "circleGeometry", "=", "/** @type {import(\"../geom/Circle.js\").default} */", "(", "geometry", ")", ";", "if", "(", "segmentData", ".", "index", "===", "CIRCLE_CIRCUMFERENCE_INDEX", ")", "{", "const", "distanceToCenterSquared", "=", "squaredCoordinateDistance", "(", "circleGeometry", ".", "getCenter", "(", ")", ",", "pointCoordinates", ")", ";", "const", "distanceToCircumference", "=", "Math", ".", "sqrt", "(", "distanceToCenterSquared", ")", "-", "circleGeometry", ".", "getRadius", "(", ")", ";", "return", "distanceToCircumference", "*", "distanceToCircumference", ";", "}", "}", "return", "squaredDistanceToSegment", "(", "pointCoordinates", ",", "segmentData", ".", "segment", ")", ";", "}" ]
Returns the distance from a point to a line segment. @param {import("../coordinate.js").Coordinate} pointCoordinates The coordinates of the point from which to calculate the distance. @param {SegmentData} segmentData The object describing the line segment we are calculating the distance to. @return {number} The square of the distance between a point and a line segment.
[ "Returns", "the", "distance", "from", "a", "point", "to", "a", "line", "segment", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/interaction/Modify.js#L1202-L1217
1,253
openlayers/openlayers
src/ol/interaction/Modify.js
closestOnSegmentData
function closestOnSegmentData(pointCoordinates, segmentData) { const geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE && segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) { return geometry.getClosestPoint(pointCoordinates); } return closestOnSegment(pointCoordinates, segmentData.segment); }
javascript
function closestOnSegmentData(pointCoordinates, segmentData) { const geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE && segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) { return geometry.getClosestPoint(pointCoordinates); } return closestOnSegment(pointCoordinates, segmentData.segment); }
[ "function", "closestOnSegmentData", "(", "pointCoordinates", ",", "segmentData", ")", "{", "const", "geometry", "=", "segmentData", ".", "geometry", ";", "if", "(", "geometry", ".", "getType", "(", ")", "===", "GeometryType", ".", "CIRCLE", "&&", "segmentData", ".", "index", "===", "CIRCLE_CIRCUMFERENCE_INDEX", ")", "{", "return", "geometry", ".", "getClosestPoint", "(", "pointCoordinates", ")", ";", "}", "return", "closestOnSegment", "(", "pointCoordinates", ",", "segmentData", ".", "segment", ")", ";", "}" ]
Returns the point closest to a given line segment. @param {import("../coordinate.js").Coordinate} pointCoordinates The point to which a closest point should be found. @param {SegmentData} segmentData The object describing the line segment which should contain the closest point. @return {import("../coordinate.js").Coordinate} The point closest to the specified line segment.
[ "Returns", "the", "point", "closest", "to", "a", "given", "line", "segment", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/interaction/Modify.js#L1228-L1236
1,254
openlayers/openlayers
examples/zoomslider.js
createMap
function createMap(divId) { const source = new OSM(); const layer = new TileLayer({ source: source }); const map = new Map({ layers: [layer], target: divId, view: new View({ center: [0, 0], zoom: 2 }) }); const zoomslider = new ZoomSlider(); map.addControl(zoomslider); return map; }
javascript
function createMap(divId) { const source = new OSM(); const layer = new TileLayer({ source: source }); const map = new Map({ layers: [layer], target: divId, view: new View({ center: [0, 0], zoom: 2 }) }); const zoomslider = new ZoomSlider(); map.addControl(zoomslider); return map; }
[ "function", "createMap", "(", "divId", ")", "{", "const", "source", "=", "new", "OSM", "(", ")", ";", "const", "layer", "=", "new", "TileLayer", "(", "{", "source", ":", "source", "}", ")", ";", "const", "map", "=", "new", "Map", "(", "{", "layers", ":", "[", "layer", "]", ",", "target", ":", "divId", ",", "view", ":", "new", "View", "(", "{", "center", ":", "[", "0", ",", "0", "]", ",", "zoom", ":", "2", "}", ")", "}", ")", ";", "const", "zoomslider", "=", "new", "ZoomSlider", "(", ")", ";", "map", ".", "addControl", "(", "zoomslider", ")", ";", "return", "map", ";", "}" ]
Helper method for map-creation. @param {string} divId The id of the div for the map. @return {Map} The map instance.
[ "Helper", "method", "for", "map", "-", "creation", "." ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/examples/zoomslider.js#L14-L30
1,255
openlayers/openlayers
src/ol/interaction/Snap.js
sortByDistance
function sortByDistance(a, b) { const deltaA = squaredDistanceToSegment(this.pixelCoordinate_, a.segment); const deltaB = squaredDistanceToSegment(this.pixelCoordinate_, b.segment); return deltaA - deltaB; }
javascript
function sortByDistance(a, b) { const deltaA = squaredDistanceToSegment(this.pixelCoordinate_, a.segment); const deltaB = squaredDistanceToSegment(this.pixelCoordinate_, b.segment); return deltaA - deltaB; }
[ "function", "sortByDistance", "(", "a", ",", "b", ")", "{", "const", "deltaA", "=", "squaredDistanceToSegment", "(", "this", ".", "pixelCoordinate_", ",", "a", ".", "segment", ")", ";", "const", "deltaB", "=", "squaredDistanceToSegment", "(", "this", ".", "pixelCoordinate_", ",", "b", ".", "segment", ")", ";", "return", "deltaA", "-", "deltaB", ";", "}" ]
Sort segments by distance, helper function @param {SegmentData} a The first segment data. @param {SegmentData} b The second segment data. @return {number} The difference in distance. @this {Snap}
[ "Sort", "segments", "by", "distance", "helper", "function" ]
f366eaea522388fb575b11010e69d309164baca7
https://github.com/openlayers/openlayers/blob/f366eaea522388fb575b11010e69d309164baca7/src/ol/interaction/Snap.js#L623-L627
1,256
nfarina/homebridge
example-plugins/homebridge-samplePlatform/index.js
SamplePlatform
function SamplePlatform(log, config, api) { log("SamplePlatform Init"); var platform = this; this.log = log; this.config = config; this.accessories = []; this.requestServer = http.createServer(function(request, response) { if (request.url === "/add") { this.addAccessory(new Date().toISOString()); response.writeHead(204); response.end(); } if (request.url == "/reachability") { this.updateAccessoriesReachability(); response.writeHead(204); response.end(); } if (request.url == "/remove") { this.removeAccessory(); response.writeHead(204); response.end(); } }.bind(this)); this.requestServer.listen(18081, function() { platform.log("Server Listening..."); }); if (api) { // Save the API object as plugin needs to register new accessory via this object this.api = api; // Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories. // Platform Plugin should only register new accessory that doesn't exist in homebridge after this event. // Or start discover new accessories. this.api.on('didFinishLaunching', function() { platform.log("DidFinishLaunching"); }.bind(this)); } }
javascript
function SamplePlatform(log, config, api) { log("SamplePlatform Init"); var platform = this; this.log = log; this.config = config; this.accessories = []; this.requestServer = http.createServer(function(request, response) { if (request.url === "/add") { this.addAccessory(new Date().toISOString()); response.writeHead(204); response.end(); } if (request.url == "/reachability") { this.updateAccessoriesReachability(); response.writeHead(204); response.end(); } if (request.url == "/remove") { this.removeAccessory(); response.writeHead(204); response.end(); } }.bind(this)); this.requestServer.listen(18081, function() { platform.log("Server Listening..."); }); if (api) { // Save the API object as plugin needs to register new accessory via this object this.api = api; // Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories. // Platform Plugin should only register new accessory that doesn't exist in homebridge after this event. // Or start discover new accessories. this.api.on('didFinishLaunching', function() { platform.log("DidFinishLaunching"); }.bind(this)); } }
[ "function", "SamplePlatform", "(", "log", ",", "config", ",", "api", ")", "{", "log", "(", "\"SamplePlatform Init\"", ")", ";", "var", "platform", "=", "this", ";", "this", ".", "log", "=", "log", ";", "this", ".", "config", "=", "config", ";", "this", ".", "accessories", "=", "[", "]", ";", "this", ".", "requestServer", "=", "http", ".", "createServer", "(", "function", "(", "request", ",", "response", ")", "{", "if", "(", "request", ".", "url", "===", "\"/add\"", ")", "{", "this", ".", "addAccessory", "(", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ")", ";", "response", ".", "writeHead", "(", "204", ")", ";", "response", ".", "end", "(", ")", ";", "}", "if", "(", "request", ".", "url", "==", "\"/reachability\"", ")", "{", "this", ".", "updateAccessoriesReachability", "(", ")", ";", "response", ".", "writeHead", "(", "204", ")", ";", "response", ".", "end", "(", ")", ";", "}", "if", "(", "request", ".", "url", "==", "\"/remove\"", ")", "{", "this", ".", "removeAccessory", "(", ")", ";", "response", ".", "writeHead", "(", "204", ")", ";", "response", ".", "end", "(", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "requestServer", ".", "listen", "(", "18081", ",", "function", "(", ")", "{", "platform", ".", "log", "(", "\"Server Listening...\"", ")", ";", "}", ")", ";", "if", "(", "api", ")", "{", "// Save the API object as plugin needs to register new accessory via this object", "this", ".", "api", "=", "api", ";", "// Listen to event \"didFinishLaunching\", this means homebridge already finished loading cached accessories.", "// Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.", "// Or start discover new accessories.", "this", ".", "api", ".", "on", "(", "'didFinishLaunching'", ",", "function", "(", ")", "{", "platform", ".", "log", "(", "\"DidFinishLaunching\"", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "}" ]
Platform constructor config may be null api may be null if launched from old homebridge version
[ "Platform", "constructor", "config", "may", "be", "null", "api", "may", "be", "null", "if", "launched", "from", "old", "homebridge", "version" ]
724125dc1b500dfd81048a30a1e3229ff122189a
https://github.com/nfarina/homebridge/blob/724125dc1b500dfd81048a30a1e3229ff122189a/example-plugins/homebridge-samplePlatform/index.js#L23-L65
1,257
facebook/flow
packages/flow-upgrade/src/findFlowFiles.js
done
function done() { // We don't care if we were rejected. if (rejected === true) { return; } // Decrement the number of async tasks we are waiting on. waiting--; // If we are finished waiting then we want to resolve our promise. if (waiting <= 0) { if (waiting === 0) { _resolve(filePaths); } else { reject(new Error(`Expected a positive number: ${waiting}`)); } } }
javascript
function done() { // We don't care if we were rejected. if (rejected === true) { return; } // Decrement the number of async tasks we are waiting on. waiting--; // If we are finished waiting then we want to resolve our promise. if (waiting <= 0) { if (waiting === 0) { _resolve(filePaths); } else { reject(new Error(`Expected a positive number: ${waiting}`)); } } }
[ "function", "done", "(", ")", "{", "// We don't care if we were rejected.", "if", "(", "rejected", "===", "true", ")", "{", "return", ";", "}", "// Decrement the number of async tasks we are waiting on.", "waiting", "--", ";", "// If we are finished waiting then we want to resolve our promise.", "if", "(", "waiting", "<=", "0", ")", "{", "if", "(", "waiting", "===", "0", ")", "{", "_resolve", "(", "filePaths", ")", ";", "}", "else", "{", "reject", "(", "new", "Error", "(", "`", "${", "waiting", "}", "`", ")", ")", ";", "}", "}", "}" ]
Our implementation of resolve that will only actually resolve if we are done waiting everywhere.
[ "Our", "implementation", "of", "resolve", "that", "will", "only", "actually", "resolve", "if", "we", "are", "done", "waiting", "everywhere", "." ]
25bc6aba258658eaf21ccc4722ef7124724a1d2b
https://github.com/facebook/flow/blob/25bc6aba258658eaf21ccc4722ef7124724a1d2b/packages/flow-upgrade/src/findFlowFiles.js#L161-L176
1,258
facebook/flow
packages/flow-remove-types/index.js
isLastNodeRemovedFromLine
function isLastNodeRemovedFromLine(context, node) { var tokens = context.ast.tokens; var priorTokenIdx = findTokenIndex(tokens, startOf(node)) - 1; var token = tokens[priorTokenIdx]; var line = node.loc.end.line; // Find previous token that was not removed on the same line. while ( priorTokenIdx >= 0 && token.loc.end.line === line && isRemovedToken(context, token) ) { token = tokens[--priorTokenIdx]; } // If there's no prior token (start of file), or the prior token is on another // line, this line must be fully removed. return !token || token.loc.end.line !== line; }
javascript
function isLastNodeRemovedFromLine(context, node) { var tokens = context.ast.tokens; var priorTokenIdx = findTokenIndex(tokens, startOf(node)) - 1; var token = tokens[priorTokenIdx]; var line = node.loc.end.line; // Find previous token that was not removed on the same line. while ( priorTokenIdx >= 0 && token.loc.end.line === line && isRemovedToken(context, token) ) { token = tokens[--priorTokenIdx]; } // If there's no prior token (start of file), or the prior token is on another // line, this line must be fully removed. return !token || token.loc.end.line !== line; }
[ "function", "isLastNodeRemovedFromLine", "(", "context", ",", "node", ")", "{", "var", "tokens", "=", "context", ".", "ast", ".", "tokens", ";", "var", "priorTokenIdx", "=", "findTokenIndex", "(", "tokens", ",", "startOf", "(", "node", ")", ")", "-", "1", ";", "var", "token", "=", "tokens", "[", "priorTokenIdx", "]", ";", "var", "line", "=", "node", ".", "loc", ".", "end", ".", "line", ";", "// Find previous token that was not removed on the same line.", "while", "(", "priorTokenIdx", ">=", "0", "&&", "token", ".", "loc", ".", "end", ".", "line", "===", "line", "&&", "isRemovedToken", "(", "context", ",", "token", ")", ")", "{", "token", "=", "tokens", "[", "--", "priorTokenIdx", "]", ";", "}", "// If there's no prior token (start of file), or the prior token is on another", "// line, this line must be fully removed.", "return", "!", "token", "||", "token", ".", "loc", ".", "end", ".", "line", "!==", "line", ";", "}" ]
Returns true if node is the last to be removed from a line.
[ "Returns", "true", "if", "node", "is", "the", "last", "to", "be", "removed", "from", "a", "line", "." ]
25bc6aba258658eaf21ccc4722ef7124724a1d2b
https://github.com/facebook/flow/blob/25bc6aba258658eaf21ccc4722ef7124724a1d2b/packages/flow-remove-types/index.js#L409-L427
1,259
facebook/flow
packages/flow-remove-types/index.js
visit
function visit(ast, context, visitor) { var stack; var parent; var keys = []; var index = -1; do { index++; if (stack && index === keys.length) { parent = stack.parent; keys = stack.keys; index = stack.index; stack = stack.prev; } else { var node = parent ? parent[keys[index]] : getProgram(ast); if (node && typeof node === 'object' && (node.type || node.length)) { if (node.type) { var visitFn = visitor[node.type]; if (visitFn && visitFn(context, node, ast) === false) { continue; } } stack = {parent: parent, keys: keys, index: index, prev: stack}; parent = node; keys = Object.keys(node); index = -1; } } } while (stack); }
javascript
function visit(ast, context, visitor) { var stack; var parent; var keys = []; var index = -1; do { index++; if (stack && index === keys.length) { parent = stack.parent; keys = stack.keys; index = stack.index; stack = stack.prev; } else { var node = parent ? parent[keys[index]] : getProgram(ast); if (node && typeof node === 'object' && (node.type || node.length)) { if (node.type) { var visitFn = visitor[node.type]; if (visitFn && visitFn(context, node, ast) === false) { continue; } } stack = {parent: parent, keys: keys, index: index, prev: stack}; parent = node; keys = Object.keys(node); index = -1; } } } while (stack); }
[ "function", "visit", "(", "ast", ",", "context", ",", "visitor", ")", "{", "var", "stack", ";", "var", "parent", ";", "var", "keys", "=", "[", "]", ";", "var", "index", "=", "-", "1", ";", "do", "{", "index", "++", ";", "if", "(", "stack", "&&", "index", "===", "keys", ".", "length", ")", "{", "parent", "=", "stack", ".", "parent", ";", "keys", "=", "stack", ".", "keys", ";", "index", "=", "stack", ".", "index", ";", "stack", "=", "stack", ".", "prev", ";", "}", "else", "{", "var", "node", "=", "parent", "?", "parent", "[", "keys", "[", "index", "]", "]", ":", "getProgram", "(", "ast", ")", ";", "if", "(", "node", "&&", "typeof", "node", "===", "'object'", "&&", "(", "node", ".", "type", "||", "node", ".", "length", ")", ")", "{", "if", "(", "node", ".", "type", ")", "{", "var", "visitFn", "=", "visitor", "[", "node", ".", "type", "]", ";", "if", "(", "visitFn", "&&", "visitFn", "(", "context", ",", "node", ",", "ast", ")", "===", "false", ")", "{", "continue", ";", "}", "}", "stack", "=", "{", "parent", ":", "parent", ",", "keys", ":", "keys", ",", "index", ":", "index", ",", "prev", ":", "stack", "}", ";", "parent", "=", "node", ";", "keys", "=", "Object", ".", "keys", "(", "node", ")", ";", "index", "=", "-", "1", ";", "}", "}", "}", "while", "(", "stack", ")", ";", "}" ]
Given the AST output from the parser, walk through in a depth-first order, calling methods on the given visitor, providing context as the first argument.
[ "Given", "the", "AST", "output", "from", "the", "parser", "walk", "through", "in", "a", "depth", "-", "first", "order", "calling", "methods", "on", "the", "given", "visitor", "providing", "context", "as", "the", "first", "argument", "." ]
25bc6aba258658eaf21ccc4722ef7124724a1d2b
https://github.com/facebook/flow/blob/25bc6aba258658eaf21ccc4722ef7124724a1d2b/packages/flow-remove-types/index.js#L461-L490
1,260
facebook/flow
packages/flow-remove-types/index.js
space
function space(size) { var sp = ' '; var result = ''; for (;;) { if ((size & 1) === 1) { result += sp; } size >>>= 1; if (size === 0) { break; } sp += sp; } return result; }
javascript
function space(size) { var sp = ' '; var result = ''; for (;;) { if ((size & 1) === 1) { result += sp; } size >>>= 1; if (size === 0) { break; } sp += sp; } return result; }
[ "function", "space", "(", "size", ")", "{", "var", "sp", "=", "' '", ";", "var", "result", "=", "''", ";", "for", "(", ";", ";", ")", "{", "if", "(", "(", "size", "&", "1", ")", "===", "1", ")", "{", "result", "+=", "sp", ";", "}", "size", ">>>=", "1", ";", "if", "(", "size", "===", "0", ")", "{", "break", ";", "}", "sp", "+=", "sp", ";", "}", "return", "result", ";", "}" ]
Produce a string full of space characters of a given size.
[ "Produce", "a", "string", "full", "of", "space", "characters", "of", "a", "given", "size", "." ]
25bc6aba258658eaf21ccc4722ef7124724a1d2b
https://github.com/facebook/flow/blob/25bc6aba258658eaf21ccc4722ef7124724a1d2b/packages/flow-remove-types/index.js#L519-L534
1,261
sass/node-sass
lib/index.js
getOutputFile
function getOutputFile(options) { var outFile = options.outFile; if (!outFile || typeof outFile !== 'string' || (!options.data && !options.file)) { return null; } return path.resolve(outFile); }
javascript
function getOutputFile(options) { var outFile = options.outFile; if (!outFile || typeof outFile !== 'string' || (!options.data && !options.file)) { return null; } return path.resolve(outFile); }
[ "function", "getOutputFile", "(", "options", ")", "{", "var", "outFile", "=", "options", ".", "outFile", ";", "if", "(", "!", "outFile", "||", "typeof", "outFile", "!==", "'string'", "||", "(", "!", "options", ".", "data", "&&", "!", "options", ".", "file", ")", ")", "{", "return", "null", ";", "}", "return", "path", ".", "resolve", "(", "outFile", ")", ";", "}" ]
Get output file @param {Object} options @api private
[ "Get", "output", "file" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/index.js#L34-L42
1,262
sass/node-sass
lib/index.js
getSourceMap
function getSourceMap(options) { var sourceMap = options.sourceMap; if (sourceMap && typeof sourceMap !== 'string' && options.outFile) { sourceMap = options.outFile + '.map'; } return sourceMap && typeof sourceMap === 'string' ? path.resolve(sourceMap) : null; }
javascript
function getSourceMap(options) { var sourceMap = options.sourceMap; if (sourceMap && typeof sourceMap !== 'string' && options.outFile) { sourceMap = options.outFile + '.map'; } return sourceMap && typeof sourceMap === 'string' ? path.resolve(sourceMap) : null; }
[ "function", "getSourceMap", "(", "options", ")", "{", "var", "sourceMap", "=", "options", ".", "sourceMap", ";", "if", "(", "sourceMap", "&&", "typeof", "sourceMap", "!==", "'string'", "&&", "options", ".", "outFile", ")", "{", "sourceMap", "=", "options", ".", "outFile", "+", "'.map'", ";", "}", "return", "sourceMap", "&&", "typeof", "sourceMap", "===", "'string'", "?", "path", ".", "resolve", "(", "sourceMap", ")", ":", "null", ";", "}" ]
Get source map @param {Object} options @api private
[ "Get", "source", "map" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/index.js#L51-L59
1,263
sass/node-sass
lib/index.js
buildIncludePaths
function buildIncludePaths(options) { options.includePaths = options.includePaths || []; if (process.env.hasOwnProperty('SASS_PATH')) { options.includePaths = options.includePaths.concat( process.env.SASS_PATH.split(path.delimiter) ); } // Preserve the behaviour people have come to expect. // This behaviour was removed from Sass in 3.4 and // LibSass in 3.5. options.includePaths.unshift(process.cwd()); return options.includePaths.join(path.delimiter); }
javascript
function buildIncludePaths(options) { options.includePaths = options.includePaths || []; if (process.env.hasOwnProperty('SASS_PATH')) { options.includePaths = options.includePaths.concat( process.env.SASS_PATH.split(path.delimiter) ); } // Preserve the behaviour people have come to expect. // This behaviour was removed from Sass in 3.4 and // LibSass in 3.5. options.includePaths.unshift(process.cwd()); return options.includePaths.join(path.delimiter); }
[ "function", "buildIncludePaths", "(", "options", ")", "{", "options", ".", "includePaths", "=", "options", ".", "includePaths", "||", "[", "]", ";", "if", "(", "process", ".", "env", ".", "hasOwnProperty", "(", "'SASS_PATH'", ")", ")", "{", "options", ".", "includePaths", "=", "options", ".", "includePaths", ".", "concat", "(", "process", ".", "env", ".", "SASS_PATH", ".", "split", "(", "path", ".", "delimiter", ")", ")", ";", "}", "// Preserve the behaviour people have come to expect.", "// This behaviour was removed from Sass in 3.4 and", "// LibSass in 3.5.", "options", ".", "includePaths", ".", "unshift", "(", "process", ".", "cwd", "(", ")", ")", ";", "return", "options", ".", "includePaths", ".", "join", "(", "path", ".", "delimiter", ")", ";", "}" ]
Build an includePaths string from the options.includePaths array and the SASS_PATH environment variable @param {Object} options @api private
[ "Build", "an", "includePaths", "string", "from", "the", "options", ".", "includePaths", "array", "and", "the", "SASS_PATH", "environment", "variable" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/index.js#L165-L180
1,264
sass/node-sass
lib/index.js
tryCallback
function tryCallback(callback, args) { try { return callback.apply(this, args); } catch (e) { if (typeof e === 'string') { return new binding.types.Error(e); } else if (e instanceof Error) { return new binding.types.Error(e.message); } else { return new binding.types.Error('An unexpected error occurred'); } } }
javascript
function tryCallback(callback, args) { try { return callback.apply(this, args); } catch (e) { if (typeof e === 'string') { return new binding.types.Error(e); } else if (e instanceof Error) { return new binding.types.Error(e.message); } else { return new binding.types.Error('An unexpected error occurred'); } } }
[ "function", "tryCallback", "(", "callback", ",", "args", ")", "{", "try", "{", "return", "callback", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "typeof", "e", "===", "'string'", ")", "{", "return", "new", "binding", ".", "types", ".", "Error", "(", "e", ")", ";", "}", "else", "if", "(", "e", "instanceof", "Error", ")", "{", "return", "new", "binding", ".", "types", ".", "Error", "(", "e", ".", "message", ")", ";", "}", "else", "{", "return", "new", "binding", ".", "types", ".", "Error", "(", "'An unexpected error occurred'", ")", ";", "}", "}", "}" ]
Executes a callback and transforms any exception raised into a sass error @param {Function} callback @param {Array} arguments @api private
[ "Executes", "a", "callback", "and", "transforms", "any", "exception", "raised", "into", "a", "sass", "error" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/index.js#L226-L238
1,265
sass/node-sass
lib/extensions.js
getHumanEnvironment
function getHumanEnvironment(env) { var binding = env.replace(/_binding\.node$/, ''), parts = binding.split('-'), platform = getHumanPlatform(parts[0]), arch = getHumanArchitecture(parts[1]), runtime = getHumanNodeVersion(parts[2]); if (parts.length !== 3) { return 'Unknown environment (' + binding + ')'; } if (!platform) { platform = 'Unsupported platform (' + parts[0] + ')'; } if (!arch) { arch = 'Unsupported architecture (' + parts[1] + ')'; } if (!runtime) { runtime = 'Unsupported runtime (' + parts[2] + ')'; } return [ platform, arch, 'with', runtime, ].join(' '); }
javascript
function getHumanEnvironment(env) { var binding = env.replace(/_binding\.node$/, ''), parts = binding.split('-'), platform = getHumanPlatform(parts[0]), arch = getHumanArchitecture(parts[1]), runtime = getHumanNodeVersion(parts[2]); if (parts.length !== 3) { return 'Unknown environment (' + binding + ')'; } if (!platform) { platform = 'Unsupported platform (' + parts[0] + ')'; } if (!arch) { arch = 'Unsupported architecture (' + parts[1] + ')'; } if (!runtime) { runtime = 'Unsupported runtime (' + parts[2] + ')'; } return [ platform, arch, 'with', runtime, ].join(' '); }
[ "function", "getHumanEnvironment", "(", "env", ")", "{", "var", "binding", "=", "env", ".", "replace", "(", "/", "_binding\\.node$", "/", ",", "''", ")", ",", "parts", "=", "binding", ".", "split", "(", "'-'", ")", ",", "platform", "=", "getHumanPlatform", "(", "parts", "[", "0", "]", ")", ",", "arch", "=", "getHumanArchitecture", "(", "parts", "[", "1", "]", ")", ",", "runtime", "=", "getHumanNodeVersion", "(", "parts", "[", "2", "]", ")", ";", "if", "(", "parts", ".", "length", "!==", "3", ")", "{", "return", "'Unknown environment ('", "+", "binding", "+", "')'", ";", "}", "if", "(", "!", "platform", ")", "{", "platform", "=", "'Unsupported platform ('", "+", "parts", "[", "0", "]", "+", "')'", ";", "}", "if", "(", "!", "arch", ")", "{", "arch", "=", "'Unsupported architecture ('", "+", "parts", "[", "1", "]", "+", "')'", ";", "}", "if", "(", "!", "runtime", ")", "{", "runtime", "=", "'Unsupported runtime ('", "+", "parts", "[", "2", "]", "+", "')'", ";", "}", "return", "[", "platform", ",", "arch", ",", "'with'", ",", "runtime", ",", "]", ".", "join", "(", "' '", ")", ";", "}" ]
Get a human readable description of where node-sass is running to support user error reporting when something goes wrong @param {string} env - The name of the native bindings that is to be parsed @return {string} A description of what os, architecture, and Node version that is being run @api public
[ "Get", "a", "human", "readable", "description", "of", "where", "node", "-", "sass", "is", "running", "to", "support", "user", "error", "reporting", "when", "something", "goes", "wrong" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L95-L121
1,266
sass/node-sass
lib/extensions.js
isSupportedEnvironment
function isSupportedEnvironment(platform, arch, abi) { return ( false !== getHumanPlatform(platform) && false !== getHumanArchitecture(arch) && false !== getHumanNodeVersion(abi) ); }
javascript
function isSupportedEnvironment(platform, arch, abi) { return ( false !== getHumanPlatform(platform) && false !== getHumanArchitecture(arch) && false !== getHumanNodeVersion(abi) ); }
[ "function", "isSupportedEnvironment", "(", "platform", ",", "arch", ",", "abi", ")", "{", "return", "(", "false", "!==", "getHumanPlatform", "(", "platform", ")", "&&", "false", "!==", "getHumanArchitecture", "(", "arch", ")", "&&", "false", "!==", "getHumanNodeVersion", "(", "abi", ")", ")", ";", "}" ]
Check that an environment matches the whitelisted values or the current environment if no parameters are passed @param {string} platform - The name of the OS platform(darwin, win32, etc...) @param {string} arch - The instruction set architecture of the Node environment @param {string} abi - The Node Application Binary Interface @return {Boolean} True, if node-sass supports the current platform, false otherwise @api public
[ "Check", "that", "an", "environment", "matches", "the", "whitelisted", "values", "or", "the", "current", "environment", "if", "no", "parameters", "are", "passed" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L145-L151
1,267
sass/node-sass
lib/extensions.js
getArgument
function getArgument(name, args) { var flags = args || process.argv.slice(2), index = flags.lastIndexOf(name); if (index === -1 || index + 1 >= flags.length) { return null; } return flags[index + 1]; }
javascript
function getArgument(name, args) { var flags = args || process.argv.slice(2), index = flags.lastIndexOf(name); if (index === -1 || index + 1 >= flags.length) { return null; } return flags[index + 1]; }
[ "function", "getArgument", "(", "name", ",", "args", ")", "{", "var", "flags", "=", "args", "||", "process", ".", "argv", ".", "slice", "(", "2", ")", ",", "index", "=", "flags", ".", "lastIndexOf", "(", "name", ")", ";", "if", "(", "index", "===", "-", "1", "||", "index", "+", "1", ">=", "flags", ".", "length", ")", "{", "return", "null", ";", "}", "return", "flags", "[", "index", "+", "1", "]", ";", "}" ]
Get the value of a CLI argument @param {String} name @param {Array} args @api private
[ "Get", "the", "value", "of", "a", "CLI", "argument" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L161-L170
1,268
sass/node-sass
lib/extensions.js
getBinaryUrl
function getBinaryUrl() { var site = getArgument('--sass-binary-site') || process.env.SASS_BINARY_SITE || process.env.npm_config_sass_binary_site || (pkg.nodeSassConfig && pkg.nodeSassConfig.binarySite) || 'https://github.com/sass/node-sass/releases/download'; return [site, 'v' + pkg.version, getBinaryName()].join('/'); }
javascript
function getBinaryUrl() { var site = getArgument('--sass-binary-site') || process.env.SASS_BINARY_SITE || process.env.npm_config_sass_binary_site || (pkg.nodeSassConfig && pkg.nodeSassConfig.binarySite) || 'https://github.com/sass/node-sass/releases/download'; return [site, 'v' + pkg.version, getBinaryName()].join('/'); }
[ "function", "getBinaryUrl", "(", ")", "{", "var", "site", "=", "getArgument", "(", "'--sass-binary-site'", ")", "||", "process", ".", "env", ".", "SASS_BINARY_SITE", "||", "process", ".", "env", ".", "npm_config_sass_binary_site", "||", "(", "pkg", ".", "nodeSassConfig", "&&", "pkg", ".", "nodeSassConfig", ".", "binarySite", ")", "||", "'https://github.com/sass/node-sass/releases/download'", ";", "return", "[", "site", ",", "'v'", "+", "pkg", ".", "version", ",", "getBinaryName", "(", ")", "]", ".", "join", "(", "'/'", ")", ";", "}" ]
Determine the URL to fetch binary file from. By default fetch from the node-sass distribution site on GitHub. The default URL can be overriden using the environment variable SASS_BINARY_SITE, .npmrc variable sass_binary_site or or a command line option --sass-binary-site: node scripts/install.js --sass-binary-site http://example.com/ The URL should to the mirror of the repository laid out as follows: SASS_BINARY_SITE/ v3.0.0 v3.0.0/freebsd-x64-14_binding.node .... v3.0.0 v3.0.0/freebsd-ia32-11_binding.node v3.0.0/freebsd-x64-42_binding.node ... etc. for all supported versions and platforms @api public
[ "Determine", "the", "URL", "to", "fetch", "binary", "file", "from", ".", "By", "default", "fetch", "from", "the", "node", "-", "sass", "distribution", "site", "on", "GitHub", "." ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L240-L248
1,269
sass/node-sass
lib/extensions.js
getBinaryCachePath
function getBinaryCachePath() { var i, cachePath, cachePathCandidates = getCachePathCandidates(); for (i = 0; i < cachePathCandidates.length; i++) { cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version); try { mkdir.sync(cachePath); return cachePath; } catch (e) { // Directory is not writable, try another } } return ''; }
javascript
function getBinaryCachePath() { var i, cachePath, cachePathCandidates = getCachePathCandidates(); for (i = 0; i < cachePathCandidates.length; i++) { cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version); try { mkdir.sync(cachePath); return cachePath; } catch (e) { // Directory is not writable, try another } } return ''; }
[ "function", "getBinaryCachePath", "(", ")", "{", "var", "i", ",", "cachePath", ",", "cachePathCandidates", "=", "getCachePathCandidates", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "cachePathCandidates", ".", "length", ";", "i", "++", ")", "{", "cachePath", "=", "path", ".", "join", "(", "cachePathCandidates", "[", "i", "]", ",", "pkg", ".", "name", ",", "pkg", ".", "version", ")", ";", "try", "{", "mkdir", ".", "sync", "(", "cachePath", ")", ";", "return", "cachePath", ";", "}", "catch", "(", "e", ")", "{", "// Directory is not writable, try another", "}", "}", "return", "''", ";", "}" ]
The most suitable location for caching the binding on disk. Given the candidates directories provided by `getCachePathCandidates()` this returns the first writable directory. By treating the candidate directories as a prioritised list this method is deterministic, assuming no change to the local environment. @return {String} directory to cache binding @api public
[ "The", "most", "suitable", "location", "for", "caching", "the", "binding", "on", "disk", "." ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L346-L363
1,270
sass/node-sass
lib/extensions.js
getCachedBinary
function getCachedBinary() { var i, cachePath, cacheBinary, cachePathCandidates = getCachePathCandidates(), binaryName = getBinaryName(); for (i = 0; i < cachePathCandidates.length; i++) { cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version); cacheBinary = path.join(cachePath, binaryName); if (fs.existsSync(cacheBinary)) { return cacheBinary; } } return ''; }
javascript
function getCachedBinary() { var i, cachePath, cacheBinary, cachePathCandidates = getCachePathCandidates(), binaryName = getBinaryName(); for (i = 0; i < cachePathCandidates.length; i++) { cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version); cacheBinary = path.join(cachePath, binaryName); if (fs.existsSync(cacheBinary)) { return cacheBinary; } } return ''; }
[ "function", "getCachedBinary", "(", ")", "{", "var", "i", ",", "cachePath", ",", "cacheBinary", ",", "cachePathCandidates", "=", "getCachePathCandidates", "(", ")", ",", "binaryName", "=", "getBinaryName", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "cachePathCandidates", ".", "length", ";", "i", "++", ")", "{", "cachePath", "=", "path", ".", "join", "(", "cachePathCandidates", "[", "i", "]", ",", "pkg", ".", "name", ",", "pkg", ".", "version", ")", ";", "cacheBinary", "=", "path", ".", "join", "(", "cachePath", ",", "binaryName", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "cacheBinary", ")", ")", "{", "return", "cacheBinary", ";", "}", "}", "return", "''", ";", "}" ]
The cached binding Check the candidates directories provided by `getCachePathCandidates()` for the binding file, if it exists. By treating the candidate directories as a prioritised list this method is deterministic, assuming no change to the local environment. @return {String} path to cached binary @api public
[ "The", "cached", "binding" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L376-L393
1,271
sass/node-sass
lib/extensions.js
getVersionInfo
function getVersionInfo(binding) { return [ ['node-sass', pkg.version, '(Wrapper)', '[JavaScript]'].join('\t'), ['libsass ', binding.libsassVersion(), '(Sass Compiler)', '[C/C++]'].join('\t'), ].join(eol); }
javascript
function getVersionInfo(binding) { return [ ['node-sass', pkg.version, '(Wrapper)', '[JavaScript]'].join('\t'), ['libsass ', binding.libsassVersion(), '(Sass Compiler)', '[C/C++]'].join('\t'), ].join(eol); }
[ "function", "getVersionInfo", "(", "binding", ")", "{", "return", "[", "[", "'node-sass'", ",", "pkg", ".", "version", ",", "'(Wrapper)'", ",", "'[JavaScript]'", "]", ".", "join", "(", "'\\t'", ")", ",", "[", "'libsass '", ",", "binding", ".", "libsassVersion", "(", ")", ",", "'(Sass Compiler)'", ",", "'[C/C++]'", "]", ".", "join", "(", "'\\t'", ")", ",", "]", ".", "join", "(", "eol", ")", ";", "}" ]
Get Sass version information @api public
[ "Get", "Sass", "version", "information" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L412-L417
1,272
netlify/netlify-cms
packages/netlify-cms-backend-github/src/implementation.js
isPreviewContext
function isPreviewContext(context, previewContext) { if (previewContext) { return context === previewContext; } return PREVIEW_CONTEXT_KEYWORDS.some(keyword => context.includes(keyword)); }
javascript
function isPreviewContext(context, previewContext) { if (previewContext) { return context === previewContext; } return PREVIEW_CONTEXT_KEYWORDS.some(keyword => context.includes(keyword)); }
[ "function", "isPreviewContext", "(", "context", ",", "previewContext", ")", "{", "if", "(", "previewContext", ")", "{", "return", "context", "===", "previewContext", ";", "}", "return", "PREVIEW_CONTEXT_KEYWORDS", ".", "some", "(", "keyword", "=>", "context", ".", "includes", "(", "keyword", ")", ")", ";", "}" ]
Check a given status context string to determine if it provides a link to a deploy preview. Checks for an exact match against `previewContext` if given, otherwise checks for inclusion of a value from `PREVIEW_CONTEXT_KEYWORDS`.
[ "Check", "a", "given", "status", "context", "string", "to", "determine", "if", "it", "provides", "a", "link", "to", "a", "deploy", "preview", ".", "Checks", "for", "an", "exact", "match", "against", "previewContext", "if", "given", "otherwise", "checks", "for", "inclusion", "of", "a", "value", "from", "PREVIEW_CONTEXT_KEYWORDS", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-backend-github/src/implementation.js#L19-L24
1,273
netlify/netlify-cms
packages/netlify-cms-backend-github/src/implementation.js
getPreviewStatus
function getPreviewStatus(statuses, config) { const previewContext = config.getIn(['backend', 'preview_context']); return statuses.find(({ context }) => { return isPreviewContext(context, previewContext); }); }
javascript
function getPreviewStatus(statuses, config) { const previewContext = config.getIn(['backend', 'preview_context']); return statuses.find(({ context }) => { return isPreviewContext(context, previewContext); }); }
[ "function", "getPreviewStatus", "(", "statuses", ",", "config", ")", "{", "const", "previewContext", "=", "config", ".", "getIn", "(", "[", "'backend'", ",", "'preview_context'", "]", ")", ";", "return", "statuses", ".", "find", "(", "(", "{", "context", "}", ")", "=>", "{", "return", "isPreviewContext", "(", "context", ",", "previewContext", ")", ";", "}", ")", ";", "}" ]
Retrieve a deploy preview URL from an array of statuses. By default, a matching status is inferred via `isPreviewContext`.
[ "Retrieve", "a", "deploy", "preview", "URL", "from", "an", "array", "of", "statuses", ".", "By", "default", "a", "matching", "status", "is", "inferred", "via", "isPreviewContext", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-backend-github/src/implementation.js#L30-L35
1,274
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js
createBlock
function createBlock(type, nodes, props = {}) { if (!isArray(nodes)) { props = nodes; nodes = undefined; } const node = { object: 'block', type, ...props }; return addNodes(node, nodes); }
javascript
function createBlock(type, nodes, props = {}) { if (!isArray(nodes)) { props = nodes; nodes = undefined; } const node = { object: 'block', type, ...props }; return addNodes(node, nodes); }
[ "function", "createBlock", "(", "type", ",", "nodes", ",", "props", "=", "{", "}", ")", "{", "if", "(", "!", "isArray", "(", "nodes", ")", ")", "{", "props", "=", "nodes", ";", "nodes", "=", "undefined", ";", "}", "const", "node", "=", "{", "object", ":", "'block'", ",", "type", ",", "...", "props", "}", ";", "return", "addNodes", "(", "node", ",", "nodes", ")", ";", "}" ]
Create a Slate Inline node.
[ "Create", "a", "Slate", "Inline", "node", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js#L68-L76
1,275
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js
createInline
function createInline(type, props = {}, nodes) { const node = { object: 'inline', type, ...props }; return addNodes(node, nodes); }
javascript
function createInline(type, props = {}, nodes) { const node = { object: 'inline', type, ...props }; return addNodes(node, nodes); }
[ "function", "createInline", "(", "type", ",", "props", "=", "{", "}", ",", "nodes", ")", "{", "const", "node", "=", "{", "object", ":", "'inline'", ",", "type", ",", "...", "props", "}", ";", "return", "addNodes", "(", "node", ",", "nodes", ")", ";", "}" ]
Create a Slate Block node.
[ "Create", "a", "Slate", "Block", "node", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js#L81-L84
1,276
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js
createText
function createText(value, data) { const node = { object: 'text', data }; const leaves = isArray(value) ? value : [{ text: value }]; return { ...node, leaves }; }
javascript
function createText(value, data) { const node = { object: 'text', data }; const leaves = isArray(value) ? value : [{ text: value }]; return { ...node, leaves }; }
[ "function", "createText", "(", "value", ",", "data", ")", "{", "const", "node", "=", "{", "object", ":", "'text'", ",", "data", "}", ";", "const", "leaves", "=", "isArray", "(", "value", ")", "?", "value", ":", "[", "{", "text", ":", "value", "}", "]", ";", "return", "{", "...", "node", ",", "leaves", "}", ";", "}" ]
Create a Slate Raw text node.
[ "Create", "a", "Slate", "Raw", "text", "node", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js#L89-L93
1,277
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js
convertNode
function convertNode(node, nodes) { switch (node.type) { /** * General * * Convert simple cases that only require a type and children, with no * additional properties. */ case 'root': case 'paragraph': case 'listItem': case 'blockquote': case 'tableRow': case 'tableCell': { return createBlock(typeMap[node.type], nodes); } /** * Shortcodes * * Shortcode nodes are represented as "void" blocks in the Slate AST. They * maintain the same data as MDAST shortcode nodes. Slate void blocks must * contain a blank text node. */ case 'shortcode': { const { data } = node; const nodes = [createText('')]; return createBlock(typeMap[node.type], nodes, { data, isVoid: true }); } /** * Text * * Text and HTML nodes are both used to render text, and should be treated * the same. HTML is treated as text because we never want to escape or * encode it. */ case 'text': case 'html': { return createText(node.value, node.data); } /** * Inline Code * * Inline code nodes from an MDAST are represented in our Slate schema as * text nodes with a "code" mark. We manually create the "leaf" containing * the inline code value and a "code" mark, and place it in an array for use * as a Slate text node's children array. */ case 'inlineCode': { const leaf = { text: node.value, marks: [{ type: 'code' }], }; return createText([leaf]); } /** * Marks * * Marks are typically decorative sub-types that apply to text nodes. In an * MDAST, marks are nodes that can contain other nodes. This nested * hierarchy has to be flattened and split into distinct text nodes with * their own set of marks. */ case 'strong': case 'emphasis': case 'delete': { return convertMarkNode(node); } /** * Headings * * MDAST headings use a single type with a separate "depth" property to * indicate the heading level, while the Slate schema uses a separate node * type for each heading level. Here we get the proper Slate node name based * on the MDAST node depth. */ case 'heading': { const depthMap = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six' }; const slateType = `heading-${depthMap[node.depth]}`; return createBlock(slateType, nodes); } /** * Code Blocks * * MDAST code blocks are a distinct node type with a simple text value. We * convert that value into a nested child text node for Slate. We also carry * over the "lang" data property if it's defined. */ case 'code': { const data = { lang: node.lang }; const text = createText(node.value); const nodes = [text]; return createBlock(typeMap[node.type], nodes, { data }); } /** * Lists * * MDAST has a single list type and an "ordered" property. We derive that * information into the Slate schema's distinct list node types. We also * include the "start" property, which indicates the number an ordered list * starts at, if defined. */ case 'list': { const slateType = node.ordered ? 'numbered-list' : 'bulleted-list'; const data = { start: node.start }; return createBlock(slateType, nodes, { data }); } /** * Breaks * * MDAST soft break nodes represent a trailing double space or trailing * slash from a Markdown document. In Slate, these are simply transformed to * line breaks within a text node. */ case 'break': { const textNode = createText('\n'); return createInline('break', {}, [textNode]); } /** * Thematic Breaks * * Thematic breaks are void nodes in the Slate schema. */ case 'thematicBreak': { return createBlock(typeMap[node.type], { isVoid: true }); } /** * Links * * MDAST stores the link attributes directly on the node, while our Slate * schema references them in the data object. */ case 'link': { const { title, url, data } = node; const newData = { ...data, title, url }; return createInline(typeMap[node.type], { data: newData }, nodes); } /** * Images * * Identical to link nodes except for the lack of child nodes and addition * of alt attribute data MDAST stores the link attributes directly on the * node, while our Slate schema references them in the data object. */ case 'image': { const { title, url, alt, data } = node; const newData = { ...data, title, alt, url }; return createInline(typeMap[node.type], { isVoid: true, data: newData }); } /** * Tables * * Tables are parsed separately because they may include an "align" * property, which should be passed to the Slate node. */ case 'table': { const data = { align: node.align }; return createBlock(typeMap[node.type], nodes, { data }); } } }
javascript
function convertNode(node, nodes) { switch (node.type) { /** * General * * Convert simple cases that only require a type and children, with no * additional properties. */ case 'root': case 'paragraph': case 'listItem': case 'blockquote': case 'tableRow': case 'tableCell': { return createBlock(typeMap[node.type], nodes); } /** * Shortcodes * * Shortcode nodes are represented as "void" blocks in the Slate AST. They * maintain the same data as MDAST shortcode nodes. Slate void blocks must * contain a blank text node. */ case 'shortcode': { const { data } = node; const nodes = [createText('')]; return createBlock(typeMap[node.type], nodes, { data, isVoid: true }); } /** * Text * * Text and HTML nodes are both used to render text, and should be treated * the same. HTML is treated as text because we never want to escape or * encode it. */ case 'text': case 'html': { return createText(node.value, node.data); } /** * Inline Code * * Inline code nodes from an MDAST are represented in our Slate schema as * text nodes with a "code" mark. We manually create the "leaf" containing * the inline code value and a "code" mark, and place it in an array for use * as a Slate text node's children array. */ case 'inlineCode': { const leaf = { text: node.value, marks: [{ type: 'code' }], }; return createText([leaf]); } /** * Marks * * Marks are typically decorative sub-types that apply to text nodes. In an * MDAST, marks are nodes that can contain other nodes. This nested * hierarchy has to be flattened and split into distinct text nodes with * their own set of marks. */ case 'strong': case 'emphasis': case 'delete': { return convertMarkNode(node); } /** * Headings * * MDAST headings use a single type with a separate "depth" property to * indicate the heading level, while the Slate schema uses a separate node * type for each heading level. Here we get the proper Slate node name based * on the MDAST node depth. */ case 'heading': { const depthMap = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six' }; const slateType = `heading-${depthMap[node.depth]}`; return createBlock(slateType, nodes); } /** * Code Blocks * * MDAST code blocks are a distinct node type with a simple text value. We * convert that value into a nested child text node for Slate. We also carry * over the "lang" data property if it's defined. */ case 'code': { const data = { lang: node.lang }; const text = createText(node.value); const nodes = [text]; return createBlock(typeMap[node.type], nodes, { data }); } /** * Lists * * MDAST has a single list type and an "ordered" property. We derive that * information into the Slate schema's distinct list node types. We also * include the "start" property, which indicates the number an ordered list * starts at, if defined. */ case 'list': { const slateType = node.ordered ? 'numbered-list' : 'bulleted-list'; const data = { start: node.start }; return createBlock(slateType, nodes, { data }); } /** * Breaks * * MDAST soft break nodes represent a trailing double space or trailing * slash from a Markdown document. In Slate, these are simply transformed to * line breaks within a text node. */ case 'break': { const textNode = createText('\n'); return createInline('break', {}, [textNode]); } /** * Thematic Breaks * * Thematic breaks are void nodes in the Slate schema. */ case 'thematicBreak': { return createBlock(typeMap[node.type], { isVoid: true }); } /** * Links * * MDAST stores the link attributes directly on the node, while our Slate * schema references them in the data object. */ case 'link': { const { title, url, data } = node; const newData = { ...data, title, url }; return createInline(typeMap[node.type], { data: newData }, nodes); } /** * Images * * Identical to link nodes except for the lack of child nodes and addition * of alt attribute data MDAST stores the link attributes directly on the * node, while our Slate schema references them in the data object. */ case 'image': { const { title, url, alt, data } = node; const newData = { ...data, title, alt, url }; return createInline(typeMap[node.type], { isVoid: true, data: newData }); } /** * Tables * * Tables are parsed separately because they may include an "align" * property, which should be passed to the Slate node. */ case 'table': { const data = { align: node.align }; return createBlock(typeMap[node.type], nodes, { data }); } } }
[ "function", "convertNode", "(", "node", ",", "nodes", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "/**\n * General\n *\n * Convert simple cases that only require a type and children, with no\n * additional properties.\n */", "case", "'root'", ":", "case", "'paragraph'", ":", "case", "'listItem'", ":", "case", "'blockquote'", ":", "case", "'tableRow'", ":", "case", "'tableCell'", ":", "{", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ")", ";", "}", "/**\n * Shortcodes\n *\n * Shortcode nodes are represented as \"void\" blocks in the Slate AST. They\n * maintain the same data as MDAST shortcode nodes. Slate void blocks must\n * contain a blank text node.\n */", "case", "'shortcode'", ":", "{", "const", "{", "data", "}", "=", "node", ";", "const", "nodes", "=", "[", "createText", "(", "''", ")", "]", ";", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ",", "{", "data", ",", "isVoid", ":", "true", "}", ")", ";", "}", "/**\n * Text\n *\n * Text and HTML nodes are both used to render text, and should be treated\n * the same. HTML is treated as text because we never want to escape or\n * encode it.\n */", "case", "'text'", ":", "case", "'html'", ":", "{", "return", "createText", "(", "node", ".", "value", ",", "node", ".", "data", ")", ";", "}", "/**\n * Inline Code\n *\n * Inline code nodes from an MDAST are represented in our Slate schema as\n * text nodes with a \"code\" mark. We manually create the \"leaf\" containing\n * the inline code value and a \"code\" mark, and place it in an array for use\n * as a Slate text node's children array.\n */", "case", "'inlineCode'", ":", "{", "const", "leaf", "=", "{", "text", ":", "node", ".", "value", ",", "marks", ":", "[", "{", "type", ":", "'code'", "}", "]", ",", "}", ";", "return", "createText", "(", "[", "leaf", "]", ")", ";", "}", "/**\n * Marks\n *\n * Marks are typically decorative sub-types that apply to text nodes. In an\n * MDAST, marks are nodes that can contain other nodes. This nested\n * hierarchy has to be flattened and split into distinct text nodes with\n * their own set of marks.\n */", "case", "'strong'", ":", "case", "'emphasis'", ":", "case", "'delete'", ":", "{", "return", "convertMarkNode", "(", "node", ")", ";", "}", "/**\n * Headings\n *\n * MDAST headings use a single type with a separate \"depth\" property to\n * indicate the heading level, while the Slate schema uses a separate node\n * type for each heading level. Here we get the proper Slate node name based\n * on the MDAST node depth.\n */", "case", "'heading'", ":", "{", "const", "depthMap", "=", "{", "1", ":", "'one'", ",", "2", ":", "'two'", ",", "3", ":", "'three'", ",", "4", ":", "'four'", ",", "5", ":", "'five'", ",", "6", ":", "'six'", "}", ";", "const", "slateType", "=", "`", "${", "depthMap", "[", "node", ".", "depth", "]", "}", "`", ";", "return", "createBlock", "(", "slateType", ",", "nodes", ")", ";", "}", "/**\n * Code Blocks\n *\n * MDAST code blocks are a distinct node type with a simple text value. We\n * convert that value into a nested child text node for Slate. We also carry\n * over the \"lang\" data property if it's defined.\n */", "case", "'code'", ":", "{", "const", "data", "=", "{", "lang", ":", "node", ".", "lang", "}", ";", "const", "text", "=", "createText", "(", "node", ".", "value", ")", ";", "const", "nodes", "=", "[", "text", "]", ";", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ",", "{", "data", "}", ")", ";", "}", "/**\n * Lists\n *\n * MDAST has a single list type and an \"ordered\" property. We derive that\n * information into the Slate schema's distinct list node types. We also\n * include the \"start\" property, which indicates the number an ordered list\n * starts at, if defined.\n */", "case", "'list'", ":", "{", "const", "slateType", "=", "node", ".", "ordered", "?", "'numbered-list'", ":", "'bulleted-list'", ";", "const", "data", "=", "{", "start", ":", "node", ".", "start", "}", ";", "return", "createBlock", "(", "slateType", ",", "nodes", ",", "{", "data", "}", ")", ";", "}", "/**\n * Breaks\n *\n * MDAST soft break nodes represent a trailing double space or trailing\n * slash from a Markdown document. In Slate, these are simply transformed to\n * line breaks within a text node.\n */", "case", "'break'", ":", "{", "const", "textNode", "=", "createText", "(", "'\\n'", ")", ";", "return", "createInline", "(", "'break'", ",", "{", "}", ",", "[", "textNode", "]", ")", ";", "}", "/**\n * Thematic Breaks\n *\n * Thematic breaks are void nodes in the Slate schema.\n */", "case", "'thematicBreak'", ":", "{", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "isVoid", ":", "true", "}", ")", ";", "}", "/**\n * Links\n *\n * MDAST stores the link attributes directly on the node, while our Slate\n * schema references them in the data object.\n */", "case", "'link'", ":", "{", "const", "{", "title", ",", "url", ",", "data", "}", "=", "node", ";", "const", "newData", "=", "{", "...", "data", ",", "title", ",", "url", "}", ";", "return", "createInline", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "data", ":", "newData", "}", ",", "nodes", ")", ";", "}", "/**\n * Images\n *\n * Identical to link nodes except for the lack of child nodes and addition\n * of alt attribute data MDAST stores the link attributes directly on the\n * node, while our Slate schema references them in the data object.\n */", "case", "'image'", ":", "{", "const", "{", "title", ",", "url", ",", "alt", ",", "data", "}", "=", "node", ";", "const", "newData", "=", "{", "...", "data", ",", "title", ",", "alt", ",", "url", "}", ";", "return", "createInline", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "isVoid", ":", "true", ",", "data", ":", "newData", "}", ")", ";", "}", "/**\n * Tables\n *\n * Tables are parsed separately because they may include an \"align\"\n * property, which should be passed to the Slate node.\n */", "case", "'table'", ":", "{", "const", "data", "=", "{", "align", ":", "node", ".", "align", "}", ";", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ",", "{", "data", "}", ")", ";", "}", "}", "}" ]
Convert a single MDAST node to a Slate Raw node. Uses local node factories that mimic the unist-builder function utilized in the slateRemark transformer.
[ "Convert", "a", "single", "MDAST", "node", "to", "a", "Slate", "Raw", "node", ".", "Uses", "local", "node", "factories", "that", "mimic", "the", "unist", "-", "builder", "function", "utilized", "in", "the", "slateRemark", "transformer", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/remarkSlate.js#L171-L342
1,278
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/index.js
markdownToRemarkRemoveTokenizers
function markdownToRemarkRemoveTokenizers({ inlineTokenizers }) { inlineTokenizers && inlineTokenizers.forEach(tokenizer => { delete this.Parser.prototype.inlineTokenizers[tokenizer]; }); }
javascript
function markdownToRemarkRemoveTokenizers({ inlineTokenizers }) { inlineTokenizers && inlineTokenizers.forEach(tokenizer => { delete this.Parser.prototype.inlineTokenizers[tokenizer]; }); }
[ "function", "markdownToRemarkRemoveTokenizers", "(", "{", "inlineTokenizers", "}", ")", "{", "inlineTokenizers", "&&", "inlineTokenizers", ".", "forEach", "(", "tokenizer", "=>", "{", "delete", "this", ".", "Parser", ".", "prototype", ".", "inlineTokenizers", "[", "tokenizer", "]", ";", "}", ")", ";", "}" ]
Remove named tokenizers from the parser, effectively deactivating them.
[ "Remove", "named", "tokenizers", "from", "the", "parser", "effectively", "deactivating", "them", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/index.js#L85-L90
1,279
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/index.js
remarkAllowAllText
function remarkAllowAllText() { const Compiler = this.Compiler; const visitors = Compiler.prototype.visitors; visitors.text = node => node.value; }
javascript
function remarkAllowAllText() { const Compiler = this.Compiler; const visitors = Compiler.prototype.visitors; visitors.text = node => node.value; }
[ "function", "remarkAllowAllText", "(", ")", "{", "const", "Compiler", "=", "this", ".", "Compiler", ";", "const", "visitors", "=", "Compiler", ".", "prototype", ".", "visitors", ";", "visitors", ".", "text", "=", "node", "=>", "node", ".", "value", ";", "}" ]
Rewrite the remark-stringify text visitor to simply return the text value, without encoding or escaping any characters. This means we're completely trusting the markdown that we receive.
[ "Rewrite", "the", "remark", "-", "stringify", "text", "visitor", "to", "simply", "return", "the", "text", "value", "without", "encoding", "or", "escaping", "any", "characters", ".", "This", "means", "we", "re", "completely", "trusting", "the", "markdown", "that", "we", "receive", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/index.js#L101-L105
1,280
netlify/netlify-cms
packages/netlify-cms-core/src/bootstrap.js
getRoot
function getRoot() { /** * Return existing root if found. */ const existingRoot = document.getElementById(ROOT_ID); if (existingRoot) { return existingRoot; } /** * If no existing root, create and return a new root. */ const newRoot = document.createElement('div'); newRoot.id = ROOT_ID; document.body.appendChild(newRoot); return newRoot; }
javascript
function getRoot() { /** * Return existing root if found. */ const existingRoot = document.getElementById(ROOT_ID); if (existingRoot) { return existingRoot; } /** * If no existing root, create and return a new root. */ const newRoot = document.createElement('div'); newRoot.id = ROOT_ID; document.body.appendChild(newRoot); return newRoot; }
[ "function", "getRoot", "(", ")", "{", "/**\n * Return existing root if found.\n */", "const", "existingRoot", "=", "document", ".", "getElementById", "(", "ROOT_ID", ")", ";", "if", "(", "existingRoot", ")", "{", "return", "existingRoot", ";", "}", "/**\n * If no existing root, create and return a new root.\n */", "const", "newRoot", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "newRoot", ".", "id", "=", "ROOT_ID", ";", "document", ".", "body", ".", "appendChild", "(", "newRoot", ")", ";", "return", "newRoot", ";", "}" ]
Get DOM element where app will mount.
[ "Get", "DOM", "element", "where", "app", "will", "mount", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-core/src/bootstrap.js#L33-L49
1,281
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
transform
function transform(node) { /** * Combine adjacent text and inline nodes before processing so they can * share marks. */ const combinedChildren = node.nodes && combineTextAndInline(node.nodes); /** * Call `transform` recursively on child nodes, and flatten the resulting * array. */ const children = !isEmpty(combinedChildren) && flatMap(combinedChildren, transform); /** * Run individual nodes through conversion factories. */ return ['text'].includes(node.object) ? convertTextNode(node) : convertNode(node, children); }
javascript
function transform(node) { /** * Combine adjacent text and inline nodes before processing so they can * share marks. */ const combinedChildren = node.nodes && combineTextAndInline(node.nodes); /** * Call `transform` recursively on child nodes, and flatten the resulting * array. */ const children = !isEmpty(combinedChildren) && flatMap(combinedChildren, transform); /** * Run individual nodes through conversion factories. */ return ['text'].includes(node.object) ? convertTextNode(node) : convertNode(node, children); }
[ "function", "transform", "(", "node", ")", "{", "/**\n * Combine adjacent text and inline nodes before processing so they can\n * share marks.\n */", "const", "combinedChildren", "=", "node", ".", "nodes", "&&", "combineTextAndInline", "(", "node", ".", "nodes", ")", ";", "/**\n * Call `transform` recursively on child nodes, and flatten the resulting\n * array.\n */", "const", "children", "=", "!", "isEmpty", "(", "combinedChildren", ")", "&&", "flatMap", "(", "combinedChildren", ",", "transform", ")", ";", "/**\n * Run individual nodes through conversion factories.\n */", "return", "[", "'text'", "]", ".", "includes", "(", "node", ".", "object", ")", "?", "convertTextNode", "(", "node", ")", ":", "convertNode", "(", "node", ",", "children", ")", ";", "}" ]
The transform function mimics the approach of a Remark plugin for conformity with the other serialization functions. This function converts Slate nodes to MDAST nodes, and recursively calls itself to process child nodes to arbitrary depth.
[ "The", "transform", "function", "mimics", "the", "approach", "of", "a", "Remark", "plugin", "for", "conformity", "with", "the", "other", "serialization", "functions", ".", "This", "function", "converts", "Slate", "nodes", "to", "MDAST", "nodes", "and", "recursively", "calls", "itself", "to", "process", "child", "nodes", "to", "arbitrary", "depth", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L57-L74
1,282
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
combineTextAndInline
function combineTextAndInline(nodes) { return nodes.reduce((acc, node) => { const prevNode = last(acc); const prevNodeLeaves = get(prevNode, 'leaves'); const data = node.data || {}; /** * If the previous node has leaves and the current node has marks in data * (only happens when we place them on inline nodes here in the parser), or * the current node also has leaves (because the previous node was * originally an inline node that we've already squashed into a leaf) * combine the current node into the previous. */ if (!isEmpty(prevNodeLeaves) && !isEmpty(data.marks)) { prevNodeLeaves.push({ node, marks: data.marks }); return acc; } if (!isEmpty(prevNodeLeaves) && !isEmpty(node.leaves)) { prevNode.leaves = prevNodeLeaves.concat(node.leaves); return acc; } /** * Break nodes contain a single child text node with a newline character * for visual purposes in the editor, but Remark break nodes have no * children, so we remove the child node here. */ if (node.type === 'break') { acc.push({ object: 'inline', type: 'break' }); return acc; } /** * Convert remaining inline nodes to standalone text nodes with leaves. */ if (node.object === 'inline') { acc.push({ object: 'text', leaves: [{ node, marks: data.marks }] }); return acc; } /** * Only remaining case is an actual text node, can be pushed as is. */ acc.push(node); return acc; }, []); }
javascript
function combineTextAndInline(nodes) { return nodes.reduce((acc, node) => { const prevNode = last(acc); const prevNodeLeaves = get(prevNode, 'leaves'); const data = node.data || {}; /** * If the previous node has leaves and the current node has marks in data * (only happens when we place them on inline nodes here in the parser), or * the current node also has leaves (because the previous node was * originally an inline node that we've already squashed into a leaf) * combine the current node into the previous. */ if (!isEmpty(prevNodeLeaves) && !isEmpty(data.marks)) { prevNodeLeaves.push({ node, marks: data.marks }); return acc; } if (!isEmpty(prevNodeLeaves) && !isEmpty(node.leaves)) { prevNode.leaves = prevNodeLeaves.concat(node.leaves); return acc; } /** * Break nodes contain a single child text node with a newline character * for visual purposes in the editor, but Remark break nodes have no * children, so we remove the child node here. */ if (node.type === 'break') { acc.push({ object: 'inline', type: 'break' }); return acc; } /** * Convert remaining inline nodes to standalone text nodes with leaves. */ if (node.object === 'inline') { acc.push({ object: 'text', leaves: [{ node, marks: data.marks }] }); return acc; } /** * Only remaining case is an actual text node, can be pushed as is. */ acc.push(node); return acc; }, []); }
[ "function", "combineTextAndInline", "(", "nodes", ")", "{", "return", "nodes", ".", "reduce", "(", "(", "acc", ",", "node", ")", "=>", "{", "const", "prevNode", "=", "last", "(", "acc", ")", ";", "const", "prevNodeLeaves", "=", "get", "(", "prevNode", ",", "'leaves'", ")", ";", "const", "data", "=", "node", ".", "data", "||", "{", "}", ";", "/**\n * If the previous node has leaves and the current node has marks in data\n * (only happens when we place them on inline nodes here in the parser), or\n * the current node also has leaves (because the previous node was\n * originally an inline node that we've already squashed into a leaf)\n * combine the current node into the previous.\n */", "if", "(", "!", "isEmpty", "(", "prevNodeLeaves", ")", "&&", "!", "isEmpty", "(", "data", ".", "marks", ")", ")", "{", "prevNodeLeaves", ".", "push", "(", "{", "node", ",", "marks", ":", "data", ".", "marks", "}", ")", ";", "return", "acc", ";", "}", "if", "(", "!", "isEmpty", "(", "prevNodeLeaves", ")", "&&", "!", "isEmpty", "(", "node", ".", "leaves", ")", ")", "{", "prevNode", ".", "leaves", "=", "prevNodeLeaves", ".", "concat", "(", "node", ".", "leaves", ")", ";", "return", "acc", ";", "}", "/**\n * Break nodes contain a single child text node with a newline character\n * for visual purposes in the editor, but Remark break nodes have no\n * children, so we remove the child node here.\n */", "if", "(", "node", ".", "type", "===", "'break'", ")", "{", "acc", ".", "push", "(", "{", "object", ":", "'inline'", ",", "type", ":", "'break'", "}", ")", ";", "return", "acc", ";", "}", "/**\n * Convert remaining inline nodes to standalone text nodes with leaves.\n */", "if", "(", "node", ".", "object", "===", "'inline'", ")", "{", "acc", ".", "push", "(", "{", "object", ":", "'text'", ",", "leaves", ":", "[", "{", "node", ",", "marks", ":", "data", ".", "marks", "}", "]", "}", ")", ";", "return", "acc", ";", "}", "/**\n * Only remaining case is an actual text node, can be pushed as is.\n */", "acc", ".", "push", "(", "node", ")", ";", "return", "acc", ";", "}", ",", "[", "]", ")", ";", "}" ]
Includes inline nodes as leaves in adjacent text nodes where appropriate, so that mark node combining logic can apply to both text and inline nodes. This is necessary because Slate doesn't allow inline nodes to have marks while inline nodes in MDAST may be nested within mark nodes. Treating them as if they were text is a bit of a necessary hack.
[ "Includes", "inline", "nodes", "as", "leaves", "in", "adjacent", "text", "nodes", "where", "appropriate", "so", "that", "mark", "node", "combining", "logic", "can", "apply", "to", "both", "text", "and", "inline", "nodes", ".", "This", "is", "necessary", "because", "Slate", "doesn", "t", "allow", "inline", "nodes", "to", "have", "marks", "while", "inline", "nodes", "in", "MDAST", "may", "be", "nested", "within", "mark", "nodes", ".", "Treating", "them", "as", "if", "they", "were", "text", "is", "a", "bit", "of", "a", "necessary", "hack", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L83-L130
1,283
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
processCodeMark
function processCodeMark(markTypes) { const isInlineCode = markTypes.includes('inlineCode'); const filteredMarkTypes = isInlineCode ? without(markTypes, 'inlineCode') : markTypes; const textNodeType = isInlineCode ? 'inlineCode' : 'html'; return { filteredMarkTypes, textNodeType }; }
javascript
function processCodeMark(markTypes) { const isInlineCode = markTypes.includes('inlineCode'); const filteredMarkTypes = isInlineCode ? without(markTypes, 'inlineCode') : markTypes; const textNodeType = isInlineCode ? 'inlineCode' : 'html'; return { filteredMarkTypes, textNodeType }; }
[ "function", "processCodeMark", "(", "markTypes", ")", "{", "const", "isInlineCode", "=", "markTypes", ".", "includes", "(", "'inlineCode'", ")", ";", "const", "filteredMarkTypes", "=", "isInlineCode", "?", "without", "(", "markTypes", ",", "'inlineCode'", ")", ":", "markTypes", ";", "const", "textNodeType", "=", "isInlineCode", "?", "'inlineCode'", ":", "'html'", ";", "return", "{", "filteredMarkTypes", ",", "textNodeType", "}", ";", "}" ]
Slate treats inline code decoration as a standard mark, but MDAST does not allow inline code nodes to contain children, only a single text value. An MDAST inline code node can be nested within mark nodes such as "emphasis" and "strong", but it cannot contain them. Because of this, if a "code" mark (translated to MDAST "inlineCode") is in the markTypes array, we make the base text node an "inlineCode" type instead of a standard text node.
[ "Slate", "treats", "inline", "code", "decoration", "as", "a", "standard", "mark", "but", "MDAST", "does", "not", "allow", "inline", "code", "nodes", "to", "contain", "children", "only", "a", "single", "text", "value", ".", "An", "MDAST", "inline", "code", "node", "can", "be", "nested", "within", "mark", "nodes", "such", "as", "emphasis", "and", "strong", "but", "it", "cannot", "contain", "them", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L142-L147
1,284
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
convertTextNode
function convertTextNode(node) { /** * If the Slate text node has a "leaves" property, translate the Slate AST to * a nested MDAST structure. Otherwise, just return an equivalent MDAST text * node. */ if (node.leaves) { const processedLeaves = node.leaves.map(processLeaves); // Compensate for Slate including leading and trailing whitespace in styled text nodes, which // cannot be represented in markdown (https://github.com/netlify/netlify-cms/issues/1448) for (let i = 0; i < processedLeaves.length; i += 1) { const leaf = processedLeaves[i]; if (leaf.marks.length > 0 && leaf.text && leaf.text.trim() !== leaf.text) { const [, leadingWhitespace, trailingWhitespace] = leaf.text.match(/^(\s*).*?(\s*)$/); // Move the leading whitespace to a separate unstyled leaf, unless the current leaf // is preceded by another one with (at least) the same marks applied: if ( leadingWhitespace.length > 0 && (i === 0 || !leaf.marks.every( mark => processedLeaves[i - 1].marks && processedLeaves[i - 1].marks.includes(mark), )) ) { processedLeaves.splice(i, 0, { text: leadingWhitespace, marks: [], textNodeType: leaf.textNodeType, }); i += 1; leaf.text = leaf.text.replace(/^\s+/, ''); } // Move the trailing whitespace to a separate unstyled leaf, unless the current leaf // is followed by another one with (at least) the same marks applied: if ( trailingWhitespace.length > 0 && (i === processedLeaves.length - 1 || !leaf.marks.every( mark => processedLeaves[i + 1].marks && processedLeaves[i + 1].marks.includes(mark), )) ) { processedLeaves.splice(i + 1, 0, { text: trailingWhitespace, marks: [], textNodeType: leaf.textNodeType, }); i += 1; leaf.text = leaf.text.replace(/\s+$/, ''); } } } const condensedNodes = processedLeaves.reduce(condenseNodesReducer, { nodes: [] }); return condensedNodes.nodes; } if (node.object === 'inline') { return transform(node); } return u('html', node.text); }
javascript
function convertTextNode(node) { /** * If the Slate text node has a "leaves" property, translate the Slate AST to * a nested MDAST structure. Otherwise, just return an equivalent MDAST text * node. */ if (node.leaves) { const processedLeaves = node.leaves.map(processLeaves); // Compensate for Slate including leading and trailing whitespace in styled text nodes, which // cannot be represented in markdown (https://github.com/netlify/netlify-cms/issues/1448) for (let i = 0; i < processedLeaves.length; i += 1) { const leaf = processedLeaves[i]; if (leaf.marks.length > 0 && leaf.text && leaf.text.trim() !== leaf.text) { const [, leadingWhitespace, trailingWhitespace] = leaf.text.match(/^(\s*).*?(\s*)$/); // Move the leading whitespace to a separate unstyled leaf, unless the current leaf // is preceded by another one with (at least) the same marks applied: if ( leadingWhitespace.length > 0 && (i === 0 || !leaf.marks.every( mark => processedLeaves[i - 1].marks && processedLeaves[i - 1].marks.includes(mark), )) ) { processedLeaves.splice(i, 0, { text: leadingWhitespace, marks: [], textNodeType: leaf.textNodeType, }); i += 1; leaf.text = leaf.text.replace(/^\s+/, ''); } // Move the trailing whitespace to a separate unstyled leaf, unless the current leaf // is followed by another one with (at least) the same marks applied: if ( trailingWhitespace.length > 0 && (i === processedLeaves.length - 1 || !leaf.marks.every( mark => processedLeaves[i + 1].marks && processedLeaves[i + 1].marks.includes(mark), )) ) { processedLeaves.splice(i + 1, 0, { text: trailingWhitespace, marks: [], textNodeType: leaf.textNodeType, }); i += 1; leaf.text = leaf.text.replace(/\s+$/, ''); } } } const condensedNodes = processedLeaves.reduce(condenseNodesReducer, { nodes: [] }); return condensedNodes.nodes; } if (node.object === 'inline') { return transform(node); } return u('html', node.text); }
[ "function", "convertTextNode", "(", "node", ")", "{", "/**\n * If the Slate text node has a \"leaves\" property, translate the Slate AST to\n * a nested MDAST structure. Otherwise, just return an equivalent MDAST text\n * node.\n */", "if", "(", "node", ".", "leaves", ")", "{", "const", "processedLeaves", "=", "node", ".", "leaves", ".", "map", "(", "processLeaves", ")", ";", "// Compensate for Slate including leading and trailing whitespace in styled text nodes, which", "// cannot be represented in markdown (https://github.com/netlify/netlify-cms/issues/1448)", "for", "(", "let", "i", "=", "0", ";", "i", "<", "processedLeaves", ".", "length", ";", "i", "+=", "1", ")", "{", "const", "leaf", "=", "processedLeaves", "[", "i", "]", ";", "if", "(", "leaf", ".", "marks", ".", "length", ">", "0", "&&", "leaf", ".", "text", "&&", "leaf", ".", "text", ".", "trim", "(", ")", "!==", "leaf", ".", "text", ")", "{", "const", "[", ",", "leadingWhitespace", ",", "trailingWhitespace", "]", "=", "leaf", ".", "text", ".", "match", "(", "/", "^(\\s*).*?(\\s*)$", "/", ")", ";", "// Move the leading whitespace to a separate unstyled leaf, unless the current leaf", "// is preceded by another one with (at least) the same marks applied:", "if", "(", "leadingWhitespace", ".", "length", ">", "0", "&&", "(", "i", "===", "0", "||", "!", "leaf", ".", "marks", ".", "every", "(", "mark", "=>", "processedLeaves", "[", "i", "-", "1", "]", ".", "marks", "&&", "processedLeaves", "[", "i", "-", "1", "]", ".", "marks", ".", "includes", "(", "mark", ")", ",", ")", ")", ")", "{", "processedLeaves", ".", "splice", "(", "i", ",", "0", ",", "{", "text", ":", "leadingWhitespace", ",", "marks", ":", "[", "]", ",", "textNodeType", ":", "leaf", ".", "textNodeType", ",", "}", ")", ";", "i", "+=", "1", ";", "leaf", ".", "text", "=", "leaf", ".", "text", ".", "replace", "(", "/", "^\\s+", "/", ",", "''", ")", ";", "}", "// Move the trailing whitespace to a separate unstyled leaf, unless the current leaf", "// is followed by another one with (at least) the same marks applied:", "if", "(", "trailingWhitespace", ".", "length", ">", "0", "&&", "(", "i", "===", "processedLeaves", ".", "length", "-", "1", "||", "!", "leaf", ".", "marks", ".", "every", "(", "mark", "=>", "processedLeaves", "[", "i", "+", "1", "]", ".", "marks", "&&", "processedLeaves", "[", "i", "+", "1", "]", ".", "marks", ".", "includes", "(", "mark", ")", ",", ")", ")", ")", "{", "processedLeaves", ".", "splice", "(", "i", "+", "1", ",", "0", ",", "{", "text", ":", "trailingWhitespace", ",", "marks", ":", "[", "]", ",", "textNodeType", ":", "leaf", ".", "textNodeType", ",", "}", ")", ";", "i", "+=", "1", ";", "leaf", ".", "text", "=", "leaf", ".", "text", ".", "replace", "(", "/", "\\s+$", "/", ",", "''", ")", ";", "}", "}", "}", "const", "condensedNodes", "=", "processedLeaves", ".", "reduce", "(", "condenseNodesReducer", ",", "{", "nodes", ":", "[", "]", "}", ")", ";", "return", "condensedNodes", ".", "nodes", ";", "}", "if", "(", "node", ".", "object", "===", "'inline'", ")", "{", "return", "transform", "(", "node", ")", ";", "}", "return", "u", "(", "'html'", ",", "node", ".", "text", ")", ";", "}" ]
Converts a Slate Raw text node to an MDAST text node. Slate text nodes without marks often simply have a "text" property with the value. In this case the conversion to MDAST is simple. If a Slate text node does not have a "text" property, it will instead have a "leaves" property containing an array of objects, each with an array of marks, such as "bold" or "italic", along with a "text" property. MDAST instead expresses such marks in a nested structure, with individual nodes for each mark type nested until the deepest mark node, which will contain the text node. To convert a Slate text node's marks to MDAST, we treat each "leaf" as a separate text node, convert the text node itself to an MDAST text node, and then recursively wrap the text node for each mark, collecting the results of each leaf in a single array of child nodes. For example, this Slate text node: { object: 'text', leaves: [ { text: 'test', marks: ['bold', 'italic'] }, { text: 'test two' } ] } ...would be converted to this MDAST nested structure: [ { type: 'strong', children: [{ type: 'emphasis', children: [{ type: 'text', value: 'test' }] }] }, { type: 'text', value: 'test two' } ] This example also demonstrates how a single Slate node may need to be replaced with multiple MDAST nodes, so the resulting array must be flattened.
[ "Converts", "a", "Slate", "Raw", "text", "node", "to", "an", "MDAST", "text", "node", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L204-L263
1,285
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
processLeaves
function processLeaves(leaf) { /** * Get an array of the mark types, converted to their MDAST equivalent * types. */ const { marks = [], text } = leaf; const markTypes = marks.map(mark => markMap[mark.type]); if (typeof leaf.text === 'string') { /** * Code marks must be removed from the marks array, and the presence of a * code mark changes the text node type that should be used. */ const { filteredMarkTypes, textNodeType } = processCodeMark(markTypes); return { text, marks: filteredMarkTypes, textNodeType }; } return { node: leaf.node, marks: markTypes }; }
javascript
function processLeaves(leaf) { /** * Get an array of the mark types, converted to their MDAST equivalent * types. */ const { marks = [], text } = leaf; const markTypes = marks.map(mark => markMap[mark.type]); if (typeof leaf.text === 'string') { /** * Code marks must be removed from the marks array, and the presence of a * code mark changes the text node type that should be used. */ const { filteredMarkTypes, textNodeType } = processCodeMark(markTypes); return { text, marks: filteredMarkTypes, textNodeType }; } return { node: leaf.node, marks: markTypes }; }
[ "function", "processLeaves", "(", "leaf", ")", "{", "/**\n * Get an array of the mark types, converted to their MDAST equivalent\n * types.\n */", "const", "{", "marks", "=", "[", "]", ",", "text", "}", "=", "leaf", ";", "const", "markTypes", "=", "marks", ".", "map", "(", "mark", "=>", "markMap", "[", "mark", ".", "type", "]", ")", ";", "if", "(", "typeof", "leaf", ".", "text", "===", "'string'", ")", "{", "/**\n * Code marks must be removed from the marks array, and the presence of a\n * code mark changes the text node type that should be used.\n */", "const", "{", "filteredMarkTypes", ",", "textNodeType", "}", "=", "processCodeMark", "(", "markTypes", ")", ";", "return", "{", "text", ",", "marks", ":", "filteredMarkTypes", ",", "textNodeType", "}", ";", "}", "return", "{", "node", ":", "leaf", ".", "node", ",", "marks", ":", "markTypes", "}", ";", "}" ]
Process Slate node leaves in preparation for MDAST transformation.
[ "Process", "Slate", "node", "leaves", "in", "preparation", "for", "MDAST", "transformation", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L268-L286
1,286
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
getMarkLength
function getMarkLength(markType, nodes) { let length = 0; while (nodes[length] && nodes[length].marks.includes(markType)) { ++length; } return { markType, length }; }
javascript
function getMarkLength(markType, nodes) { let length = 0; while (nodes[length] && nodes[length].marks.includes(markType)) { ++length; } return { markType, length }; }
[ "function", "getMarkLength", "(", "markType", ",", "nodes", ")", "{", "let", "length", "=", "0", ";", "while", "(", "nodes", "[", "length", "]", "&&", "nodes", "[", "length", "]", ".", "marks", ".", "includes", "(", "markType", ")", ")", "{", "++", "length", ";", "}", "return", "{", "markType", ",", "length", "}", ";", "}" ]
Get the number of consecutive Slate nodes containing a given mark beginning from the first received node.
[ "Get", "the", "number", "of", "consecutive", "Slate", "nodes", "containing", "a", "given", "mark", "beginning", "from", "the", "first", "received", "node", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L373-L379
1,287
netlify/netlify-cms
packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js
convertNode
function convertNode(node, children) { switch (node.type) { /** * General * * Convert simple cases that only require a type and children, with no * additional properties. */ case 'root': case 'paragraph': case 'quote': case 'list-item': case 'table': case 'table-row': case 'table-cell': { return u(typeMap[node.type], children); } /** * Shortcodes * * Shortcode nodes only exist in Slate's Raw AST if they were inserted * via the plugin toolbar in memory, so they should always have * shortcode data attached. The "shortcode" data property contains the * name of the registered shortcode plugin, and the "shortcodeData" data * property contains the data received from the shortcode plugin's * `fromBlock` method when the shortcode node was created. * * Here we create a `shortcode` MDAST node that contains only the shortcode * data. */ case 'shortcode': { const { data } = node; return u(typeMap[node.type], { data }); } /** * Headings * * Slate schemas don't usually infer basic type info from data, so each * level of heading is a separately named type. The MDAST schema just * has a single "heading" type with the depth stored in a "depth" * property on the node. Here we derive the depth from the Slate node * type - e.g., for "heading-two", we need a depth value of "2". */ case 'heading-one': case 'heading-two': case 'heading-three': case 'heading-four': case 'heading-five': case 'heading-six': { const depthMap = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6 }; const depthText = node.type.split('-')[1]; const depth = depthMap[depthText]; return u(typeMap[node.type], { depth }, children); } /** * Code Blocks * * Code block nodes have a single text child, and may have a code language * stored in the "lang" data property. Here we transfer both the node * value and the "lang" data property to the new MDAST node. */ case 'code': { const value = flatMap(node.nodes, child => { return flatMap(child.leaves, 'text'); }).join(''); const { lang, ...data } = get(node, 'data', {}); return u(typeMap[node.type], { lang, data }, value); } /** * Lists * * Our Slate schema has separate node types for ordered and unordered * lists, but the MDAST spec uses a single type with a boolean "ordered" * property to indicate whether the list is numbered. The MDAST spec also * allows for a "start" property to indicate the first number used for an * ordered list. Here we translate both values to our Slate schema. */ case 'numbered-list': case 'bulleted-list': { const ordered = node.type === 'numbered-list'; const props = { ordered, start: get(node.data, 'start') || 1 }; return u(typeMap[node.type], props, children); } /** * Breaks * * Breaks don't have children. We parse them separately for clarity. */ case 'break': case 'thematic-break': { return u(typeMap[node.type]); } /** * Links * * The url and title attributes of link nodes are stored in properties on * the node for both Slate and Remark schemas. */ case 'link': { const { url, title, ...data } = get(node, 'data', {}); return u(typeMap[node.type], { url, title, data }, children); } /** * Images * * This transformation is almost identical to that of links, except for the * lack of child nodes and addition of `alt` attribute data. */ case 'image': { const { url, title, alt, ...data } = get(node, 'data', {}); return u(typeMap[node.type], { url, title, alt, data }); } /** * No default case is supplied because an unhandled case should never * occur. In the event that it does, let the error throw (for now). */ } }
javascript
function convertNode(node, children) { switch (node.type) { /** * General * * Convert simple cases that only require a type and children, with no * additional properties. */ case 'root': case 'paragraph': case 'quote': case 'list-item': case 'table': case 'table-row': case 'table-cell': { return u(typeMap[node.type], children); } /** * Shortcodes * * Shortcode nodes only exist in Slate's Raw AST if they were inserted * via the plugin toolbar in memory, so they should always have * shortcode data attached. The "shortcode" data property contains the * name of the registered shortcode plugin, and the "shortcodeData" data * property contains the data received from the shortcode plugin's * `fromBlock` method when the shortcode node was created. * * Here we create a `shortcode` MDAST node that contains only the shortcode * data. */ case 'shortcode': { const { data } = node; return u(typeMap[node.type], { data }); } /** * Headings * * Slate schemas don't usually infer basic type info from data, so each * level of heading is a separately named type. The MDAST schema just * has a single "heading" type with the depth stored in a "depth" * property on the node. Here we derive the depth from the Slate node * type - e.g., for "heading-two", we need a depth value of "2". */ case 'heading-one': case 'heading-two': case 'heading-three': case 'heading-four': case 'heading-five': case 'heading-six': { const depthMap = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6 }; const depthText = node.type.split('-')[1]; const depth = depthMap[depthText]; return u(typeMap[node.type], { depth }, children); } /** * Code Blocks * * Code block nodes have a single text child, and may have a code language * stored in the "lang" data property. Here we transfer both the node * value and the "lang" data property to the new MDAST node. */ case 'code': { const value = flatMap(node.nodes, child => { return flatMap(child.leaves, 'text'); }).join(''); const { lang, ...data } = get(node, 'data', {}); return u(typeMap[node.type], { lang, data }, value); } /** * Lists * * Our Slate schema has separate node types for ordered and unordered * lists, but the MDAST spec uses a single type with a boolean "ordered" * property to indicate whether the list is numbered. The MDAST spec also * allows for a "start" property to indicate the first number used for an * ordered list. Here we translate both values to our Slate schema. */ case 'numbered-list': case 'bulleted-list': { const ordered = node.type === 'numbered-list'; const props = { ordered, start: get(node.data, 'start') || 1 }; return u(typeMap[node.type], props, children); } /** * Breaks * * Breaks don't have children. We parse them separately for clarity. */ case 'break': case 'thematic-break': { return u(typeMap[node.type]); } /** * Links * * The url and title attributes of link nodes are stored in properties on * the node for both Slate and Remark schemas. */ case 'link': { const { url, title, ...data } = get(node, 'data', {}); return u(typeMap[node.type], { url, title, data }, children); } /** * Images * * This transformation is almost identical to that of links, except for the * lack of child nodes and addition of `alt` attribute data. */ case 'image': { const { url, title, alt, ...data } = get(node, 'data', {}); return u(typeMap[node.type], { url, title, alt, data }); } /** * No default case is supplied because an unhandled case should never * occur. In the event that it does, let the error throw (for now). */ } }
[ "function", "convertNode", "(", "node", ",", "children", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "/**\n * General\n *\n * Convert simple cases that only require a type and children, with no\n * additional properties.\n */", "case", "'root'", ":", "case", "'paragraph'", ":", "case", "'quote'", ":", "case", "'list-item'", ":", "case", "'table'", ":", "case", "'table-row'", ":", "case", "'table-cell'", ":", "{", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "children", ")", ";", "}", "/**\n * Shortcodes\n *\n * Shortcode nodes only exist in Slate's Raw AST if they were inserted\n * via the plugin toolbar in memory, so they should always have\n * shortcode data attached. The \"shortcode\" data property contains the\n * name of the registered shortcode plugin, and the \"shortcodeData\" data\n * property contains the data received from the shortcode plugin's\n * `fromBlock` method when the shortcode node was created.\n *\n * Here we create a `shortcode` MDAST node that contains only the shortcode\n * data.\n */", "case", "'shortcode'", ":", "{", "const", "{", "data", "}", "=", "node", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "data", "}", ")", ";", "}", "/**\n * Headings\n *\n * Slate schemas don't usually infer basic type info from data, so each\n * level of heading is a separately named type. The MDAST schema just\n * has a single \"heading\" type with the depth stored in a \"depth\"\n * property on the node. Here we derive the depth from the Slate node\n * type - e.g., for \"heading-two\", we need a depth value of \"2\".\n */", "case", "'heading-one'", ":", "case", "'heading-two'", ":", "case", "'heading-three'", ":", "case", "'heading-four'", ":", "case", "'heading-five'", ":", "case", "'heading-six'", ":", "{", "const", "depthMap", "=", "{", "one", ":", "1", ",", "two", ":", "2", ",", "three", ":", "3", ",", "four", ":", "4", ",", "five", ":", "5", ",", "six", ":", "6", "}", ";", "const", "depthText", "=", "node", ".", "type", ".", "split", "(", "'-'", ")", "[", "1", "]", ";", "const", "depth", "=", "depthMap", "[", "depthText", "]", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "depth", "}", ",", "children", ")", ";", "}", "/**\n * Code Blocks\n *\n * Code block nodes have a single text child, and may have a code language\n * stored in the \"lang\" data property. Here we transfer both the node\n * value and the \"lang\" data property to the new MDAST node.\n */", "case", "'code'", ":", "{", "const", "value", "=", "flatMap", "(", "node", ".", "nodes", ",", "child", "=>", "{", "return", "flatMap", "(", "child", ".", "leaves", ",", "'text'", ")", ";", "}", ")", ".", "join", "(", "''", ")", ";", "const", "{", "lang", ",", "...", "data", "}", "=", "get", "(", "node", ",", "'data'", ",", "{", "}", ")", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "lang", ",", "data", "}", ",", "value", ")", ";", "}", "/**\n * Lists\n *\n * Our Slate schema has separate node types for ordered and unordered\n * lists, but the MDAST spec uses a single type with a boolean \"ordered\"\n * property to indicate whether the list is numbered. The MDAST spec also\n * allows for a \"start\" property to indicate the first number used for an\n * ordered list. Here we translate both values to our Slate schema.\n */", "case", "'numbered-list'", ":", "case", "'bulleted-list'", ":", "{", "const", "ordered", "=", "node", ".", "type", "===", "'numbered-list'", ";", "const", "props", "=", "{", "ordered", ",", "start", ":", "get", "(", "node", ".", "data", ",", "'start'", ")", "||", "1", "}", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "props", ",", "children", ")", ";", "}", "/**\n * Breaks\n *\n * Breaks don't have children. We parse them separately for clarity.\n */", "case", "'break'", ":", "case", "'thematic-break'", ":", "{", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ")", ";", "}", "/**\n * Links\n *\n * The url and title attributes of link nodes are stored in properties on\n * the node for both Slate and Remark schemas.\n */", "case", "'link'", ":", "{", "const", "{", "url", ",", "title", ",", "...", "data", "}", "=", "get", "(", "node", ",", "'data'", ",", "{", "}", ")", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "url", ",", "title", ",", "data", "}", ",", "children", ")", ";", "}", "/**\n * Images\n *\n * This transformation is almost identical to that of links, except for the\n * lack of child nodes and addition of `alt` attribute data.\n */", "case", "'image'", ":", "{", "const", "{", "url", ",", "title", ",", "alt", ",", "...", "data", "}", "=", "get", "(", "node", ",", "'data'", ",", "{", "}", ")", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "url", ",", "title", ",", "alt", ",", "data", "}", ")", ";", "}", "/**\n * No default case is supplied because an unhandled case should never\n * occur. In the event that it does, let the error throw (for now).\n */", "}", "}" ]
Convert a single Slate Raw node to an MDAST node. Uses the unist-builder `u` function to create MDAST nodes.
[ "Convert", "a", "single", "Slate", "Raw", "node", "to", "an", "MDAST", "node", ".", "Uses", "the", "unist", "-", "builder", "u", "function", "to", "create", "MDAST", "nodes", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js#L385-L510
1,288
netlify/netlify-cms
packages/netlify-cms-core/src/lib/stringTemplate.js
getExplicitFieldReplacement
function getExplicitFieldReplacement(key, data) { if (!key.startsWith(FIELD_PREFIX)) { return; } const fieldName = key.substring(FIELD_PREFIX.length); return data.get(fieldName, ''); }
javascript
function getExplicitFieldReplacement(key, data) { if (!key.startsWith(FIELD_PREFIX)) { return; } const fieldName = key.substring(FIELD_PREFIX.length); return data.get(fieldName, ''); }
[ "function", "getExplicitFieldReplacement", "(", "key", ",", "data", ")", "{", "if", "(", "!", "key", ".", "startsWith", "(", "FIELD_PREFIX", ")", ")", "{", "return", ";", "}", "const", "fieldName", "=", "key", ".", "substring", "(", "FIELD_PREFIX", ".", "length", ")", ";", "return", "data", ".", "get", "(", "fieldName", ",", "''", ")", ";", "}" ]
Allow `fields.` prefix in placeholder to override built in replacements like "slug" and "year" with values from fields of the same name.
[ "Allow", "fields", ".", "prefix", "in", "placeholder", "to", "override", "built", "in", "replacements", "like", "slug", "and", "year", "with", "values", "from", "fields", "of", "the", "same", "name", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-core/src/lib/stringTemplate.js#L26-L32
1,289
netlify/netlify-cms
packages/netlify-cms-media-library-uploadcare/src/index.js
isFileGroup
function isFileGroup(files) { const basePatternString = `~${files.length}/nth/`; const mapExpression = (val, idx) => new RegExp(`${basePatternString}${idx}/$`); const expressions = Array.from({ length: files.length }, mapExpression); return expressions.every(exp => files.some(url => exp.test(url))); }
javascript
function isFileGroup(files) { const basePatternString = `~${files.length}/nth/`; const mapExpression = (val, idx) => new RegExp(`${basePatternString}${idx}/$`); const expressions = Array.from({ length: files.length }, mapExpression); return expressions.every(exp => files.some(url => exp.test(url))); }
[ "function", "isFileGroup", "(", "files", ")", "{", "const", "basePatternString", "=", "`", "${", "files", ".", "length", "}", "`", ";", "const", "mapExpression", "=", "(", "val", ",", "idx", ")", "=>", "new", "RegExp", "(", "`", "${", "basePatternString", "}", "${", "idx", "}", "`", ")", ";", "const", "expressions", "=", "Array", ".", "from", "(", "{", "length", ":", "files", ".", "length", "}", ",", "mapExpression", ")", ";", "return", "expressions", ".", "every", "(", "exp", "=>", "files", ".", "some", "(", "url", "=>", "exp", ".", "test", "(", "url", ")", ")", ")", ";", "}" ]
Determine whether an array of urls represents an unaltered set of Uploadcare group urls. If they've been changed or any are missing, a new group will need to be created to represent the current values.
[ "Determine", "whether", "an", "array", "of", "urls", "represents", "an", "unaltered", "set", "of", "Uploadcare", "group", "urls", ".", "If", "they", "ve", "been", "changed", "or", "any", "are", "missing", "a", "new", "group", "will", "need", "to", "be", "created", "to", "represent", "the", "current", "values", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-media-library-uploadcare/src/index.js#L24-L29
1,290
netlify/netlify-cms
packages/netlify-cms-media-library-uploadcare/src/index.js
getFileGroup
function getFileGroup(files) { /** * Capture the group id from the first file in the files array. */ const groupId = new RegExp(`^.+/([^/]+~${files.length})/nth/`).exec(files[0])[1]; /** * The `openDialog` method handles the jQuery promise object returned by * `fileFrom`, but requires the promise returned by `loadFileGroup` to provide * the result of it's `done` method. */ return new Promise(resolve => uploadcare.loadFileGroup(groupId).done(group => resolve(group))); }
javascript
function getFileGroup(files) { /** * Capture the group id from the first file in the files array. */ const groupId = new RegExp(`^.+/([^/]+~${files.length})/nth/`).exec(files[0])[1]; /** * The `openDialog` method handles the jQuery promise object returned by * `fileFrom`, but requires the promise returned by `loadFileGroup` to provide * the result of it's `done` method. */ return new Promise(resolve => uploadcare.loadFileGroup(groupId).done(group => resolve(group))); }
[ "function", "getFileGroup", "(", "files", ")", "{", "/**\n * Capture the group id from the first file in the files array.\n */", "const", "groupId", "=", "new", "RegExp", "(", "`", "${", "files", ".", "length", "}", "`", ")", ".", "exec", "(", "files", "[", "0", "]", ")", "[", "1", "]", ";", "/**\n * The `openDialog` method handles the jQuery promise object returned by\n * `fileFrom`, but requires the promise returned by `loadFileGroup` to provide\n * the result of it's `done` method.\n */", "return", "new", "Promise", "(", "resolve", "=>", "uploadcare", ".", "loadFileGroup", "(", "groupId", ")", ".", "done", "(", "group", "=>", "resolve", "(", "group", ")", ")", ")", ";", "}" ]
Returns a fileGroupInfo object wrapped in a promise-like object.
[ "Returns", "a", "fileGroupInfo", "object", "wrapped", "in", "a", "promise", "-", "like", "object", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-media-library-uploadcare/src/index.js#L34-L46
1,291
netlify/netlify-cms
packages/netlify-cms-media-library-uploadcare/src/index.js
openDialog
function openDialog(files, config, handleInsert) { uploadcare.openDialog(files, config).done(({ promise }) => promise().then(({ cdnUrl, count }) => { if (config.multiple) { const urls = Array.from({ length: count }, (val, idx) => `${cdnUrl}nth/${idx}/`); handleInsert(urls); } else { handleInsert(cdnUrl); } }), ); }
javascript
function openDialog(files, config, handleInsert) { uploadcare.openDialog(files, config).done(({ promise }) => promise().then(({ cdnUrl, count }) => { if (config.multiple) { const urls = Array.from({ length: count }, (val, idx) => `${cdnUrl}nth/${idx}/`); handleInsert(urls); } else { handleInsert(cdnUrl); } }), ); }
[ "function", "openDialog", "(", "files", ",", "config", ",", "handleInsert", ")", "{", "uploadcare", ".", "openDialog", "(", "files", ",", "config", ")", ".", "done", "(", "(", "{", "promise", "}", ")", "=>", "promise", "(", ")", ".", "then", "(", "(", "{", "cdnUrl", ",", "count", "}", ")", "=>", "{", "if", "(", "config", ".", "multiple", ")", "{", "const", "urls", "=", "Array", ".", "from", "(", "{", "length", ":", "count", "}", ",", "(", "val", ",", "idx", ")", "=>", "`", "${", "cdnUrl", "}", "${", "idx", "}", "`", ")", ";", "handleInsert", "(", "urls", ")", ";", "}", "else", "{", "handleInsert", "(", "cdnUrl", ")", ";", "}", "}", ")", ",", ")", ";", "}" ]
Open the standalone dialog. A single instance is created and destroyed for each use.
[ "Open", "the", "standalone", "dialog", ".", "A", "single", "instance", "is", "created", "and", "destroyed", "for", "each", "use", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-media-library-uploadcare/src/index.js#L76-L87
1,292
netlify/netlify-cms
packages/netlify-cms-media-library-uploadcare/src/index.js
init
async function init({ options = { config: {} }, handleInsert } = {}) { const { publicKey, ...globalConfig } = options.config; const baseConfig = { ...defaultConfig, ...globalConfig }; window.UPLOADCARE_PUBLIC_KEY = publicKey; /** * Register the effects tab by default because the effects tab is awesome. Can * be disabled via config. */ uploadcare.registerTab('preview', uploadcareTabEffects); return { /** * On show, create a new widget, cache it in the widgets object, and open. * No hide method is provided because the widget doesn't provide it. */ show: ({ value, config: instanceConfig = {}, allowMultiple, imagesOnly = false } = {}) => { const config = { ...baseConfig, imagesOnly, ...instanceConfig }; const multiple = allowMultiple === false ? false : !!config.multiple; const resolvedConfig = { ...config, multiple }; const files = getFiles(value); /** * Resolve the promise only if it's ours. Only the jQuery promise objects * from the Uploadcare library will have a `state` method. */ if (files && !files.state) { return files.then(result => openDialog(result, resolvedConfig, handleInsert)); } else { return openDialog(files, resolvedConfig, handleInsert); } }, /** * Uploadcare doesn't provide a "media library" widget for viewing and * selecting existing files, so we return `false` here so Netlify CMS only * opens the Uploadcare widget when called from an editor control. This * results in the "Media" button in the global nav being hidden. */ enableStandalone: () => false, }; }
javascript
async function init({ options = { config: {} }, handleInsert } = {}) { const { publicKey, ...globalConfig } = options.config; const baseConfig = { ...defaultConfig, ...globalConfig }; window.UPLOADCARE_PUBLIC_KEY = publicKey; /** * Register the effects tab by default because the effects tab is awesome. Can * be disabled via config. */ uploadcare.registerTab('preview', uploadcareTabEffects); return { /** * On show, create a new widget, cache it in the widgets object, and open. * No hide method is provided because the widget doesn't provide it. */ show: ({ value, config: instanceConfig = {}, allowMultiple, imagesOnly = false } = {}) => { const config = { ...baseConfig, imagesOnly, ...instanceConfig }; const multiple = allowMultiple === false ? false : !!config.multiple; const resolvedConfig = { ...config, multiple }; const files = getFiles(value); /** * Resolve the promise only if it's ours. Only the jQuery promise objects * from the Uploadcare library will have a `state` method. */ if (files && !files.state) { return files.then(result => openDialog(result, resolvedConfig, handleInsert)); } else { return openDialog(files, resolvedConfig, handleInsert); } }, /** * Uploadcare doesn't provide a "media library" widget for viewing and * selecting existing files, so we return `false` here so Netlify CMS only * opens the Uploadcare widget when called from an editor control. This * results in the "Media" button in the global nav being hidden. */ enableStandalone: () => false, }; }
[ "async", "function", "init", "(", "{", "options", "=", "{", "config", ":", "{", "}", "}", ",", "handleInsert", "}", "=", "{", "}", ")", "{", "const", "{", "publicKey", ",", "...", "globalConfig", "}", "=", "options", ".", "config", ";", "const", "baseConfig", "=", "{", "...", "defaultConfig", ",", "...", "globalConfig", "}", ";", "window", ".", "UPLOADCARE_PUBLIC_KEY", "=", "publicKey", ";", "/**\n * Register the effects tab by default because the effects tab is awesome. Can\n * be disabled via config.\n */", "uploadcare", ".", "registerTab", "(", "'preview'", ",", "uploadcareTabEffects", ")", ";", "return", "{", "/**\n * On show, create a new widget, cache it in the widgets object, and open.\n * No hide method is provided because the widget doesn't provide it.\n */", "show", ":", "(", "{", "value", ",", "config", ":", "instanceConfig", "=", "{", "}", ",", "allowMultiple", ",", "imagesOnly", "=", "false", "}", "=", "{", "}", ")", "=>", "{", "const", "config", "=", "{", "...", "baseConfig", ",", "imagesOnly", ",", "...", "instanceConfig", "}", ";", "const", "multiple", "=", "allowMultiple", "===", "false", "?", "false", ":", "!", "!", "config", ".", "multiple", ";", "const", "resolvedConfig", "=", "{", "...", "config", ",", "multiple", "}", ";", "const", "files", "=", "getFiles", "(", "value", ")", ";", "/**\n * Resolve the promise only if it's ours. Only the jQuery promise objects\n * from the Uploadcare library will have a `state` method.\n */", "if", "(", "files", "&&", "!", "files", ".", "state", ")", "{", "return", "files", ".", "then", "(", "result", "=>", "openDialog", "(", "result", ",", "resolvedConfig", ",", "handleInsert", ")", ")", ";", "}", "else", "{", "return", "openDialog", "(", "files", ",", "resolvedConfig", ",", "handleInsert", ")", ";", "}", "}", ",", "/**\n * Uploadcare doesn't provide a \"media library\" widget for viewing and\n * selecting existing files, so we return `false` here so Netlify CMS only\n * opens the Uploadcare widget when called from an editor control. This\n * results in the \"Media\" button in the global nav being hidden.\n */", "enableStandalone", ":", "(", ")", "=>", "false", ",", "}", ";", "}" ]
Initialization function will only run once, returns an API object for Netlify CMS to call methods on.
[ "Initialization", "function", "will", "only", "run", "once", "returns", "an", "API", "object", "for", "Netlify", "CMS", "to", "call", "methods", "on", "." ]
2488556590cbfdcefa626f2f2de01e7a160cf6ee
https://github.com/netlify/netlify-cms/blob/2488556590cbfdcefa626f2f2de01e7a160cf6ee/packages/netlify-cms-media-library-uploadcare/src/index.js#L93-L135
1,293
BrainJS/brain.js
dist/recurrent/matrix/all-ones.js
allOnes
function allOnes(product) { for (var i = 0; i < product.weights.length; i++) { product.weights[i] = 1; product.deltas[i] = 0; } }
javascript
function allOnes(product) { for (var i = 0; i < product.weights.length; i++) { product.weights[i] = 1; product.deltas[i] = 0; } }
[ "function", "allOnes", "(", "product", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "product", ".", "weights", ".", "length", ";", "i", "++", ")", "{", "product", ".", "weights", "[", "i", "]", "=", "1", ";", "product", ".", "deltas", "[", "i", "]", "=", "0", ";", "}", "}" ]
makes matrix weights and deltas all ones @param {Matrix} product
[ "makes", "matrix", "weights", "and", "deltas", "all", "ones" ]
ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef
https://github.com/BrainJS/brain.js/blob/ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef/dist/recurrent/matrix/all-ones.js#L11-L16
1,294
BrainJS/brain.js
dist/neural-network-gpu.js
mse
function mse(errors) { var sum = 0; for (var i = 0; i < this.constants.size; i++) { sum += Math.pow(errors[i], 2); } return sum / this.constants.size; }
javascript
function mse(errors) { var sum = 0; for (var i = 0; i < this.constants.size; i++) { sum += Math.pow(errors[i], 2); } return sum / this.constants.size; }
[ "function", "mse", "(", "errors", ")", "{", "var", "sum", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "constants", ".", "size", ";", "i", "++", ")", "{", "sum", "+=", "Math", ".", "pow", "(", "errors", "[", "i", "]", ",", "2", ")", ";", "}", "return", "sum", "/", "this", ".", "constants", ".", "size", ";", "}" ]
mean squared error, reimplemented for GPU
[ "mean", "squared", "error", "reimplemented", "for", "GPU" ]
ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef
https://github.com/BrainJS/brain.js/blob/ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef/dist/neural-network-gpu.js#L521-L527
1,295
BrainJS/brain.js
dist/utilities/random.js
gaussRandom
function gaussRandom() { if (gaussRandom.returnV) { gaussRandom.returnV = false; return gaussRandom.vVal; } var u = 2 * Math.random() - 1; var v = 2 * Math.random() - 1; var r = u * u + v * v; if (r == 0 || r > 1) { return gaussRandom(); } var c = Math.sqrt(-2 * Math.log(r) / r); gaussRandom.vVal = v * c; // cache this gaussRandom.returnV = true; return u * c; }
javascript
function gaussRandom() { if (gaussRandom.returnV) { gaussRandom.returnV = false; return gaussRandom.vVal; } var u = 2 * Math.random() - 1; var v = 2 * Math.random() - 1; var r = u * u + v * v; if (r == 0 || r > 1) { return gaussRandom(); } var c = Math.sqrt(-2 * Math.log(r) / r); gaussRandom.vVal = v * c; // cache this gaussRandom.returnV = true; return u * c; }
[ "function", "gaussRandom", "(", ")", "{", "if", "(", "gaussRandom", ".", "returnV", ")", "{", "gaussRandom", ".", "returnV", "=", "false", ";", "return", "gaussRandom", ".", "vVal", ";", "}", "var", "u", "=", "2", "*", "Math", ".", "random", "(", ")", "-", "1", ";", "var", "v", "=", "2", "*", "Math", ".", "random", "(", ")", "-", "1", ";", "var", "r", "=", "u", "*", "u", "+", "v", "*", "v", ";", "if", "(", "r", "==", "0", "||", "r", ">", "1", ")", "{", "return", "gaussRandom", "(", ")", ";", "}", "var", "c", "=", "Math", ".", "sqrt", "(", "-", "2", "*", "Math", ".", "log", "(", "r", ")", "/", "r", ")", ";", "gaussRandom", ".", "vVal", "=", "v", "*", "c", ";", "// cache this", "gaussRandom", ".", "returnV", "=", "true", ";", "return", "u", "*", "c", ";", "}" ]
Random numbers utils
[ "Random", "numbers", "utils" ]
ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef
https://github.com/BrainJS/brain.js/blob/ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef/dist/utilities/random.js#L22-L37
1,296
BrainJS/brain.js
examples/stream-example.js
function(obj) { console.log(`trained in ${ obj.iterations } iterations with error: ${ obj.error }`); const result01 = net.run([0, 1]); const result00 = net.run([0, 0]); const result11 = net.run([1, 1]); const result10 = net.run([1, 0]); assert(result01[0] > 0.9); assert(result00[0] < 0.1); assert(result11[0] < 0.1); assert(result10[0] > 0.9); console.log('0 XOR 1: ', result01); // 0.987 console.log('0 XOR 0: ', result00); // 0.058 console.log('1 XOR 1: ', result11); // 0.087 console.log('1 XOR 0: ', result10); // 0.934 }
javascript
function(obj) { console.log(`trained in ${ obj.iterations } iterations with error: ${ obj.error }`); const result01 = net.run([0, 1]); const result00 = net.run([0, 0]); const result11 = net.run([1, 1]); const result10 = net.run([1, 0]); assert(result01[0] > 0.9); assert(result00[0] < 0.1); assert(result11[0] < 0.1); assert(result10[0] > 0.9); console.log('0 XOR 1: ', result01); // 0.987 console.log('0 XOR 0: ', result00); // 0.058 console.log('1 XOR 1: ', result11); // 0.087 console.log('1 XOR 0: ', result10); // 0.934 }
[ "function", "(", "obj", ")", "{", "console", ".", "log", "(", "`", "${", "obj", ".", "iterations", "}", "${", "obj", ".", "error", "}", "`", ")", ";", "const", "result01", "=", "net", ".", "run", "(", "[", "0", ",", "1", "]", ")", ";", "const", "result00", "=", "net", ".", "run", "(", "[", "0", ",", "0", "]", ")", ";", "const", "result11", "=", "net", ".", "run", "(", "[", "1", ",", "1", "]", ")", ";", "const", "result10", "=", "net", ".", "run", "(", "[", "1", ",", "0", "]", ")", ";", "assert", "(", "result01", "[", "0", "]", ">", "0.9", ")", ";", "assert", "(", "result00", "[", "0", "]", "<", "0.1", ")", ";", "assert", "(", "result11", "[", "0", "]", "<", "0.1", ")", ";", "assert", "(", "result10", "[", "0", "]", ">", "0.9", ")", ";", "console", ".", "log", "(", "'0 XOR 1: '", ",", "result01", ")", ";", "// 0.987", "console", ".", "log", "(", "'0 XOR 0: '", ",", "result00", ")", ";", "// 0.058", "console", ".", "log", "(", "'1 XOR 1: '", ",", "result11", ")", ";", "// 0.087", "console", ".", "log", "(", "'1 XOR 0: '", ",", "result10", ")", ";", "// 0.934", "}" ]
Called when the network is done training.
[ "Called", "when", "the", "network", "is", "done", "training", "." ]
ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef
https://github.com/BrainJS/brain.js/blob/ab09bfc74a0d29d4731dcbdebfa17aeba7f7b1ef/examples/stream-example.js#L25-L42
1,297
mozilla-services/react-jsonschema-form
src/validate.js
transformAjvErrors
function transformAjvErrors(errors = []) { if (errors === null) { return []; } return errors.map(e => { const { dataPath, keyword, message, params, schemaPath } = e; let property = `${dataPath}`; // put data in expected format return { name: keyword, property, message, params, // specific to ajv stack: `${property} ${message}`.trim(), schemaPath, }; }); }
javascript
function transformAjvErrors(errors = []) { if (errors === null) { return []; } return errors.map(e => { const { dataPath, keyword, message, params, schemaPath } = e; let property = `${dataPath}`; // put data in expected format return { name: keyword, property, message, params, // specific to ajv stack: `${property} ${message}`.trim(), schemaPath, }; }); }
[ "function", "transformAjvErrors", "(", "errors", "=", "[", "]", ")", "{", "if", "(", "errors", "===", "null", ")", "{", "return", "[", "]", ";", "}", "return", "errors", ".", "map", "(", "e", "=>", "{", "const", "{", "dataPath", ",", "keyword", ",", "message", ",", "params", ",", "schemaPath", "}", "=", "e", ";", "let", "property", "=", "`", "${", "dataPath", "}", "`", ";", "// put data in expected format", "return", "{", "name", ":", "keyword", ",", "property", ",", "message", ",", "params", ",", "// specific to ajv", "stack", ":", "`", "${", "property", "}", "${", "message", "}", "`", ".", "trim", "(", ")", ",", "schemaPath", ",", "}", ";", "}", ")", ";", "}" ]
Transforming the error output from ajv to format used by jsonschema. At some point, components should be updated to support ajv.
[ "Transforming", "the", "error", "output", "from", "ajv", "to", "format", "used", "by", "jsonschema", ".", "At", "some", "point", "components", "should", "be", "updated", "to", "support", "ajv", "." ]
1ee343d4654a6d98ac08ece97330ce2a3f9f1de3
https://github.com/mozilla-services/react-jsonschema-form/blob/1ee343d4654a6d98ac08ece97330ce2a3f9f1de3/src/validate.js#L141-L160
1,298
mozilla-services/react-jsonschema-form
src/components/widgets/CheckboxWidget.js
schemaRequiresTrueValue
function schemaRequiresTrueValue(schema) { // Check if const is a truthy value if (schema.const) { return true; } // Check if an enum has a single value of true if (schema.enum && schema.enum.length === 1 && schema.enum[0] === true) { return true; } // If anyOf has a single value, evaluate the subschema if (schema.anyOf && schema.anyOf.length === 1) { return schemaRequiresTrueValue(schema.anyOf[0]); } // If oneOf has a single value, evaluate the subschema if (schema.oneOf && schema.oneOf.length === 1) { return schemaRequiresTrueValue(schema.oneOf[0]); } // Evaluate each subschema in allOf, to see if one of them requires a true // value if (schema.allOf) { return schema.allOf.some(schemaRequiresTrueValue); } }
javascript
function schemaRequiresTrueValue(schema) { // Check if const is a truthy value if (schema.const) { return true; } // Check if an enum has a single value of true if (schema.enum && schema.enum.length === 1 && schema.enum[0] === true) { return true; } // If anyOf has a single value, evaluate the subschema if (schema.anyOf && schema.anyOf.length === 1) { return schemaRequiresTrueValue(schema.anyOf[0]); } // If oneOf has a single value, evaluate the subschema if (schema.oneOf && schema.oneOf.length === 1) { return schemaRequiresTrueValue(schema.oneOf[0]); } // Evaluate each subschema in allOf, to see if one of them requires a true // value if (schema.allOf) { return schema.allOf.some(schemaRequiresTrueValue); } }
[ "function", "schemaRequiresTrueValue", "(", "schema", ")", "{", "// Check if const is a truthy value", "if", "(", "schema", ".", "const", ")", "{", "return", "true", ";", "}", "// Check if an enum has a single value of true", "if", "(", "schema", ".", "enum", "&&", "schema", ".", "enum", ".", "length", "===", "1", "&&", "schema", ".", "enum", "[", "0", "]", "===", "true", ")", "{", "return", "true", ";", "}", "// If anyOf has a single value, evaluate the subschema", "if", "(", "schema", ".", "anyOf", "&&", "schema", ".", "anyOf", ".", "length", "===", "1", ")", "{", "return", "schemaRequiresTrueValue", "(", "schema", ".", "anyOf", "[", "0", "]", ")", ";", "}", "// If oneOf has a single value, evaluate the subschema", "if", "(", "schema", ".", "oneOf", "&&", "schema", ".", "oneOf", ".", "length", "===", "1", ")", "{", "return", "schemaRequiresTrueValue", "(", "schema", ".", "oneOf", "[", "0", "]", ")", ";", "}", "// Evaluate each subschema in allOf, to see if one of them requires a true", "// value", "if", "(", "schema", ".", "allOf", ")", "{", "return", "schema", ".", "allOf", ".", "some", "(", "schemaRequiresTrueValue", ")", ";", "}", "}" ]
Check to see if a schema specifies that a value must be true
[ "Check", "to", "see", "if", "a", "schema", "specifies", "that", "a", "value", "must", "be", "true" ]
1ee343d4654a6d98ac08ece97330ce2a3f9f1de3
https://github.com/mozilla-services/react-jsonschema-form/blob/1ee343d4654a6d98ac08ece97330ce2a3f9f1de3/src/components/widgets/CheckboxWidget.js#L6-L32
1,299
mozilla-services/react-jsonschema-form
src/components/fields/ArrayField.js
DefaultArrayItem
function DefaultArrayItem(props) { const btnStyle = { flex: 1, paddingLeft: 6, paddingRight: 6, fontWeight: "bold", }; return ( <div key={props.index} className={props.className}> <div className={props.hasToolbar ? "col-xs-9" : "col-xs-12"}> {props.children} </div> {props.hasToolbar && ( <div className="col-xs-3 array-item-toolbox"> <div className="btn-group" style={{ display: "flex", justifyContent: "space-around", }}> {(props.hasMoveUp || props.hasMoveDown) && ( <IconButton icon="arrow-up" className="array-item-move-up" tabIndex="-1" style={btnStyle} disabled={props.disabled || props.readonly || !props.hasMoveUp} onClick={props.onReorderClick(props.index, props.index - 1)} /> )} {(props.hasMoveUp || props.hasMoveDown) && ( <IconButton icon="arrow-down" className="array-item-move-down" tabIndex="-1" style={btnStyle} disabled={ props.disabled || props.readonly || !props.hasMoveDown } onClick={props.onReorderClick(props.index, props.index + 1)} /> )} {props.hasRemove && ( <IconButton type="danger" icon="remove" className="array-item-remove" tabIndex="-1" style={btnStyle} disabled={props.disabled || props.readonly} onClick={props.onDropIndexClick(props.index)} /> )} </div> </div> )} </div> ); }
javascript
function DefaultArrayItem(props) { const btnStyle = { flex: 1, paddingLeft: 6, paddingRight: 6, fontWeight: "bold", }; return ( <div key={props.index} className={props.className}> <div className={props.hasToolbar ? "col-xs-9" : "col-xs-12"}> {props.children} </div> {props.hasToolbar && ( <div className="col-xs-3 array-item-toolbox"> <div className="btn-group" style={{ display: "flex", justifyContent: "space-around", }}> {(props.hasMoveUp || props.hasMoveDown) && ( <IconButton icon="arrow-up" className="array-item-move-up" tabIndex="-1" style={btnStyle} disabled={props.disabled || props.readonly || !props.hasMoveUp} onClick={props.onReorderClick(props.index, props.index - 1)} /> )} {(props.hasMoveUp || props.hasMoveDown) && ( <IconButton icon="arrow-down" className="array-item-move-down" tabIndex="-1" style={btnStyle} disabled={ props.disabled || props.readonly || !props.hasMoveDown } onClick={props.onReorderClick(props.index, props.index + 1)} /> )} {props.hasRemove && ( <IconButton type="danger" icon="remove" className="array-item-remove" tabIndex="-1" style={btnStyle} disabled={props.disabled || props.readonly} onClick={props.onDropIndexClick(props.index)} /> )} </div> </div> )} </div> ); }
[ "function", "DefaultArrayItem", "(", "props", ")", "{", "const", "btnStyle", "=", "{", "flex", ":", "1", ",", "paddingLeft", ":", "6", ",", "paddingRight", ":", "6", ",", "fontWeight", ":", "\"bold\"", ",", "}", ";", "return", "(", "<", "div", "key", "=", "{", "props", ".", "index", "}", "className", "=", "{", "props", ".", "className", "}", ">", "\n ", "<", "div", "className", "=", "{", "props", ".", "hasToolbar", "?", "\"col-xs-9\"", ":", "\"col-xs-12\"", "}", ">", "\n ", "{", "props", ".", "children", "}", "\n ", "<", "/", "div", ">", "\n\n ", "{", "props", ".", "hasToolbar", "&&", "(", "<", "div", "className", "=", "\"col-xs-3 array-item-toolbox\"", ">", "\n ", "<", "div", "className", "=", "\"btn-group\"", "style", "=", "{", "{", "display", ":", "\"flex\"", ",", "justifyContent", ":", "\"space-around\"", ",", "}", "}", ">", "\n ", "{", "(", "props", ".", "hasMoveUp", "||", "props", ".", "hasMoveDown", ")", "&&", "(", "<", "IconButton", "icon", "=", "\"arrow-up\"", "className", "=", "\"array-item-move-up\"", "tabIndex", "=", "\"-1\"", "style", "=", "{", "btnStyle", "}", "disabled", "=", "{", "props", ".", "disabled", "||", "props", ".", "readonly", "||", "!", "props", ".", "hasMoveUp", "}", "onClick", "=", "{", "props", ".", "onReorderClick", "(", "props", ".", "index", ",", "props", ".", "index", "-", "1", ")", "}", "/", ">", ")", "}", "\n\n ", "{", "(", "props", ".", "hasMoveUp", "||", "props", ".", "hasMoveDown", ")", "&&", "(", "<", "IconButton", "icon", "=", "\"arrow-down\"", "className", "=", "\"array-item-move-down\"", "tabIndex", "=", "\"-1\"", "style", "=", "{", "btnStyle", "}", "disabled", "=", "{", "props", ".", "disabled", "||", "props", ".", "readonly", "||", "!", "props", ".", "hasMoveDown", "}", "onClick", "=", "{", "props", ".", "onReorderClick", "(", "props", ".", "index", ",", "props", ".", "index", "+", "1", ")", "}", "/", ">", ")", "}", "\n\n ", "{", "props", ".", "hasRemove", "&&", "(", "<", "IconButton", "type", "=", "\"danger\"", "icon", "=", "\"remove\"", "className", "=", "\"array-item-remove\"", "tabIndex", "=", "\"-1\"", "style", "=", "{", "btnStyle", "}", "disabled", "=", "{", "props", ".", "disabled", "||", "props", ".", "readonly", "}", "onClick", "=", "{", "props", ".", "onDropIndexClick", "(", "props", ".", "index", ")", "}", "/", ">", ")", "}", "\n ", "<", "/", "div", ">", "\n ", "<", "/", "div", ">", ")", "}", "\n ", "<", "/", "div", ">", ")", ";", "}" ]
Used in the two templates
[ "Used", "in", "the", "two", "templates" ]
1ee343d4654a6d98ac08ece97330ce2a3f9f1de3
https://github.com/mozilla-services/react-jsonschema-form/blob/1ee343d4654a6d98ac08ece97330ce2a3f9f1de3/src/components/fields/ArrayField.js#L39-L100