repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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'", ",", "(", ")", "=>", "{", "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
train
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
train
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
train
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", ")", ")", "{", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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'", ",", "\\n", ")", ".", "\\n", "nsdefs", ".", "sort", "(", ")", ";", "concat", "(", "blocks", ".", "sort", "(", ")", ")", "}" ]
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "{", "}", "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
train
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
train
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", "(", "(", "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
train
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
train
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", "(", "geom", ")", ".", "getFlatCoordinates", "===", "'function'", ")", "{", "const", "dimInfo", "=", "encodeGeometryLayout", "(", "(", "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
train
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
train
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", "=", "(", "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
train
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
train
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
train
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
train
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", ")", "{", "this", ".", "api", "=", "api", ";", "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
train
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", "(", ")", "{", "if", "(", "rejected", "===", "true", ")", "{", "return", ";", "}", "waiting", "--", ";", "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
train
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", ";", "while", "(", "priorTokenIdx", ">=", "0", "&&", "token", ".", "loc", ".", "end", ".", "line", "===", "line", "&&", "isRemovedToken", "(", "context", ",", "token", ")", ")", "{", "token", "=", "tokens", "[", "--", "priorTokenIdx", "]", ";", "}", "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
train
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
train
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
train
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
train
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
train
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", ")", ")", ";", "}", "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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "{", "}", "}", "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
train
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
train
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'", ")", ",", "\\t", ",", "]", ".", "[", "'libsass '", ",", "binding", ".", "libsassVersion", "(", ")", ",", "'(Sass Compiler)'", ",", "'[C/C++]'", "]", ".", "join", "(", "'\\t'", ")", "\\t", ";", "}" ]
Get Sass version information @api public
[ "Get", "Sass", "version", "information" ]
0c1a49eefa37544d16041c5fe5b2e3d9168004b7
https://github.com/sass/node-sass/blob/0c1a49eefa37544d16041c5fe5b2e3d9168004b7/lib/extensions.js#L412-L417
train
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
train
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
train
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
train
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
train
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
train
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", ")", "{", "case", "'root'", ":", "case", "'paragraph'", ":", "case", "'listItem'", ":", "case", "'blockquote'", ":", "case", "'tableRow'", ":", "case", "'tableCell'", ":", "{", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ")", ";", "}", "case", "'shortcode'", ":", "{", "const", "{", "data", "}", "=", "node", ";", "const", "nodes", "=", "[", "createText", "(", "''", ")", "]", ";", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ",", "{", "data", ",", "isVoid", ":", "true", "}", ")", ";", "}", "case", "'text'", ":", "case", "'html'", ":", "{", "return", "createText", "(", "node", ".", "value", ",", "node", ".", "data", ")", ";", "}", "case", "'inlineCode'", ":", "{", "const", "leaf", "=", "{", "text", ":", "node", ".", "value", ",", "marks", ":", "[", "{", "type", ":", "'code'", "}", "]", ",", "}", ";", "return", "createText", "(", "[", "leaf", "]", ")", ";", "}", "case", "'strong'", ":", "case", "'emphasis'", ":", "case", "'delete'", ":", "{", "return", "convertMarkNode", "(", "node", ")", ";", "}", "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", ")", ";", "}", "case", "'code'", ":", "{", "const", "data", "=", "{", "lang", ":", "node", ".", "lang", "}", ";", "const", "text", "=", "createText", "(", "node", ".", "value", ")", ";", "const", "nodes", "=", "[", "text", "]", ";", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "nodes", ",", "{", "data", "}", ")", ";", "}", "case", "'list'", ":", "{", "const", "slateType", "=", "node", ".", "ordered", "?", "'numbered-list'", ":", "'bulleted-list'", ";", "const", "data", "=", "{", "start", ":", "node", ".", "start", "}", ";", "return", "createBlock", "(", "slateType", ",", "nodes", ",", "{", "data", "}", ")", ";", "}", "case", "'break'", ":", "{", "const", "textNode", "=", "createText", "(", "'\\n'", ")", ";", "\\n", "}", "return", "createInline", "(", "'break'", ",", "{", "}", ",", "[", "textNode", "]", ")", ";", "case", "'thematicBreak'", ":", "{", "return", "createBlock", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "isVoid", ":", "true", "}", ")", ";", "}", "case", "'link'", ":", "{", "const", "{", "title", ",", "url", ",", "data", "}", "=", "node", ";", "const", "newData", "=", "{", "...", "data", ",", "title", ",", "url", "}", ";", "return", "createInline", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "data", ":", "newData", "}", ",", "nodes", ")", ";", "}", "case", "'image'", ":", "{", "const", "{", "title", ",", "url", ",", "alt", ",", "data", "}", "=", "node", ";", "const", "newData", "=", "{", "...", "data", ",", "title", ",", "alt", ",", "url", "}", ";", "return", "createInline", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "isVoid", ":", "true", ",", "data", ":", "newData", "}", ")", ";", "}", "}", "}" ]
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
train
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
train
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
train
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", "(", ")", "{", "const", "existingRoot", "=", "document", ".", "getElementById", "(", "ROOT_ID", ")", ";", "if", "(", "existingRoot", ")", "{", "return", "existingRoot", ";", "}", "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
train
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", ")", "{", "const", "combinedChildren", "=", "node", ".", "nodes", "&&", "combineTextAndInline", "(", "node", ".", "nodes", ")", ";", "const", "children", "=", "!", "isEmpty", "(", "combinedChildren", ")", "&&", "flatMap", "(", "combinedChildren", ",", "transform", ")", ";", "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
train
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", "||", "{", "}", ";", "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", ";", "}", "if", "(", "node", ".", "type", "===", "'break'", ")", "{", "acc", ".", "push", "(", "{", "object", ":", "'inline'", ",", "type", ":", "'break'", "}", ")", ";", "return", "acc", ";", "}", "if", "(", "node", ".", "object", "===", "'inline'", ")", "{", "acc", ".", "push", "(", "{", "object", ":", "'text'", ",", "leaves", ":", "[", "{", "node", ",", "marks", ":", "data", ".", "marks", "}", "]", "}", ")", ";", "return", "acc", ";", "}", "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
train
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
train
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", ")", "{", "if", "(", "node", ".", "leaves", ")", "{", "const", "processedLeaves", "=", "node", ".", "leaves", ".", "map", "(", "processLeaves", ")", ";", "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*)$", "/", ")", ";", "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+", "/", ",", "''", ")", ";", "}", "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
train
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", ")", "{", "const", "{", "marks", "=", "[", "]", ",", "text", "}", "=", "leaf", ";", "const", "markTypes", "=", "marks", ".", "map", "(", "mark", "=>", "markMap", "[", "mark", ".", "type", "]", ")", ";", "if", "(", "typeof", "leaf", ".", "text", "===", "'string'", ")", "{", "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
train
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
train
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", ")", "{", "case", "'root'", ":", "case", "'paragraph'", ":", "case", "'quote'", ":", "case", "'list-item'", ":", "case", "'table'", ":", "case", "'table-row'", ":", "case", "'table-cell'", ":", "{", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "children", ")", ";", "}", "case", "'shortcode'", ":", "{", "const", "{", "data", "}", "=", "node", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "data", "}", ")", ";", "}", "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", ")", ";", "}", "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", ")", ";", "}", "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", ")", ";", "}", "case", "'break'", ":", "case", "'thematic-break'", ":", "{", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ")", ";", "}", "case", "'link'", ":", "{", "const", "{", "url", ",", "title", ",", "...", "data", "}", "=", "get", "(", "node", ",", "'data'", ",", "{", "}", ")", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "url", ",", "title", ",", "data", "}", ",", "children", ")", ";", "}", "case", "'image'", ":", "{", "const", "{", "url", ",", "title", ",", "alt", ",", "...", "data", "}", "=", "get", "(", "node", ",", "'data'", ",", "{", "}", ")", ";", "return", "u", "(", "typeMap", "[", "node", ".", "type", "]", ",", "{", "url", ",", "title", ",", "alt", ",", "data", "}", ")", ";", "}", "}", "}" ]
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
train
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
train
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
train
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", ")", "{", "const", "groupId", "=", "new", "RegExp", "(", "`", "${", "files", ".", "length", "}", "`", ")", ".", "exec", "(", "files", "[", "0", "]", ")", "[", "1", "]", ";", "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
train
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
train
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", ";", "uploadcare", ".", "registerTab", "(", "'preview'", ",", "uploadcareTabEffects", ")", ";", "return", "{", "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", ")", ";", "if", "(", "files", "&&", "!", "files", ".", "state", ")", "{", "return", "files", ".", "then", "(", "result", "=>", "openDialog", "(", "result", ",", "resolvedConfig", ",", "handleInsert", ")", ")", ";", "}", "else", "{", "return", "openDialog", "(", "files", ",", "resolvedConfig", ",", "handleInsert", ")", ";", "}", "}", ",", "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
train
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
train
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
train
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", ";", "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
train
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", ")", ";", "console", ".", "log", "(", "'0 XOR 0: '", ",", "result00", ")", ";", "console", ".", "log", "(", "'1 XOR 1: '", ",", "result11", ")", ";", "console", ".", "log", "(", "'1 XOR 0: '", ",", "result10", ")", ";", "}" ]
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
train
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", "}", "`", ";", "return", "{", "name", ":", "keyword", ",", "property", ",", "message", ",", "params", ",", "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
train
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", ")", "{", "if", "(", "schema", ".", "const", ")", "{", "return", "true", ";", "}", "if", "(", "schema", ".", "enum", "&&", "schema", ".", "enum", ".", "length", "===", "1", "&&", "schema", ".", "enum", "[", "0", "]", "===", "true", ")", "{", "return", "true", ";", "}", "if", "(", "schema", ".", "anyOf", "&&", "schema", ".", "anyOf", ".", "length", "===", "1", ")", "{", "return", "schemaRequiresTrueValue", "(", "schema", ".", "anyOf", "[", "0", "]", ")", ";", "}", "if", "(", "schema", ".", "oneOf", "&&", "schema", ".", "oneOf", ".", "length", "===", "1", ")", "{", "return", "schemaRequiresTrueValue", "(", "schema", ".", "oneOf", "[", "0", "]", ")", ";", "}", "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
train
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", "}", ">", " ", "<", "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", ">", ")", ";", "}" ]
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
train
mozilla-services/react-jsonschema-form
src/components/widgets/SelectWidget.js
processValue
function processValue(schema, value) { // "enum" is a reserved word, so only "type" and "items" can be destructured const { type, items } = schema; if (value === "") { return undefined; } else if (type === "array" && items && nums.has(items.type)) { return value.map(asNumber); } else if (type === "boolean") { return value === "true"; } else if (type === "number") { return asNumber(value); } // If type is undefined, but an enum is present, try and infer the type from // the enum values if (schema.enum) { if (schema.enum.every(x => guessType(x) === "number")) { return asNumber(value); } else if (schema.enum.every(x => guessType(x) === "boolean")) { return value === "true"; } } return value; }
javascript
function processValue(schema, value) { // "enum" is a reserved word, so only "type" and "items" can be destructured const { type, items } = schema; if (value === "") { return undefined; } else if (type === "array" && items && nums.has(items.type)) { return value.map(asNumber); } else if (type === "boolean") { return value === "true"; } else if (type === "number") { return asNumber(value); } // If type is undefined, but an enum is present, try and infer the type from // the enum values if (schema.enum) { if (schema.enum.every(x => guessType(x) === "number")) { return asNumber(value); } else if (schema.enum.every(x => guessType(x) === "boolean")) { return value === "true"; } } return value; }
[ "function", "processValue", "(", "schema", ",", "value", ")", "{", "const", "{", "type", ",", "items", "}", "=", "schema", ";", "if", "(", "value", "===", "\"\"", ")", "{", "return", "undefined", ";", "}", "else", "if", "(", "type", "===", "\"array\"", "&&", "items", "&&", "nums", ".", "has", "(", "items", ".", "type", ")", ")", "{", "return", "value", ".", "map", "(", "asNumber", ")", ";", "}", "else", "if", "(", "type", "===", "\"boolean\"", ")", "{", "return", "value", "===", "\"true\"", ";", "}", "else", "if", "(", "type", "===", "\"number\"", ")", "{", "return", "asNumber", "(", "value", ")", ";", "}", "if", "(", "schema", ".", "enum", ")", "{", "if", "(", "schema", ".", "enum", ".", "every", "(", "x", "=>", "guessType", "(", "x", ")", "===", "\"number\"", ")", ")", "{", "return", "asNumber", "(", "value", ")", ";", "}", "else", "if", "(", "schema", ".", "enum", ".", "every", "(", "x", "=>", "guessType", "(", "x", ")", "===", "\"boolean\"", ")", ")", "{", "return", "value", "===", "\"true\"", ";", "}", "}", "return", "value", ";", "}" ]
This is a silly limitation in the DOM where option change event values are always retrieved as strings.
[ "This", "is", "a", "silly", "limitation", "in", "the", "DOM", "where", "option", "change", "event", "values", "are", "always", "retrieved", "as", "strings", "." ]
1ee343d4654a6d98ac08ece97330ce2a3f9f1de3
https://github.com/mozilla-services/react-jsonschema-form/blob/1ee343d4654a6d98ac08ece97330ce2a3f9f1de3/src/components/widgets/SelectWidget.js#L12-L36
train
nosir/cleave.js
src/Cleave.js
function (element, opts) { var owner = this; var hasMultipleElements = false; if (typeof element === 'string') { owner.element = document.querySelector(element); hasMultipleElements = document.querySelectorAll(element).length > 1; } else { if (typeof element.length !== 'undefined' && element.length > 0) { owner.element = element[0]; hasMultipleElements = element.length > 1; } else { owner.element = element; } } if (!owner.element) { throw new Error('[cleave.js] Please check the element'); } if (hasMultipleElements) { try { // eslint-disable-next-line console.warn('[cleave.js] Multiple input fields matched, cleave.js will only take the first one.'); } catch (e) { // Old IE } } opts.initValue = owner.element.value; owner.properties = Cleave.DefaultProperties.assign({}, opts); owner.init(); }
javascript
function (element, opts) { var owner = this; var hasMultipleElements = false; if (typeof element === 'string') { owner.element = document.querySelector(element); hasMultipleElements = document.querySelectorAll(element).length > 1; } else { if (typeof element.length !== 'undefined' && element.length > 0) { owner.element = element[0]; hasMultipleElements = element.length > 1; } else { owner.element = element; } } if (!owner.element) { throw new Error('[cleave.js] Please check the element'); } if (hasMultipleElements) { try { // eslint-disable-next-line console.warn('[cleave.js] Multiple input fields matched, cleave.js will only take the first one.'); } catch (e) { // Old IE } } opts.initValue = owner.element.value; owner.properties = Cleave.DefaultProperties.assign({}, opts); owner.init(); }
[ "function", "(", "element", ",", "opts", ")", "{", "var", "owner", "=", "this", ";", "var", "hasMultipleElements", "=", "false", ";", "if", "(", "typeof", "element", "===", "'string'", ")", "{", "owner", ".", "element", "=", "document", ".", "querySelector", "(", "element", ")", ";", "hasMultipleElements", "=", "document", ".", "querySelectorAll", "(", "element", ")", ".", "length", ">", "1", ";", "}", "else", "{", "if", "(", "typeof", "element", ".", "length", "!==", "'undefined'", "&&", "element", ".", "length", ">", "0", ")", "{", "owner", ".", "element", "=", "element", "[", "0", "]", ";", "hasMultipleElements", "=", "element", ".", "length", ">", "1", ";", "}", "else", "{", "owner", ".", "element", "=", "element", ";", "}", "}", "if", "(", "!", "owner", ".", "element", ")", "{", "throw", "new", "Error", "(", "'[cleave.js] Please check the element'", ")", ";", "}", "if", "(", "hasMultipleElements", ")", "{", "try", "{", "console", ".", "warn", "(", "'[cleave.js] Multiple input fields matched, cleave.js will only take the first one.'", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "opts", ".", "initValue", "=", "owner", ".", "element", ".", "value", ";", "owner", ".", "properties", "=", "Cleave", ".", "DefaultProperties", ".", "assign", "(", "{", "}", ",", "opts", ")", ";", "owner", ".", "init", "(", ")", ";", "}" ]
Construct a new Cleave instance by passing the configuration object @param {String | HTMLElement} element @param {Object} opts
[ "Construct", "a", "new", "Cleave", "instance", "by", "passing", "the", "configuration", "object" ]
fc1bcca55589e0e95465f39b4dc22c25634e7cf5
https://github.com/nosir/cleave.js/blob/fc1bcca55589e0e95465f39b4dc22c25634e7cf5/src/Cleave.js#L9-L43
train
nhn/tui.editor
src/js/extensions/table/mergedTableAddRow.js
_findFocusTd
function _findFocusTd($newTable, rowIndex, colIndex) { const tableData = dataHandler.createTableData($newTable); const newRowIndex = dataHandler.findRowMergedLastIndex(tableData, rowIndex, colIndex) + 1; const cellElementIndex = dataHandler.findElementIndex(tableData, newRowIndex, colIndex); return $newTable.find('tr').eq(cellElementIndex.rowIndex).find('td')[cellElementIndex.colIndex]; }
javascript
function _findFocusTd($newTable, rowIndex, colIndex) { const tableData = dataHandler.createTableData($newTable); const newRowIndex = dataHandler.findRowMergedLastIndex(tableData, rowIndex, colIndex) + 1; const cellElementIndex = dataHandler.findElementIndex(tableData, newRowIndex, colIndex); return $newTable.find('tr').eq(cellElementIndex.rowIndex).find('td')[cellElementIndex.colIndex]; }
[ "function", "_findFocusTd", "(", "$newTable", ",", "rowIndex", ",", "colIndex", ")", "{", "const", "tableData", "=", "dataHandler", ".", "createTableData", "(", "$newTable", ")", ";", "const", "newRowIndex", "=", "dataHandler", ".", "findRowMergedLastIndex", "(", "tableData", ",", "rowIndex", ",", "colIndex", ")", "+", "1", ";", "const", "cellElementIndex", "=", "dataHandler", ".", "findElementIndex", "(", "tableData", ",", "newRowIndex", ",", "colIndex", ")", ";", "return", "$newTable", ".", "find", "(", "'tr'", ")", ".", "eq", "(", "cellElementIndex", ".", "rowIndex", ")", ".", "find", "(", "'td'", ")", "[", "cellElementIndex", ".", "colIndex", "]", ";", "}" ]
Find focus td element. @param {jQuery} $newTable - changed table jQuery element @param {number} rowIndex - row index of table data @param {number} colIndex - column index of tabld data @returns {HTMLElement} @private
[ "Find", "focus", "td", "element", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableAddRow.js#L133-L139
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
_parseCell
function _parseCell(cell, rowIndex, colIndex) { const $cell = $(cell); const colspan = $cell.attr('colspan'); const rowspan = $cell.attr('rowspan'); const {nodeName} = cell; if (nodeName !== 'TH' && nodeName !== 'TD') { return null; } const cellData = { nodeName: cell.nodeName, colspan: colspan ? parseInt(colspan, 10) : 1, rowspan: rowspan ? parseInt(rowspan, 10) : 1, content: $cell.html(), elementIndex: { rowIndex, colIndex } }; if (cell.nodeName === 'TH' && cell.align) { cellData.align = cell.align; } return cellData; }
javascript
function _parseCell(cell, rowIndex, colIndex) { const $cell = $(cell); const colspan = $cell.attr('colspan'); const rowspan = $cell.attr('rowspan'); const {nodeName} = cell; if (nodeName !== 'TH' && nodeName !== 'TD') { return null; } const cellData = { nodeName: cell.nodeName, colspan: colspan ? parseInt(colspan, 10) : 1, rowspan: rowspan ? parseInt(rowspan, 10) : 1, content: $cell.html(), elementIndex: { rowIndex, colIndex } }; if (cell.nodeName === 'TH' && cell.align) { cellData.align = cell.align; } return cellData; }
[ "function", "_parseCell", "(", "cell", ",", "rowIndex", ",", "colIndex", ")", "{", "const", "$cell", "=", "$", "(", "cell", ")", ";", "const", "colspan", "=", "$cell", ".", "attr", "(", "'colspan'", ")", ";", "const", "rowspan", "=", "$cell", ".", "attr", "(", "'rowspan'", ")", ";", "const", "{", "nodeName", "}", "=", "cell", ";", "if", "(", "nodeName", "!==", "'TH'", "&&", "nodeName", "!==", "'TD'", ")", "{", "return", "null", ";", "}", "const", "cellData", "=", "{", "nodeName", ":", "cell", ".", "nodeName", ",", "colspan", ":", "colspan", "?", "parseInt", "(", "colspan", ",", "10", ")", ":", "1", ",", "rowspan", ":", "rowspan", "?", "parseInt", "(", "rowspan", ",", "10", ")", ":", "1", ",", "content", ":", "$cell", ".", "html", "(", ")", ",", "elementIndex", ":", "{", "rowIndex", ",", "colIndex", "}", "}", ";", "if", "(", "cell", ".", "nodeName", "===", "'TH'", "&&", "cell", ".", "align", ")", "{", "cellData", ".", "align", "=", "cell", ".", "align", ";", "}", "return", "cellData", ";", "}" ]
Parse cell like td or th. @param {HTMLElement} cell - cell element like td or th @param {number} rowIndex - row index @param {number} colIndex - column index @returns {{ nodeName: string, colspan: number, rowspan: number, content: string, align: ?string }} @private
[ "Parse", "cell", "like", "td", "or", "th", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L22-L48
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
_addMergedCell
function _addMergedCell(base, cellData, startRowIndex, startCellIndex) { const { colspan, rowspan, nodeName } = cellData; const colMerged = colspan > 1; const rowMerged = rowspan > 1; if (!colMerged && !rowMerged) { return; } const limitRowIndex = startRowIndex + rowspan; const limitCellIndex = startCellIndex + colspan; util.range(startRowIndex, limitRowIndex).forEach(rowIndex => { base[rowIndex] = base[rowIndex] || []; util.range(startCellIndex, limitCellIndex).forEach(cellIndex => { const mergedData = { nodeName }; if (rowIndex === startRowIndex && cellIndex === startCellIndex) { return; } if (colMerged) { mergedData.colMergeWith = startCellIndex; } if (rowMerged) { mergedData.rowMergeWith = startRowIndex; } base[rowIndex][cellIndex] = mergedData; }); }); }
javascript
function _addMergedCell(base, cellData, startRowIndex, startCellIndex) { const { colspan, rowspan, nodeName } = cellData; const colMerged = colspan > 1; const rowMerged = rowspan > 1; if (!colMerged && !rowMerged) { return; } const limitRowIndex = startRowIndex + rowspan; const limitCellIndex = startCellIndex + colspan; util.range(startRowIndex, limitRowIndex).forEach(rowIndex => { base[rowIndex] = base[rowIndex] || []; util.range(startCellIndex, limitCellIndex).forEach(cellIndex => { const mergedData = { nodeName }; if (rowIndex === startRowIndex && cellIndex === startCellIndex) { return; } if (colMerged) { mergedData.colMergeWith = startCellIndex; } if (rowMerged) { mergedData.rowMergeWith = startRowIndex; } base[rowIndex][cellIndex] = mergedData; }); }); }
[ "function", "_addMergedCell", "(", "base", ",", "cellData", ",", "startRowIndex", ",", "startCellIndex", ")", "{", "const", "{", "colspan", ",", "rowspan", ",", "nodeName", "}", "=", "cellData", ";", "const", "colMerged", "=", "colspan", ">", "1", ";", "const", "rowMerged", "=", "rowspan", ">", "1", ";", "if", "(", "!", "colMerged", "&&", "!", "rowMerged", ")", "{", "return", ";", "}", "const", "limitRowIndex", "=", "startRowIndex", "+", "rowspan", ";", "const", "limitCellIndex", "=", "startCellIndex", "+", "colspan", ";", "util", ".", "range", "(", "startRowIndex", ",", "limitRowIndex", ")", ".", "forEach", "(", "rowIndex", "=>", "{", "base", "[", "rowIndex", "]", "=", "base", "[", "rowIndex", "]", "||", "[", "]", ";", "util", ".", "range", "(", "startCellIndex", ",", "limitCellIndex", ")", ".", "forEach", "(", "cellIndex", "=>", "{", "const", "mergedData", "=", "{", "nodeName", "}", ";", "if", "(", "rowIndex", "===", "startRowIndex", "&&", "cellIndex", "===", "startCellIndex", ")", "{", "return", ";", "}", "if", "(", "colMerged", ")", "{", "mergedData", ".", "colMergeWith", "=", "startCellIndex", ";", "}", "if", "(", "rowMerged", ")", "{", "mergedData", ".", "rowMergeWith", "=", "startRowIndex", ";", "}", "base", "[", "rowIndex", "]", "[", "cellIndex", "]", "=", "mergedData", ";", "}", ")", ";", "}", ")", ";", "}" ]
Add merged cell. @param {object} base - base table data @param {object} cellData - cell data @param {number} startRowIndex - start row index @param {number} startCellIndex - start cell index @private
[ "Add", "merged", "cell", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L58-L97
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
_getHeaderAligns
function _getHeaderAligns(tableData) { const [headRowData] = tableData; return headRowData.map(cellData => { let align; if (util.isExisty(cellData.colMergeWith)) { ({align} = headRowData[cellData.colMergeWith]); } else { ({align} = cellData); } return align; }); }
javascript
function _getHeaderAligns(tableData) { const [headRowData] = tableData; return headRowData.map(cellData => { let align; if (util.isExisty(cellData.colMergeWith)) { ({align} = headRowData[cellData.colMergeWith]); } else { ({align} = cellData); } return align; }); }
[ "function", "_getHeaderAligns", "(", "tableData", ")", "{", "const", "[", "headRowData", "]", "=", "tableData", ";", "return", "headRowData", ".", "map", "(", "cellData", "=>", "{", "let", "align", ";", "if", "(", "util", ".", "isExisty", "(", "cellData", ".", "colMergeWith", ")", ")", "{", "(", "{", "align", "}", "=", "headRowData", "[", "cellData", ".", "colMergeWith", "]", ")", ";", "}", "else", "{", "(", "{", "align", "}", "=", "cellData", ")", ";", "}", "return", "align", ";", "}", ")", ";", "}" ]
Get header aligns. @param {Array.<Array.<object>>} tableData - table data @returns {Array.<?string>} @private
[ "Get", "header", "aligns", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L170-L184
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
createRenderData
function createRenderData(tableData, cellIndexData) { const headerAligns = _getHeaderAligns(tableData); const renderData = cellIndexData.map(row => row.map(({rowIndex, colIndex}) => (util.extend({ align: headerAligns[colIndex] }, tableData[rowIndex][colIndex])))); if (tableData.className) { renderData.className = tableData.className; } return renderData; }
javascript
function createRenderData(tableData, cellIndexData) { const headerAligns = _getHeaderAligns(tableData); const renderData = cellIndexData.map(row => row.map(({rowIndex, colIndex}) => (util.extend({ align: headerAligns[colIndex] }, tableData[rowIndex][colIndex])))); if (tableData.className) { renderData.className = tableData.className; } return renderData; }
[ "function", "createRenderData", "(", "tableData", ",", "cellIndexData", ")", "{", "const", "headerAligns", "=", "_getHeaderAligns", "(", "tableData", ")", ";", "const", "renderData", "=", "cellIndexData", ".", "map", "(", "row", "=>", "row", ".", "map", "(", "(", "{", "rowIndex", ",", "colIndex", "}", ")", "=>", "(", "util", ".", "extend", "(", "{", "align", ":", "headerAligns", "[", "colIndex", "]", "}", ",", "tableData", "[", "rowIndex", "]", "[", "colIndex", "]", ")", ")", ")", ")", ";", "if", "(", "tableData", ".", "className", ")", "{", "renderData", ".", "className", "=", "tableData", ".", "className", ";", "}", "return", "renderData", ";", "}" ]
Create render data. @param {Array.<object>} tableData - table data @param {Array.<object>} cellIndexData - cell index data @returns {Array.<Array.<object>>} @ignore
[ "Create", "render", "data", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L193-L204
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
createBasicCell
function createBasicCell(rowIndex, colIndex, nodeName) { return { nodeName: nodeName || 'TD', colspan: 1, rowspan: 1, content: BASIC_CELL_CONTENT, elementIndex: { rowIndex, colIndex } }; }
javascript
function createBasicCell(rowIndex, colIndex, nodeName) { return { nodeName: nodeName || 'TD', colspan: 1, rowspan: 1, content: BASIC_CELL_CONTENT, elementIndex: { rowIndex, colIndex } }; }
[ "function", "createBasicCell", "(", "rowIndex", ",", "colIndex", ",", "nodeName", ")", "{", "return", "{", "nodeName", ":", "nodeName", "||", "'TD'", ",", "colspan", ":", "1", ",", "rowspan", ":", "1", ",", "content", ":", "BASIC_CELL_CONTENT", ",", "elementIndex", ":", "{", "rowIndex", ",", "colIndex", "}", "}", ";", "}" ]
Create basic cell data. @param {number} rowIndex - row index @param {number} colIndex - column index @param {string} nodeName - node name @returns {{ nodeName: string, colspan: number, rowspan: number, content: string }} @ignore
[ "Create", "basic", "cell", "data", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L221-L232
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
findElementIndex
function findElementIndex(tableData, rowIndex, colIndex) { const cellData = tableData[rowIndex][colIndex]; rowIndex = util.isExisty(cellData.rowMergeWith) ? cellData.rowMergeWith : rowIndex; colIndex = util.isExisty(cellData.colMergeWith) ? cellData.colMergeWith : colIndex; return tableData[rowIndex][colIndex].elementIndex; }
javascript
function findElementIndex(tableData, rowIndex, colIndex) { const cellData = tableData[rowIndex][colIndex]; rowIndex = util.isExisty(cellData.rowMergeWith) ? cellData.rowMergeWith : rowIndex; colIndex = util.isExisty(cellData.colMergeWith) ? cellData.colMergeWith : colIndex; return tableData[rowIndex][colIndex].elementIndex; }
[ "function", "findElementIndex", "(", "tableData", ",", "rowIndex", ",", "colIndex", ")", "{", "const", "cellData", "=", "tableData", "[", "rowIndex", "]", "[", "colIndex", "]", ";", "rowIndex", "=", "util", ".", "isExisty", "(", "cellData", ".", "rowMergeWith", ")", "?", "cellData", ".", "rowMergeWith", ":", "rowIndex", ";", "colIndex", "=", "util", ".", "isExisty", "(", "cellData", ".", "colMergeWith", ")", "?", "cellData", ".", "colMergeWith", ":", "colIndex", ";", "return", "tableData", "[", "rowIndex", "]", "[", "colIndex", "]", ".", "elementIndex", ";", "}" ]
Find cell element index. @param {Array.<Array.<object>>} tableData - tableData data @param {number} rowIndex - row index of base data @param {number} colIndex - col index of base data @returns {{rowIndex: number, colIndex: number}} @ignore
[ "Find", "cell", "element", "index", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L321-L328
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
stuffCellsIntoIncompleteRow
function stuffCellsIntoIncompleteRow(tableData, limitIndex) { tableData.forEach((rowData, rowIndex) => { const startIndex = rowData.length; if (startIndex) { const [{nodeName}] = rowData; util.range(startIndex, limitIndex).forEach(colIndex => { rowData.push(createBasicCell(rowIndex, colIndex, nodeName)); }); } }); }
javascript
function stuffCellsIntoIncompleteRow(tableData, limitIndex) { tableData.forEach((rowData, rowIndex) => { const startIndex = rowData.length; if (startIndex) { const [{nodeName}] = rowData; util.range(startIndex, limitIndex).forEach(colIndex => { rowData.push(createBasicCell(rowIndex, colIndex, nodeName)); }); } }); }
[ "function", "stuffCellsIntoIncompleteRow", "(", "tableData", ",", "limitIndex", ")", "{", "tableData", ".", "forEach", "(", "(", "rowData", ",", "rowIndex", ")", "=>", "{", "const", "startIndex", "=", "rowData", ".", "length", ";", "if", "(", "startIndex", ")", "{", "const", "[", "{", "nodeName", "}", "]", "=", "rowData", ";", "util", ".", "range", "(", "startIndex", ",", "limitIndex", ")", ".", "forEach", "(", "colIndex", "=>", "{", "rowData", ".", "push", "(", "createBasicCell", "(", "rowIndex", ",", "colIndex", ",", "nodeName", ")", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Stuff cells into incomplete row. @param {Array.<Array.<object>>} tableData - table data @param {number} limitIndex - limit index @ignore
[ "Stuff", "cells", "into", "incomplete", "row", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L336-L347
train
nhn/tui.editor
src/js/extensions/table/tableDataHandler.js
addTbodyOrTheadIfNeed
function addTbodyOrTheadIfNeed(tableData) { const [header] = tableData; const cellCount = header.length; let added = true; if (!cellCount && tableData[1]) { util.range(0, tableData[1].length).forEach(colIndex => { header.push(createBasicCell(0, colIndex, 'TH')); }); } else if (tableData[0][0].nodeName !== 'TH') { const newHeader = util.range(0, cellCount).map(colIndex => createBasicCell(0, colIndex, 'TH')); [].concat(...tableData).forEach(cellData => { if (cellData.elementIndex) { cellData.elementIndex.rowIndex += 1; } }); tableData.unshift(newHeader); } else if (tableData.length === 1) { const newRow = util.range(0, cellCount).map(colIndex => ( createBasicCell(1, colIndex, 'TD') )); tableData.push(newRow); } else { added = false; } return added; }
javascript
function addTbodyOrTheadIfNeed(tableData) { const [header] = tableData; const cellCount = header.length; let added = true; if (!cellCount && tableData[1]) { util.range(0, tableData[1].length).forEach(colIndex => { header.push(createBasicCell(0, colIndex, 'TH')); }); } else if (tableData[0][0].nodeName !== 'TH') { const newHeader = util.range(0, cellCount).map(colIndex => createBasicCell(0, colIndex, 'TH')); [].concat(...tableData).forEach(cellData => { if (cellData.elementIndex) { cellData.elementIndex.rowIndex += 1; } }); tableData.unshift(newHeader); } else if (tableData.length === 1) { const newRow = util.range(0, cellCount).map(colIndex => ( createBasicCell(1, colIndex, 'TD') )); tableData.push(newRow); } else { added = false; } return added; }
[ "function", "addTbodyOrTheadIfNeed", "(", "tableData", ")", "{", "const", "[", "header", "]", "=", "tableData", ";", "const", "cellCount", "=", "header", ".", "length", ";", "let", "added", "=", "true", ";", "if", "(", "!", "cellCount", "&&", "tableData", "[", "1", "]", ")", "{", "util", ".", "range", "(", "0", ",", "tableData", "[", "1", "]", ".", "length", ")", ".", "forEach", "(", "colIndex", "=>", "{", "header", ".", "push", "(", "createBasicCell", "(", "0", ",", "colIndex", ",", "'TH'", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "tableData", "[", "0", "]", "[", "0", "]", ".", "nodeName", "!==", "'TH'", ")", "{", "const", "newHeader", "=", "util", ".", "range", "(", "0", ",", "cellCount", ")", ".", "map", "(", "colIndex", "=>", "createBasicCell", "(", "0", ",", "colIndex", ",", "'TH'", ")", ")", ";", "[", "]", ".", "concat", "(", "...", "tableData", ")", ".", "forEach", "(", "cellData", "=>", "{", "if", "(", "cellData", ".", "elementIndex", ")", "{", "cellData", ".", "elementIndex", ".", "rowIndex", "+=", "1", ";", "}", "}", ")", ";", "tableData", ".", "unshift", "(", "newHeader", ")", ";", "}", "else", "if", "(", "tableData", ".", "length", "===", "1", ")", "{", "const", "newRow", "=", "util", ".", "range", "(", "0", ",", "cellCount", ")", ".", "map", "(", "colIndex", "=>", "(", "createBasicCell", "(", "1", ",", "colIndex", ",", "'TD'", ")", ")", ")", ";", "tableData", ".", "push", "(", "newRow", ")", ";", "}", "else", "{", "added", "=", "false", ";", "}", "return", "added", ";", "}" ]
Add tbody or thead of table data if need. @param {Array.<Array.<object>>} tableData - table data @returns {boolean} @ignore
[ "Add", "tbody", "or", "thead", "of", "table", "data", "if", "need", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableDataHandler.js#L355-L385
train
nhn/tui.editor
src/js/wysiwygCommands/italic.js
styleItalic
function styleItalic(sq) { if (sq.hasFormat('i') || sq.hasFormat('em')) { sq.changeFormat(null, {tag: 'i'}); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); } sq.italic(); } }
javascript
function styleItalic(sq) { if (sq.hasFormat('i') || sq.hasFormat('em')) { sq.changeFormat(null, {tag: 'i'}); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); } sq.italic(); } }
[ "function", "styleItalic", "(", "sq", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'i'", ")", "||", "sq", ".", "hasFormat", "(", "'em'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'i'", "}", ")", ";", "}", "else", "if", "(", "!", "sq", ".", "hasFormat", "(", "'a'", ")", "&&", "!", "sq", ".", "hasFormat", "(", "'PRE'", ")", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'code'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'code'", "}", ")", ";", "}", "sq", ".", "italic", "(", ")", ";", "}", "}" ]
Style italic. @param {object} sq - squire editor instance
[ "Style", "italic", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/italic.js#L44-L53
train
nhn/tui.editor
src/js/extensions/table/mergeCell.js
_pickContent
function _pickContent(targetRows, startColIndex, endColIndex) { const limitColIndex = endColIndex + 1; const cells = [].concat(...targetRows.map(rowData => rowData.slice(startColIndex, limitColIndex))); const foundCellData = cells.filter(({content}) => content && content !== BASIC_CELL_CONTENT); return foundCellData.length ? foundCellData[0].content : BASIC_CELL_CONTENT; }
javascript
function _pickContent(targetRows, startColIndex, endColIndex) { const limitColIndex = endColIndex + 1; const cells = [].concat(...targetRows.map(rowData => rowData.slice(startColIndex, limitColIndex))); const foundCellData = cells.filter(({content}) => content && content !== BASIC_CELL_CONTENT); return foundCellData.length ? foundCellData[0].content : BASIC_CELL_CONTENT; }
[ "function", "_pickContent", "(", "targetRows", ",", "startColIndex", ",", "endColIndex", ")", "{", "const", "limitColIndex", "=", "endColIndex", "+", "1", ";", "const", "cells", "=", "[", "]", ".", "concat", "(", "...", "targetRows", ".", "map", "(", "rowData", "=>", "rowData", ".", "slice", "(", "startColIndex", ",", "limitColIndex", ")", ")", ")", ";", "const", "foundCellData", "=", "cells", ".", "filter", "(", "(", "{", "content", "}", ")", "=>", "content", "&&", "content", "!==", "BASIC_CELL_CONTENT", ")", ";", "return", "foundCellData", ".", "length", "?", "foundCellData", "[", "0", "]", ".", "content", ":", "BASIC_CELL_CONTENT", ";", "}" ]
Pick merger content from selected cells. @param {Array.<Array.<object>>} targetRows - target rows @param {number} startColIndex - start column index @param {number} endColIndex - end column index @returns {string} @private
[ "Pick", "merger", "content", "from", "selected", "cells", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergeCell.js#L64-L70
train
nhn/tui.editor
src/js/extensions/table/mergeCell.js
_initCellData
function _initCellData(targetRows, startColIndex, endColIndex) { const limitColIndex = endColIndex + 1; const targetCells = targetRows.map(rowData => rowData.slice(startColIndex, limitColIndex)); [].concat(...targetCells).slice(1).forEach(cellData => { const {nodeName} = cellData; util.forEach(cellData, (value, name) => (delete cellData[name])); cellData.nodeName = nodeName; }); }
javascript
function _initCellData(targetRows, startColIndex, endColIndex) { const limitColIndex = endColIndex + 1; const targetCells = targetRows.map(rowData => rowData.slice(startColIndex, limitColIndex)); [].concat(...targetCells).slice(1).forEach(cellData => { const {nodeName} = cellData; util.forEach(cellData, (value, name) => (delete cellData[name])); cellData.nodeName = nodeName; }); }
[ "function", "_initCellData", "(", "targetRows", ",", "startColIndex", ",", "endColIndex", ")", "{", "const", "limitColIndex", "=", "endColIndex", "+", "1", ";", "const", "targetCells", "=", "targetRows", ".", "map", "(", "rowData", "=>", "rowData", ".", "slice", "(", "startColIndex", ",", "limitColIndex", ")", ")", ";", "[", "]", ".", "concat", "(", "...", "targetCells", ")", ".", "slice", "(", "1", ")", ".", "forEach", "(", "cellData", "=>", "{", "const", "{", "nodeName", "}", "=", "cellData", ";", "util", ".", "forEach", "(", "cellData", ",", "(", "value", ",", "name", ")", "=>", "(", "delete", "cellData", "[", "name", "]", ")", ")", ";", "cellData", ".", "nodeName", "=", "nodeName", ";", "}", ")", ";", "}" ]
Initialize cell data of target rows. @param {Array.<Array.<object>>} targetRows - target rows @param {number} startColIndex - start column index @param {number} endColIndex - end column index @private
[ "Initialize", "cell", "data", "of", "target", "rows", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergeCell.js#L79-L89
train
nhn/tui.editor
src/js/extensions/table/mergeCell.js
_updateRowMergeWith
function _updateRowMergeWith(targetRows, startColIndex, endColIndex, rowMergeWith) { const limitColIndex = endColIndex + 1; targetRows.forEach(rowData => { rowData.slice(startColIndex, limitColIndex).forEach(cellData => { cellData.rowMergeWith = rowMergeWith; }); }); }
javascript
function _updateRowMergeWith(targetRows, startColIndex, endColIndex, rowMergeWith) { const limitColIndex = endColIndex + 1; targetRows.forEach(rowData => { rowData.slice(startColIndex, limitColIndex).forEach(cellData => { cellData.rowMergeWith = rowMergeWith; }); }); }
[ "function", "_updateRowMergeWith", "(", "targetRows", ",", "startColIndex", ",", "endColIndex", ",", "rowMergeWith", ")", "{", "const", "limitColIndex", "=", "endColIndex", "+", "1", ";", "targetRows", ".", "forEach", "(", "rowData", "=>", "{", "rowData", ".", "slice", "(", "startColIndex", ",", "limitColIndex", ")", ".", "forEach", "(", "cellData", "=>", "{", "cellData", ".", "rowMergeWith", "=", "rowMergeWith", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update rowMergeWith property of target rows for row merge. @param {Array.<Array.<object>>} targetRows - target rows @param {number} startColIndex - start column index @param {number} endColIndex - end column index @param {number} rowMergeWith - index of row merger @private
[ "Update", "rowMergeWith", "property", "of", "target", "rows", "for", "row", "merge", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergeCell.js#L99-L107
train
nhn/tui.editor
src/js/extensions/table/mergeCell.js
_updateColMergeWith
function _updateColMergeWith(targetRows, startColIndex, endColIndex, colMergeWith) { const limitColIndex = endColIndex + 1; targetRows.forEach(rowData => { rowData.slice(startColIndex, limitColIndex).forEach(cellData => { cellData.colMergeWith = colMergeWith; }); }); }
javascript
function _updateColMergeWith(targetRows, startColIndex, endColIndex, colMergeWith) { const limitColIndex = endColIndex + 1; targetRows.forEach(rowData => { rowData.slice(startColIndex, limitColIndex).forEach(cellData => { cellData.colMergeWith = colMergeWith; }); }); }
[ "function", "_updateColMergeWith", "(", "targetRows", ",", "startColIndex", ",", "endColIndex", ",", "colMergeWith", ")", "{", "const", "limitColIndex", "=", "endColIndex", "+", "1", ";", "targetRows", ".", "forEach", "(", "rowData", "=>", "{", "rowData", ".", "slice", "(", "startColIndex", ",", "limitColIndex", ")", ".", "forEach", "(", "cellData", "=>", "{", "cellData", ".", "colMergeWith", "=", "colMergeWith", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update colMergeWith property of target rows for column merge. @param {Array.<Array.<object>>} targetRows - target rows @param {number} startColIndex - start column index @param {number} endColIndex - end column index @param {number} colMergeWith - index of column merger @private
[ "Update", "colMergeWith", "property", "of", "target", "rows", "for", "column", "merge", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergeCell.js#L117-L125
train
nhn/tui.editor
src/js/wysiwygCommands/tableRemoveRow.js
focusToFirstTd
function focusToFirstTd(sq, range, $tr, tableMgr) { const nextFocusCell = $tr.find('td').get(0); range.setStart(nextFocusCell, 0); range.collapse(true); tableMgr.setLastCellNode(nextFocusCell); sq.setSelection(range); }
javascript
function focusToFirstTd(sq, range, $tr, tableMgr) { const nextFocusCell = $tr.find('td').get(0); range.setStart(nextFocusCell, 0); range.collapse(true); tableMgr.setLastCellNode(nextFocusCell); sq.setSelection(range); }
[ "function", "focusToFirstTd", "(", "sq", ",", "range", ",", "$tr", ",", "tableMgr", ")", "{", "const", "nextFocusCell", "=", "$tr", ".", "find", "(", "'td'", ")", ".", "get", "(", "0", ")", ";", "range", ".", "setStart", "(", "nextFocusCell", ",", "0", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "tableMgr", ".", "setLastCellNode", "(", "nextFocusCell", ")", ";", "sq", ".", "setSelection", "(", "range", ")", ";", "}" ]
Focus to first TD in given TR @param {SquireExt} sq Squire instance @param {Range} range Range object @param {jQuery} $tr jQuery wrapped TR @param {object} tableMgr Table manager
[ "Focus", "to", "first", "TD", "in", "given", "TR" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableRemoveRow.js#L53-L60
train
nhn/tui.editor
src/js/wysiwygCommands/tableRemoveRow.js
getSelectedRows
function getSelectedRows(firstSelectedCell, rangeInformation, $table) { const tbodyRowLength = $table.find('tbody tr').length; const isStartContainerInThead = $(firstSelectedCell).parents('thead').length; let startRowIndex = rangeInformation.from.row; let endRowIndex = rangeInformation.to.row; if (isStartContainerInThead) { startRowIndex += 1; } const isWholeTbodySelected = (startRowIndex === 1 || isStartContainerInThead) && endRowIndex === tbodyRowLength; if (isWholeTbodySelected) { endRowIndex -= 1; } return $table.find('tr').slice(startRowIndex, endRowIndex + 1); }
javascript
function getSelectedRows(firstSelectedCell, rangeInformation, $table) { const tbodyRowLength = $table.find('tbody tr').length; const isStartContainerInThead = $(firstSelectedCell).parents('thead').length; let startRowIndex = rangeInformation.from.row; let endRowIndex = rangeInformation.to.row; if (isStartContainerInThead) { startRowIndex += 1; } const isWholeTbodySelected = (startRowIndex === 1 || isStartContainerInThead) && endRowIndex === tbodyRowLength; if (isWholeTbodySelected) { endRowIndex -= 1; } return $table.find('tr').slice(startRowIndex, endRowIndex + 1); }
[ "function", "getSelectedRows", "(", "firstSelectedCell", ",", "rangeInformation", ",", "$table", ")", "{", "const", "tbodyRowLength", "=", "$table", ".", "find", "(", "'tbody tr'", ")", ".", "length", ";", "const", "isStartContainerInThead", "=", "$", "(", "firstSelectedCell", ")", ".", "parents", "(", "'thead'", ")", ".", "length", ";", "let", "startRowIndex", "=", "rangeInformation", ".", "from", ".", "row", ";", "let", "endRowIndex", "=", "rangeInformation", ".", "to", ".", "row", ";", "if", "(", "isStartContainerInThead", ")", "{", "startRowIndex", "+=", "1", ";", "}", "const", "isWholeTbodySelected", "=", "(", "startRowIndex", "===", "1", "||", "isStartContainerInThead", ")", "&&", "endRowIndex", "===", "tbodyRowLength", ";", "if", "(", "isWholeTbodySelected", ")", "{", "endRowIndex", "-=", "1", ";", "}", "return", "$table", ".", "find", "(", "'tr'", ")", ".", "slice", "(", "startRowIndex", ",", "endRowIndex", "+", "1", ")", ";", "}" ]
Get start, end row index from current range @param {HTMLElement} firstSelectedCell Range object @param {object} rangeInformation Range information object @param {jQuery} $table jquery wrapped TABLE @returns {jQuery}
[ "Get", "start", "end", "row", "index", "from", "current", "range" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableRemoveRow.js#L69-L86
train
nhn/tui.editor
src/js/extensions/table/table.js
_changeWysiwygManagers
function _changeWysiwygManagers(wwComponentManager) { wwComponentManager.removeManager('table'); wwComponentManager.removeManager('tableSelection'); wwComponentManager.addManager(WwMergedTableManager); wwComponentManager.addManager(WwMergedTableSelectionManager); }
javascript
function _changeWysiwygManagers(wwComponentManager) { wwComponentManager.removeManager('table'); wwComponentManager.removeManager('tableSelection'); wwComponentManager.addManager(WwMergedTableManager); wwComponentManager.addManager(WwMergedTableSelectionManager); }
[ "function", "_changeWysiwygManagers", "(", "wwComponentManager", ")", "{", "wwComponentManager", ".", "removeManager", "(", "'table'", ")", ";", "wwComponentManager", ".", "removeManager", "(", "'tableSelection'", ")", ";", "wwComponentManager", ".", "addManager", "(", "WwMergedTableManager", ")", ";", "wwComponentManager", ".", "addManager", "(", "WwMergedTableSelectionManager", ")", ";", "}" ]
Change wysiwyg component managers. @param {object} wwComponentManager - componentMananger instance @private
[ "Change", "wysiwyg", "component", "managers", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/table.js#L65-L71
train