id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
3,500
zloirock/core-js
packages/core-js/modules/web.url-search-params.js
forEach
function forEach(callback /* , thisArg */) { var entries = getInternalParamsState(this).entries; var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); var i = 0; var entry; while (i < entries.length) { entry = entries[i++]; boundFunction(entry.value, entry.key, this); } }
javascript
function forEach(callback /* , thisArg */) { var entries = getInternalParamsState(this).entries; var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); var i = 0; var entry; while (i < entries.length) { entry = entries[i++]; boundFunction(entry.value, entry.key, this); } }
[ "function", "forEach", "(", "callback", "/* , thisArg */", ")", "{", "var", "entries", "=", "getInternalParamsState", "(", "this", ")", ".", "entries", ";", "var", "boundFunction", "=", "bind", "(", "callback", ",", "arguments", ".", "length", ">", "1", "?", "arguments", "[", "1", "]", ":", "undefined", ",", "3", ")", ";", "var", "i", "=", "0", ";", "var", "entry", ";", "while", "(", "i", "<", "entries", ".", "length", ")", "{", "entry", "=", "entries", "[", "i", "++", "]", ";", "boundFunction", "(", "entry", ".", "value", ",", "entry", ".", "key", ",", "this", ")", ";", "}", "}" ]
`URLSearchParams.prototype.forEach` method
[ "URLSearchParams", ".", "prototype", ".", "forEach", "method" ]
fe7c8511a6d27d03a9b8e075b3351416aae95c58
https://github.com/zloirock/core-js/blob/fe7c8511a6d27d03a9b8e075b3351416aae95c58/packages/core-js/modules/web.url-search-params.js#L245-L254
3,501
caolan/async
lib/sortBy.js
sortBy
function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); return map(coll, (x, iterCb) => { _iteratee(x, (err, criteria) => { if (err) return iterCb(err); iterCb(err, {value: x, criteria}); }); }, (err, results) => { if (err) return callback(err); callback(null, results.sort(comparator).map(v => v.value)); }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }
javascript
function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); return map(coll, (x, iterCb) => { _iteratee(x, (err, criteria) => { if (err) return iterCb(err); iterCb(err, {value: x, criteria}); }); }, (err, results) => { if (err) return callback(err); callback(null, results.sort(comparator).map(v => v.value)); }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }
[ "function", "sortBy", "(", "coll", ",", "iteratee", ",", "callback", ")", "{", "var", "_iteratee", "=", "wrapAsync", "(", "iteratee", ")", ";", "return", "map", "(", "coll", ",", "(", "x", ",", "iterCb", ")", "=>", "{", "_iteratee", "(", "x", ",", "(", "err", ",", "criteria", ")", "=>", "{", "if", "(", "err", ")", "return", "iterCb", "(", "err", ")", ";", "iterCb", "(", "err", ",", "{", "value", ":", "x", ",", "criteria", "}", ")", ";", "}", ")", ";", "}", ",", "(", "err", ",", "results", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "results", ".", "sort", "(", "comparator", ")", ".", "map", "(", "v", "=>", "v", ".", "value", ")", ")", ";", "}", ")", ";", "function", "comparator", "(", "left", ",", "right", ")", "{", "var", "a", "=", "left", ".", "criteria", ",", "b", "=", "right", ".", "criteria", ";", "return", "a", "<", "b", "?", "-", "1", ":", "a", ">", "b", "?", "1", ":", "0", ";", "}", "}" ]
Sorts a list by the results of running each `coll` value through an async `iteratee`. @name sortBy @static @memberOf module:Collections @method @category Collection @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. @param {AsyncFunction} iteratee - An async function to apply to each item in `coll`. The iteratee should complete with a value to use as the sort criteria as its `result`. Invoked with (item, callback). @param {Function} callback - A callback which is called after all the `iteratee` functions have finished, or an error occurs. Results is the items from the original `coll` sorted by the values returned by the `iteratee` calls. Invoked with (err, results). @returns {Promise} a promise, if no callback passed @example async.sortBy(['file1','file2','file3'], function(file, callback) { fs.stat(file, function(err, stats) { callback(err, stats.mtime); }); }, function(err, results) { // results is now the original array of files sorted by // modified date }); // By modifying the callback parameter the // sorting order can be influenced: // ascending order async.sortBy([1,9,3,5], function(x, callback) { callback(null, x); }, function(err,result) { // result callback }); // descending order async.sortBy([1,9,3,5], function(x, callback) { callback(null, x*-1); //<- x*-1 instead of x, turns the order around }, function(err,result) { // result callback });
[ "Sorts", "a", "list", "by", "the", "results", "of", "running", "each", "coll", "value", "through", "an", "async", "iteratee", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/sortBy.js#L53-L69
3,502
caolan/async
lib/whilst.js
whilst
function whilst(test, iteratee, callback) { callback = onlyOnce(callback); var _fn = wrapAsync(iteratee); var _test = wrapAsync(test); var results = []; function next(err, ...rest) { if (err) return callback(err); results = rest; if (err === false) return; _test(check); } function check(err, truth) { if (err) return callback(err); if (err === false) return; if (!truth) return callback(null, ...results); _fn(next); } return _test(check); }
javascript
function whilst(test, iteratee, callback) { callback = onlyOnce(callback); var _fn = wrapAsync(iteratee); var _test = wrapAsync(test); var results = []; function next(err, ...rest) { if (err) return callback(err); results = rest; if (err === false) return; _test(check); } function check(err, truth) { if (err) return callback(err); if (err === false) return; if (!truth) return callback(null, ...results); _fn(next); } return _test(check); }
[ "function", "whilst", "(", "test", ",", "iteratee", ",", "callback", ")", "{", "callback", "=", "onlyOnce", "(", "callback", ")", ";", "var", "_fn", "=", "wrapAsync", "(", "iteratee", ")", ";", "var", "_test", "=", "wrapAsync", "(", "test", ")", ";", "var", "results", "=", "[", "]", ";", "function", "next", "(", "err", ",", "...", "rest", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "results", "=", "rest", ";", "if", "(", "err", "===", "false", ")", "return", ";", "_test", "(", "check", ")", ";", "}", "function", "check", "(", "err", ",", "truth", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "if", "(", "err", "===", "false", ")", "return", ";", "if", "(", "!", "truth", ")", "return", "callback", "(", "null", ",", "...", "results", ")", ";", "_fn", "(", "next", ")", ";", "}", "return", "_test", "(", "check", ")", ";", "}" ]
Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when stopped, or an error occurs. @name whilst @static @memberOf module:ControlFlow @method @category Control Flow @param {AsyncFunction} test - asynchronous truth test to perform before each execution of `iteratee`. Invoked with (). @param {AsyncFunction} iteratee - An async function which is called each time `test` passes. Invoked with (callback). @param {Function} [callback] - A callback which is called after the test function has failed and repeated execution of `iteratee` has stopped. `callback` will be passed an error and any arguments passed to the final `iteratee`'s callback. Invoked with (err, [results]); @returns {Promise} a promise, if no callback is passed @example var count = 0; async.whilst( function test(cb) { cb(null, count < 5;) }, function iter(callback) { count++; setTimeout(function() { callback(null, count); }, 1000); }, function (err, n) { // 5 seconds have passed, n = 5 } );
[ "Repeatedly", "call", "iteratee", "while", "test", "returns", "true", ".", "Calls", "callback", "when", "stopped", "or", "an", "error", "occurs", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/whilst.js#L39-L60
3,503
caolan/async
lib/every.js
every
function every(coll, iteratee, callback) { return createTester(bool => !bool, res => !res)(eachOf, coll, iteratee, callback) }
javascript
function every(coll, iteratee, callback) { return createTester(bool => !bool, res => !res)(eachOf, coll, iteratee, callback) }
[ "function", "every", "(", "coll", ",", "iteratee", ",", "callback", ")", "{", "return", "createTester", "(", "bool", "=>", "!", "bool", ",", "res", "=>", "!", "res", ")", "(", "eachOf", ",", "coll", ",", "iteratee", ",", "callback", ")", "}" ]
Returns `true` if every element in `coll` satisfies an async test. If any iteratee call returns `false`, the main `callback` is immediately called. @name every @static @memberOf module:Collections @method @alias all @category Collection @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. @param {AsyncFunction} iteratee - An async truth test to apply to each item in the collection in parallel. The iteratee must complete with a boolean result value. Invoked with (item, callback). @param {Function} [callback] - A callback which is called after all the `iteratee` functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). @returns {Promise} a promise, if no callback provided @example async.every(['file1','file2','file3'], function(filePath, callback) { fs.access(filePath, function(err) { callback(null, !err) }); }, function(err, result) { // if result is true then every file exists });
[ "Returns", "true", "if", "every", "element", "in", "coll", "satisfies", "an", "async", "test", ".", "If", "any", "iteratee", "call", "returns", "false", "the", "main", "callback", "is", "immediately", "called", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/every.js#L34-L36
3,504
caolan/async
lib/eachOf.js
eachOfArrayLike
function eachOfArrayLike(coll, iteratee, callback) { callback = once(callback); var index = 0, completed = 0, {length} = coll, canceled = false; if (length === 0) { callback(null); } function iteratorCallback(err, value) { if (err === false) { canceled = true } if (canceled === true) return if (err) { callback(err); } else if ((++completed === length) || value === breakLoop) { callback(null); } } for (; index < length; index++) { iteratee(coll[index], index, onlyOnce(iteratorCallback)); } }
javascript
function eachOfArrayLike(coll, iteratee, callback) { callback = once(callback); var index = 0, completed = 0, {length} = coll, canceled = false; if (length === 0) { callback(null); } function iteratorCallback(err, value) { if (err === false) { canceled = true } if (canceled === true) return if (err) { callback(err); } else if ((++completed === length) || value === breakLoop) { callback(null); } } for (; index < length; index++) { iteratee(coll[index], index, onlyOnce(iteratorCallback)); } }
[ "function", "eachOfArrayLike", "(", "coll", ",", "iteratee", ",", "callback", ")", "{", "callback", "=", "once", "(", "callback", ")", ";", "var", "index", "=", "0", ",", "completed", "=", "0", ",", "{", "length", "}", "=", "coll", ",", "canceled", "=", "false", ";", "if", "(", "length", "===", "0", ")", "{", "callback", "(", "null", ")", ";", "}", "function", "iteratorCallback", "(", "err", ",", "value", ")", "{", "if", "(", "err", "===", "false", ")", "{", "canceled", "=", "true", "}", "if", "(", "canceled", "===", "true", ")", "return", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "if", "(", "(", "++", "completed", "===", "length", ")", "||", "value", "===", "breakLoop", ")", "{", "callback", "(", "null", ")", ";", "}", "}", "for", "(", ";", "index", "<", "length", ";", "index", "++", ")", "{", "iteratee", "(", "coll", "[", "index", "]", ",", "index", ",", "onlyOnce", "(", "iteratorCallback", ")", ")", ";", "}", "}" ]
eachOf implementation optimized for array-likes
[ "eachOf", "implementation", "optimized", "for", "array", "-", "likes" ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/eachOf.js#L10-L35
3,505
caolan/async
lib/reduce.js
reduce
function reduce(coll, memo, iteratee, callback) { callback = once(callback); var _iteratee = wrapAsync(iteratee); return eachOfSeries(coll, (x, i, iterCb) => { _iteratee(memo, x, (err, v) => { memo = v; iterCb(err); }); }, err => callback(err, memo)); }
javascript
function reduce(coll, memo, iteratee, callback) { callback = once(callback); var _iteratee = wrapAsync(iteratee); return eachOfSeries(coll, (x, i, iterCb) => { _iteratee(memo, x, (err, v) => { memo = v; iterCb(err); }); }, err => callback(err, memo)); }
[ "function", "reduce", "(", "coll", ",", "memo", ",", "iteratee", ",", "callback", ")", "{", "callback", "=", "once", "(", "callback", ")", ";", "var", "_iteratee", "=", "wrapAsync", "(", "iteratee", ")", ";", "return", "eachOfSeries", "(", "coll", ",", "(", "x", ",", "i", ",", "iterCb", ")", "=>", "{", "_iteratee", "(", "memo", ",", "x", ",", "(", "err", ",", "v", ")", "=>", "{", "memo", "=", "v", ";", "iterCb", "(", "err", ")", ";", "}", ")", ";", "}", ",", "err", "=>", "callback", "(", "err", ",", "memo", ")", ")", ";", "}" ]
Reduces `coll` into a single value using an async `iteratee` to return each successive step. `memo` is the initial state of the reduction. This function only operates in series. For performance reasons, it may make sense to split a call to this function into a parallel map, and then use the normal `Array.prototype.reduce` on the results. This function is for situations where each step in the reduction needs to be async; if you can get the data before reducing it, then it's probably a good idea to do so. @name reduce @static @memberOf module:Collections @method @alias inject @alias foldl @category Collection @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. @param {*} memo - The initial state of the reduction. @param {AsyncFunction} iteratee - A function applied to each item in the array to produce the next step in the reduction. The `iteratee` should complete with the next state of the reduction. If the iteratee complete with an error, the reduction is stopped and the main `callback` is immediately called with the error. Invoked with (memo, item, callback). @param {Function} [callback] - A callback which is called after all the `iteratee` functions have finished. Result is the reduced value. Invoked with (err, result). @returns {Promise} a promise, if no callback is passed @example async.reduce([1,2,3], 0, function(memo, item, callback) { // pointless async: process.nextTick(function() { callback(null, memo + item) }); }, function(err, result) { // result is now equal to the last value of memo, which is 6 });
[ "Reduces", "coll", "into", "a", "single", "value", "using", "an", "async", "iteratee", "to", "return", "each", "successive", "step", ".", "memo", "is", "the", "initial", "state", "of", "the", "reduction", ".", "This", "function", "only", "operates", "in", "series", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/reduce.js#L47-L56
3,506
caolan/async
lib/waterfall.js
waterfall
function waterfall (tasks, callback) { callback = once(callback); if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); if (!tasks.length) return callback(); var taskIndex = 0; function nextTask(args) { var task = wrapAsync(tasks[taskIndex++]); task(...args, onlyOnce(next)); } function next(err, ...args) { if (err === false) return if (err || taskIndex === tasks.length) { return callback(err, ...args); } nextTask(args); } nextTask([]); }
javascript
function waterfall (tasks, callback) { callback = once(callback); if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); if (!tasks.length) return callback(); var taskIndex = 0; function nextTask(args) { var task = wrapAsync(tasks[taskIndex++]); task(...args, onlyOnce(next)); } function next(err, ...args) { if (err === false) return if (err || taskIndex === tasks.length) { return callback(err, ...args); } nextTask(args); } nextTask([]); }
[ "function", "waterfall", "(", "tasks", ",", "callback", ")", "{", "callback", "=", "once", "(", "callback", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "tasks", ")", ")", "return", "callback", "(", "new", "Error", "(", "'First argument to waterfall must be an array of functions'", ")", ")", ";", "if", "(", "!", "tasks", ".", "length", ")", "return", "callback", "(", ")", ";", "var", "taskIndex", "=", "0", ";", "function", "nextTask", "(", "args", ")", "{", "var", "task", "=", "wrapAsync", "(", "tasks", "[", "taskIndex", "++", "]", ")", ";", "task", "(", "...", "args", ",", "onlyOnce", "(", "next", ")", ")", ";", "}", "function", "next", "(", "err", ",", "...", "args", ")", "{", "if", "(", "err", "===", "false", ")", "return", "if", "(", "err", "||", "taskIndex", "===", "tasks", ".", "length", ")", "{", "return", "callback", "(", "err", ",", "...", "args", ")", ";", "}", "nextTask", "(", "args", ")", ";", "}", "nextTask", "(", "[", "]", ")", ";", "}" ]
Runs the `tasks` array of functions in series, each passing their results to the next in the array. However, if any of the `tasks` pass an error to their own callback, the next function is not executed, and the main `callback` is immediately called with the error. @name waterfall @static @memberOf module:ControlFlow @method @category Control Flow @param {Array} tasks - An array of [async functions]{@link AsyncFunction} to run. Each function should complete with any number of `result` values. The `result` values will be passed as arguments, in order, to the next task. @param {Function} [callback] - An optional callback to run once all the functions have completed. This will be passed the results of the last task's callback. Invoked with (err, [results]). @returns undefined @example async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' }); // Or, with named functions: async.waterfall([ myFirstFunction, mySecondFunction, myLastFunction, ], function (err, result) { // result now equals 'done' }); function myFirstFunction(callback) { callback(null, 'one', 'two'); } function mySecondFunction(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); } function myLastFunction(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); }
[ "Runs", "the", "tasks", "array", "of", "functions", "in", "series", "each", "passing", "their", "results", "to", "the", "next", "in", "the", "array", ".", "However", "if", "any", "of", "the", "tasks", "pass", "an", "error", "to", "their", "own", "callback", "the", "next", "function", "is", "not", "executed", "and", "the", "main", "callback", "is", "immediately", "called", "with", "the", "error", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/waterfall.js#L64-L84
3,507
caolan/async
lib/some.js
some
function some(coll, iteratee, callback) { return createTester(Boolean, res => res)(eachOf, coll, iteratee, callback) }
javascript
function some(coll, iteratee, callback) { return createTester(Boolean, res => res)(eachOf, coll, iteratee, callback) }
[ "function", "some", "(", "coll", ",", "iteratee", ",", "callback", ")", "{", "return", "createTester", "(", "Boolean", ",", "res", "=>", "res", ")", "(", "eachOf", ",", "coll", ",", "iteratee", ",", "callback", ")", "}" ]
Returns `true` if at least one element in the `coll` satisfies an async test. If any iteratee call returns `true`, the main `callback` is immediately called. @name some @static @memberOf module:Collections @method @alias any @category Collection @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. @param {AsyncFunction} iteratee - An async truth test to apply to each item in the collections in parallel. The iteratee should complete with a boolean `result` value. Invoked with (item, callback). @param {Function} [callback] - A callback which is called as soon as any iteratee returns `true`, or after all the iteratee functions have finished. Result will be either `true` or `false` depending on the values of the async tests. Invoked with (err, result). @returns {Promise} a promise, if no callback provided @example async.some(['file1','file2','file3'], function(filePath, callback) { fs.access(filePath, function(err) { callback(null, !err) }); }, function(err, result) { // if result is true then at least one of the files exists });
[ "Returns", "true", "if", "at", "least", "one", "element", "in", "the", "coll", "satisfies", "an", "async", "test", ".", "If", "any", "iteratee", "call", "returns", "true", "the", "main", "callback", "is", "immediately", "called", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/some.js#L36-L38
3,508
caolan/async
support/jsdoc/theme/publish.js
sortStrs
function sortStrs(strArr) { return strArr.sort(function(s1, s2) { var lowerCaseS1 = s1.toLowerCase(); var lowerCaseS2 = s2.toLowerCase(); if (lowerCaseS1 < lowerCaseS2) { return -1; } else if (lowerCaseS1 > lowerCaseS2) { return 1; } else { return 0; } }); }
javascript
function sortStrs(strArr) { return strArr.sort(function(s1, s2) { var lowerCaseS1 = s1.toLowerCase(); var lowerCaseS2 = s2.toLowerCase(); if (lowerCaseS1 < lowerCaseS2) { return -1; } else if (lowerCaseS1 > lowerCaseS2) { return 1; } else { return 0; } }); }
[ "function", "sortStrs", "(", "strArr", ")", "{", "return", "strArr", ".", "sort", "(", "function", "(", "s1", ",", "s2", ")", "{", "var", "lowerCaseS1", "=", "s1", ".", "toLowerCase", "(", ")", ";", "var", "lowerCaseS2", "=", "s2", ".", "toLowerCase", "(", ")", ";", "if", "(", "lowerCaseS1", "<", "lowerCaseS2", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "lowerCaseS1", ">", "lowerCaseS2", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", ")", ";", "}" ]
Sorts an array of strings alphabetically @param {Array<String>} strArr - Array of strings to sort @return {Array<String>} The sorted array
[ "Sorts", "an", "array", "of", "strings", "alphabetically" ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/support/jsdoc/theme/publish.js#L395-L408
3,509
caolan/async
lib/forever.js
forever
function forever(fn, errback) { var done = onlyOnce(errback); var task = wrapAsync(ensureAsync(fn)); function next(err) { if (err) return done(err); if (err === false) return; task(next); } return next(); }
javascript
function forever(fn, errback) { var done = onlyOnce(errback); var task = wrapAsync(ensureAsync(fn)); function next(err) { if (err) return done(err); if (err === false) return; task(next); } return next(); }
[ "function", "forever", "(", "fn", ",", "errback", ")", "{", "var", "done", "=", "onlyOnce", "(", "errback", ")", ";", "var", "task", "=", "wrapAsync", "(", "ensureAsync", "(", "fn", ")", ")", ";", "function", "next", "(", "err", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "if", "(", "err", "===", "false", ")", "return", ";", "task", "(", "next", ")", ";", "}", "return", "next", "(", ")", ";", "}" ]
Calls the asynchronous function `fn` with a callback parameter that allows it to call itself again, in series, indefinitely. If an error is passed to the callback then `errback` is called with the error, and execution stops, otherwise it will never be called. @name forever @static @memberOf module:ControlFlow @method @category Control Flow @param {AsyncFunction} fn - an async function to call repeatedly. Invoked with (next). @param {Function} [errback] - when `fn` passes an error to it's callback, this function will be called, and execution stops. Invoked with (err). @returns {Promise} a promise that rejects if an error occurs and an errback is not passed @example async.forever( function(next) { // next is suitable for passing to things that need a callback(err [, whatever]); // it will result in this function being called again. }, function(err) { // if next is called with a value in its first parameter, it will appear // in here as 'err', and execution will stop. } );
[ "Calls", "the", "asynchronous", "function", "fn", "with", "a", "callback", "parameter", "that", "allows", "it", "to", "call", "itself", "again", "in", "series", "indefinitely", "." ]
4330d536c106592139fa82062494c9dba0da1fdb
https://github.com/caolan/async/blob/4330d536c106592139fa82062494c9dba0da1fdb/lib/forever.js#L37-L47
3,510
ecomfe/zrender
src/core/BoundingRect.js
function (b) { var a = this; var sx = b.width / a.width; var sy = b.height / a.height; var m = matrix.create(); // 矩阵右乘 matrix.translate(m, m, [-a.x, -a.y]); matrix.scale(m, m, [sx, sy]); matrix.translate(m, m, [b.x, b.y]); return m; }
javascript
function (b) { var a = this; var sx = b.width / a.width; var sy = b.height / a.height; var m = matrix.create(); // 矩阵右乘 matrix.translate(m, m, [-a.x, -a.y]); matrix.scale(m, m, [sx, sy]); matrix.translate(m, m, [b.x, b.y]); return m; }
[ "function", "(", "b", ")", "{", "var", "a", "=", "this", ";", "var", "sx", "=", "b", ".", "width", "/", "a", ".", "width", ";", "var", "sy", "=", "b", ".", "height", "/", "a", ".", "height", ";", "var", "m", "=", "matrix", ".", "create", "(", ")", ";", "// 矩阵右乘", "matrix", ".", "translate", "(", "m", ",", "m", ",", "[", "-", "a", ".", "x", ",", "-", "a", ".", "y", "]", ")", ";", "matrix", ".", "scale", "(", "m", ",", "m", ",", "[", "sx", ",", "sy", "]", ")", ";", "matrix", ".", "translate", "(", "m", ",", "m", ",", "[", "b", ".", "x", ",", "b", ".", "y", "]", ")", ";", "return", "m", ";", "}" ]
Calculate matrix of transforming from self to target rect @param {module:zrender/core/BoundingRect} b @return {Array.<number>}
[ "Calculate", "matrix", "of", "transforming", "from", "self", "to", "target", "rect" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/core/BoundingRect.js#L107-L120
3,511
ecomfe/zrender
src/graphic/States.js
function (state, subPropKey, key, transitionCfg, done) { var el = this._el; var stateObj = subPropKey ? state[subPropKey] : state; var elObj = subPropKey ? el[subPropKey] : el; var availableProp = stateObj && (key in stateObj) && elObj && (key in elObj); var transitionAnimators = this._transitionAnimators; if (availableProp) { var obj = {}; if (stateObj[key] === elObj[key]) { return 0; } obj[key] = stateObj[key]; var animator = el.animate(subPropKey) .when(transitionCfg.duration, obj) .delay(transitionCfg.dealy) .done(function () { var idx = zrUtil.indexOf(transitionAnimators, 1); if (idx > 0) { transitionAnimators.splice(idx, 1); } done(); }) .start(transitionCfg.easing); transitionAnimators.push(animator); return 1; } return 0; }
javascript
function (state, subPropKey, key, transitionCfg, done) { var el = this._el; var stateObj = subPropKey ? state[subPropKey] : state; var elObj = subPropKey ? el[subPropKey] : el; var availableProp = stateObj && (key in stateObj) && elObj && (key in elObj); var transitionAnimators = this._transitionAnimators; if (availableProp) { var obj = {}; if (stateObj[key] === elObj[key]) { return 0; } obj[key] = stateObj[key]; var animator = el.animate(subPropKey) .when(transitionCfg.duration, obj) .delay(transitionCfg.dealy) .done(function () { var idx = zrUtil.indexOf(transitionAnimators, 1); if (idx > 0) { transitionAnimators.splice(idx, 1); } done(); }) .start(transitionCfg.easing); transitionAnimators.push(animator); return 1; } return 0; }
[ "function", "(", "state", ",", "subPropKey", ",", "key", ",", "transitionCfg", ",", "done", ")", "{", "var", "el", "=", "this", ".", "_el", ";", "var", "stateObj", "=", "subPropKey", "?", "state", "[", "subPropKey", "]", ":", "state", ";", "var", "elObj", "=", "subPropKey", "?", "el", "[", "subPropKey", "]", ":", "el", ";", "var", "availableProp", "=", "stateObj", "&&", "(", "key", "in", "stateObj", ")", "&&", "elObj", "&&", "(", "key", "in", "elObj", ")", ";", "var", "transitionAnimators", "=", "this", ".", "_transitionAnimators", ";", "if", "(", "availableProp", ")", "{", "var", "obj", "=", "{", "}", ";", "if", "(", "stateObj", "[", "key", "]", "===", "elObj", "[", "key", "]", ")", "{", "return", "0", ";", "}", "obj", "[", "key", "]", "=", "stateObj", "[", "key", "]", ";", "var", "animator", "=", "el", ".", "animate", "(", "subPropKey", ")", ".", "when", "(", "transitionCfg", ".", "duration", ",", "obj", ")", ".", "delay", "(", "transitionCfg", ".", "dealy", ")", ".", "done", "(", "function", "(", ")", "{", "var", "idx", "=", "zrUtil", ".", "indexOf", "(", "transitionAnimators", ",", "1", ")", ";", "if", "(", "idx", ">", "0", ")", "{", "transitionAnimators", ".", "splice", "(", "idx", ",", "1", ")", ";", "}", "done", "(", ")", ";", "}", ")", ".", "start", "(", "transitionCfg", ".", "easing", ")", ";", "transitionAnimators", ".", "push", "(", "animator", ")", ";", "return", "1", ";", "}", "return", "0", ";", "}" ]
Do transition animation of particular property @param {Object} state @param {string} subPropKey @param {string} key @param {Object} transitionCfg @param {Function} done @private
[ "Do", "transition", "animation", "of", "particular", "property" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/graphic/States.js#L359-L390
3,512
ecomfe/zrender
src/Painter.js
function (cb, context) { var zlevelList = this._zlevelList; var z; var i; for (i = 0; i < zlevelList.length; i++) { z = zlevelList[i]; cb.call(context, this._layers[z], z); } }
javascript
function (cb, context) { var zlevelList = this._zlevelList; var z; var i; for (i = 0; i < zlevelList.length; i++) { z = zlevelList[i]; cb.call(context, this._layers[z], z); } }
[ "function", "(", "cb", ",", "context", ")", "{", "var", "zlevelList", "=", "this", ".", "_zlevelList", ";", "var", "z", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "zlevelList", ".", "length", ";", "i", "++", ")", "{", "z", "=", "zlevelList", "[", "i", "]", ";", "cb", ".", "call", "(", "context", ",", "this", ".", "_layers", "[", "z", "]", ",", "z", ")", ";", "}", "}" ]
Iterate each layer
[ "Iterate", "each", "layer" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/Painter.js#L634-L642
3,513
ecomfe/zrender
src/Painter.js
function (opts) { opts = opts || {}; if (this._singleCanvas && !this._compositeManually) { return this._layers[CANVAS_ZLEVEL].dom; } var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr); imageLayer.initContext(); imageLayer.clear(false, opts.backgroundColor || this._backgroundColor); if (opts.pixelRatio <= this.dpr) { this.refresh(); var width = imageLayer.dom.width; var height = imageLayer.dom.height; var ctx = imageLayer.ctx; this.eachLayer(function (layer) { if (layer.__builtin__) { ctx.drawImage(layer.dom, 0, 0, width, height); } else if (layer.renderToCanvas) { imageLayer.ctx.save(); layer.renderToCanvas(imageLayer.ctx); imageLayer.ctx.restore(); } }); } else { // PENDING, echarts-gl and incremental rendering. var scope = {}; var displayList = this.storage.getDisplayList(true); for (var i = 0; i < displayList.length; i++) { var el = displayList[i]; this._doPaintEl(el, imageLayer, true, scope); } } return imageLayer.dom; }
javascript
function (opts) { opts = opts || {}; if (this._singleCanvas && !this._compositeManually) { return this._layers[CANVAS_ZLEVEL].dom; } var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr); imageLayer.initContext(); imageLayer.clear(false, opts.backgroundColor || this._backgroundColor); if (opts.pixelRatio <= this.dpr) { this.refresh(); var width = imageLayer.dom.width; var height = imageLayer.dom.height; var ctx = imageLayer.ctx; this.eachLayer(function (layer) { if (layer.__builtin__) { ctx.drawImage(layer.dom, 0, 0, width, height); } else if (layer.renderToCanvas) { imageLayer.ctx.save(); layer.renderToCanvas(imageLayer.ctx); imageLayer.ctx.restore(); } }); } else { // PENDING, echarts-gl and incremental rendering. var scope = {}; var displayList = this.storage.getDisplayList(true); for (var i = 0; i < displayList.length; i++) { var el = displayList[i]; this._doPaintEl(el, imageLayer, true, scope); } } return imageLayer.dom; }
[ "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "this", ".", "_singleCanvas", "&&", "!", "this", ".", "_compositeManually", ")", "{", "return", "this", ".", "_layers", "[", "CANVAS_ZLEVEL", "]", ".", "dom", ";", "}", "var", "imageLayer", "=", "new", "Layer", "(", "'image'", ",", "this", ",", "opts", ".", "pixelRatio", "||", "this", ".", "dpr", ")", ";", "imageLayer", ".", "initContext", "(", ")", ";", "imageLayer", ".", "clear", "(", "false", ",", "opts", ".", "backgroundColor", "||", "this", ".", "_backgroundColor", ")", ";", "if", "(", "opts", ".", "pixelRatio", "<=", "this", ".", "dpr", ")", "{", "this", ".", "refresh", "(", ")", ";", "var", "width", "=", "imageLayer", ".", "dom", ".", "width", ";", "var", "height", "=", "imageLayer", ".", "dom", ".", "height", ";", "var", "ctx", "=", "imageLayer", ".", "ctx", ";", "this", ".", "eachLayer", "(", "function", "(", "layer", ")", "{", "if", "(", "layer", ".", "__builtin__", ")", "{", "ctx", ".", "drawImage", "(", "layer", ".", "dom", ",", "0", ",", "0", ",", "width", ",", "height", ")", ";", "}", "else", "if", "(", "layer", ".", "renderToCanvas", ")", "{", "imageLayer", ".", "ctx", ".", "save", "(", ")", ";", "layer", ".", "renderToCanvas", "(", "imageLayer", ".", "ctx", ")", ";", "imageLayer", ".", "ctx", ".", "restore", "(", ")", ";", "}", "}", ")", ";", "}", "else", "{", "// PENDING, echarts-gl and incremental rendering.", "var", "scope", "=", "{", "}", ";", "var", "displayList", "=", "this", ".", "storage", ".", "getDisplayList", "(", "true", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "displayList", ".", "length", ";", "i", "++", ")", "{", "var", "el", "=", "displayList", "[", "i", "]", ";", "this", ".", "_doPaintEl", "(", "el", ",", "imageLayer", ",", "true", ",", "scope", ")", ";", "}", "}", "return", "imageLayer", ".", "dom", ";", "}" ]
Get canvas which has all thing rendered @param {Object} opts @param {string} [opts.backgroundColor] @param {number} [opts.pixelRatio]
[ "Get", "canvas", "which", "has", "all", "thing", "rendered" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/Painter.js#L913-L951
3,514
ecomfe/zrender
src/core/util.js
function (cb, context) { context !== void 0 && (cb = bind(cb, context)); for (var key in this.data) { this.data.hasOwnProperty(key) && cb(this.data[key], key); } }
javascript
function (cb, context) { context !== void 0 && (cb = bind(cb, context)); for (var key in this.data) { this.data.hasOwnProperty(key) && cb(this.data[key], key); } }
[ "function", "(", "cb", ",", "context", ")", "{", "context", "!==", "void", "0", "&&", "(", "cb", "=", "bind", "(", "cb", ",", "context", ")", ")", ";", "for", "(", "var", "key", "in", "this", ".", "data", ")", "{", "this", ".", "data", ".", "hasOwnProperty", "(", "key", ")", "&&", "cb", "(", "this", ".", "data", "[", "key", "]", ",", "key", ")", ";", "}", "}" ]
Although util.each can be performed on this hashMap directly, user should not use the exposed keys, who are prefixed.
[ "Although", "util", ".", "each", "can", "be", "performed", "on", "this", "hashMap", "directly", "user", "should", "not", "use", "the", "exposed", "keys", "who", "are", "prefixed", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/core/util.js#L642-L647
3,515
ecomfe/zrender
src/graphic/shape/BezierCurve.js
function (t) { var p = someVectorAt(this.shape, t, true); return vec2.normalize(p, p); }
javascript
function (t) { var p = someVectorAt(this.shape, t, true); return vec2.normalize(p, p); }
[ "function", "(", "t", ")", "{", "var", "p", "=", "someVectorAt", "(", "this", ".", "shape", ",", "t", ",", "true", ")", ";", "return", "vec2", ".", "normalize", "(", "p", ",", "p", ")", ";", "}" ]
Get tangent at percent @param {number} t @return {Array.<number>}
[ "Get", "tangent", "at", "percent" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/graphic/shape/BezierCurve.js#L131-L134
3,516
ecomfe/zrender
src/animation/Animator.js
fillArr
function fillArr(arr0, arr1, arrDim) { var arr0Len = arr0.length; var arr1Len = arr1.length; if (arr0Len !== arr1Len) { // FIXME Not work for TypedArray var isPreviousLarger = arr0Len > arr1Len; if (isPreviousLarger) { // Cut the previous arr0.length = arr1Len; } else { // Fill the previous for (var i = arr0Len; i < arr1Len; i++) { arr0.push( arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]) ); } } } // Handling NaN value var len2 = arr0[0] && arr0[0].length; for (var i = 0; i < arr0.length; i++) { if (arrDim === 1) { if (isNaN(arr0[i])) { arr0[i] = arr1[i]; } } else { for (var j = 0; j < len2; j++) { if (isNaN(arr0[i][j])) { arr0[i][j] = arr1[i][j]; } } } } }
javascript
function fillArr(arr0, arr1, arrDim) { var arr0Len = arr0.length; var arr1Len = arr1.length; if (arr0Len !== arr1Len) { // FIXME Not work for TypedArray var isPreviousLarger = arr0Len > arr1Len; if (isPreviousLarger) { // Cut the previous arr0.length = arr1Len; } else { // Fill the previous for (var i = arr0Len; i < arr1Len; i++) { arr0.push( arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]) ); } } } // Handling NaN value var len2 = arr0[0] && arr0[0].length; for (var i = 0; i < arr0.length; i++) { if (arrDim === 1) { if (isNaN(arr0[i])) { arr0[i] = arr1[i]; } } else { for (var j = 0; j < len2; j++) { if (isNaN(arr0[i][j])) { arr0[i][j] = arr1[i][j]; } } } } }
[ "function", "fillArr", "(", "arr0", ",", "arr1", ",", "arrDim", ")", "{", "var", "arr0Len", "=", "arr0", ".", "length", ";", "var", "arr1Len", "=", "arr1", ".", "length", ";", "if", "(", "arr0Len", "!==", "arr1Len", ")", "{", "// FIXME Not work for TypedArray", "var", "isPreviousLarger", "=", "arr0Len", ">", "arr1Len", ";", "if", "(", "isPreviousLarger", ")", "{", "// Cut the previous", "arr0", ".", "length", "=", "arr1Len", ";", "}", "else", "{", "// Fill the previous", "for", "(", "var", "i", "=", "arr0Len", ";", "i", "<", "arr1Len", ";", "i", "++", ")", "{", "arr0", ".", "push", "(", "arrDim", "===", "1", "?", "arr1", "[", "i", "]", ":", "arraySlice", ".", "call", "(", "arr1", "[", "i", "]", ")", ")", ";", "}", "}", "}", "// Handling NaN value", "var", "len2", "=", "arr0", "[", "0", "]", "&&", "arr0", "[", "0", "]", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr0", ".", "length", ";", "i", "++", ")", "{", "if", "(", "arrDim", "===", "1", ")", "{", "if", "(", "isNaN", "(", "arr0", "[", "i", "]", ")", ")", "{", "arr0", "[", "i", "]", "=", "arr1", "[", "i", "]", ";", "}", "}", "else", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "len2", ";", "j", "++", ")", "{", "if", "(", "isNaN", "(", "arr0", "[", "i", "]", "[", "j", "]", ")", ")", "{", "arr0", "[", "i", "]", "[", "j", "]", "=", "arr1", "[", "i", "]", "[", "j", "]", ";", "}", "}", "}", "}", "}" ]
arr0 is source array, arr1 is target array. Do some preprocess to avoid error happened when interpolating from arr0 to arr1
[ "arr0", "is", "source", "array", "arr1", "is", "target", "array", ".", "Do", "some", "preprocess", "to", "avoid", "error", "happened", "when", "interpolating", "from", "arr0", "to", "arr1" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/animation/Animator.js#L67-L102
3,517
ecomfe/zrender
src/animation/Animator.js
catmullRomInterpolateArray
function catmullRomInterpolateArray( p0, p1, p2, p3, t, t2, t3, out, arrDim ) { var len = p0.length; if (arrDim === 1) { for (var i = 0; i < len; i++) { out[i] = catmullRomInterpolate( p0[i], p1[i], p2[i], p3[i], t, t2, t3 ); } } else { var len2 = p0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = catmullRomInterpolate( p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3 ); } } } }
javascript
function catmullRomInterpolateArray( p0, p1, p2, p3, t, t2, t3, out, arrDim ) { var len = p0.length; if (arrDim === 1) { for (var i = 0; i < len; i++) { out[i] = catmullRomInterpolate( p0[i], p1[i], p2[i], p3[i], t, t2, t3 ); } } else { var len2 = p0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = catmullRomInterpolate( p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3 ); } } } }
[ "function", "catmullRomInterpolateArray", "(", "p0", ",", "p1", ",", "p2", ",", "p3", ",", "t", ",", "t2", ",", "t3", ",", "out", ",", "arrDim", ")", "{", "var", "len", "=", "p0", ".", "length", ";", "if", "(", "arrDim", "===", "1", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "out", "[", "i", "]", "=", "catmullRomInterpolate", "(", "p0", "[", "i", "]", ",", "p1", "[", "i", "]", ",", "p2", "[", "i", "]", ",", "p3", "[", "i", "]", ",", "t", ",", "t2", ",", "t3", ")", ";", "}", "}", "else", "{", "var", "len2", "=", "p0", "[", "0", "]", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "len2", ";", "j", "++", ")", "{", "out", "[", "i", "]", "[", "j", "]", "=", "catmullRomInterpolate", "(", "p0", "[", "i", "]", "[", "j", "]", ",", "p1", "[", "i", "]", "[", "j", "]", ",", "p2", "[", "i", "]", "[", "j", "]", ",", "p3", "[", "i", "]", "[", "j", "]", ",", "t", ",", "t2", ",", "t3", ")", ";", "}", "}", "}", "}" ]
Catmull Rom interpolate array @param {Array} p0 @param {Array} p1 @param {Array} p2 @param {Array} p3 @param {number} t @param {number} t2 @param {number} t3 @param {Array} out @param {number} arrDim
[ "Catmull", "Rom", "interpolate", "array" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/animation/Animator.js#L150-L172
3,518
ecomfe/zrender
src/mixin/Eventful.js
function (event, query, handler, context) { return on(this, event, query, handler, context, true); }
javascript
function (event, query, handler, context) { return on(this, event, query, handler, context, true); }
[ "function", "(", "event", ",", "query", ",", "handler", ",", "context", ")", "{", "return", "on", "(", "this", ",", "event", ",", "query", ",", "handler", ",", "context", ",", "true", ")", ";", "}" ]
The handler can only be triggered once, then removed. @param {string} event The event name. @param {string|Object} [query] Condition used on event filter. @param {Function} handler The event handler. @param {Object} context
[ "The", "handler", "can", "only", "be", "triggered", "once", "then", "removed", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L45-L47
3,519
ecomfe/zrender
src/mixin/Eventful.js
function (event, query, handler, context) { return on(this, event, query, handler, context, false); }
javascript
function (event, query, handler, context) { return on(this, event, query, handler, context, false); }
[ "function", "(", "event", ",", "query", ",", "handler", ",", "context", ")", "{", "return", "on", "(", "this", ",", "event", ",", "query", ",", "handler", ",", "context", ",", "false", ")", ";", "}" ]
Bind a handler. @param {string} event The event name. @param {string|Object} [query] Condition used on event filter. @param {Function} handler The event handler. @param {Object} [context]
[ "Bind", "a", "handler", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L57-L59
3,520
ecomfe/zrender
src/mixin/Eventful.js
function (event, handler) { var _h = this._$handlers; if (!event) { this._$handlers = {}; return this; } if (handler) { if (_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i].h !== handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if (_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return this; }
javascript
function (event, handler) { var _h = this._$handlers; if (!event) { this._$handlers = {}; return this; } if (handler) { if (_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i].h !== handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if (_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return this; }
[ "function", "(", "event", ",", "handler", ")", "{", "var", "_h", "=", "this", ".", "_$handlers", ";", "if", "(", "!", "event", ")", "{", "this", ".", "_$handlers", "=", "{", "}", ";", "return", "this", ";", "}", "if", "(", "handler", ")", "{", "if", "(", "_h", "[", "event", "]", ")", "{", "var", "newList", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "_h", "[", "event", "]", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "_h", "[", "event", "]", "[", "i", "]", ".", "h", "!==", "handler", ")", "{", "newList", ".", "push", "(", "_h", "[", "event", "]", "[", "i", "]", ")", ";", "}", "}", "_h", "[", "event", "]", "=", "newList", ";", "}", "if", "(", "_h", "[", "event", "]", "&&", "_h", "[", "event", "]", ".", "length", "===", "0", ")", "{", "delete", "_h", "[", "event", "]", ";", "}", "}", "else", "{", "delete", "_h", "[", "event", "]", ";", "}", "return", "this", ";", "}" ]
Unbind a event. @param {string} event The event name. @param {Function} [handler] The event handler.
[ "Unbind", "a", "event", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L78-L106
3,521
ecomfe/zrender
src/mixin/Eventful.js
function (type) { var _h = this._$handlers[type]; var eventProcessor = this._$eventProcessor; if (_h) { var args = arguments; var argLen = args.length; if (argLen > 3) { args = arrySlice.call(args, 1); } var len = _h.length; for (var i = 0; i < len;) { var hItem = _h[i]; if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query) ) { i++; continue; } // Optimize advise from backbone switch (argLen) { case 1: hItem.h.call(hItem.ctx); break; case 2: hItem.h.call(hItem.ctx, args[1]); break; case 3: hItem.h.call(hItem.ctx, args[1], args[2]); break; default: // have more than 2 given arguments hItem.h.apply(hItem.ctx, args); break; } if (hItem.one) { _h.splice(i, 1); len--; } else { i++; } } } eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type); return this; }
javascript
function (type) { var _h = this._$handlers[type]; var eventProcessor = this._$eventProcessor; if (_h) { var args = arguments; var argLen = args.length; if (argLen > 3) { args = arrySlice.call(args, 1); } var len = _h.length; for (var i = 0; i < len;) { var hItem = _h[i]; if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query) ) { i++; continue; } // Optimize advise from backbone switch (argLen) { case 1: hItem.h.call(hItem.ctx); break; case 2: hItem.h.call(hItem.ctx, args[1]); break; case 3: hItem.h.call(hItem.ctx, args[1], args[2]); break; default: // have more than 2 given arguments hItem.h.apply(hItem.ctx, args); break; } if (hItem.one) { _h.splice(i, 1); len--; } else { i++; } } } eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type); return this; }
[ "function", "(", "type", ")", "{", "var", "_h", "=", "this", ".", "_$handlers", "[", "type", "]", ";", "var", "eventProcessor", "=", "this", ".", "_$eventProcessor", ";", "if", "(", "_h", ")", "{", "var", "args", "=", "arguments", ";", "var", "argLen", "=", "args", ".", "length", ";", "if", "(", "argLen", ">", "3", ")", "{", "args", "=", "arrySlice", ".", "call", "(", "args", ",", "1", ")", ";", "}", "var", "len", "=", "_h", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", ")", "{", "var", "hItem", "=", "_h", "[", "i", "]", ";", "if", "(", "eventProcessor", "&&", "eventProcessor", ".", "filter", "&&", "hItem", ".", "query", "!=", "null", "&&", "!", "eventProcessor", ".", "filter", "(", "type", ",", "hItem", ".", "query", ")", ")", "{", "i", "++", ";", "continue", ";", "}", "// Optimize advise from backbone", "switch", "(", "argLen", ")", "{", "case", "1", ":", "hItem", ".", "h", ".", "call", "(", "hItem", ".", "ctx", ")", ";", "break", ";", "case", "2", ":", "hItem", ".", "h", ".", "call", "(", "hItem", ".", "ctx", ",", "args", "[", "1", "]", ")", ";", "break", ";", "case", "3", ":", "hItem", ".", "h", ".", "call", "(", "hItem", ".", "ctx", ",", "args", "[", "1", "]", ",", "args", "[", "2", "]", ")", ";", "break", ";", "default", ":", "// have more than 2 given arguments", "hItem", ".", "h", ".", "apply", "(", "hItem", ".", "ctx", ",", "args", ")", ";", "break", ";", "}", "if", "(", "hItem", ".", "one", ")", "{", "_h", ".", "splice", "(", "i", ",", "1", ")", ";", "len", "--", ";", "}", "else", "{", "i", "++", ";", "}", "}", "}", "eventProcessor", "&&", "eventProcessor", ".", "afterTrigger", "&&", "eventProcessor", ".", "afterTrigger", "(", "type", ")", ";", "return", "this", ";", "}" ]
Dispatch a event. @param {string} type The event name.
[ "Dispatch", "a", "event", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L113-L168
3,522
ecomfe/zrender
src/dom/HandlerProxy.js
function (event) { event = normalizeEvent(this.dom, event); var element = event.toElement || event.relatedTarget; if (element !== this.dom) { while (element && element.nodeType !== 9) { // 忽略包含在root中的dom引起的mouseOut if (element === this.dom) { return; } element = element.parentNode; } } this.trigger('mouseout', event); }
javascript
function (event) { event = normalizeEvent(this.dom, event); var element = event.toElement || event.relatedTarget; if (element !== this.dom) { while (element && element.nodeType !== 9) { // 忽略包含在root中的dom引起的mouseOut if (element === this.dom) { return; } element = element.parentNode; } } this.trigger('mouseout', event); }
[ "function", "(", "event", ")", "{", "event", "=", "normalizeEvent", "(", "this", ".", "dom", ",", "event", ")", ";", "var", "element", "=", "event", ".", "toElement", "||", "event", ".", "relatedTarget", ";", "if", "(", "element", "!==", "this", ".", "dom", ")", "{", "while", "(", "element", "&&", "element", ".", "nodeType", "!==", "9", ")", "{", "// 忽略包含在root中的dom引起的mouseOut", "if", "(", "element", "===", "this", ".", "dom", ")", "{", "return", ";", "}", "element", "=", "element", ".", "parentNode", ";", "}", "}", "this", ".", "trigger", "(", "'mouseout'", ",", "event", ")", ";", "}" ]
Mouse out handler @inner @param {Event} event
[ "Mouse", "out", "handler" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/dom/HandlerProxy.js#L81-L97
3,523
ecomfe/zrender
src/core/PathProxy.js
function (x1, y1, x2, y2, x3, y3) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var t; var dx; var dy; var cubicAt = curve.cubicAt; var bezierLen = 0; var idx = this._dashIdx; var nDash = lineDash.length; var x; var y; var tmpLen = 0; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; // Bezier approx length for (t = 0; t < 1; t += 0.1) { dx = cubicAt(x0, x1, x2, x3, t + 0.1) - cubicAt(x0, x1, x2, x3, t); dy = cubicAt(y0, y1, y2, y3, t + 0.1) - cubicAt(y0, y1, y2, y3, t); bezierLen += mathSqrt(dx * dx + dy * dy); } // Find idx after add offset for (; idx < nDash; idx++) { tmpLen += lineDash[idx]; if (tmpLen > offset) { break; } } t = (tmpLen - offset) / bezierLen; while (t <= 1) { x = cubicAt(x0, x1, x2, x3, t); y = cubicAt(y0, y1, y2, y3, t); // Use line to approximate dashed bezier // Bad result if dash is long idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); t += lineDash[idx] / bezierLen; idx = (idx + 1) % nDash; } // Finish the last segment and calculate the new offset (idx % 2 !== 0) && ctx.lineTo(x3, y3); dx = x3 - x; dy = y3 - y; this._dashOffset = -mathSqrt(dx * dx + dy * dy); }
javascript
function (x1, y1, x2, y2, x3, y3) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var t; var dx; var dy; var cubicAt = curve.cubicAt; var bezierLen = 0; var idx = this._dashIdx; var nDash = lineDash.length; var x; var y; var tmpLen = 0; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; // Bezier approx length for (t = 0; t < 1; t += 0.1) { dx = cubicAt(x0, x1, x2, x3, t + 0.1) - cubicAt(x0, x1, x2, x3, t); dy = cubicAt(y0, y1, y2, y3, t + 0.1) - cubicAt(y0, y1, y2, y3, t); bezierLen += mathSqrt(dx * dx + dy * dy); } // Find idx after add offset for (; idx < nDash; idx++) { tmpLen += lineDash[idx]; if (tmpLen > offset) { break; } } t = (tmpLen - offset) / bezierLen; while (t <= 1) { x = cubicAt(x0, x1, x2, x3, t); y = cubicAt(y0, y1, y2, y3, t); // Use line to approximate dashed bezier // Bad result if dash is long idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); t += lineDash[idx] / bezierLen; idx = (idx + 1) % nDash; } // Finish the last segment and calculate the new offset (idx % 2 !== 0) && ctx.lineTo(x3, y3); dx = x3 - x; dy = y3 - y; this._dashOffset = -mathSqrt(dx * dx + dy * dy); }
[ "function", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ")", "{", "var", "dashSum", "=", "this", ".", "_dashSum", ";", "var", "offset", "=", "this", ".", "_dashOffset", ";", "var", "lineDash", "=", "this", ".", "_lineDash", ";", "var", "ctx", "=", "this", ".", "_ctx", ";", "var", "x0", "=", "this", ".", "_xi", ";", "var", "y0", "=", "this", ".", "_yi", ";", "var", "t", ";", "var", "dx", ";", "var", "dy", ";", "var", "cubicAt", "=", "curve", ".", "cubicAt", ";", "var", "bezierLen", "=", "0", ";", "var", "idx", "=", "this", ".", "_dashIdx", ";", "var", "nDash", "=", "lineDash", ".", "length", ";", "var", "x", ";", "var", "y", ";", "var", "tmpLen", "=", "0", ";", "if", "(", "offset", "<", "0", ")", "{", "// Convert to positive offset", "offset", "=", "dashSum", "+", "offset", ";", "}", "offset", "%=", "dashSum", ";", "// Bezier approx length", "for", "(", "t", "=", "0", ";", "t", "<", "1", ";", "t", "+=", "0.1", ")", "{", "dx", "=", "cubicAt", "(", "x0", ",", "x1", ",", "x2", ",", "x3", ",", "t", "+", "0.1", ")", "-", "cubicAt", "(", "x0", ",", "x1", ",", "x2", ",", "x3", ",", "t", ")", ";", "dy", "=", "cubicAt", "(", "y0", ",", "y1", ",", "y2", ",", "y3", ",", "t", "+", "0.1", ")", "-", "cubicAt", "(", "y0", ",", "y1", ",", "y2", ",", "y3", ",", "t", ")", ";", "bezierLen", "+=", "mathSqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "}", "// Find idx after add offset", "for", "(", ";", "idx", "<", "nDash", ";", "idx", "++", ")", "{", "tmpLen", "+=", "lineDash", "[", "idx", "]", ";", "if", "(", "tmpLen", ">", "offset", ")", "{", "break", ";", "}", "}", "t", "=", "(", "tmpLen", "-", "offset", ")", "/", "bezierLen", ";", "while", "(", "t", "<=", "1", ")", "{", "x", "=", "cubicAt", "(", "x0", ",", "x1", ",", "x2", ",", "x3", ",", "t", ")", ";", "y", "=", "cubicAt", "(", "y0", ",", "y1", ",", "y2", ",", "y3", ",", "t", ")", ";", "// Use line to approximate dashed bezier", "// Bad result if dash is long", "idx", "%", "2", "?", "ctx", ".", "moveTo", "(", "x", ",", "y", ")", ":", "ctx", ".", "lineTo", "(", "x", ",", "y", ")", ";", "t", "+=", "lineDash", "[", "idx", "]", "/", "bezierLen", ";", "idx", "=", "(", "idx", "+", "1", ")", "%", "nDash", ";", "}", "// Finish the last segment and calculate the new offset", "(", "idx", "%", "2", "!==", "0", ")", "&&", "ctx", ".", "lineTo", "(", "x3", ",", "y3", ")", ";", "dx", "=", "x3", "-", "x", ";", "dy", "=", "y3", "-", "y", ";", "this", ".", "_dashOffset", "=", "-", "mathSqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "}" ]
Not accurate dashed line to
[ "Not", "accurate", "dashed", "line", "to" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/core/PathProxy.js#L471-L535
3,524
ecomfe/zrender
src/graphic/Style.js
function (otherStyle, overwrite) { if (otherStyle) { for (var name in otherStyle) { if (otherStyle.hasOwnProperty(name) && (overwrite === true || ( overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null ) ) ) { this[name] = otherStyle[name]; } } } }
javascript
function (otherStyle, overwrite) { if (otherStyle) { for (var name in otherStyle) { if (otherStyle.hasOwnProperty(name) && (overwrite === true || ( overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null ) ) ) { this[name] = otherStyle[name]; } } } }
[ "function", "(", "otherStyle", ",", "overwrite", ")", "{", "if", "(", "otherStyle", ")", "{", "for", "(", "var", "name", "in", "otherStyle", ")", "{", "if", "(", "otherStyle", ".", "hasOwnProperty", "(", "name", ")", "&&", "(", "overwrite", "===", "true", "||", "(", "overwrite", "===", "false", "?", "!", "this", ".", "hasOwnProperty", "(", "name", ")", ":", "otherStyle", "[", "name", "]", "!=", "null", ")", ")", ")", "{", "this", "[", "name", "]", "=", "otherStyle", "[", "name", "]", ";", "}", "}", "}", "}" ]
Extend from other style @param {zrender/graphic/Style} otherStyle @param {boolean} overwrite true: overwrirte any way. false: overwrite only when !target.hasOwnProperty others: overwrite when property is not null/undefined.
[ "Extend", "from", "other", "style" ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/graphic/Style.js#L424-L440
3,525
ecomfe/zrender
build/babel-plugin-transform-modules-commonjs-ec.js
normalizeModuleAndLoadMetadata
function normalizeModuleAndLoadMetadata(programPath) { nameAnonymousExports(programPath); const {local, source} = getModuleMetadata(programPath); removeModuleDeclarations(programPath); // Reuse the imported namespace name if there is one. for (const [, metadata] of source) { if (metadata.importsNamespace.size > 0) { // This is kind of gross. If we stop using `loose: true` we should // just make this destructuring assignment. metadata.name = metadata.importsNamespace.values().next().value; } } return { exportName: 'exports', exportNameListName: null, local, source }; }
javascript
function normalizeModuleAndLoadMetadata(programPath) { nameAnonymousExports(programPath); const {local, source} = getModuleMetadata(programPath); removeModuleDeclarations(programPath); // Reuse the imported namespace name if there is one. for (const [, metadata] of source) { if (metadata.importsNamespace.size > 0) { // This is kind of gross. If we stop using `loose: true` we should // just make this destructuring assignment. metadata.name = metadata.importsNamespace.values().next().value; } } return { exportName: 'exports', exportNameListName: null, local, source }; }
[ "function", "normalizeModuleAndLoadMetadata", "(", "programPath", ")", "{", "nameAnonymousExports", "(", "programPath", ")", ";", "const", "{", "local", ",", "source", "}", "=", "getModuleMetadata", "(", "programPath", ")", ";", "removeModuleDeclarations", "(", "programPath", ")", ";", "// Reuse the imported namespace name if there is one.", "for", "(", "const", "[", ",", "metadata", "]", "of", "source", ")", "{", "if", "(", "metadata", ".", "importsNamespace", ".", "size", ">", "0", ")", "{", "// This is kind of gross. If we stop using `loose: true` we should", "// just make this destructuring assignment.", "metadata", ".", "name", "=", "metadata", ".", "importsNamespace", ".", "values", "(", ")", ".", "next", "(", ")", ".", "value", ";", "}", "}", "return", "{", "exportName", ":", "'exports'", ",", "exportNameListName", ":", "null", ",", "local", ",", "source", "}", ";", "}" ]
Remove all imports and exports from the file, and return all metadata needed to reconstruct the module's behavior. @return {ModuleMetadata}
[ "Remove", "all", "imports", "and", "exports", "from", "the", "file", "and", "return", "all", "metadata", "needed", "to", "reconstruct", "the", "module", "s", "behavior", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/build/babel-plugin-transform-modules-commonjs-ec.js#L70-L93
3,526
ecomfe/zrender
build/babel-plugin-transform-modules-commonjs-ec.js
nameAnonymousExports
function nameAnonymousExports(programPath) { // Name anonymous exported locals. programPath.get('body').forEach(child => { if (!child.isExportDefaultDeclaration()) { return; } // export default foo; const declaration = child.get('declaration'); if (declaration.isFunctionDeclaration()) { if (!declaration.node.id) { declaration.node.id = declaration.scope.generateUidIdentifier('default'); } } else if (declaration.isClassDeclaration()) { if (!declaration.node.id) { declaration.node.id = declaration.scope.generateUidIdentifier('default'); } } else { const id = declaration.scope.generateUidIdentifier('default'); const namedDecl = babelTypes.exportNamedDeclaration(null, [ babelTypes.exportSpecifier(babelTypes.identifier(id.name), babelTypes.identifier('default')), ]); namedDecl._blockHoist = child.node._blockHoist; const varDecl = babelTypes.variableDeclaration('var', [ babelTypes.variableDeclarator(id, declaration.node), ]); varDecl._blockHoist = child.node._blockHoist; child.replaceWithMultiple([namedDecl, varDecl]); } }); }
javascript
function nameAnonymousExports(programPath) { // Name anonymous exported locals. programPath.get('body').forEach(child => { if (!child.isExportDefaultDeclaration()) { return; } // export default foo; const declaration = child.get('declaration'); if (declaration.isFunctionDeclaration()) { if (!declaration.node.id) { declaration.node.id = declaration.scope.generateUidIdentifier('default'); } } else if (declaration.isClassDeclaration()) { if (!declaration.node.id) { declaration.node.id = declaration.scope.generateUidIdentifier('default'); } } else { const id = declaration.scope.generateUidIdentifier('default'); const namedDecl = babelTypes.exportNamedDeclaration(null, [ babelTypes.exportSpecifier(babelTypes.identifier(id.name), babelTypes.identifier('default')), ]); namedDecl._blockHoist = child.node._blockHoist; const varDecl = babelTypes.variableDeclaration('var', [ babelTypes.variableDeclarator(id, declaration.node), ]); varDecl._blockHoist = child.node._blockHoist; child.replaceWithMultiple([namedDecl, varDecl]); } }); }
[ "function", "nameAnonymousExports", "(", "programPath", ")", "{", "// Name anonymous exported locals.", "programPath", ".", "get", "(", "'body'", ")", ".", "forEach", "(", "child", "=>", "{", "if", "(", "!", "child", ".", "isExportDefaultDeclaration", "(", ")", ")", "{", "return", ";", "}", "// export default foo;", "const", "declaration", "=", "child", ".", "get", "(", "'declaration'", ")", ";", "if", "(", "declaration", ".", "isFunctionDeclaration", "(", ")", ")", "{", "if", "(", "!", "declaration", ".", "node", ".", "id", ")", "{", "declaration", ".", "node", ".", "id", "=", "declaration", ".", "scope", ".", "generateUidIdentifier", "(", "'default'", ")", ";", "}", "}", "else", "if", "(", "declaration", ".", "isClassDeclaration", "(", ")", ")", "{", "if", "(", "!", "declaration", ".", "node", ".", "id", ")", "{", "declaration", ".", "node", ".", "id", "=", "declaration", ".", "scope", ".", "generateUidIdentifier", "(", "'default'", ")", ";", "}", "}", "else", "{", "const", "id", "=", "declaration", ".", "scope", ".", "generateUidIdentifier", "(", "'default'", ")", ";", "const", "namedDecl", "=", "babelTypes", ".", "exportNamedDeclaration", "(", "null", ",", "[", "babelTypes", ".", "exportSpecifier", "(", "babelTypes", ".", "identifier", "(", "id", ".", "name", ")", ",", "babelTypes", ".", "identifier", "(", "'default'", ")", ")", ",", "]", ")", ";", "namedDecl", ".", "_blockHoist", "=", "child", ".", "node", ".", "_blockHoist", ";", "const", "varDecl", "=", "babelTypes", ".", "variableDeclaration", "(", "'var'", ",", "[", "babelTypes", ".", "variableDeclarator", "(", "id", ",", "declaration", ".", "node", ")", ",", "]", ")", ";", "varDecl", ".", "_blockHoist", "=", "child", ".", "node", ".", "_blockHoist", ";", "child", ".", "replaceWithMultiple", "(", "[", "namedDecl", ",", "varDecl", "]", ")", ";", "}", "}", ")", ";", "}" ]
Ensure that all exported values have local binding names.
[ "Ensure", "that", "all", "exported", "values", "have", "local", "binding", "names", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/build/babel-plugin-transform-modules-commonjs-ec.js#L368-L402
3,527
ecomfe/zrender
src/graphic/mixin/RectText.js
function (ctx, rect) { var style = this.style; rect = style.textRect || rect; // Optimize, avoid normalize every time. this.__dirty && textHelper.normalizeTextStyle(style, true); var text = style.text; // Convert to string text != null && (text += ''); if (!textHelper.needDrawText(text, style)) { return; } // FIXME // Do not provide prevEl to `textHelper.renderText` for ctx prop cache, // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect // text propably break the cache for its host elements. ctx.save(); // Transform rect to view space var transform = this.transform; if (!style.transformText) { if (transform) { tmpRect.copy(rect); tmpRect.applyTransform(transform); rect = tmpRect; } } else { this.setTransform(ctx); } // transformText and textRotation can not be used at the same time. textHelper.renderText(this, ctx, text, style, rect, WILL_BE_RESTORED); ctx.restore(); }
javascript
function (ctx, rect) { var style = this.style; rect = style.textRect || rect; // Optimize, avoid normalize every time. this.__dirty && textHelper.normalizeTextStyle(style, true); var text = style.text; // Convert to string text != null && (text += ''); if (!textHelper.needDrawText(text, style)) { return; } // FIXME // Do not provide prevEl to `textHelper.renderText` for ctx prop cache, // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect // text propably break the cache for its host elements. ctx.save(); // Transform rect to view space var transform = this.transform; if (!style.transformText) { if (transform) { tmpRect.copy(rect); tmpRect.applyTransform(transform); rect = tmpRect; } } else { this.setTransform(ctx); } // transformText and textRotation can not be used at the same time. textHelper.renderText(this, ctx, text, style, rect, WILL_BE_RESTORED); ctx.restore(); }
[ "function", "(", "ctx", ",", "rect", ")", "{", "var", "style", "=", "this", ".", "style", ";", "rect", "=", "style", ".", "textRect", "||", "rect", ";", "// Optimize, avoid normalize every time.", "this", ".", "__dirty", "&&", "textHelper", ".", "normalizeTextStyle", "(", "style", ",", "true", ")", ";", "var", "text", "=", "style", ".", "text", ";", "// Convert to string", "text", "!=", "null", "&&", "(", "text", "+=", "''", ")", ";", "if", "(", "!", "textHelper", ".", "needDrawText", "(", "text", ",", "style", ")", ")", "{", "return", ";", "}", "// FIXME", "// Do not provide prevEl to `textHelper.renderText` for ctx prop cache,", "// but use `ctx.save()` and `ctx.restore()`. Because the cache for rect", "// text propably break the cache for its host elements.", "ctx", ".", "save", "(", ")", ";", "// Transform rect to view space", "var", "transform", "=", "this", ".", "transform", ";", "if", "(", "!", "style", ".", "transformText", ")", "{", "if", "(", "transform", ")", "{", "tmpRect", ".", "copy", "(", "rect", ")", ";", "tmpRect", ".", "applyTransform", "(", "transform", ")", ";", "rect", "=", "tmpRect", ";", "}", "}", "else", "{", "this", ".", "setTransform", "(", "ctx", ")", ";", "}", "// transformText and textRotation can not be used at the same time.", "textHelper", ".", "renderText", "(", "this", ",", "ctx", ",", "text", ",", "style", ",", "rect", ",", "WILL_BE_RESTORED", ")", ";", "ctx", ".", "restore", "(", ")", ";", "}" ]
Draw text in a rect with specified position. @param {CanvasRenderingContext2D} ctx @param {Object} rect Displayable rect
[ "Draw", "text", "in", "a", "rect", "with", "specified", "position", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/graphic/mixin/RectText.js#L23-L63
3,528
ecomfe/zrender
src/Element.js
function (zr) { this.__zr = zr; // 添加动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.addAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.addSelfToZr(zr); } }
javascript
function (zr) { this.__zr = zr; // 添加动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.addAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.addSelfToZr(zr); } }
[ "function", "(", "zr", ")", "{", "this", ".", "__zr", "=", "zr", ";", "// 添加动画", "var", "animators", "=", "this", ".", "animators", ";", "if", "(", "animators", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "animators", ".", "length", ";", "i", "++", ")", "{", "zr", ".", "animation", ".", "addAnimator", "(", "animators", "[", "i", "]", ")", ";", "}", "}", "if", "(", "this", ".", "clipPath", ")", "{", "this", ".", "clipPath", ".", "addSelfToZr", "(", "zr", ")", ";", "}", "}" ]
Add self from zrender instance. Not recursively because it will be invoked when element added to storage. @param {module:zrender/ZRender} zr
[ "Add", "self", "from", "zrender", "instance", ".", "Not", "recursively", "because", "it", "will", "be", "invoked", "when", "element", "added", "to", "storage", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/Element.js#L222-L235
3,529
ecomfe/zrender
src/Element.js
function (zr) { this.__zr = null; // 移除动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.removeAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.removeSelfFromZr(zr); } }
javascript
function (zr) { this.__zr = null; // 移除动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.removeAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.removeSelfFromZr(zr); } }
[ "function", "(", "zr", ")", "{", "this", ".", "__zr", "=", "null", ";", "// 移除动画", "var", "animators", "=", "this", ".", "animators", ";", "if", "(", "animators", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "animators", ".", "length", ";", "i", "++", ")", "{", "zr", ".", "animation", ".", "removeAnimator", "(", "animators", "[", "i", "]", ")", ";", "}", "}", "if", "(", "this", ".", "clipPath", ")", "{", "this", ".", "clipPath", ".", "removeSelfFromZr", "(", "zr", ")", ";", "}", "}" ]
Remove self from zrender instance. Not recursively because it will be invoked when element added to storage. @param {module:zrender/ZRender} zr
[ "Remove", "self", "from", "zrender", "instance", ".", "Not", "recursively", "because", "it", "will", "be", "invoked", "when", "element", "added", "to", "storage", "." ]
30321b57cba3149c30eacb0c1e18276f0f001b9f
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/Element.js#L242-L255
3,530
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
getScrollParent
function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well const { overflow, overflowX, overflowY } = getStyleComputedProperty(element); if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); }
javascript
function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well const { overflow, overflowX, overflowY } = getStyleComputedProperty(element); if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); }
[ "function", "getScrollParent", "(", "element", ")", "{", "// Return body, `getScroll` will take care to get the correct `scrollTop` from it", "if", "(", "!", "element", ")", "{", "return", "document", ".", "body", ";", "}", "switch", "(", "element", ".", "nodeName", ")", "{", "case", "'HTML'", ":", "case", "'BODY'", ":", "return", "element", ".", "ownerDocument", ".", "body", ";", "case", "'#document'", ":", "return", "element", ".", "body", ";", "}", "// Firefox want us to check `-x` and `-y` variations as well", "const", "{", "overflow", ",", "overflowX", ",", "overflowY", "}", "=", "getStyleComputedProperty", "(", "element", ")", ";", "if", "(", "/", "(auto|scroll|overlay)", "/", ".", "test", "(", "overflow", "+", "overflowY", "+", "overflowX", ")", ")", "{", "return", "element", ";", "}", "return", "getScrollParent", "(", "getParentNode", "(", "element", ")", ")", ";", "}" ]
Returns the scrolling parent of the given element @method @memberof Popper.Utils @argument {Element} element @returns {Element} scroll parent
[ "Returns", "the", "scrolling", "parent", "of", "the", "given", "element" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L126-L147
3,531
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
getOffsetParent
function getOffsetParent(element) { if (!element) { return document.documentElement; } const noOffsetParent = isIE(10) ? document.body : null; // NOTE: 1 DOM access here let offsetParent = element.offsetParent || null; // Skip hidden elements which don't have an offsetParent while (offsetParent === noOffsetParent && element.nextElementSibling) { offsetParent = (element = element.nextElementSibling).offsetParent; } const nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return element ? element.ownerDocument.documentElement : document.documentElement; } // .offsetParent will return the closest TH, TD or TABLE in case // no offsetParent is present, I hate this job... if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; }
javascript
function getOffsetParent(element) { if (!element) { return document.documentElement; } const noOffsetParent = isIE(10) ? document.body : null; // NOTE: 1 DOM access here let offsetParent = element.offsetParent || null; // Skip hidden elements which don't have an offsetParent while (offsetParent === noOffsetParent && element.nextElementSibling) { offsetParent = (element = element.nextElementSibling).offsetParent; } const nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return element ? element.ownerDocument.documentElement : document.documentElement; } // .offsetParent will return the closest TH, TD or TABLE in case // no offsetParent is present, I hate this job... if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; }
[ "function", "getOffsetParent", "(", "element", ")", "{", "if", "(", "!", "element", ")", "{", "return", "document", ".", "documentElement", ";", "}", "const", "noOffsetParent", "=", "isIE", "(", "10", ")", "?", "document", ".", "body", ":", "null", ";", "// NOTE: 1 DOM access here", "let", "offsetParent", "=", "element", ".", "offsetParent", "||", "null", ";", "// Skip hidden elements which don't have an offsetParent", "while", "(", "offsetParent", "===", "noOffsetParent", "&&", "element", ".", "nextElementSibling", ")", "{", "offsetParent", "=", "(", "element", "=", "element", ".", "nextElementSibling", ")", ".", "offsetParent", ";", "}", "const", "nodeName", "=", "offsetParent", "&&", "offsetParent", ".", "nodeName", ";", "if", "(", "!", "nodeName", "||", "nodeName", "===", "'BODY'", "||", "nodeName", "===", "'HTML'", ")", "{", "return", "element", "?", "element", ".", "ownerDocument", ".", "documentElement", ":", "document", ".", "documentElement", ";", "}", "// .offsetParent will return the closest TH, TD or TABLE in case", "// no offsetParent is present, I hate this job...", "if", "(", "[", "'TH'", ",", "'TD'", ",", "'TABLE'", "]", ".", "indexOf", "(", "offsetParent", ".", "nodeName", ")", "!==", "-", "1", "&&", "getStyleComputedProperty", "(", "offsetParent", ",", "'position'", ")", "===", "'static'", ")", "{", "return", "getOffsetParent", "(", "offsetParent", ")", ";", "}", "return", "offsetParent", ";", "}" ]
Returns the offset parent of the given element @method @memberof Popper.Utils @argument {Element} element @returns {Element} offset parent
[ "Returns", "the", "offset", "parent", "of", "the", "given", "element" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L176-L203
3,532
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
findCommonOffsetParent
function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; const start = order ? element1 : element2; const end = order ? element2 : element1; // Get common ancestor container const range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); const { commonAncestorContainer } = range; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one const element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } }
javascript
function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; const start = order ? element1 : element2; const end = order ? element2 : element1; // Get common ancestor container const range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); const { commonAncestorContainer } = range; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one const element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } }
[ "function", "findCommonOffsetParent", "(", "element1", ",", "element2", ")", "{", "// This check is needed to avoid errors in case one of the elements isn't defined for any reason", "if", "(", "!", "element1", "||", "!", "element1", ".", "nodeType", "||", "!", "element2", "||", "!", "element2", ".", "nodeType", ")", "{", "return", "document", ".", "documentElement", ";", "}", "// Here we make sure to give as \"start\" the element that comes first in the DOM", "const", "order", "=", "element1", ".", "compareDocumentPosition", "(", "element2", ")", "&", "Node", ".", "DOCUMENT_POSITION_FOLLOWING", ";", "const", "start", "=", "order", "?", "element1", ":", "element2", ";", "const", "end", "=", "order", "?", "element2", ":", "element1", ";", "// Get common ancestor container", "const", "range", "=", "document", ".", "createRange", "(", ")", ";", "range", ".", "setStart", "(", "start", ",", "0", ")", ";", "range", ".", "setEnd", "(", "end", ",", "0", ")", ";", "const", "{", "commonAncestorContainer", "}", "=", "range", ";", "// Both nodes are inside #document", "if", "(", "element1", "!==", "commonAncestorContainer", "&&", "element2", "!==", "commonAncestorContainer", "||", "start", ".", "contains", "(", "end", ")", ")", "{", "if", "(", "isOffsetContainer", "(", "commonAncestorContainer", ")", ")", "{", "return", "commonAncestorContainer", ";", "}", "return", "getOffsetParent", "(", "commonAncestorContainer", ")", ";", "}", "// one of the nodes is inside shadowDOM, find which one", "const", "element1root", "=", "getRoot", "(", "element1", ")", ";", "if", "(", "element1root", ".", "host", ")", "{", "return", "findCommonOffsetParent", "(", "element1root", ".", "host", ",", "element2", ")", ";", "}", "else", "{", "return", "findCommonOffsetParent", "(", "element1", ",", "getRoot", "(", "element2", ")", ".", "host", ")", ";", "}", "}" ]
Finds the offset parent common to the two provided nodes @method @memberof Popper.Utils @argument {Element} element1 @argument {Element} element2 @returns {Element} common offset parent
[ "Finds", "the", "offset", "parent", "common", "to", "the", "two", "provided", "nodes" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L236-L269
3,533
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
computeAutoPlacement
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) { if (placement.indexOf('auto') === -1) { return placement; } const boundaries = getBoundaries(popper, reference, padding, boundariesElement); const rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; const sortedAreas = Object.keys(rects).map(key => _extends({ key }, rects[key], { area: getArea(rects[key]) })).sort((a, b) => b.area - a.area); const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight); const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; const variation = placement.split('-')[1]; return computedPlacement + (variation ? `-${variation}` : ''); }
javascript
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) { if (placement.indexOf('auto') === -1) { return placement; } const boundaries = getBoundaries(popper, reference, padding, boundariesElement); const rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; const sortedAreas = Object.keys(rects).map(key => _extends({ key }, rects[key], { area: getArea(rects[key]) })).sort((a, b) => b.area - a.area); const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight); const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; const variation = placement.split('-')[1]; return computedPlacement + (variation ? `-${variation}` : ''); }
[ "function", "computeAutoPlacement", "(", "placement", ",", "refRect", ",", "popper", ",", "reference", ",", "boundariesElement", ",", "padding", "=", "0", ")", "{", "if", "(", "placement", ".", "indexOf", "(", "'auto'", ")", "===", "-", "1", ")", "{", "return", "placement", ";", "}", "const", "boundaries", "=", "getBoundaries", "(", "popper", ",", "reference", ",", "padding", ",", "boundariesElement", ")", ";", "const", "rects", "=", "{", "top", ":", "{", "width", ":", "boundaries", ".", "width", ",", "height", ":", "refRect", ".", "top", "-", "boundaries", ".", "top", "}", ",", "right", ":", "{", "width", ":", "boundaries", ".", "right", "-", "refRect", ".", "right", ",", "height", ":", "boundaries", ".", "height", "}", ",", "bottom", ":", "{", "width", ":", "boundaries", ".", "width", ",", "height", ":", "boundaries", ".", "bottom", "-", "refRect", ".", "bottom", "}", ",", "left", ":", "{", "width", ":", "refRect", ".", "left", "-", "boundaries", ".", "left", ",", "height", ":", "boundaries", ".", "height", "}", "}", ";", "const", "sortedAreas", "=", "Object", ".", "keys", "(", "rects", ")", ".", "map", "(", "key", "=>", "_extends", "(", "{", "key", "}", ",", "rects", "[", "key", "]", ",", "{", "area", ":", "getArea", "(", "rects", "[", "key", "]", ")", "}", ")", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "b", ".", "area", "-", "a", ".", "area", ")", ";", "const", "filteredAreas", "=", "sortedAreas", ".", "filter", "(", "(", "{", "width", ",", "height", "}", ")", "=>", "width", ">=", "popper", ".", "clientWidth", "&&", "height", ">=", "popper", ".", "clientHeight", ")", ";", "const", "computedPlacement", "=", "filteredAreas", ".", "length", ">", "0", "?", "filteredAreas", "[", "0", "]", ".", "key", ":", "sortedAreas", "[", "0", "]", ".", "key", ";", "const", "variation", "=", "placement", ".", "split", "(", "'-'", ")", "[", "1", "]", ";", "return", "computedPlacement", "+", "(", "variation", "?", "`", "${", "variation", "}", "`", ":", "''", ")", ";", "}" ]
Utility used to transform the `auto` placement to the placement with more available space. @method @memberof Popper.Utils @argument {Object} data - The data object generated by update method @argument {Object} options - Modifiers configuration and options @returns {Object} The data object, properly modified
[ "Utility", "used", "to", "transform", "the", "auto", "placement", "to", "the", "placement", "with", "more", "available", "space", "." ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L613-L652
3,534
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
getOppositePlacement
function getOppositePlacement(placement) { const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, matched => hash[matched]); }
javascript
function getOppositePlacement(placement) { const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, matched => hash[matched]); }
[ "function", "getOppositePlacement", "(", "placement", ")", "{", "const", "hash", "=", "{", "left", ":", "'right'", ",", "right", ":", "'left'", ",", "bottom", ":", "'top'", ",", "top", ":", "'bottom'", "}", ";", "return", "placement", ".", "replace", "(", "/", "left|right|bottom|top", "/", "g", ",", "matched", "=>", "hash", "[", "matched", "]", ")", ";", "}" ]
Get the opposite placement of the given one @method @memberof Popper.Utils @argument {String} placement @returns {String} flipped placement
[ "Get", "the", "opposite", "placement", "of", "the", "given", "one" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L695-L698
3,535
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
getPopperOffsets
function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes const popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object const popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently const isHoriz = ['right', 'left'].indexOf(placement) !== -1; const mainSide = isHoriz ? 'top' : 'left'; const secondarySide = isHoriz ? 'left' : 'top'; const measurement = isHoriz ? 'height' : 'width'; const secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; }
javascript
function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes const popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object const popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently const isHoriz = ['right', 'left'].indexOf(placement) !== -1; const mainSide = isHoriz ? 'top' : 'left'; const secondarySide = isHoriz ? 'left' : 'top'; const measurement = isHoriz ? 'height' : 'width'; const secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; }
[ "function", "getPopperOffsets", "(", "popper", ",", "referenceOffsets", ",", "placement", ")", "{", "placement", "=", "placement", ".", "split", "(", "'-'", ")", "[", "0", "]", ";", "// Get popper node sizes", "const", "popperRect", "=", "getOuterSizes", "(", "popper", ")", ";", "// Add position, width and height to our offsets object", "const", "popperOffsets", "=", "{", "width", ":", "popperRect", ".", "width", ",", "height", ":", "popperRect", ".", "height", "}", ";", "// depending by the popper placement we have to compute its offsets slightly differently", "const", "isHoriz", "=", "[", "'right'", ",", "'left'", "]", ".", "indexOf", "(", "placement", ")", "!==", "-", "1", ";", "const", "mainSide", "=", "isHoriz", "?", "'top'", ":", "'left'", ";", "const", "secondarySide", "=", "isHoriz", "?", "'left'", ":", "'top'", ";", "const", "measurement", "=", "isHoriz", "?", "'height'", ":", "'width'", ";", "const", "secondaryMeasurement", "=", "!", "isHoriz", "?", "'height'", ":", "'width'", ";", "popperOffsets", "[", "mainSide", "]", "=", "referenceOffsets", "[", "mainSide", "]", "+", "referenceOffsets", "[", "measurement", "]", "/", "2", "-", "popperRect", "[", "measurement", "]", "/", "2", ";", "if", "(", "placement", "===", "secondarySide", ")", "{", "popperOffsets", "[", "secondarySide", "]", "=", "referenceOffsets", "[", "secondarySide", "]", "-", "popperRect", "[", "secondaryMeasurement", "]", ";", "}", "else", "{", "popperOffsets", "[", "secondarySide", "]", "=", "referenceOffsets", "[", "getOppositePlacement", "(", "secondarySide", ")", "]", ";", "}", "return", "popperOffsets", ";", "}" ]
Get offsets to the popper @method @memberof Popper.Utils @param {Object} position - CSS position the Popper will get applied @param {HTMLElement} popper - the popper element @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) @param {String} placement - one of the valid placement options @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
[ "Get", "offsets", "to", "the", "popper" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L710-L737
3,536
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
isModifierEnabled
function isModifierEnabled(modifiers, modifierName) { return modifiers.some(({ name, enabled }) => enabled && name === modifierName); }
javascript
function isModifierEnabled(modifiers, modifierName) { return modifiers.some(({ name, enabled }) => enabled && name === modifierName); }
[ "function", "isModifierEnabled", "(", "modifiers", ",", "modifierName", ")", "{", "return", "modifiers", ".", "some", "(", "(", "{", "name", ",", "enabled", "}", ")", "=>", "enabled", "&&", "name", "===", "modifierName", ")", ";", "}" ]
Helper used to know if the given modifier is enabled. @method @memberof Popper.Utils @returns {Boolean}
[ "Helper", "used", "to", "know", "if", "the", "given", "modifier", "is", "enabled", "." ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L870-L872
3,537
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
getSupportedPropertyName
function getSupportedPropertyName(property) { const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; const upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (let i = 0; i < prefixes.length; i++) { const prefix = prefixes[i]; const toCheck = prefix ? `${prefix}${upperProp}` : property; if (typeof document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; }
javascript
function getSupportedPropertyName(property) { const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; const upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (let i = 0; i < prefixes.length; i++) { const prefix = prefixes[i]; const toCheck = prefix ? `${prefix}${upperProp}` : property; if (typeof document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; }
[ "function", "getSupportedPropertyName", "(", "property", ")", "{", "const", "prefixes", "=", "[", "false", ",", "'ms'", ",", "'Webkit'", ",", "'Moz'", ",", "'O'", "]", ";", "const", "upperProp", "=", "property", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "property", ".", "slice", "(", "1", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "prefixes", ".", "length", ";", "i", "++", ")", "{", "const", "prefix", "=", "prefixes", "[", "i", "]", ";", "const", "toCheck", "=", "prefix", "?", "`", "${", "prefix", "}", "${", "upperProp", "}", "`", ":", "property", ";", "if", "(", "typeof", "document", ".", "body", ".", "style", "[", "toCheck", "]", "!==", "'undefined'", ")", "{", "return", "toCheck", ";", "}", "}", "return", "null", ";", "}" ]
Get the prefixed supported property name @method @memberof Popper.Utils @argument {String} property (camelCase) @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
[ "Get", "the", "prefixed", "supported", "property", "name" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L881-L893
3,538
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
applyStyleOnLoad
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets const referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); return options; }
javascript
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets const referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); return options; }
[ "function", "applyStyleOnLoad", "(", "reference", ",", "popper", ",", "options", ",", "modifierOptions", ",", "state", ")", "{", "// compute reference element offsets", "const", "referenceOffsets", "=", "getReferenceOffsets", "(", "state", ",", "popper", ",", "reference", ",", "options", ".", "positionFixed", ")", ";", "// compute auto placement, store placement inside the data object,", "// modifiers will be able to edit `placement` if needed", "// and refer to originalPlacement to know the original value", "const", "placement", "=", "computeAutoPlacement", "(", "options", ".", "placement", ",", "referenceOffsets", ",", "popper", ",", "reference", ",", "options", ".", "modifiers", ".", "flip", ".", "boundariesElement", ",", "options", ".", "modifiers", ".", "flip", ".", "padding", ")", ";", "popper", ".", "setAttribute", "(", "'x-placement'", ",", "placement", ")", ";", "// Apply `position` to popper before anything else because", "// without the position applied we can't guarantee correct computations", "setStyles", "(", "popper", ",", "{", "position", ":", "options", ".", "positionFixed", "?", "'fixed'", ":", "'absolute'", "}", ")", ";", "return", "options", ";", "}" ]
Set the x-placement attribute before everything else because it could be used to add margins to the popper margins needs to be calculated to get the correct popper offsets. @method @memberof Popper.modifiers @param {HTMLElement} reference - The reference element used to position the popper @param {HTMLElement} popper - The HTML element used as popper @param {Object} options - Popper.js options
[ "Set", "the", "x", "-", "placement", "attribute", "before", "everything", "else", "because", "it", "could", "be", "used", "to", "add", "margins", "to", "the", "popper", "margins", "needs", "to", "be", "calculated", "to", "get", "the", "correct", "popper", "offsets", "." ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L1102-L1118
3,539
thomaspark/bootswatch
docs/_vendor/popper.js/dist/popper.js
parseOffset
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { const offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim()); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1)); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. const splitRegex = /\s*,\s*|\s+/; let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map((op, index) => { // Most of the units rely on the orientation of the popper const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; let mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce((a, b) => { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(str => toValue(str, measurement, popperOffsets, referenceOffsets)); }); // Loop trough the offsets arrays and execute the operations ops.forEach((op, index) => { op.forEach((frag, index2) => { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; }
javascript
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { const offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim()); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1)); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. const splitRegex = /\s*,\s*|\s+/; let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map((op, index) => { // Most of the units rely on the orientation of the popper const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; let mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce((a, b) => { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(str => toValue(str, measurement, popperOffsets, referenceOffsets)); }); // Loop trough the offsets arrays and execute the operations ops.forEach((op, index) => { op.forEach((frag, index2) => { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; }
[ "function", "parseOffset", "(", "offset", ",", "popperOffsets", ",", "referenceOffsets", ",", "basePlacement", ")", "{", "const", "offsets", "=", "[", "0", ",", "0", "]", ";", "// Use height if placement is left or right and index is 0 otherwise use width", "// in this way the first offset will use an axis and the second one", "// will use the other one", "const", "useHeight", "=", "[", "'right'", ",", "'left'", "]", ".", "indexOf", "(", "basePlacement", ")", "!==", "-", "1", ";", "// Split the offset string to obtain a list of values and operands", "// The regex addresses values with the plus or minus sign in front (+10, -20, etc)", "const", "fragments", "=", "offset", ".", "split", "(", "/", "(\\+|\\-)", "/", ")", ".", "map", "(", "frag", "=>", "frag", ".", "trim", "(", ")", ")", ";", "// Detect if the offset string contains a pair of values or a single one", "// they could be separated by comma or space", "const", "divider", "=", "fragments", ".", "indexOf", "(", "find", "(", "fragments", ",", "frag", "=>", "frag", ".", "search", "(", "/", ",|\\s", "/", ")", "!==", "-", "1", ")", ")", ";", "if", "(", "fragments", "[", "divider", "]", "&&", "fragments", "[", "divider", "]", ".", "indexOf", "(", "','", ")", "===", "-", "1", ")", "{", "console", ".", "warn", "(", "'Offsets separated by white space(s) are deprecated, use a comma (,) instead.'", ")", ";", "}", "// If divider is found, we divide the list of values and operands to divide", "// them by ofset X and Y.", "const", "splitRegex", "=", "/", "\\s*,\\s*|\\s+", "/", ";", "let", "ops", "=", "divider", "!==", "-", "1", "?", "[", "fragments", ".", "slice", "(", "0", ",", "divider", ")", ".", "concat", "(", "[", "fragments", "[", "divider", "]", ".", "split", "(", "splitRegex", ")", "[", "0", "]", "]", ")", ",", "[", "fragments", "[", "divider", "]", ".", "split", "(", "splitRegex", ")", "[", "1", "]", "]", ".", "concat", "(", "fragments", ".", "slice", "(", "divider", "+", "1", ")", ")", "]", ":", "[", "fragments", "]", ";", "// Convert the values with units to absolute pixels to allow our computations", "ops", "=", "ops", ".", "map", "(", "(", "op", ",", "index", ")", "=>", "{", "// Most of the units rely on the orientation of the popper", "const", "measurement", "=", "(", "index", "===", "1", "?", "!", "useHeight", ":", "useHeight", ")", "?", "'height'", ":", "'width'", ";", "let", "mergeWithPrevious", "=", "false", ";", "return", "op", "// This aggregates any `+` or `-` sign that aren't considered operators", "// e.g.: 10 + +5 => [10, +, +5]", ".", "reduce", "(", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "a", "[", "a", ".", "length", "-", "1", "]", "===", "''", "&&", "[", "'+'", ",", "'-'", "]", ".", "indexOf", "(", "b", ")", "!==", "-", "1", ")", "{", "a", "[", "a", ".", "length", "-", "1", "]", "=", "b", ";", "mergeWithPrevious", "=", "true", ";", "return", "a", ";", "}", "else", "if", "(", "mergeWithPrevious", ")", "{", "a", "[", "a", ".", "length", "-", "1", "]", "+=", "b", ";", "mergeWithPrevious", "=", "false", ";", "return", "a", ";", "}", "else", "{", "return", "a", ".", "concat", "(", "b", ")", ";", "}", "}", ",", "[", "]", ")", "// Here we convert the string values into number values (in px)", ".", "map", "(", "str", "=>", "toValue", "(", "str", ",", "measurement", ",", "popperOffsets", ",", "referenceOffsets", ")", ")", ";", "}", ")", ";", "// Loop trough the offsets arrays and execute the operations", "ops", ".", "forEach", "(", "(", "op", ",", "index", ")", "=>", "{", "op", ".", "forEach", "(", "(", "frag", ",", "index2", ")", "=>", "{", "if", "(", "isNumeric", "(", "frag", ")", ")", "{", "offsets", "[", "index", "]", "+=", "frag", "*", "(", "op", "[", "index2", "-", "1", "]", "===", "'-'", "?", "-", "1", ":", "1", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "offsets", ";", "}" ]
Parse an `offset` string to extrapolate `x` and `y` numeric offsets. @function @memberof {modifiers~offset} @private @argument {String} offset @argument {Object} popperOffsets @argument {Object} referenceOffsets @argument {String} basePlacement @returns {Array} a two cells array with x and y offsets in numbers
[ "Parse", "an", "offset", "string", "to", "extrapolate", "x", "and", "y", "numeric", "offsets", "." ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L1617-L1676
3,540
thomaspark/bootswatch
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
addElements
function addElements(newElements, ownerDocument) { var elements = html5.elements; if(typeof elements != 'string'){ elements = elements.join(' '); } if(typeof newElements != 'string'){ newElements = newElements.join(' '); } html5.elements = elements +' '+ newElements; shivDocument(ownerDocument); }
javascript
function addElements(newElements, ownerDocument) { var elements = html5.elements; if(typeof elements != 'string'){ elements = elements.join(' '); } if(typeof newElements != 'string'){ newElements = newElements.join(' '); } html5.elements = elements +' '+ newElements; shivDocument(ownerDocument); }
[ "function", "addElements", "(", "newElements", ",", "ownerDocument", ")", "{", "var", "elements", "=", "html5", ".", "elements", ";", "if", "(", "typeof", "elements", "!=", "'string'", ")", "{", "elements", "=", "elements", ".", "join", "(", "' '", ")", ";", "}", "if", "(", "typeof", "newElements", "!=", "'string'", ")", "{", "newElements", "=", "newElements", ".", "join", "(", "' '", ")", ";", "}", "html5", ".", "elements", "=", "elements", "+", "' '", "+", "newElements", ";", "shivDocument", "(", "ownerDocument", ")", ";", "}" ]
Extends the built-in list of html5 elements @memberOf html5 @param {String|Array} newElements whitespace separated list or array of new element names to shiv @param {Document} ownerDocument The context document.
[ "Extends", "the", "built", "-", "in", "list", "of", "html5", "elements" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L91-L101
3,541
thomaspark/bootswatch
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
getExpandoData
function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; }
javascript
function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; }
[ "function", "getExpandoData", "(", "ownerDocument", ")", "{", "var", "data", "=", "expandoData", "[", "ownerDocument", "[", "expando", "]", "]", ";", "if", "(", "!", "data", ")", "{", "data", "=", "{", "}", ";", "expanID", "++", ";", "ownerDocument", "[", "expando", "]", "=", "expanID", ";", "expandoData", "[", "expanID", "]", "=", "data", ";", "}", "return", "data", ";", "}" ]
Returns the data associated to the given document @private @param {Document} ownerDocument The document. @returns {Object} An object of data.
[ "Returns", "the", "data", "associated", "to", "the", "given", "document" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L109-L118
3,542
thomaspark/bootswatch
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
createElement
function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; }
javascript
function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; }
[ "function", "createElement", "(", "nodeName", ",", "ownerDocument", ",", "data", ")", "{", "if", "(", "!", "ownerDocument", ")", "{", "ownerDocument", "=", "document", ";", "}", "if", "(", "supportsUnknownElements", ")", "{", "return", "ownerDocument", ".", "createElement", "(", "nodeName", ")", ";", "}", "if", "(", "!", "data", ")", "{", "data", "=", "getExpandoData", "(", "ownerDocument", ")", ";", "}", "var", "node", ";", "if", "(", "data", ".", "cache", "[", "nodeName", "]", ")", "{", "node", "=", "data", ".", "cache", "[", "nodeName", "]", ".", "cloneNode", "(", ")", ";", "}", "else", "if", "(", "saveClones", ".", "test", "(", "nodeName", ")", ")", "{", "node", "=", "(", "data", ".", "cache", "[", "nodeName", "]", "=", "data", ".", "createElem", "(", "nodeName", ")", ")", ".", "cloneNode", "(", ")", ";", "}", "else", "{", "node", "=", "data", ".", "createElem", "(", "nodeName", ")", ";", "}", "// Avoid adding some elements to fragments in IE < 9 because", "// * Attributes like `name` or `type` cannot be set/changed once an element", "// is inserted into a document/fragment", "// * Link elements with `src` attributes that are inaccessible, as with", "// a 403 response, will cause the tab/window to crash", "// * Script elements appended to fragments will execute when their `src`", "// or `text` property is set", "return", "node", ".", "canHaveChildren", "&&", "!", "reSkip", ".", "test", "(", "nodeName", ")", "&&", "!", "node", ".", "tagUrn", "?", "data", ".", "frag", ".", "appendChild", "(", "node", ")", ":", "node", ";", "}" ]
returns a shived element for the given nodeName and document @memberOf html5 @param {String} nodeName name of the element @param {Document} ownerDocument The context document. @returns {Object} The shived element.
[ "returns", "a", "shived", "element", "for", "the", "given", "nodeName", "and", "document" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L127-L155
3,543
thomaspark/bootswatch
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
createDocumentFragment
function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; }
javascript
function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; }
[ "function", "createDocumentFragment", "(", "ownerDocument", ",", "data", ")", "{", "if", "(", "!", "ownerDocument", ")", "{", "ownerDocument", "=", "document", ";", "}", "if", "(", "supportsUnknownElements", ")", "{", "return", "ownerDocument", ".", "createDocumentFragment", "(", ")", ";", "}", "data", "=", "data", "||", "getExpandoData", "(", "ownerDocument", ")", ";", "var", "clone", "=", "data", ".", "frag", ".", "cloneNode", "(", ")", ",", "i", "=", "0", ",", "elems", "=", "getElements", "(", ")", ",", "l", "=", "elems", ".", "length", ";", "for", "(", ";", "i", "<", "l", ";", "i", "++", ")", "{", "clone", ".", "createElement", "(", "elems", "[", "i", "]", ")", ";", "}", "return", "clone", ";", "}" ]
returns a shived DocumentFragment for the given document @memberOf html5 @param {Document} ownerDocument The context document. @returns {Object} The shived DocumentFragment.
[ "returns", "a", "shived", "DocumentFragment", "for", "the", "given", "document" ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L163-L179
3,544
thomaspark/bootswatch
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
createWrapper
function createWrapper(element) { var node, nodes = element.attributes, index = nodes.length, wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName); // copy element attributes to the wrapper while (index--) { node = nodes[index]; node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue); } // copy element styles to the wrapper wrapper.style.cssText = element.style.cssText; return wrapper; }
javascript
function createWrapper(element) { var node, nodes = element.attributes, index = nodes.length, wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName); // copy element attributes to the wrapper while (index--) { node = nodes[index]; node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue); } // copy element styles to the wrapper wrapper.style.cssText = element.style.cssText; return wrapper; }
[ "function", "createWrapper", "(", "element", ")", "{", "var", "node", ",", "nodes", "=", "element", ".", "attributes", ",", "index", "=", "nodes", ".", "length", ",", "wrapper", "=", "element", ".", "ownerDocument", ".", "createElement", "(", "shivNamespace", "+", "':'", "+", "element", ".", "nodeName", ")", ";", "// copy element attributes to the wrapper", "while", "(", "index", "--", ")", "{", "node", "=", "nodes", "[", "index", "]", ";", "node", ".", "specified", "&&", "wrapper", ".", "setAttribute", "(", "node", ".", "nodeName", ",", "node", ".", "nodeValue", ")", ";", "}", "// copy element styles to the wrapper", "wrapper", ".", "style", ".", "cssText", "=", "element", ".", "style", ".", "cssText", ";", "return", "wrapper", ";", "}" ]
Creates a printable wrapper for the given element. @private @param {Element} element The element. @returns {Element} The wrapper.
[ "Creates", "a", "printable", "wrapper", "for", "the", "given", "element", "." ]
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L374-L388
3,545
spencermountain/compromise
src/terms/index.js
function(arr, world, refText, refTerms) { this.terms = arr; this.world = world || w; this.refText = refText; this._refTerms = refTerms; this.get = n => { return this.terms[n]; }; //apply getters let keys = Object.keys(getters); for (let i = 0; i < keys.length; i++) { Object.defineProperty(this, keys[i], getters[keys[i]]); } }
javascript
function(arr, world, refText, refTerms) { this.terms = arr; this.world = world || w; this.refText = refText; this._refTerms = refTerms; this.get = n => { return this.terms[n]; }; //apply getters let keys = Object.keys(getters); for (let i = 0; i < keys.length; i++) { Object.defineProperty(this, keys[i], getters[keys[i]]); } }
[ "function", "(", "arr", ",", "world", ",", "refText", ",", "refTerms", ")", "{", "this", ".", "terms", "=", "arr", ";", "this", ".", "world", "=", "world", "||", "w", ";", "this", ".", "refText", "=", "refText", ";", "this", ".", "_refTerms", "=", "refTerms", ";", "this", ".", "get", "=", "n", "=>", "{", "return", "this", ".", "terms", "[", "n", "]", ";", "}", ";", "//apply getters", "let", "keys", "=", "Object", ".", "keys", "(", "getters", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "keys", "[", "i", "]", ",", "getters", "[", "keys", "[", "i", "]", "]", ")", ";", "}", "}" ]
Terms is an array of Term objects, and methods that wrap around them
[ "Terms", "is", "an", "array", "of", "Term", "objects", "and", "methods", "that", "wrap", "around", "them" ]
526b1cab28a45ccbb430fbf2824db420acd587cf
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/terms/index.js#L7-L20
3,546
spencermountain/compromise
src/text/methods/sort/methods.js
function(arr) { arr = arr.sort((a, b) => { if (a.index > b.index) { return 1; } if (a.index === b.index) { return 0; } return -1; }); //return ts objects return arr.map((o) => o.ts); }
javascript
function(arr) { arr = arr.sort((a, b) => { if (a.index > b.index) { return 1; } if (a.index === b.index) { return 0; } return -1; }); //return ts objects return arr.map((o) => o.ts); }
[ "function", "(", "arr", ")", "{", "arr", "=", "arr", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "{", "if", "(", "a", ".", "index", ">", "b", ".", "index", ")", "{", "return", "1", ";", "}", "if", "(", "a", ".", "index", "===", "b", ".", "index", ")", "{", "return", "0", ";", "}", "return", "-", "1", ";", "}", ")", ";", "//return ts objects", "return", "arr", ".", "map", "(", "(", "o", ")", "=>", "o", ".", "ts", ")", ";", "}" ]
perform sort on pre-computed values
[ "perform", "sort", "on", "pre", "-", "computed", "values" ]
526b1cab28a45ccbb430fbf2824db420acd587cf
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/text/methods/sort/methods.js#L4-L16
3,547
spencermountain/compromise
src/index.js
function(str, lex) { if (lex) { w.plugin({ words: lex }); } let doc = buildText(str, w); doc.tagger(); return doc; }
javascript
function(str, lex) { if (lex) { w.plugin({ words: lex }); } let doc = buildText(str, w); doc.tagger(); return doc; }
[ "function", "(", "str", ",", "lex", ")", "{", "if", "(", "lex", ")", "{", "w", ".", "plugin", "(", "{", "words", ":", "lex", "}", ")", ";", "}", "let", "doc", "=", "buildText", "(", "str", ",", "w", ")", ";", "doc", ".", "tagger", "(", ")", ";", "return", "doc", ";", "}" ]
the main function
[ "the", "main", "function" ]
526b1cab28a45ccbb430fbf2824db420acd587cf
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/index.js#L10-L19
3,548
spencermountain/compromise
src/index.js
function(str, lex) { if (lex) { w2.plugin({ words: lex }); } let doc = buildText(str, w2); doc.tagger(); return doc; }
javascript
function(str, lex) { if (lex) { w2.plugin({ words: lex }); } let doc = buildText(str, w2); doc.tagger(); return doc; }
[ "function", "(", "str", ",", "lex", ")", "{", "if", "(", "lex", ")", "{", "w2", ".", "plugin", "(", "{", "words", ":", "lex", "}", ")", ";", "}", "let", "doc", "=", "buildText", "(", "str", ",", "w2", ")", ";", "doc", ".", "tagger", "(", ")", ";", "return", "doc", ";", "}" ]
this is weird, but it's okay
[ "this", "is", "weird", "but", "it", "s", "okay" ]
526b1cab28a45ccbb430fbf2824db420acd587cf
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/index.js#L76-L85
3,549
google/code-prettify
js-modules/prettify.js
registerLangHandler
function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if (win['console']) { console['warn']('cannot override language handler %s', ext); } } }
javascript
function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if (win['console']) { console['warn']('cannot override language handler %s', ext); } } }
[ "function", "registerLangHandler", "(", "handler", ",", "fileExtensions", ")", "{", "for", "(", "var", "i", "=", "fileExtensions", ".", "length", ";", "--", "i", ">=", "0", ";", ")", "{", "var", "ext", "=", "fileExtensions", "[", "i", "]", ";", "if", "(", "!", "langHandlerRegistry", ".", "hasOwnProperty", "(", "ext", ")", ")", "{", "langHandlerRegistry", "[", "ext", "]", "=", "handler", ";", "}", "else", "if", "(", "win", "[", "'console'", "]", ")", "{", "console", "[", "'warn'", "]", "(", "'cannot override language handler %s'", ",", "ext", ")", ";", "}", "}", "}" ]
Register a language handler for the given file extensions. @param {function (JobT)} handler a function from source code to a list of decorations. Takes a single argument job which describes the state of the computation and attaches the decorations to it. @param {Array.<string>} fileExtensions
[ "Register", "a", "language", "handler", "for", "the", "given", "file", "extensions", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/prettify.js#L679-L688
3,550
google/code-prettify
js-modules/prettify.js
$prettyPrintOne
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) { /** @type{number|boolean} */ var nl = opt_numberLines || false; /** @type{string|null} */ var langExtension = opt_langExtension || null; /** @type{!Element} */ var container = document.createElement('div'); // This could cause images to load and onload listeners to fire. // E.g. <img onerror="alert(1337)" src="nosuchimage.png">. // We assume that the inner HTML is from a trusted source. // The pre-tag is required for IE8 which strips newlines from innerHTML // when it is injected into a <pre> tag. // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>'; container = /** @type{!Element} */(container.firstChild); if (nl) { numberLines(container, nl, true); } /** @type{JobT} */ var job = { langExtension: langExtension, numberLines: nl, sourceNode: container, pre: 1, sourceCode: null, basePos: null, spans: null, decorations: null }; applyDecorator(job); return container.innerHTML; }
javascript
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) { /** @type{number|boolean} */ var nl = opt_numberLines || false; /** @type{string|null} */ var langExtension = opt_langExtension || null; /** @type{!Element} */ var container = document.createElement('div'); // This could cause images to load and onload listeners to fire. // E.g. <img onerror="alert(1337)" src="nosuchimage.png">. // We assume that the inner HTML is from a trusted source. // The pre-tag is required for IE8 which strips newlines from innerHTML // when it is injected into a <pre> tag. // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>'; container = /** @type{!Element} */(container.firstChild); if (nl) { numberLines(container, nl, true); } /** @type{JobT} */ var job = { langExtension: langExtension, numberLines: nl, sourceNode: container, pre: 1, sourceCode: null, basePos: null, spans: null, decorations: null }; applyDecorator(job); return container.innerHTML; }
[ "function", "$prettyPrintOne", "(", "sourceCodeHtml", ",", "opt_langExtension", ",", "opt_numberLines", ")", "{", "/** @type{number|boolean} */", "var", "nl", "=", "opt_numberLines", "||", "false", ";", "/** @type{string|null} */", "var", "langExtension", "=", "opt_langExtension", "||", "null", ";", "/** @type{!Element} */", "var", "container", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "// This could cause images to load and onload listeners to fire.", "// E.g. <img onerror=\"alert(1337)\" src=\"nosuchimage.png\">.", "// We assume that the inner HTML is from a trusted source.", "// The pre-tag is required for IE8 which strips newlines from innerHTML", "// when it is injected into a <pre> tag.", "// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie", "// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript", "container", ".", "innerHTML", "=", "'<pre>'", "+", "sourceCodeHtml", "+", "'</pre>'", ";", "container", "=", "/** @type{!Element} */", "(", "container", ".", "firstChild", ")", ";", "if", "(", "nl", ")", "{", "numberLines", "(", "container", ",", "nl", ",", "true", ")", ";", "}", "/** @type{JobT} */", "var", "job", "=", "{", "langExtension", ":", "langExtension", ",", "numberLines", ":", "nl", ",", "sourceNode", ":", "container", ",", "pre", ":", "1", ",", "sourceCode", ":", "null", ",", "basePos", ":", "null", ",", "spans", ":", "null", ",", "decorations", ":", "null", "}", ";", "applyDecorator", "(", "job", ")", ";", "return", "container", ".", "innerHTML", ";", "}" ]
Pretty print a chunk of code. @param sourceCodeHtml {string} The HTML to pretty print. @param opt_langExtension {string} The language name to use. Typically, a filename extension like 'cpp' or 'java'. @param opt_numberLines {number|boolean} True to number lines, or the 1-indexed number of the first line in sourceCodeHtml.
[ "Pretty", "print", "a", "chunk", "of", "code", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/prettify.js#L833-L866
3,551
google/code-prettify
js-modules/run_prettify.js
loadStylesheetsFallingBack
function loadStylesheetsFallingBack(stylesheets) { var n = stylesheets.length; function load(i) { if (i === n) { return; } var link = doc.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; if (i + 1 < n) { // http://pieisgood.org/test/script-link-events/ indicates that many // versions of IE do not support onerror on <link>s, though // http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx // indicates that recent IEs do support error. link.error = link.onerror = function () { load(i + 1); }; } link.href = stylesheets[i]; head.appendChild(link); } load(0); }
javascript
function loadStylesheetsFallingBack(stylesheets) { var n = stylesheets.length; function load(i) { if (i === n) { return; } var link = doc.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; if (i + 1 < n) { // http://pieisgood.org/test/script-link-events/ indicates that many // versions of IE do not support onerror on <link>s, though // http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx // indicates that recent IEs do support error. link.error = link.onerror = function () { load(i + 1); }; } link.href = stylesheets[i]; head.appendChild(link); } load(0); }
[ "function", "loadStylesheetsFallingBack", "(", "stylesheets", ")", "{", "var", "n", "=", "stylesheets", ".", "length", ";", "function", "load", "(", "i", ")", "{", "if", "(", "i", "===", "n", ")", "{", "return", ";", "}", "var", "link", "=", "doc", ".", "createElement", "(", "'link'", ")", ";", "link", ".", "rel", "=", "'stylesheet'", ";", "link", ".", "type", "=", "'text/css'", ";", "if", "(", "i", "+", "1", "<", "n", ")", "{", "// http://pieisgood.org/test/script-link-events/ indicates that many", "// versions of IE do not support onerror on <link>s, though", "// http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx", "// indicates that recent IEs do support error.", "link", ".", "error", "=", "link", ".", "onerror", "=", "function", "(", ")", "{", "load", "(", "i", "+", "1", ")", ";", "}", ";", "}", "link", ".", "href", "=", "stylesheets", "[", "i", "]", ";", "head", ".", "appendChild", "(", "link", ")", ";", "}", "load", "(", "0", ")", ";", "}" ]
Given a list of URLs to stylesheets, loads the first that loads without triggering an error event.
[ "Given", "a", "list", "of", "URLs", "to", "stylesheets", "loads", "the", "first", "that", "loads", "without", "triggering", "an", "error", "event", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/run_prettify.js#L122-L140
3,552
google/code-prettify
js-modules/run_prettify.js
onLangsLoaded
function onLangsLoaded() { if (autorun) { contentLoaded( function () { var n = callbacks.length; var callback = n ? function () { for (var i = 0; i < n; ++i) { (function (i) { win.setTimeout( function () { win['exports'][callbacks[i]].apply(win, arguments); }, 0); })(i); } } : void 0; prettyPrint(callback); }); } }
javascript
function onLangsLoaded() { if (autorun) { contentLoaded( function () { var n = callbacks.length; var callback = n ? function () { for (var i = 0; i < n; ++i) { (function (i) { win.setTimeout( function () { win['exports'][callbacks[i]].apply(win, arguments); }, 0); })(i); } } : void 0; prettyPrint(callback); }); } }
[ "function", "onLangsLoaded", "(", ")", "{", "if", "(", "autorun", ")", "{", "contentLoaded", "(", "function", "(", ")", "{", "var", "n", "=", "callbacks", ".", "length", ";", "var", "callback", "=", "n", "?", "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "++", "i", ")", "{", "(", "function", "(", "i", ")", "{", "win", ".", "setTimeout", "(", "function", "(", ")", "{", "win", "[", "'exports'", "]", "[", "callbacks", "[", "i", "]", "]", ".", "apply", "(", "win", ",", "arguments", ")", ";", "}", ",", "0", ")", ";", "}", ")", "(", "i", ")", ";", "}", "}", ":", "void", "0", ";", "prettyPrint", "(", "callback", ")", ";", "}", ")", ";", "}", "}" ]
If this script is deferred or async and the document is already loaded we need to wait for language handlers to load before performing any autorun.
[ "If", "this", "script", "is", "deferred", "or", "async", "and", "the", "document", "is", "already", "loaded", "we", "need", "to", "wait", "for", "language", "handlers", "to", "load", "before", "performing", "any", "autorun", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/run_prettify.js#L240-L258
3,553
google/code-prettify
tasks/aliases.js
syncTimestamp
function syncTimestamp(src, dest, timestamp) { if (timestamp) { var stat = fs.lstatSync(src); var fd = fs.openSync(dest, process.platform === 'win32' ? 'r+' : 'r'); fs.futimesSync(fd, stat.atime, stat.mtime); fs.closeSync(fd); } }
javascript
function syncTimestamp(src, dest, timestamp) { if (timestamp) { var stat = fs.lstatSync(src); var fd = fs.openSync(dest, process.platform === 'win32' ? 'r+' : 'r'); fs.futimesSync(fd, stat.atime, stat.mtime); fs.closeSync(fd); } }
[ "function", "syncTimestamp", "(", "src", ",", "dest", ",", "timestamp", ")", "{", "if", "(", "timestamp", ")", "{", "var", "stat", "=", "fs", ".", "lstatSync", "(", "src", ")", ";", "var", "fd", "=", "fs", ".", "openSync", "(", "dest", ",", "process", ".", "platform", "===", "'win32'", "?", "'r+'", ":", "'r'", ")", ";", "fs", ".", "futimesSync", "(", "fd", ",", "stat", ".", "atime", ",", "stat", ".", "mtime", ")", ";", "fs", ".", "closeSync", "(", "fd", ")", ";", "}", "}" ]
Copy timestamp from source to destination file. @param {string} src @param {string} dest @param {boolean} timestamp
[ "Copy", "timestamp", "from", "source", "to", "destination", "file", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/aliases.js#L21-L28
3,554
google/code-prettify
tasks/aliases.js
syncMod
function syncMod(src, dest, mode) { if (mode !== false) { fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode); } }
javascript
function syncMod(src, dest, mode) { if (mode !== false) { fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode); } }
[ "function", "syncMod", "(", "src", ",", "dest", ",", "mode", ")", "{", "if", "(", "mode", "!==", "false", ")", "{", "fs", ".", "chmodSync", "(", "dest", ",", "(", "mode", "===", "true", ")", "?", "fs", ".", "lstatSync", "(", "src", ")", ".", "mode", ":", "mode", ")", ";", "}", "}" ]
Copy file mode from source to destination. @param {string} src @param {string} dest @param {boolean|number} mode
[ "Copy", "file", "mode", "from", "source", "to", "destination", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/aliases.js#L36-L40
3,555
google/code-prettify
js-modules/numberLines.js
breakAfter
function breakAfter(lineEndNode) { // If there's nothing to the right, then we can skip ending the line // here, and move root-wards since splitting just before an end-tag // would require us to create a bunch of empty copies. while (!lineEndNode.nextSibling) { lineEndNode = lineEndNode.parentNode; if (!lineEndNode) { return; } } function breakLeftOf(limit, copy) { // Clone shallowly if this node needs to be on both sides of the break. var rightSide = copy ? limit.cloneNode(false) : limit; var parent = limit.parentNode; if (parent) { // We clone the parent chain. // This helps us resurrect important styling elements that cross lines. // E.g. in <i>Foo<br>Bar</i> // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>. var parentClone = breakLeftOf(parent, 1); // Move the clone and everything to the right of the original // onto the cloned parent. var next = limit.nextSibling; parentClone.appendChild(rightSide); for (var sibling = next; sibling; sibling = next) { next = sibling.nextSibling; parentClone.appendChild(sibling); } } return rightSide; } var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0); // Walk the parent chain until we reach an unattached LI. for (var parent; // Check nodeType since IE invents document fragments. (parent = copiedListItem.parentNode) && parent.nodeType === 1;) { copiedListItem = parent; } // Put it on the list of lines for later processing. listItems.push(copiedListItem); }
javascript
function breakAfter(lineEndNode) { // If there's nothing to the right, then we can skip ending the line // here, and move root-wards since splitting just before an end-tag // would require us to create a bunch of empty copies. while (!lineEndNode.nextSibling) { lineEndNode = lineEndNode.parentNode; if (!lineEndNode) { return; } } function breakLeftOf(limit, copy) { // Clone shallowly if this node needs to be on both sides of the break. var rightSide = copy ? limit.cloneNode(false) : limit; var parent = limit.parentNode; if (parent) { // We clone the parent chain. // This helps us resurrect important styling elements that cross lines. // E.g. in <i>Foo<br>Bar</i> // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>. var parentClone = breakLeftOf(parent, 1); // Move the clone and everything to the right of the original // onto the cloned parent. var next = limit.nextSibling; parentClone.appendChild(rightSide); for (var sibling = next; sibling; sibling = next) { next = sibling.nextSibling; parentClone.appendChild(sibling); } } return rightSide; } var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0); // Walk the parent chain until we reach an unattached LI. for (var parent; // Check nodeType since IE invents document fragments. (parent = copiedListItem.parentNode) && parent.nodeType === 1;) { copiedListItem = parent; } // Put it on the list of lines for later processing. listItems.push(copiedListItem); }
[ "function", "breakAfter", "(", "lineEndNode", ")", "{", "// If there's nothing to the right, then we can skip ending the line", "// here, and move root-wards since splitting just before an end-tag", "// would require us to create a bunch of empty copies.", "while", "(", "!", "lineEndNode", ".", "nextSibling", ")", "{", "lineEndNode", "=", "lineEndNode", ".", "parentNode", ";", "if", "(", "!", "lineEndNode", ")", "{", "return", ";", "}", "}", "function", "breakLeftOf", "(", "limit", ",", "copy", ")", "{", "// Clone shallowly if this node needs to be on both sides of the break.", "var", "rightSide", "=", "copy", "?", "limit", ".", "cloneNode", "(", "false", ")", ":", "limit", ";", "var", "parent", "=", "limit", ".", "parentNode", ";", "if", "(", "parent", ")", "{", "// We clone the parent chain.", "// This helps us resurrect important styling elements that cross lines.", "// E.g. in <i>Foo<br>Bar</i>", "// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.", "var", "parentClone", "=", "breakLeftOf", "(", "parent", ",", "1", ")", ";", "// Move the clone and everything to the right of the original", "// onto the cloned parent.", "var", "next", "=", "limit", ".", "nextSibling", ";", "parentClone", ".", "appendChild", "(", "rightSide", ")", ";", "for", "(", "var", "sibling", "=", "next", ";", "sibling", ";", "sibling", "=", "next", ")", "{", "next", "=", "sibling", ".", "nextSibling", ";", "parentClone", ".", "appendChild", "(", "sibling", ")", ";", "}", "}", "return", "rightSide", ";", "}", "var", "copiedListItem", "=", "breakLeftOf", "(", "lineEndNode", ".", "nextSibling", ",", "0", ")", ";", "// Walk the parent chain until we reach an unattached LI.", "for", "(", "var", "parent", ";", "// Check nodeType since IE invents document fragments.", "(", "parent", "=", "copiedListItem", ".", "parentNode", ")", "&&", "parent", ".", "nodeType", "===", "1", ";", ")", "{", "copiedListItem", "=", "parent", ";", "}", "// Put it on the list of lines for later processing.", "listItems", ".", "push", "(", "copiedListItem", ")", ";", "}" ]
Split a line after the given node.
[ "Split", "a", "line", "after", "the", "given", "node", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/numberLines.js#L66-L107
3,556
google/code-prettify
tasks/lib/lang-aliases.js
createSandbox
function createSandbox() { // collect registered language extensions var sandbox = {}; sandbox.extensions = []; // mock prettify.js API sandbox.window = {}; sandbox.window.PR = sandbox.PR = { registerLangHandler: function (handler, exts) { sandbox.extensions = sandbox.extensions.concat(exts); }, createSimpleLexer: function (sPatterns, fPatterns) { return function (job) {}; }, sourceDecorator: function (options) { return function (job) {}; }, prettyPrintOne: function (src, lang, ln) { return src; }, prettyPrint: function (done, root) {}, PR_ATTRIB_NAME: 'atn', PR_ATTRIB_VALUE: 'atv', PR_COMMENT: 'com', PR_DECLARATION: 'dec', PR_KEYWORD: 'kwd', PR_LITERAL: 'lit', PR_NOCODE: 'nocode', PR_PLAIN: 'pln', PR_PUNCTUATION: 'pun', PR_SOURCE: 'src', PR_STRING: 'str', PR_TAG: 'tag', PR_TYPE: 'typ' }; return sandbox; }
javascript
function createSandbox() { // collect registered language extensions var sandbox = {}; sandbox.extensions = []; // mock prettify.js API sandbox.window = {}; sandbox.window.PR = sandbox.PR = { registerLangHandler: function (handler, exts) { sandbox.extensions = sandbox.extensions.concat(exts); }, createSimpleLexer: function (sPatterns, fPatterns) { return function (job) {}; }, sourceDecorator: function (options) { return function (job) {}; }, prettyPrintOne: function (src, lang, ln) { return src; }, prettyPrint: function (done, root) {}, PR_ATTRIB_NAME: 'atn', PR_ATTRIB_VALUE: 'atv', PR_COMMENT: 'com', PR_DECLARATION: 'dec', PR_KEYWORD: 'kwd', PR_LITERAL: 'lit', PR_NOCODE: 'nocode', PR_PLAIN: 'pln', PR_PUNCTUATION: 'pun', PR_SOURCE: 'src', PR_STRING: 'str', PR_TAG: 'tag', PR_TYPE: 'typ' }; return sandbox; }
[ "function", "createSandbox", "(", ")", "{", "// collect registered language extensions", "var", "sandbox", "=", "{", "}", ";", "sandbox", ".", "extensions", "=", "[", "]", ";", "// mock prettify.js API", "sandbox", ".", "window", "=", "{", "}", ";", "sandbox", ".", "window", ".", "PR", "=", "sandbox", ".", "PR", "=", "{", "registerLangHandler", ":", "function", "(", "handler", ",", "exts", ")", "{", "sandbox", ".", "extensions", "=", "sandbox", ".", "extensions", ".", "concat", "(", "exts", ")", ";", "}", ",", "createSimpleLexer", ":", "function", "(", "sPatterns", ",", "fPatterns", ")", "{", "return", "function", "(", "job", ")", "{", "}", ";", "}", ",", "sourceDecorator", ":", "function", "(", "options", ")", "{", "return", "function", "(", "job", ")", "{", "}", ";", "}", ",", "prettyPrintOne", ":", "function", "(", "src", ",", "lang", ",", "ln", ")", "{", "return", "src", ";", "}", ",", "prettyPrint", ":", "function", "(", "done", ",", "root", ")", "{", "}", ",", "PR_ATTRIB_NAME", ":", "'atn'", ",", "PR_ATTRIB_VALUE", ":", "'atv'", ",", "PR_COMMENT", ":", "'com'", ",", "PR_DECLARATION", ":", "'dec'", ",", "PR_KEYWORD", ":", "'kwd'", ",", "PR_LITERAL", ":", "'lit'", ",", "PR_NOCODE", ":", "'nocode'", ",", "PR_PLAIN", ":", "'pln'", ",", "PR_PUNCTUATION", ":", "'pun'", ",", "PR_SOURCE", ":", "'src'", ",", "PR_STRING", ":", "'str'", ",", "PR_TAG", ":", "'tag'", ",", "PR_TYPE", ":", "'typ'", "}", ";", "return", "sandbox", ";", "}" ]
Returns a mock object PR of the prettify API. This is used to collect registered language file extensions. @return {Object} PR object with an additional `extensions` property.
[ "Returns", "a", "mock", "object", "PR", "of", "the", "prettify", "API", ".", "This", "is", "used", "to", "collect", "registered", "language", "file", "extensions", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/lib/lang-aliases.js#L19-L54
3,557
google/code-prettify
tasks/lib/lang-aliases.js
runLanguageHandler
function runLanguageHandler(src) { // execute source code in an isolated sandbox with a mock PR object var sandbox = createSandbox(); vm.runInNewContext(fs.readFileSync(src), sandbox, { filename: src }); // language name var lang = path.basename(src, path.extname(src)).replace(/^lang-/, ''); // collect and filter extensions var exts = sandbox.extensions.map(function (ext) { // case-insensitive names return ext.toLowerCase(); }).filter(function (ext) { // skip self, and internal names like foo-bar-baz or lang.foo return ext !== lang && !/\W/.test(ext); }); exts = exts.filter(function (ext, pos) { // remove duplicates return exts.indexOf(ext) === pos; }); return exts; }
javascript
function runLanguageHandler(src) { // execute source code in an isolated sandbox with a mock PR object var sandbox = createSandbox(); vm.runInNewContext(fs.readFileSync(src), sandbox, { filename: src }); // language name var lang = path.basename(src, path.extname(src)).replace(/^lang-/, ''); // collect and filter extensions var exts = sandbox.extensions.map(function (ext) { // case-insensitive names return ext.toLowerCase(); }).filter(function (ext) { // skip self, and internal names like foo-bar-baz or lang.foo return ext !== lang && !/\W/.test(ext); }); exts = exts.filter(function (ext, pos) { // remove duplicates return exts.indexOf(ext) === pos; }); return exts; }
[ "function", "runLanguageHandler", "(", "src", ")", "{", "// execute source code in an isolated sandbox with a mock PR object", "var", "sandbox", "=", "createSandbox", "(", ")", ";", "vm", ".", "runInNewContext", "(", "fs", ".", "readFileSync", "(", "src", ")", ",", "sandbox", ",", "{", "filename", ":", "src", "}", ")", ";", "// language name", "var", "lang", "=", "path", ".", "basename", "(", "src", ",", "path", ".", "extname", "(", "src", ")", ")", ".", "replace", "(", "/", "^lang-", "/", ",", "''", ")", ";", "// collect and filter extensions", "var", "exts", "=", "sandbox", ".", "extensions", ".", "map", "(", "function", "(", "ext", ")", "{", "// case-insensitive names", "return", "ext", ".", "toLowerCase", "(", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "ext", ")", "{", "// skip self, and internal names like foo-bar-baz or lang.foo", "return", "ext", "!==", "lang", "&&", "!", "/", "\\W", "/", ".", "test", "(", "ext", ")", ";", "}", ")", ";", "exts", "=", "exts", ".", "filter", "(", "function", "(", "ext", ",", "pos", ")", "{", "// remove duplicates", "return", "exts", ".", "indexOf", "(", "ext", ")", "===", "pos", ";", "}", ")", ";", "return", "exts", ";", "}" ]
Runs a language handler file under VM to collect extensions. Given a lang-*.js file, runs the language handler in a fake context where PR.registerLangHandler collects handler names without doing anything else. This is later used to makes copies of the JS extension under all its registered language names lang-<EXT>.js @param {string} src path to lang-xxx.js language handler @return {Array<string>} registered file extensions
[ "Runs", "a", "language", "handler", "file", "under", "VM", "to", "collect", "extensions", "." ]
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/lib/lang-aliases.js#L67-L90
3,558
avajs/ava
lib/babel-pipeline.js
makeValueChecker
function makeValueChecker(ref) { const expected = require(ref); return ({value}) => value === expected || value === expected.default; }
javascript
function makeValueChecker(ref) { const expected = require(ref); return ({value}) => value === expected || value === expected.default; }
[ "function", "makeValueChecker", "(", "ref", ")", "{", "const", "expected", "=", "require", "(", "ref", ")", ";", "return", "(", "{", "value", "}", ")", "=>", "value", "===", "expected", "||", "value", "===", "expected", ".", "default", ";", "}" ]
Compare actual values rather than file paths, which should be more reliable.
[ "Compare", "actual", "values", "rather", "than", "file", "paths", "which", "should", "be", "more", "reliable", "." ]
08e99e516e13af75d3ebe70f12194a89b610217c
https://github.com/avajs/ava/blob/08e99e516e13af75d3ebe70f12194a89b610217c/lib/babel-pipeline.js#L64-L67
3,559
shipshapecode/shepherd
src/js/utils/dom.js
getElementFromObject
function getElementFromObject(attachTo) { const op = attachTo.element; if (op instanceof HTMLElement) { return op; } return document.querySelector(op); }
javascript
function getElementFromObject(attachTo) { const op = attachTo.element; if (op instanceof HTMLElement) { return op; } return document.querySelector(op); }
[ "function", "getElementFromObject", "(", "attachTo", ")", "{", "const", "op", "=", "attachTo", ".", "element", ";", "if", "(", "op", "instanceof", "HTMLElement", ")", "{", "return", "op", ";", "}", "return", "document", ".", "querySelector", "(", "op", ")", ";", "}" ]
Get the element from an option object @method getElementFromObject @param Object attachTo @returns {Element} @private
[ "Get", "the", "element", "from", "an", "option", "object" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/dom.js#L22-L30
3,560
shipshapecode/shepherd
src/js/utils/dom.js
getElementForStep
function getElementForStep(step) { const { options: { attachTo } } = step; if (!attachTo) { return null; } const type = typeof attachTo; let element; if (type === 'string') { element = getElementFromString(attachTo); } else if (type === 'object') { element = getElementFromObject(attachTo); } else { /* istanbul ignore next: cannot test undefined attachTo, but it does work! */ element = null; } return element; }
javascript
function getElementForStep(step) { const { options: { attachTo } } = step; if (!attachTo) { return null; } const type = typeof attachTo; let element; if (type === 'string') { element = getElementFromString(attachTo); } else if (type === 'object') { element = getElementFromObject(attachTo); } else { /* istanbul ignore next: cannot test undefined attachTo, but it does work! */ element = null; } return element; }
[ "function", "getElementForStep", "(", "step", ")", "{", "const", "{", "options", ":", "{", "attachTo", "}", "}", "=", "step", ";", "if", "(", "!", "attachTo", ")", "{", "return", "null", ";", "}", "const", "type", "=", "typeof", "attachTo", ";", "let", "element", ";", "if", "(", "type", "===", "'string'", ")", "{", "element", "=", "getElementFromString", "(", "attachTo", ")", ";", "}", "else", "if", "(", "type", "===", "'object'", ")", "{", "element", "=", "getElementFromObject", "(", "attachTo", ")", ";", "}", "else", "{", "/* istanbul ignore next: cannot test undefined attachTo, but it does work! */", "element", "=", "null", ";", "}", "return", "element", ";", "}" ]
Return the element for a step @method getElementForStep @param step step the step to get an element for @returns {Element} the element for this step @private
[ "Return", "the", "element", "for", "a", "step" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/dom.js#L40-L60
3,561
shipshapecode/shepherd
src/js/utils/general.js
_makeTippyInstance
function _makeTippyInstance(attachToOptions) { if (!attachToOptions.element) { return _makeCenteredTippy.call(this); } const tippyOptions = _makeAttachedTippyOptions.call(this, attachToOptions); return tippy(attachToOptions.element, tippyOptions); }
javascript
function _makeTippyInstance(attachToOptions) { if (!attachToOptions.element) { return _makeCenteredTippy.call(this); } const tippyOptions = _makeAttachedTippyOptions.call(this, attachToOptions); return tippy(attachToOptions.element, tippyOptions); }
[ "function", "_makeTippyInstance", "(", "attachToOptions", ")", "{", "if", "(", "!", "attachToOptions", ".", "element", ")", "{", "return", "_makeCenteredTippy", ".", "call", "(", "this", ")", ";", "}", "const", "tippyOptions", "=", "_makeAttachedTippyOptions", ".", "call", "(", "this", ",", "attachToOptions", ")", ";", "return", "tippy", "(", "attachToOptions", ".", "element", ",", "tippyOptions", ")", ";", "}" ]
Generates a `Tippy` instance from a set of base `attachTo` options @return {tippy} The final tippy instance @private
[ "Generates", "a", "Tippy", "instance", "from", "a", "set", "of", "base", "attachTo", "options" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/general.js#L192-L200
3,562
shipshapecode/shepherd
src/js/utils/general.js
_makeAttachedTippyOptions
function _makeAttachedTippyOptions(attachToOptions) { const resultingTippyOptions = { content: this.el, flipOnUpdate: true, placement: attachToOptions.on || 'right' }; Object.assign(resultingTippyOptions, this.options.tippyOptions); if (this.options.title) { const existingTheme = resultingTippyOptions.theme; resultingTippyOptions.theme = existingTheme ? `${existingTheme} shepherd-has-title` : 'shepherd-has-title'; } if (this.options.tippyOptions && this.options.tippyOptions.popperOptions) { Object.assign(defaultPopperOptions, this.options.tippyOptions.popperOptions); } resultingTippyOptions.popperOptions = defaultPopperOptions; return resultingTippyOptions; }
javascript
function _makeAttachedTippyOptions(attachToOptions) { const resultingTippyOptions = { content: this.el, flipOnUpdate: true, placement: attachToOptions.on || 'right' }; Object.assign(resultingTippyOptions, this.options.tippyOptions); if (this.options.title) { const existingTheme = resultingTippyOptions.theme; resultingTippyOptions.theme = existingTheme ? `${existingTheme} shepherd-has-title` : 'shepherd-has-title'; } if (this.options.tippyOptions && this.options.tippyOptions.popperOptions) { Object.assign(defaultPopperOptions, this.options.tippyOptions.popperOptions); } resultingTippyOptions.popperOptions = defaultPopperOptions; return resultingTippyOptions; }
[ "function", "_makeAttachedTippyOptions", "(", "attachToOptions", ")", "{", "const", "resultingTippyOptions", "=", "{", "content", ":", "this", ".", "el", ",", "flipOnUpdate", ":", "true", ",", "placement", ":", "attachToOptions", ".", "on", "||", "'right'", "}", ";", "Object", ".", "assign", "(", "resultingTippyOptions", ",", "this", ".", "options", ".", "tippyOptions", ")", ";", "if", "(", "this", ".", "options", ".", "title", ")", "{", "const", "existingTheme", "=", "resultingTippyOptions", ".", "theme", ";", "resultingTippyOptions", ".", "theme", "=", "existingTheme", "?", "`", "${", "existingTheme", "}", "`", ":", "'shepherd-has-title'", ";", "}", "if", "(", "this", ".", "options", ".", "tippyOptions", "&&", "this", ".", "options", ".", "tippyOptions", ".", "popperOptions", ")", "{", "Object", ".", "assign", "(", "defaultPopperOptions", ",", "this", ".", "options", ".", "tippyOptions", ".", "popperOptions", ")", ";", "}", "resultingTippyOptions", ".", "popperOptions", "=", "defaultPopperOptions", ";", "return", "resultingTippyOptions", ";", "}" ]
Generates the hash of options that will be passed to `Tippy` instances target an element in the DOM. @param {Object} attachToOptions The local `attachTo` options @return {Object} The final tippy options object @private
[ "Generates", "the", "hash", "of", "options", "that", "will", "be", "passed", "to", "Tippy", "instances", "target", "an", "element", "in", "the", "DOM", "." ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/general.js#L210-L231
3,563
shipshapecode/shepherd
src/js/utils/bind.js
_setupAdvanceOnHandler
function _setupAdvanceOnHandler(selector) { return (event) => { if (this.isOpen()) { const targetIsEl = this.el && event.target === this.el; const targetIsSelector = !isUndefined(selector) && event.target.matches(selector); if (targetIsSelector || targetIsEl) { this.tour.next(); } } }; }
javascript
function _setupAdvanceOnHandler(selector) { return (event) => { if (this.isOpen()) { const targetIsEl = this.el && event.target === this.el; const targetIsSelector = !isUndefined(selector) && event.target.matches(selector); if (targetIsSelector || targetIsEl) { this.tour.next(); } } }; }
[ "function", "_setupAdvanceOnHandler", "(", "selector", ")", "{", "return", "(", "event", ")", "=>", "{", "if", "(", "this", ".", "isOpen", "(", ")", ")", "{", "const", "targetIsEl", "=", "this", ".", "el", "&&", "event", ".", "target", "===", "this", ".", "el", ";", "const", "targetIsSelector", "=", "!", "isUndefined", "(", "selector", ")", "&&", "event", ".", "target", ".", "matches", "(", "selector", ")", ";", "if", "(", "targetIsSelector", "||", "targetIsEl", ")", "{", "this", ".", "tour", ".", "next", "(", ")", ";", "}", "}", "}", ";", "}" ]
Sets up the handler to determine if we should advance the tour @private
[ "Sets", "up", "the", "handler", "to", "determine", "if", "we", "should", "advance", "the", "tour" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/bind.js#L8-L19
3,564
shipshapecode/shepherd
src/js/utils/modal.js
positionModalOpening
function positionModalOpening(targetElement, openingElement) { if (targetElement.getBoundingClientRect && openingElement instanceof SVGElement) { const { x, y, width, height, left, top } = targetElement.getBoundingClientRect(); // getBoundingClientRect is not consistent. Some browsers use x and y, while others use left and top _setAttributes(openingElement, { x: x || left, y: y || top, width, height }); } }
javascript
function positionModalOpening(targetElement, openingElement) { if (targetElement.getBoundingClientRect && openingElement instanceof SVGElement) { const { x, y, width, height, left, top } = targetElement.getBoundingClientRect(); // getBoundingClientRect is not consistent. Some browsers use x and y, while others use left and top _setAttributes(openingElement, { x: x || left, y: y || top, width, height }); } }
[ "function", "positionModalOpening", "(", "targetElement", ",", "openingElement", ")", "{", "if", "(", "targetElement", ".", "getBoundingClientRect", "&&", "openingElement", "instanceof", "SVGElement", ")", "{", "const", "{", "x", ",", "y", ",", "width", ",", "height", ",", "left", ",", "top", "}", "=", "targetElement", ".", "getBoundingClientRect", "(", ")", ";", "// getBoundingClientRect is not consistent. Some browsers use x and y, while others use left and top", "_setAttributes", "(", "openingElement", ",", "{", "x", ":", "x", "||", "left", ",", "y", ":", "y", "||", "top", ",", "width", ",", "height", "}", ")", ";", "}", "}" ]
Uses the bounds of the element we want the opening overtop of to set the dimensions of the opening and position it @param {HTMLElement} targetElement The element the opening will expose @param {SVGElement} openingElement The svg mask for the opening
[ "Uses", "the", "bounds", "of", "the", "element", "we", "want", "the", "opening", "overtop", "of", "to", "set", "the", "dimensions", "of", "the", "opening", "and", "position", "it" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/modal.js#L131-L138
3,565
shipshapecode/shepherd
src/js/utils/modal.js
toggleShepherdModalClass
function toggleShepherdModalClass(currentElement) { const shepherdModal = document.querySelector(`${classNames.modalTarget}`); if (shepherdModal) { shepherdModal.classList.remove(classNames.modalTarget); } currentElement.classList.add(classNames.modalTarget); }
javascript
function toggleShepherdModalClass(currentElement) { const shepherdModal = document.querySelector(`${classNames.modalTarget}`); if (shepherdModal) { shepherdModal.classList.remove(classNames.modalTarget); } currentElement.classList.add(classNames.modalTarget); }
[ "function", "toggleShepherdModalClass", "(", "currentElement", ")", "{", "const", "shepherdModal", "=", "document", ".", "querySelector", "(", "`", "${", "classNames", ".", "modalTarget", "}", "`", ")", ";", "if", "(", "shepherdModal", ")", "{", "shepherdModal", ".", "classList", ".", "remove", "(", "classNames", ".", "modalTarget", ")", ";", "}", "currentElement", ".", "classList", ".", "add", "(", "classNames", ".", "modalTarget", ")", ";", "}" ]
Remove any leftover modal target classes and add the modal target class to the currentElement @param {HTMLElement} currentElement The element for the current step
[ "Remove", "any", "leftover", "modal", "target", "classes", "and", "add", "the", "modal", "target", "class", "to", "the", "currentElement" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/modal.js#L167-L175
3,566
shipshapecode/shepherd
src/js/utils/modal.js
_setAttributes
function _setAttributes(el, attrs) { Object.keys(attrs).forEach((key) => { el.setAttribute(key, attrs[key]); }); }
javascript
function _setAttributes(el, attrs) { Object.keys(attrs).forEach((key) => { el.setAttribute(key, attrs[key]); }); }
[ "function", "_setAttributes", "(", "el", ",", "attrs", ")", "{", "Object", ".", "keys", "(", "attrs", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "el", ".", "setAttribute", "(", "key", ",", "attrs", "[", "key", "]", ")", ";", "}", ")", ";", "}" ]
Set multiple attributes on an element, via a hash @param {HTMLElement|SVGElement} el The element to set the attributes on @param {Object} attrs A hash of key value pairs for attributes to set @private
[ "Set", "multiple", "attributes", "on", "an", "element", "via", "a", "hash" ]
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/modal.js#L183-L187
3,567
markdown-it/markdown-it
lib/common/utils.js
arrayReplaceAt
function arrayReplaceAt(src, pos, newElements) { return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); }
javascript
function arrayReplaceAt(src, pos, newElements) { return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); }
[ "function", "arrayReplaceAt", "(", "src", ",", "pos", ",", "newElements", ")", "{", "return", "[", "]", ".", "concat", "(", "src", ".", "slice", "(", "0", ",", "pos", ")", ",", "newElements", ",", "src", ".", "slice", "(", "pos", "+", "1", ")", ")", ";", "}" ]
Remove element from array and put another array at those position. Useful for some operations with tokens
[ "Remove", "element", "from", "array", "and", "put", "another", "array", "at", "those", "position", ".", "Useful", "for", "some", "operations", "with", "tokens" ]
ba6830ba13fb92953a91fb90318964ccd15b82c4
https://github.com/markdown-it/markdown-it/blob/ba6830ba13fb92953a91fb90318964ccd15b82c4/lib/common/utils.js#L38-L40
3,568
zalmoxisus/redux-devtools-extension
src/app/middlewares/api.js
messaging
function messaging(request, sender, sendResponse) { let tabId = getId(sender); if (!tabId) return; if (sender.frameId) tabId = `${tabId}-${sender.frameId}`; if (request.type === 'STOP') { if (!Object.keys(window.store.getState().instances.connections).length) { window.store.dispatch({ type: DISCONNECTED }); } return; } if (request.type === 'OPEN_OPTIONS') { chrome.runtime.openOptionsPage(); return; } if (request.type === 'GET_OPTIONS') { window.syncOptions.get(options => { sendResponse({ options }); }); return; } if (request.type === 'GET_REPORT') { getReport(request.payload, tabId, request.instanceId); return; } if (request.type === 'OPEN') { let position = 'devtools-left'; if (['remote', 'panel', 'left', 'right', 'bottom'].indexOf(request.position) !== -1) { position = 'devtools-' + request.position; } openDevToolsWindow(position); return; } if (request.type === 'ERROR') { if (request.payload) { toMonitors(request, tabId); return; } if (!request.message) return; const reducerError = getReducerError(); chrome.notifications.create('app-error', { type: 'basic', title: reducerError ? 'An error occurred in the reducer' : 'An error occurred in the app', message: reducerError || request.message, iconUrl: 'img/logo/48x48.png', isClickable: !!reducerError }); return; } const action = { type: UPDATE_STATE, request, id: tabId }; const instanceId = `${tabId}/${request.instanceId}`; if (request.split) { if (request.split === 'start') { chunks[instanceId] = request; return; } if (request.split === 'chunk') { chunks[instanceId][request.chunk[0]] = (chunks[instanceId][request.chunk[0]] || '') + request.chunk[1]; return; } action.request = chunks[instanceId]; delete chunks[instanceId]; } if (request.instanceId) { action.request.instanceId = instanceId; } window.store.dispatch(action); if (request.type === 'EXPORT') { toMonitors(action, tabId, true); } else { toMonitors(action, tabId); } }
javascript
function messaging(request, sender, sendResponse) { let tabId = getId(sender); if (!tabId) return; if (sender.frameId) tabId = `${tabId}-${sender.frameId}`; if (request.type === 'STOP') { if (!Object.keys(window.store.getState().instances.connections).length) { window.store.dispatch({ type: DISCONNECTED }); } return; } if (request.type === 'OPEN_OPTIONS') { chrome.runtime.openOptionsPage(); return; } if (request.type === 'GET_OPTIONS') { window.syncOptions.get(options => { sendResponse({ options }); }); return; } if (request.type === 'GET_REPORT') { getReport(request.payload, tabId, request.instanceId); return; } if (request.type === 'OPEN') { let position = 'devtools-left'; if (['remote', 'panel', 'left', 'right', 'bottom'].indexOf(request.position) !== -1) { position = 'devtools-' + request.position; } openDevToolsWindow(position); return; } if (request.type === 'ERROR') { if (request.payload) { toMonitors(request, tabId); return; } if (!request.message) return; const reducerError = getReducerError(); chrome.notifications.create('app-error', { type: 'basic', title: reducerError ? 'An error occurred in the reducer' : 'An error occurred in the app', message: reducerError || request.message, iconUrl: 'img/logo/48x48.png', isClickable: !!reducerError }); return; } const action = { type: UPDATE_STATE, request, id: tabId }; const instanceId = `${tabId}/${request.instanceId}`; if (request.split) { if (request.split === 'start') { chunks[instanceId] = request; return; } if (request.split === 'chunk') { chunks[instanceId][request.chunk[0]] = (chunks[instanceId][request.chunk[0]] || '') + request.chunk[1]; return; } action.request = chunks[instanceId]; delete chunks[instanceId]; } if (request.instanceId) { action.request.instanceId = instanceId; } window.store.dispatch(action); if (request.type === 'EXPORT') { toMonitors(action, tabId, true); } else { toMonitors(action, tabId); } }
[ "function", "messaging", "(", "request", ",", "sender", ",", "sendResponse", ")", "{", "let", "tabId", "=", "getId", "(", "sender", ")", ";", "if", "(", "!", "tabId", ")", "return", ";", "if", "(", "sender", ".", "frameId", ")", "tabId", "=", "`", "${", "tabId", "}", "${", "sender", ".", "frameId", "}", "`", ";", "if", "(", "request", ".", "type", "===", "'STOP'", ")", "{", "if", "(", "!", "Object", ".", "keys", "(", "window", ".", "store", ".", "getState", "(", ")", ".", "instances", ".", "connections", ")", ".", "length", ")", "{", "window", ".", "store", ".", "dispatch", "(", "{", "type", ":", "DISCONNECTED", "}", ")", ";", "}", "return", ";", "}", "if", "(", "request", ".", "type", "===", "'OPEN_OPTIONS'", ")", "{", "chrome", ".", "runtime", ".", "openOptionsPage", "(", ")", ";", "return", ";", "}", "if", "(", "request", ".", "type", "===", "'GET_OPTIONS'", ")", "{", "window", ".", "syncOptions", ".", "get", "(", "options", "=>", "{", "sendResponse", "(", "{", "options", "}", ")", ";", "}", ")", ";", "return", ";", "}", "if", "(", "request", ".", "type", "===", "'GET_REPORT'", ")", "{", "getReport", "(", "request", ".", "payload", ",", "tabId", ",", "request", ".", "instanceId", ")", ";", "return", ";", "}", "if", "(", "request", ".", "type", "===", "'OPEN'", ")", "{", "let", "position", "=", "'devtools-left'", ";", "if", "(", "[", "'remote'", ",", "'panel'", ",", "'left'", ",", "'right'", ",", "'bottom'", "]", ".", "indexOf", "(", "request", ".", "position", ")", "!==", "-", "1", ")", "{", "position", "=", "'devtools-'", "+", "request", ".", "position", ";", "}", "openDevToolsWindow", "(", "position", ")", ";", "return", ";", "}", "if", "(", "request", ".", "type", "===", "'ERROR'", ")", "{", "if", "(", "request", ".", "payload", ")", "{", "toMonitors", "(", "request", ",", "tabId", ")", ";", "return", ";", "}", "if", "(", "!", "request", ".", "message", ")", "return", ";", "const", "reducerError", "=", "getReducerError", "(", ")", ";", "chrome", ".", "notifications", ".", "create", "(", "'app-error'", ",", "{", "type", ":", "'basic'", ",", "title", ":", "reducerError", "?", "'An error occurred in the reducer'", ":", "'An error occurred in the app'", ",", "message", ":", "reducerError", "||", "request", ".", "message", ",", "iconUrl", ":", "'img/logo/48x48.png'", ",", "isClickable", ":", "!", "!", "reducerError", "}", ")", ";", "return", ";", "}", "const", "action", "=", "{", "type", ":", "UPDATE_STATE", ",", "request", ",", "id", ":", "tabId", "}", ";", "const", "instanceId", "=", "`", "${", "tabId", "}", "${", "request", ".", "instanceId", "}", "`", ";", "if", "(", "request", ".", "split", ")", "{", "if", "(", "request", ".", "split", "===", "'start'", ")", "{", "chunks", "[", "instanceId", "]", "=", "request", ";", "return", ";", "}", "if", "(", "request", ".", "split", "===", "'chunk'", ")", "{", "chunks", "[", "instanceId", "]", "[", "request", ".", "chunk", "[", "0", "]", "]", "=", "(", "chunks", "[", "instanceId", "]", "[", "request", ".", "chunk", "[", "0", "]", "]", "||", "''", ")", "+", "request", ".", "chunk", "[", "1", "]", ";", "return", ";", "}", "action", ".", "request", "=", "chunks", "[", "instanceId", "]", ";", "delete", "chunks", "[", "instanceId", "]", ";", "}", "if", "(", "request", ".", "instanceId", ")", "{", "action", ".", "request", ".", "instanceId", "=", "instanceId", ";", "}", "window", ".", "store", ".", "dispatch", "(", "action", ")", ";", "if", "(", "request", ".", "type", "===", "'EXPORT'", ")", "{", "toMonitors", "(", "action", ",", "tabId", ",", "true", ")", ";", "}", "else", "{", "toMonitors", "(", "action", ",", "tabId", ")", ";", "}", "}" ]
Receive messages from content scripts
[ "Receive", "messages", "from", "content", "scripts" ]
d127175196388c9b1f874b04b2792cf487c5d5e0
https://github.com/zalmoxisus/redux-devtools-extension/blob/d127175196388c9b1f874b04b2792cf487c5d5e0/src/app/middlewares/api.js#L79-L153
3,569
zalmoxisus/redux-devtools-extension
src/browser/extension/inject/contentScript.js
handleMessages
function handleMessages(event) { if (!isAllowed()) return; if (!event || event.source !== window || typeof event.data !== 'object') return; const message = event.data; if (message.source !== pageSource) return; if (message.type === 'DISCONNECT') { if (bg) { bg.disconnect(); connected = false; } return; } tryCatch(send, message); }
javascript
function handleMessages(event) { if (!isAllowed()) return; if (!event || event.source !== window || typeof event.data !== 'object') return; const message = event.data; if (message.source !== pageSource) return; if (message.type === 'DISCONNECT') { if (bg) { bg.disconnect(); connected = false; } return; } tryCatch(send, message); }
[ "function", "handleMessages", "(", "event", ")", "{", "if", "(", "!", "isAllowed", "(", ")", ")", "return", ";", "if", "(", "!", "event", "||", "event", ".", "source", "!==", "window", "||", "typeof", "event", ".", "data", "!==", "'object'", ")", "return", ";", "const", "message", "=", "event", ".", "data", ";", "if", "(", "message", ".", "source", "!==", "pageSource", ")", "return", ";", "if", "(", "message", ".", "type", "===", "'DISCONNECT'", ")", "{", "if", "(", "bg", ")", "{", "bg", ".", "disconnect", "(", ")", ";", "connected", "=", "false", ";", "}", "return", ";", "}", "tryCatch", "(", "send", ",", "message", ")", ";", "}" ]
Resend messages from the page to the background script
[ "Resend", "messages", "from", "the", "page", "to", "the", "background", "script" ]
d127175196388c9b1f874b04b2792cf487c5d5e0
https://github.com/zalmoxisus/redux-devtools-extension/blob/d127175196388c9b1f874b04b2792cf487c5d5e0/src/browser/extension/inject/contentScript.js#L102-L116
3,570
google/closure-library
closure/goog/dom/uri.js
normalizeUri
function normalizeUri(uri) { const anchor = createElement(TagName.A); // This is safe even though the URL might be untrustworthy. // The SafeURL is only used to set the href of an HTMLAnchorElement // that is never added to the DOM. Therefore, the user cannot navigate // to this URL. const safeUrl = uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract( Const.from('This URL is never added to the DOM'), uri); setAnchorHref(anchor, safeUrl); return anchor.href; }
javascript
function normalizeUri(uri) { const anchor = createElement(TagName.A); // This is safe even though the URL might be untrustworthy. // The SafeURL is only used to set the href of an HTMLAnchorElement // that is never added to the DOM. Therefore, the user cannot navigate // to this URL. const safeUrl = uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract( Const.from('This URL is never added to the DOM'), uri); setAnchorHref(anchor, safeUrl); return anchor.href; }
[ "function", "normalizeUri", "(", "uri", ")", "{", "const", "anchor", "=", "createElement", "(", "TagName", ".", "A", ")", ";", "// This is safe even though the URL might be untrustworthy.", "// The SafeURL is only used to set the href of an HTMLAnchorElement", "// that is never added to the DOM. Therefore, the user cannot navigate", "// to this URL.", "const", "safeUrl", "=", "uncheckedconversions", ".", "safeUrlFromStringKnownToSatisfyTypeContract", "(", "Const", ".", "from", "(", "'This URL is never added to the DOM'", ")", ",", "uri", ")", ";", "setAnchorHref", "(", "anchor", ",", "safeUrl", ")", ";", "return", "anchor", ".", "href", ";", "}" ]
Normalizes a URL by assigning it to an anchor element and reading back href. This converts relative URLs to absolute, and cleans up whitespace. @param {string} uri A string containing a URI. @return {string} Normalized, absolute form of uri.
[ "Normalizes", "a", "URL", "by", "assigning", "it", "to", "an", "anchor", "element", "and", "reading", "back", "href", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/dom/uri.js#L30-L41
3,571
google/closure-library
browser_capabilities.js
getBrowserName
function getBrowserName(browserCap) { var name = browserCap.browserName == 'internet explorer' ? 'ie' : browserCap.browserName; var version = browserCap.version || '-latest'; return name + version; }
javascript
function getBrowserName(browserCap) { var name = browserCap.browserName == 'internet explorer' ? 'ie' : browserCap.browserName; var version = browserCap.version || '-latest'; return name + version; }
[ "function", "getBrowserName", "(", "browserCap", ")", "{", "var", "name", "=", "browserCap", ".", "browserName", "==", "'internet explorer'", "?", "'ie'", ":", "browserCap", ".", "browserName", ";", "var", "version", "=", "browserCap", ".", "version", "||", "'-latest'", ";", "return", "name", "+", "version", ";", "}" ]
Returns a versioned name for the given capability object. @param {!Object} browserCap @return {string}
[ "Returns", "a", "versioned", "name", "for", "the", "given", "capability", "object", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/browser_capabilities.js#L22-L28
3,572
google/closure-library
browser_capabilities.js
getJobName
function getJobName(browserCap) { var browserName = getBrowserName(browserCap); return process.env.TRAVIS_PULL_REQUEST == 'false' ? 'CO-' + process.env.TRAVIS_BRANCH + '-' + browserName : 'PR-' + process.env.TRAVIS_PULL_REQUEST + '-' + browserName + '-' + process.env.TRAVIS_BRANCH; }
javascript
function getJobName(browserCap) { var browserName = getBrowserName(browserCap); return process.env.TRAVIS_PULL_REQUEST == 'false' ? 'CO-' + process.env.TRAVIS_BRANCH + '-' + browserName : 'PR-' + process.env.TRAVIS_PULL_REQUEST + '-' + browserName + '-' + process.env.TRAVIS_BRANCH; }
[ "function", "getJobName", "(", "browserCap", ")", "{", "var", "browserName", "=", "getBrowserName", "(", "browserCap", ")", ";", "return", "process", ".", "env", ".", "TRAVIS_PULL_REQUEST", "==", "'false'", "?", "'CO-'", "+", "process", ".", "env", ".", "TRAVIS_BRANCH", "+", "'-'", "+", "browserName", ":", "'PR-'", "+", "process", ".", "env", ".", "TRAVIS_PULL_REQUEST", "+", "'-'", "+", "browserName", "+", "'-'", "+", "process", ".", "env", ".", "TRAVIS_BRANCH", ";", "}" ]
Returns the travis job name for the given capability object. @param {!Object} browserCap @return {string}
[ "Returns", "the", "travis", "job", "name", "for", "the", "given", "capability", "object", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/browser_capabilities.js#L35-L42
3,573
google/closure-library
browser_capabilities.js
getBrowserCapabilities
function getBrowserCapabilities(browsers) { for (var i = 0; i < browsers.length; i++) { var b = browsers[i]; b['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; b['build'] = process.env.TRAVIS_BUILD_NUMBER; b['name'] = getJobName(b); } return browsers; }
javascript
function getBrowserCapabilities(browsers) { for (var i = 0; i < browsers.length; i++) { var b = browsers[i]; b['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; b['build'] = process.env.TRAVIS_BUILD_NUMBER; b['name'] = getJobName(b); } return browsers; }
[ "function", "getBrowserCapabilities", "(", "browsers", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "browsers", ".", "length", ";", "i", "++", ")", "{", "var", "b", "=", "browsers", "[", "i", "]", ";", "b", "[", "'tunnel-identifier'", "]", "=", "process", ".", "env", ".", "TRAVIS_JOB_NUMBER", ";", "b", "[", "'build'", "]", "=", "process", ".", "env", ".", "TRAVIS_BUILD_NUMBER", ";", "b", "[", "'name'", "]", "=", "getJobName", "(", "b", ")", ";", "}", "return", "browsers", ";", "}" ]
Adds 'name', 'build', and 'tunnel-identifier' properties to all elements, based on runtime information from the environment. @param {!Array<!Object>} browsers @return {!Array<!Object>} The original array, whose objects are augmented.
[ "Adds", "name", "build", "and", "tunnel", "-", "identifier", "properties", "to", "all", "elements", "based", "on", "runtime", "information", "from", "the", "environment", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/browser_capabilities.js#L50-L58
3,574
google/closure-library
closure/goog/html/sanitizer/noclobber.js
prototypeMethodOrNull
function prototypeMethodOrNull(className, method) { var ctor = goog.global[className]; return (ctor && ctor.prototype && ctor.prototype[method]) || null; }
javascript
function prototypeMethodOrNull(className, method) { var ctor = goog.global[className]; return (ctor && ctor.prototype && ctor.prototype[method]) || null; }
[ "function", "prototypeMethodOrNull", "(", "className", ",", "method", ")", "{", "var", "ctor", "=", "goog", ".", "global", "[", "className", "]", ";", "return", "(", "ctor", "&&", "ctor", ".", "prototype", "&&", "ctor", ".", "prototype", "[", "method", "]", ")", "||", "null", ";", "}" ]
Shorthand for `DOMInterface.prototype.method` to improve readability during initialization of `Methods`. @param {string} className @param {string} method @return {?Function}
[ "Shorthand", "for", "DOMInterface", ".", "prototype", ".", "method", "to", "improve", "readability", "during", "initialization", "of", "Methods", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L73-L76
3,575
google/closure-library
closure/goog/html/sanitizer/noclobber.js
genericPropertyGet
function genericPropertyGet(fn, object, fallbackPropertyName, fallbackTest) { if (fn) { return fn.apply(object); } var propertyValue = object[fallbackPropertyName]; if (!fallbackTest(propertyValue)) { throw new Error('Clobbering detected'); } return propertyValue; }
javascript
function genericPropertyGet(fn, object, fallbackPropertyName, fallbackTest) { if (fn) { return fn.apply(object); } var propertyValue = object[fallbackPropertyName]; if (!fallbackTest(propertyValue)) { throw new Error('Clobbering detected'); } return propertyValue; }
[ "function", "genericPropertyGet", "(", "fn", ",", "object", ",", "fallbackPropertyName", ",", "fallbackTest", ")", "{", "if", "(", "fn", ")", "{", "return", "fn", ".", "apply", "(", "object", ")", ";", "}", "var", "propertyValue", "=", "object", "[", "fallbackPropertyName", "]", ";", "if", "(", "!", "fallbackTest", "(", "propertyValue", ")", ")", "{", "throw", "new", "Error", "(", "'Clobbering detected'", ")", ";", "}", "return", "propertyValue", ";", "}" ]
Calls the provided DOM property descriptor and returns its result. If the descriptor is not available, use fallbackPropertyName to get the property value in a clobber-vulnerable way, and use fallbackTest to check if the property was clobbered, throwing an exception if so. @param {?Function} fn @param {*} object @param {string} fallbackPropertyName @param {function(*):boolean} fallbackTest @return {?}
[ "Calls", "the", "provided", "DOM", "property", "descriptor", "and", "returns", "its", "result", ".", "If", "the", "descriptor", "is", "not", "available", "use", "fallbackPropertyName", "to", "get", "the", "property", "value", "in", "a", "clobber", "-", "vulnerable", "way", "and", "use", "fallbackTest", "to", "check", "if", "the", "property", "was", "clobbered", "throwing", "an", "exception", "if", "so", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L123-L132
3,576
google/closure-library
closure/goog/html/sanitizer/noclobber.js
genericMethodCall
function genericMethodCall(fn, object, fallbackMethodName, args) { if (fn) { return fn.apply(object, args); } // IE8 and IE9 will return 'object' for // CSSStyleDeclaration.(get|set)Attribute, so we can't use typeof. if (userAgentProduct.IE && document.documentMode < 10) { if (!object[fallbackMethodName].call) { throw new Error('IE Clobbering detected'); } } else if (typeof object[fallbackMethodName] != 'function') { throw new Error('Clobbering detected'); } return object[fallbackMethodName].apply(object, args); }
javascript
function genericMethodCall(fn, object, fallbackMethodName, args) { if (fn) { return fn.apply(object, args); } // IE8 and IE9 will return 'object' for // CSSStyleDeclaration.(get|set)Attribute, so we can't use typeof. if (userAgentProduct.IE && document.documentMode < 10) { if (!object[fallbackMethodName].call) { throw new Error('IE Clobbering detected'); } } else if (typeof object[fallbackMethodName] != 'function') { throw new Error('Clobbering detected'); } return object[fallbackMethodName].apply(object, args); }
[ "function", "genericMethodCall", "(", "fn", ",", "object", ",", "fallbackMethodName", ",", "args", ")", "{", "if", "(", "fn", ")", "{", "return", "fn", ".", "apply", "(", "object", ",", "args", ")", ";", "}", "// IE8 and IE9 will return 'object' for", "// CSSStyleDeclaration.(get|set)Attribute, so we can't use typeof.", "if", "(", "userAgentProduct", ".", "IE", "&&", "document", ".", "documentMode", "<", "10", ")", "{", "if", "(", "!", "object", "[", "fallbackMethodName", "]", ".", "call", ")", "{", "throw", "new", "Error", "(", "'IE Clobbering detected'", ")", ";", "}", "}", "else", "if", "(", "typeof", "object", "[", "fallbackMethodName", "]", "!=", "'function'", ")", "{", "throw", "new", "Error", "(", "'Clobbering detected'", ")", ";", "}", "return", "object", "[", "fallbackMethodName", "]", ".", "apply", "(", "object", ",", "args", ")", ";", "}" ]
Calls the provided DOM prototype method and returns its result. If the method is not available, use fallbackMethodName to call the method in a clobber-vulnerable way, and use fallbackTest to check if the method was clobbered, throwing an exception if so. @param {?Function} fn @param {*} object @param {string} fallbackMethodName @param {!Array<*>} args @return {?}
[ "Calls", "the", "provided", "DOM", "prototype", "method", "and", "returns", "its", "result", ".", "If", "the", "method", "is", "not", "available", "use", "fallbackMethodName", "to", "call", "the", "method", "in", "a", "clobber", "-", "vulnerable", "way", "and", "use", "fallbackTest", "to", "check", "if", "the", "method", "was", "clobbered", "throwing", "an", "exception", "if", "so", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L145-L159
3,577
google/closure-library
closure/goog/html/sanitizer/noclobber.js
getCssPropertyValue
function getCssPropertyValue(cssStyle, propName) { return genericMethodCall( Methods.GET_PROPERTY_VALUE, cssStyle, cssStyle.getPropertyValue ? 'getPropertyValue' : 'getAttribute', [propName]) || ''; }
javascript
function getCssPropertyValue(cssStyle, propName) { return genericMethodCall( Methods.GET_PROPERTY_VALUE, cssStyle, cssStyle.getPropertyValue ? 'getPropertyValue' : 'getAttribute', [propName]) || ''; }
[ "function", "getCssPropertyValue", "(", "cssStyle", ",", "propName", ")", "{", "return", "genericMethodCall", "(", "Methods", ".", "GET_PROPERTY_VALUE", ",", "cssStyle", ",", "cssStyle", ".", "getPropertyValue", "?", "'getPropertyValue'", ":", "'getAttribute'", ",", "[", "propName", "]", ")", "||", "''", ";", "}" ]
Provides a way cross-browser way to get a CSS value from a CSS declaration. @param {!CSSStyleDeclaration} cssStyle A CSS style object. @param {string} propName A property name. @return {string} Value of the property as parsed by the browser. @supported IE8 and newer.
[ "Provides", "a", "way", "cross", "-", "browser", "way", "to", "get", "a", "CSS", "value", "from", "a", "CSS", "declaration", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L421-L427
3,578
google/closure-library
closure/goog/html/sanitizer/noclobber.js
setCssProperty
function setCssProperty(cssStyle, propName, sanitizedValue) { genericMethodCall( Methods.SET_PROPERTY, cssStyle, cssStyle.setProperty ? 'setProperty' : 'setAttribute', [propName, sanitizedValue]); }
javascript
function setCssProperty(cssStyle, propName, sanitizedValue) { genericMethodCall( Methods.SET_PROPERTY, cssStyle, cssStyle.setProperty ? 'setProperty' : 'setAttribute', [propName, sanitizedValue]); }
[ "function", "setCssProperty", "(", "cssStyle", ",", "propName", ",", "sanitizedValue", ")", "{", "genericMethodCall", "(", "Methods", ".", "SET_PROPERTY", ",", "cssStyle", ",", "cssStyle", ".", "setProperty", "?", "'setProperty'", ":", "'setAttribute'", ",", "[", "propName", ",", "sanitizedValue", "]", ")", ";", "}" ]
Provides a cross-browser way to set a CSS value on a CSS declaration. @param {!CSSStyleDeclaration} cssStyle A CSS style object. @param {string} propName A property name. @param {string} sanitizedValue Sanitized value of the property to be set on the CSS style object. @supported IE8 and newer.
[ "Provides", "a", "cross", "-", "browser", "way", "to", "set", "a", "CSS", "value", "on", "a", "CSS", "declaration", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L437-L442
3,579
google/closure-library
closure/goog/structs/avltree.js
function(value, opt_parent) { /** * The value stored by the node. * * @type {T} */ this.value = value; /** * The node's parent. Null if the node is the root. * * @type {?Node<T>} */ this.parent = opt_parent ? opt_parent : null; /** * The number of nodes in the subtree rooted at this node. * * @type {number} */ this.count = 1; /** * The node's left child. Null if the node does not have a left child. * * @type {?Node<T>} */ this.left = null; /** * The node's right child. Null if the node does not have a right child. * * @type {?Node<T>} */ this.right = null; /** * Height of this node. * * @type {number} */ this.height = 1; }
javascript
function(value, opt_parent) { /** * The value stored by the node. * * @type {T} */ this.value = value; /** * The node's parent. Null if the node is the root. * * @type {?Node<T>} */ this.parent = opt_parent ? opt_parent : null; /** * The number of nodes in the subtree rooted at this node. * * @type {number} */ this.count = 1; /** * The node's left child. Null if the node does not have a left child. * * @type {?Node<T>} */ this.left = null; /** * The node's right child. Null if the node does not have a right child. * * @type {?Node<T>} */ this.right = null; /** * Height of this node. * * @type {number} */ this.height = 1; }
[ "function", "(", "value", ",", "opt_parent", ")", "{", "/**\n * The value stored by the node.\n *\n * @type {T}\n */", "this", ".", "value", "=", "value", ";", "/**\n * The node's parent. Null if the node is the root.\n *\n * @type {?Node<T>}\n */", "this", ".", "parent", "=", "opt_parent", "?", "opt_parent", ":", "null", ";", "/**\n * The number of nodes in the subtree rooted at this node.\n *\n * @type {number}\n */", "this", ".", "count", "=", "1", ";", "/**\n * The node's left child. Null if the node does not have a left child.\n *\n * @type {?Node<T>}\n */", "this", ".", "left", "=", "null", ";", "/**\n * The node's right child. Null if the node does not have a right child.\n *\n * @type {?Node<T>}\n */", "this", ".", "right", "=", "null", ";", "/**\n * Height of this node.\n *\n * @type {number}\n */", "this", ".", "height", "=", "1", ";", "}" ]
Constructs an AVL-Tree node with the specified value. If no parent is specified, the node's parent is assumed to be null. The node's height defaults to 1 and its children default to null. @param {T} value Value to store in the node. @param {Node<T>=} opt_parent Optional parent node. @constructor @final @template T
[ "Constructs", "an", "AVL", "-", "Tree", "node", "with", "the", "specified", "value", ".", "If", "no", "parent", "is", "specified", "the", "node", "s", "parent", "is", "assumed", "to", "be", "null", ".", "The", "node", "s", "height", "defaults", "to", "1", "and", "its", "children", "default", "to", "null", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/structs/avltree.js#L843-L885
3,580
google/closure-library
closure/goog/net/streams/pbstreamparser.js
finishMessage
function finishMessage() { if (parser.tag_ < Parser.PADDING_TAG_) { var message = {}; message[parser.tag_] = parser.messageBuffer_; parser.result_.push(message); } parser.state_ = Parser.State_.INIT; }
javascript
function finishMessage() { if (parser.tag_ < Parser.PADDING_TAG_) { var message = {}; message[parser.tag_] = parser.messageBuffer_; parser.result_.push(message); } parser.state_ = Parser.State_.INIT; }
[ "function", "finishMessage", "(", ")", "{", "if", "(", "parser", ".", "tag_", "<", "Parser", ".", "PADDING_TAG_", ")", "{", "var", "message", "=", "{", "}", ";", "message", "[", "parser", ".", "tag_", "]", "=", "parser", ".", "messageBuffer_", ";", "parser", ".", "result_", ".", "push", "(", "message", ")", ";", "}", "parser", ".", "state_", "=", "Parser", ".", "State_", ".", "INIT", ";", "}" ]
Finishes up building the current message and resets parser state
[ "Finishes", "up", "building", "the", "current", "message", "and", "resets", "parser", "state" ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/net/streams/pbstreamparser.js#L289-L296
3,581
google/closure-library
protractor_spec.js
function(testPath) { var testStartTime = +new Date(); var waitForTest = function(resolve, reject) { // executeScript runs the passed method in the "window" context of // the current test. JSUnit exposes hooks into the test's status through // the "G_testRunner" global object. browser .executeScript(function() { if (window['G_testRunner'] && window['G_testRunner']['isFinished']()) { var status = {}; status['isFinished'] = true; status['isSuccess'] = window['G_testRunner']['isSuccess'](); status['report'] = window['G_testRunner']['getReport'](); return status; } else { return {'isFinished': false}; } }) .then( function(status) { if (status && status.isFinished) { resolve(status); } else { var currTime = +new Date(); if (currTime - testStartTime > TEST_TIMEOUT) { status.isSuccess = false; status.report = testPath + ' timed out after ' + (TEST_TIMEOUT / 1000) + 's!'; // resolve so tests continue running. resolve(status); } else { // Check every 300ms for completion. setTimeout( waitForTest.bind(undefined, resolve, reject), 300); } } }, function(err) { reject(err); }); }; return new Promise(function(resolve, reject) { waitForTest(resolve, reject); }); }
javascript
function(testPath) { var testStartTime = +new Date(); var waitForTest = function(resolve, reject) { // executeScript runs the passed method in the "window" context of // the current test. JSUnit exposes hooks into the test's status through // the "G_testRunner" global object. browser .executeScript(function() { if (window['G_testRunner'] && window['G_testRunner']['isFinished']()) { var status = {}; status['isFinished'] = true; status['isSuccess'] = window['G_testRunner']['isSuccess'](); status['report'] = window['G_testRunner']['getReport'](); return status; } else { return {'isFinished': false}; } }) .then( function(status) { if (status && status.isFinished) { resolve(status); } else { var currTime = +new Date(); if (currTime - testStartTime > TEST_TIMEOUT) { status.isSuccess = false; status.report = testPath + ' timed out after ' + (TEST_TIMEOUT / 1000) + 's!'; // resolve so tests continue running. resolve(status); } else { // Check every 300ms for completion. setTimeout( waitForTest.bind(undefined, resolve, reject), 300); } } }, function(err) { reject(err); }); }; return new Promise(function(resolve, reject) { waitForTest(resolve, reject); }); }
[ "function", "(", "testPath", ")", "{", "var", "testStartTime", "=", "+", "new", "Date", "(", ")", ";", "var", "waitForTest", "=", "function", "(", "resolve", ",", "reject", ")", "{", "// executeScript runs the passed method in the \"window\" context of", "// the current test. JSUnit exposes hooks into the test's status through", "// the \"G_testRunner\" global object.", "browser", ".", "executeScript", "(", "function", "(", ")", "{", "if", "(", "window", "[", "'G_testRunner'", "]", "&&", "window", "[", "'G_testRunner'", "]", "[", "'isFinished'", "]", "(", ")", ")", "{", "var", "status", "=", "{", "}", ";", "status", "[", "'isFinished'", "]", "=", "true", ";", "status", "[", "'isSuccess'", "]", "=", "window", "[", "'G_testRunner'", "]", "[", "'isSuccess'", "]", "(", ")", ";", "status", "[", "'report'", "]", "=", "window", "[", "'G_testRunner'", "]", "[", "'getReport'", "]", "(", ")", ";", "return", "status", ";", "}", "else", "{", "return", "{", "'isFinished'", ":", "false", "}", ";", "}", "}", ")", ".", "then", "(", "function", "(", "status", ")", "{", "if", "(", "status", "&&", "status", ".", "isFinished", ")", "{", "resolve", "(", "status", ")", ";", "}", "else", "{", "var", "currTime", "=", "+", "new", "Date", "(", ")", ";", "if", "(", "currTime", "-", "testStartTime", ">", "TEST_TIMEOUT", ")", "{", "status", ".", "isSuccess", "=", "false", ";", "status", ".", "report", "=", "testPath", "+", "' timed out after '", "+", "(", "TEST_TIMEOUT", "/", "1000", ")", "+", "'s!'", ";", "// resolve so tests continue running.", "resolve", "(", "status", ")", ";", "}", "else", "{", "// Check every 300ms for completion.", "setTimeout", "(", "waitForTest", ".", "bind", "(", "undefined", ",", "resolve", ",", "reject", ")", ",", "300", ")", ";", "}", "}", "}", ",", "function", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", ")", ";", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "waitForTest", "(", "resolve", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Polls currently loaded test page for test completion. Returns Promise that will resolve when test is finished.
[ "Polls", "currently", "loaded", "test", "page", "for", "test", "completion", ".", "Returns", "Promise", "that", "will", "resolve", "when", "test", "is", "finished", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/protractor_spec.js#L65-L112
3,582
google/closure-library
protractor_spec.js
function(testPath) { return browser.navigate() .to(TEST_SERVER + '/' + testPath) .then(function() { return waitForTestSuiteCompletion(testPath); }) .then(function(status) { if (!status.isSuccess) { failureReports.push(status.report); } return status; }); }
javascript
function(testPath) { return browser.navigate() .to(TEST_SERVER + '/' + testPath) .then(function() { return waitForTestSuiteCompletion(testPath); }) .then(function(status) { if (!status.isSuccess) { failureReports.push(status.report); } return status; }); }
[ "function", "(", "testPath", ")", "{", "return", "browser", ".", "navigate", "(", ")", ".", "to", "(", "TEST_SERVER", "+", "'/'", "+", "testPath", ")", ".", "then", "(", "function", "(", ")", "{", "return", "waitForTestSuiteCompletion", "(", "testPath", ")", ";", "}", ")", ".", "then", "(", "function", "(", "status", ")", "{", "if", "(", "!", "status", ".", "isSuccess", ")", "{", "failureReports", ".", "push", "(", "status", ".", "report", ")", ";", "}", "return", "status", ";", "}", ")", ";", "}" ]
Navigates to testPath to invoke tests. Upon completion inspects returned test status and keeps track of the total number failed tests.
[ "Navigates", "to", "testPath", "to", "invoke", "tests", ".", "Upon", "completion", "inspects", "returned", "test", "status", "and", "keeps", "track", "of", "the", "total", "number", "failed", "tests", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/protractor_spec.js#L119-L132
3,583
google/closure-library
closure/goog/html/cssspecificity.js
getSpecificity
function getSpecificity(selector) { if (userAgentProduct.IE && !userAgent.isVersionOrHigher(9)) { // IE8 has buggy regex support. return [0, 0, 0, 0]; } var specificity = specificityCache.hasOwnProperty(selector) ? specificityCache[selector] : null; if (specificity) { return specificity; } if (Object.keys(specificityCache).length > (1 << 16)) { // Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't // have such numbers of selectors. specificityCache = {}; } specificity = calculateSpecificity(selector); specificityCache[selector] = specificity; return specificity; }
javascript
function getSpecificity(selector) { if (userAgentProduct.IE && !userAgent.isVersionOrHigher(9)) { // IE8 has buggy regex support. return [0, 0, 0, 0]; } var specificity = specificityCache.hasOwnProperty(selector) ? specificityCache[selector] : null; if (specificity) { return specificity; } if (Object.keys(specificityCache).length > (1 << 16)) { // Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't // have such numbers of selectors. specificityCache = {}; } specificity = calculateSpecificity(selector); specificityCache[selector] = specificity; return specificity; }
[ "function", "getSpecificity", "(", "selector", ")", "{", "if", "(", "userAgentProduct", ".", "IE", "&&", "!", "userAgent", ".", "isVersionOrHigher", "(", "9", ")", ")", "{", "// IE8 has buggy regex support.", "return", "[", "0", ",", "0", ",", "0", ",", "0", "]", ";", "}", "var", "specificity", "=", "specificityCache", ".", "hasOwnProperty", "(", "selector", ")", "?", "specificityCache", "[", "selector", "]", ":", "null", ";", "if", "(", "specificity", ")", "{", "return", "specificity", ";", "}", "if", "(", "Object", ".", "keys", "(", "specificityCache", ")", ".", "length", ">", "(", "1", "<<", "16", ")", ")", "{", "// Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't", "// have such numbers of selectors.", "specificityCache", "=", "{", "}", ";", "}", "specificity", "=", "calculateSpecificity", "(", "selector", ")", ";", "specificityCache", "[", "selector", "]", "=", "specificity", ";", "return", "specificity", ";", "}" ]
Calculates the specificity of CSS selectors, using a global cache if supported. @see http://www.w3.org/TR/css3-selectors/#specificity @see https://specificity.keegan.st/ @param {string} selector The CSS selector. @return {!Array<number>} The CSS specificity. @supported IE9+, other browsers.
[ "Calculates", "the", "specificity", "of", "CSS", "selectors", "using", "a", "global", "cache", "if", "supported", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L39-L58
3,584
google/closure-library
closure/goog/html/cssspecificity.js
replaceWithEmptyText
function replaceWithEmptyText(selector, specificity, regex, typeIndex) { return selector.replace(regex, function(match) { specificity[typeIndex] += 1; // Replace this simple selector with whitespace so it won't be counted // in further simple selectors. return Array(match.length + 1).join(' '); }); }
javascript
function replaceWithEmptyText(selector, specificity, regex, typeIndex) { return selector.replace(regex, function(match) { specificity[typeIndex] += 1; // Replace this simple selector with whitespace so it won't be counted // in further simple selectors. return Array(match.length + 1).join(' '); }); }
[ "function", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "regex", ",", "typeIndex", ")", "{", "return", "selector", ".", "replace", "(", "regex", ",", "function", "(", "match", ")", "{", "specificity", "[", "typeIndex", "]", "+=", "1", ";", "// Replace this simple selector with whitespace so it won't be counted", "// in further simple selectors.", "return", "Array", "(", "match", ".", "length", "+", "1", ")", ".", "join", "(", "' '", ")", ";", "}", ")", ";", "}" ]
Find matches for a regular expression in the selector and increase count. @param {string} selector The selector to match the regex with. @param {!Array<number>} specificity The current specificity. @param {!RegExp} regex The regular expression. @param {number} typeIndex Index of type count. @return {string}
[ "Find", "matches", "for", "a", "regular", "expression", "in", "the", "selector", "and", "increase", "count", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L68-L75
3,585
google/closure-library
closure/goog/html/cssspecificity.js
replaceWithPlainText
function replaceWithPlainText(selector, regex) { return selector.replace(regex, function(match) { return Array(match.length + 1).join('A'); }); }
javascript
function replaceWithPlainText(selector, regex) { return selector.replace(regex, function(match) { return Array(match.length + 1).join('A'); }); }
[ "function", "replaceWithPlainText", "(", "selector", ",", "regex", ")", "{", "return", "selector", ".", "replace", "(", "regex", ",", "function", "(", "match", ")", "{", "return", "Array", "(", "match", ".", "length", "+", "1", ")", ".", "join", "(", "'A'", ")", ";", "}", ")", ";", "}" ]
Replace escaped characters with plain text, using the "A" character. @see https://www.w3.org/TR/CSS21/syndata.html#characters @param {string} selector @param {!RegExp} regex @return {string}
[ "Replace", "escaped", "characters", "with", "plain", "text", "using", "the", "A", "character", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L84-L88
3,586
google/closure-library
closure/goog/html/cssspecificity.js
calculateSpecificity
function calculateSpecificity(selector) { var specificity = [0, 0, 0, 0]; // Cannot use RegExp literals for all regular expressions, IE does not accept // the syntax. // Matches a backslash followed by six hexadecimal digits followed by an // optional single whitespace character. var escapeHexadecimalRegex = new RegExp('\\\\[0-9A-Fa-f]{6}\\s?', 'g'); // Matches a backslash followed by fewer than six hexadecimal digits // followed by a mandatory single whitespace character. var escapeHexadecimalRegex2 = new RegExp('\\\\[0-9A-Fa-f]{1,5}\\s', 'g'); // Matches a backslash followed by any character var escapeSpecialCharacter = /\\./g; selector = replaceWithPlainText(selector, escapeHexadecimalRegex); selector = replaceWithPlainText(selector, escapeHexadecimalRegex2); selector = replaceWithPlainText(selector, escapeSpecialCharacter); // Remove the negation pseudo-class (:not) but leave its argument because // specificity is calculated on its argument. var pseudoClassWithNotRegex = new RegExp(':not\\(([^\\)]*)\\)', 'g'); selector = selector.replace(pseudoClassWithNotRegex, ' $1 '); // Remove anything after a left brace in case a user has pasted in a rule, // not just a selector. var rulesRegex = new RegExp('{[^]*', 'gm'); selector = selector.replace(rulesRegex, ''); // The following regular expressions assume that selectors matching the // preceding regular expressions have been removed. // SPECIFICITY 2: Counts attribute selectors. var attributeRegex = new RegExp('(\\[[^\\]]+\\])', 'g'); selector = replaceWithEmptyText(selector, specificity, attributeRegex, 2); // SPECIFICITY 1: Counts ID selectors. var idRegex = new RegExp('(#[^\\#\\s\\+>~\\.\\[:]+)', 'g'); selector = replaceWithEmptyText(selector, specificity, idRegex, 1); // SPECIFICITY 2: Counts class selectors. var classRegex = new RegExp('(\\.[^\\s\\+>~\\.\\[:]+)', 'g'); selector = replaceWithEmptyText(selector, specificity, classRegex, 2); // SPECIFICITY 3: Counts pseudo-element selectors. var pseudoElementRegex = /(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi; selector = replaceWithEmptyText(selector, specificity, pseudoElementRegex, 3); // SPECIFICITY 2: Counts pseudo-class selectors. // A regex for pseudo classes with brackets. For example: // :nth-child() // :nth-last-child() // :nth-of-type() // :nth-last-type() // :lang() var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi; selector = replaceWithEmptyText( selector, specificity, pseudoClassWithBracketsRegex, 2); // A regex for other pseudo classes, which don't have brackets. var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g; selector = replaceWithEmptyText(selector, specificity, pseudoClassRegex, 2); // Remove universal selector and separator characters. selector = selector.replace(/[\*\s\+>~]/g, ' '); // Remove any stray dots or hashes which aren't attached to words. // These may be present if the user is live-editing this selector. selector = selector.replace(/[#\.]/g, ' '); // SPECIFICITY 3: The only things left should be element selectors. var elementRegex = /([^\s\+>~\.\[:]+)/g; selector = replaceWithEmptyText(selector, specificity, elementRegex, 3); return specificity; }
javascript
function calculateSpecificity(selector) { var specificity = [0, 0, 0, 0]; // Cannot use RegExp literals for all regular expressions, IE does not accept // the syntax. // Matches a backslash followed by six hexadecimal digits followed by an // optional single whitespace character. var escapeHexadecimalRegex = new RegExp('\\\\[0-9A-Fa-f]{6}\\s?', 'g'); // Matches a backslash followed by fewer than six hexadecimal digits // followed by a mandatory single whitespace character. var escapeHexadecimalRegex2 = new RegExp('\\\\[0-9A-Fa-f]{1,5}\\s', 'g'); // Matches a backslash followed by any character var escapeSpecialCharacter = /\\./g; selector = replaceWithPlainText(selector, escapeHexadecimalRegex); selector = replaceWithPlainText(selector, escapeHexadecimalRegex2); selector = replaceWithPlainText(selector, escapeSpecialCharacter); // Remove the negation pseudo-class (:not) but leave its argument because // specificity is calculated on its argument. var pseudoClassWithNotRegex = new RegExp(':not\\(([^\\)]*)\\)', 'g'); selector = selector.replace(pseudoClassWithNotRegex, ' $1 '); // Remove anything after a left brace in case a user has pasted in a rule, // not just a selector. var rulesRegex = new RegExp('{[^]*', 'gm'); selector = selector.replace(rulesRegex, ''); // The following regular expressions assume that selectors matching the // preceding regular expressions have been removed. // SPECIFICITY 2: Counts attribute selectors. var attributeRegex = new RegExp('(\\[[^\\]]+\\])', 'g'); selector = replaceWithEmptyText(selector, specificity, attributeRegex, 2); // SPECIFICITY 1: Counts ID selectors. var idRegex = new RegExp('(#[^\\#\\s\\+>~\\.\\[:]+)', 'g'); selector = replaceWithEmptyText(selector, specificity, idRegex, 1); // SPECIFICITY 2: Counts class selectors. var classRegex = new RegExp('(\\.[^\\s\\+>~\\.\\[:]+)', 'g'); selector = replaceWithEmptyText(selector, specificity, classRegex, 2); // SPECIFICITY 3: Counts pseudo-element selectors. var pseudoElementRegex = /(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi; selector = replaceWithEmptyText(selector, specificity, pseudoElementRegex, 3); // SPECIFICITY 2: Counts pseudo-class selectors. // A regex for pseudo classes with brackets. For example: // :nth-child() // :nth-last-child() // :nth-of-type() // :nth-last-type() // :lang() var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi; selector = replaceWithEmptyText( selector, specificity, pseudoClassWithBracketsRegex, 2); // A regex for other pseudo classes, which don't have brackets. var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g; selector = replaceWithEmptyText(selector, specificity, pseudoClassRegex, 2); // Remove universal selector and separator characters. selector = selector.replace(/[\*\s\+>~]/g, ' '); // Remove any stray dots or hashes which aren't attached to words. // These may be present if the user is live-editing this selector. selector = selector.replace(/[#\.]/g, ' '); // SPECIFICITY 3: The only things left should be element selectors. var elementRegex = /([^\s\+>~\.\[:]+)/g; selector = replaceWithEmptyText(selector, specificity, elementRegex, 3); return specificity; }
[ "function", "calculateSpecificity", "(", "selector", ")", "{", "var", "specificity", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", ";", "// Cannot use RegExp literals for all regular expressions, IE does not accept", "// the syntax.", "// Matches a backslash followed by six hexadecimal digits followed by an", "// optional single whitespace character.", "var", "escapeHexadecimalRegex", "=", "new", "RegExp", "(", "'\\\\\\\\[0-9A-Fa-f]{6}\\\\s?'", ",", "'g'", ")", ";", "// Matches a backslash followed by fewer than six hexadecimal digits", "// followed by a mandatory single whitespace character.", "var", "escapeHexadecimalRegex2", "=", "new", "RegExp", "(", "'\\\\\\\\[0-9A-Fa-f]{1,5}\\\\s'", ",", "'g'", ")", ";", "// Matches a backslash followed by any character", "var", "escapeSpecialCharacter", "=", "/", "\\\\.", "/", "g", ";", "selector", "=", "replaceWithPlainText", "(", "selector", ",", "escapeHexadecimalRegex", ")", ";", "selector", "=", "replaceWithPlainText", "(", "selector", ",", "escapeHexadecimalRegex2", ")", ";", "selector", "=", "replaceWithPlainText", "(", "selector", ",", "escapeSpecialCharacter", ")", ";", "// Remove the negation pseudo-class (:not) but leave its argument because", "// specificity is calculated on its argument.", "var", "pseudoClassWithNotRegex", "=", "new", "RegExp", "(", "':not\\\\(([^\\\\)]*)\\\\)'", ",", "'g'", ")", ";", "selector", "=", "selector", ".", "replace", "(", "pseudoClassWithNotRegex", ",", "' $1 '", ")", ";", "// Remove anything after a left brace in case a user has pasted in a rule,", "// not just a selector.", "var", "rulesRegex", "=", "new", "RegExp", "(", "'{[^]*'", ",", "'gm'", ")", ";", "selector", "=", "selector", ".", "replace", "(", "rulesRegex", ",", "''", ")", ";", "// The following regular expressions assume that selectors matching the", "// preceding regular expressions have been removed.", "// SPECIFICITY 2: Counts attribute selectors.", "var", "attributeRegex", "=", "new", "RegExp", "(", "'(\\\\[[^\\\\]]+\\\\])'", ",", "'g'", ")", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "attributeRegex", ",", "2", ")", ";", "// SPECIFICITY 1: Counts ID selectors.", "var", "idRegex", "=", "new", "RegExp", "(", "'(#[^\\\\#\\\\s\\\\+>~\\\\.\\\\[:]+)'", ",", "'g'", ")", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "idRegex", ",", "1", ")", ";", "// SPECIFICITY 2: Counts class selectors.", "var", "classRegex", "=", "new", "RegExp", "(", "'(\\\\.[^\\\\s\\\\+>~\\\\.\\\\[:]+)'", ",", "'g'", ")", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "classRegex", ",", "2", ")", ";", "// SPECIFICITY 3: Counts pseudo-element selectors.", "var", "pseudoElementRegex", "=", "/", "(::[^\\s\\+>~\\.\\[:]+|:first-line|:first-letter|:before|:after)", "/", "gi", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "pseudoElementRegex", ",", "3", ")", ";", "// SPECIFICITY 2: Counts pseudo-class selectors.", "// A regex for pseudo classes with brackets. For example:", "// :nth-child()", "// :nth-last-child()", "// :nth-of-type()", "// :nth-last-type()", "// :lang()", "var", "pseudoClassWithBracketsRegex", "=", "/", "(:[\\w-]+\\([^\\)]*\\))", "/", "gi", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "pseudoClassWithBracketsRegex", ",", "2", ")", ";", "// A regex for other pseudo classes, which don't have brackets.", "var", "pseudoClassRegex", "=", "/", "(:[^\\s\\+>~\\.\\[:]+)", "/", "g", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "pseudoClassRegex", ",", "2", ")", ";", "// Remove universal selector and separator characters.", "selector", "=", "selector", ".", "replace", "(", "/", "[\\*\\s\\+>~]", "/", "g", ",", "' '", ")", ";", "// Remove any stray dots or hashes which aren't attached to words.", "// These may be present if the user is live-editing this selector.", "selector", "=", "selector", ".", "replace", "(", "/", "[#\\.]", "/", "g", ",", "' '", ")", ";", "// SPECIFICITY 3: The only things left should be element selectors.", "var", "elementRegex", "=", "/", "([^\\s\\+>~\\.\\[:]+)", "/", "g", ";", "selector", "=", "replaceWithEmptyText", "(", "selector", ",", "specificity", ",", "elementRegex", ",", "3", ")", ";", "return", "specificity", ";", "}" ]
Calculates the specificity of CSS selectors @see http://www.w3.org/TR/css3-selectors/#specificity @see https://github.com/keeganstreet/specificity @see https://specificity.keegan.st/ @param {string} selector @return {!Array<number>} The CSS specificity.
[ "Calculates", "the", "specificity", "of", "CSS", "selectors" ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L98-L172
3,587
google/closure-library
doc/js/article.js
function(prefix, string) { return string.substring(0, prefix.length) == prefix ? string.substring(prefix.length) : ''; }
javascript
function(prefix, string) { return string.substring(0, prefix.length) == prefix ? string.substring(prefix.length) : ''; }
[ "function", "(", "prefix", ",", "string", ")", "{", "return", "string", ".", "substring", "(", "0", ",", "prefix", ".", "length", ")", "==", "prefix", "?", "string", ".", "substring", "(", "prefix", ".", "length", ")", ":", "''", ";", "}" ]
Checks for a prefix, returns everything after it if it exists
[ "Checks", "for", "a", "prefix", "returns", "everything", "after", "it", "if", "it", "exists" ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/doc/js/article.js#L292-L296
3,588
google/closure-library
closure/goog/base.js
fetchInOwnScriptThenLoad
function fetchInOwnScriptThenLoad() { /** @type {!HTMLDocument} */ var doc = goog.global.document; var key = goog.Dependency.registerCallback_(function() { goog.Dependency.unregisterCallback_(key); load(); }); var script = '<script type="text/javascript">' + goog.protectScriptTag_('goog.Dependency.callback_("' + key + '");') + '</' + 'script>'; doc.write( goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createHTML(script) : script); }
javascript
function fetchInOwnScriptThenLoad() { /** @type {!HTMLDocument} */ var doc = goog.global.document; var key = goog.Dependency.registerCallback_(function() { goog.Dependency.unregisterCallback_(key); load(); }); var script = '<script type="text/javascript">' + goog.protectScriptTag_('goog.Dependency.callback_("' + key + '");') + '</' + 'script>'; doc.write( goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createHTML(script) : script); }
[ "function", "fetchInOwnScriptThenLoad", "(", ")", "{", "/** @type {!HTMLDocument} */", "var", "doc", "=", "goog", ".", "global", ".", "document", ";", "var", "key", "=", "goog", ".", "Dependency", ".", "registerCallback_", "(", "function", "(", ")", "{", "goog", ".", "Dependency", ".", "unregisterCallback_", "(", "key", ")", ";", "load", "(", ")", ";", "}", ")", ";", "var", "script", "=", "'<script type=\"text/javascript\">'", "+", "goog", ".", "protectScriptTag_", "(", "'goog.Dependency.callback_(\"'", "+", "key", "+", "'\");'", ")", "+", "'</'", "+", "'script>'", ";", "doc", ".", "write", "(", "goog", ".", "TRUSTED_TYPES_POLICY_", "?", "goog", ".", "TRUSTED_TYPES_POLICY_", ".", "createHTML", "(", "script", ")", ":", "script", ")", ";", "}" ]
Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all events. If we fetched now and then document.write'd the contents the document.write would be an eval and would execute too soon! Instead write a script tag to fetch and eval synchronously at the correct time.
[ "Do", "not", "fetch", "now", ";", "in", "FireFox", "47", "the", "synchronous", "XHR", "doesn", "t", "block", "all", "events", ".", "If", "we", "fetched", "now", "and", "then", "document", ".", "write", "d", "the", "contents", "the", "document", ".", "write", "would", "be", "an", "eval", "and", "would", "execute", "too", "soon!", "Instead", "write", "a", "script", "tag", "to", "fetch", "and", "eval", "synchronously", "at", "the", "correct", "time", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/base.js#L3752-L3769
3,589
google/closure-library
closure/goog/html/sanitizer/csspropertysanitizer.js
getSafeUri
function getSafeUri(uri, propName, uriRewriter) { if (!uriRewriter) { return null; } var safeUri = uriRewriter(uri, propName); if (safeUri && SafeUrl.unwrap(safeUri) != SafeUrl.INNOCUOUS_STRING) { return 'url("' + SafeUrl.unwrap(safeUri).replace(NORM_URL_REGEXP, normalizeUrlChar) + '")'; } return null; }
javascript
function getSafeUri(uri, propName, uriRewriter) { if (!uriRewriter) { return null; } var safeUri = uriRewriter(uri, propName); if (safeUri && SafeUrl.unwrap(safeUri) != SafeUrl.INNOCUOUS_STRING) { return 'url("' + SafeUrl.unwrap(safeUri).replace(NORM_URL_REGEXP, normalizeUrlChar) + '")'; } return null; }
[ "function", "getSafeUri", "(", "uri", ",", "propName", ",", "uriRewriter", ")", "{", "if", "(", "!", "uriRewriter", ")", "{", "return", "null", ";", "}", "var", "safeUri", "=", "uriRewriter", "(", "uri", ",", "propName", ")", ";", "if", "(", "safeUri", "&&", "SafeUrl", ".", "unwrap", "(", "safeUri", ")", "!=", "SafeUrl", ".", "INNOCUOUS_STRING", ")", "{", "return", "'url(\"'", "+", "SafeUrl", ".", "unwrap", "(", "safeUri", ")", ".", "replace", "(", "NORM_URL_REGEXP", ",", "normalizeUrlChar", ")", "+", "'\")'", ";", "}", "return", "null", ";", "}" ]
Constructs a safe URI from a given URI and prop using a given uriRewriter function. @param {string} uri URI to be sanitized. @param {string} propName Property name which contained the URI. @param {?function(string, string):?SafeUrl} uriRewriter A URI rewriter that returns a {@link SafeUrl}. @return {?string} Safe URI for use in CSS.
[ "Constructs", "a", "safe", "URI", "from", "a", "given", "URI", "and", "prop", "using", "a", "given", "uriRewriter", "function", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/csspropertysanitizer.js#L92-L103
3,590
google/closure-library
closure/goog/labs/net/webchannel/forwardchannelrequestpool.js
function(opt_maxPoolSize) { /** * The max pool size as configured. * * @private {number} */ this.maxPoolSizeConfigured_ = opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_; /** * The current size limit of the request pool. This limit is meant to be * read-only after the channel is fully opened. * * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also * configurable. * * @private {number} */ this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ? this.maxPoolSizeConfigured_ : 1; /** * The container for all the pending request objects. * * @private {Set<ChannelRequest>} */ this.requestPool_ = null; if (this.maxSize_ > 1) { this.requestPool_ = new Set(); } /** * The single request object when the pool size is limited to one. * * @private {ChannelRequest} */ this.request_ = null; /** * Saved pending messages when the pool is cancelled. * * @private {!Array<Wire.QueuedMap>} */ this.pendingMessages_ = []; }
javascript
function(opt_maxPoolSize) { /** * The max pool size as configured. * * @private {number} */ this.maxPoolSizeConfigured_ = opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_; /** * The current size limit of the request pool. This limit is meant to be * read-only after the channel is fully opened. * * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also * configurable. * * @private {number} */ this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ? this.maxPoolSizeConfigured_ : 1; /** * The container for all the pending request objects. * * @private {Set<ChannelRequest>} */ this.requestPool_ = null; if (this.maxSize_ > 1) { this.requestPool_ = new Set(); } /** * The single request object when the pool size is limited to one. * * @private {ChannelRequest} */ this.request_ = null; /** * Saved pending messages when the pool is cancelled. * * @private {!Array<Wire.QueuedMap>} */ this.pendingMessages_ = []; }
[ "function", "(", "opt_maxPoolSize", ")", "{", "/**\n * The max pool size as configured.\n *\n * @private {number}\n */", "this", ".", "maxPoolSizeConfigured_", "=", "opt_maxPoolSize", "||", "ForwardChannelRequestPool", ".", "MAX_POOL_SIZE_", ";", "/**\n * The current size limit of the request pool. This limit is meant to be\n * read-only after the channel is fully opened.\n *\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\n * configurable.\n *\n * @private {number}\n */", "this", ".", "maxSize_", "=", "ForwardChannelRequestPool", ".", "isSpdyOrHttp2Enabled_", "(", ")", "?", "this", ".", "maxPoolSizeConfigured_", ":", "1", ";", "/**\n * The container for all the pending request objects.\n *\n * @private {Set<ChannelRequest>}\n */", "this", ".", "requestPool_", "=", "null", ";", "if", "(", "this", ".", "maxSize_", ">", "1", ")", "{", "this", ".", "requestPool_", "=", "new", "Set", "(", ")", ";", "}", "/**\n * The single request object when the pool size is limited to one.\n *\n * @private {ChannelRequest}\n */", "this", ".", "request_", "=", "null", ";", "/**\n * Saved pending messages when the pool is cancelled.\n *\n * @private {!Array<Wire.QueuedMap>}\n */", "this", ".", "pendingMessages_", "=", "[", "]", ";", "}" ]
This class represents the state of all forward channel requests. @param {number=} opt_maxPoolSize The maximum pool size. @struct @constructor @final
[ "This", "class", "represents", "the", "state", "of", "all", "forward", "channel", "requests", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js#L38-L84
3,591
google/closure-library
closure/goog/loader/activemodulemanager.js
get
function get() { if (!moduleManager && getDefault) { moduleManager = getDefault(); } asserts.assert( moduleManager != null, 'The module manager has not yet been set.'); return moduleManager; }
javascript
function get() { if (!moduleManager && getDefault) { moduleManager = getDefault(); } asserts.assert( moduleManager != null, 'The module manager has not yet been set.'); return moduleManager; }
[ "function", "get", "(", ")", "{", "if", "(", "!", "moduleManager", "&&", "getDefault", ")", "{", "moduleManager", "=", "getDefault", "(", ")", ";", "}", "asserts", ".", "assert", "(", "moduleManager", "!=", "null", ",", "'The module manager has not yet been set.'", ")", ";", "return", "moduleManager", ";", "}" ]
Gets the active module manager, instantiating one if necessary. @return {!AbstractModuleManager}
[ "Gets", "the", "active", "module", "manager", "instantiating", "one", "if", "necessary", "." ]
97390e9ca4483cebb9628e06026139fbb3023d65
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/loader/activemodulemanager.js#L36-L43
3,592
mrvautin/expressCart
lib/common.js
fixProductDates
function fixProductDates(products){ let index = 0; products.forEach((product) => { products[index].productAddedDate = new Date(); index++; }); return products; }
javascript
function fixProductDates(products){ let index = 0; products.forEach((product) => { products[index].productAddedDate = new Date(); index++; }); return products; }
[ "function", "fixProductDates", "(", "products", ")", "{", "let", "index", "=", "0", ";", "products", ".", "forEach", "(", "(", "product", ")", "=>", "{", "products", "[", "index", "]", ".", "productAddedDate", "=", "new", "Date", "(", ")", ";", "index", "++", ";", "}", ")", ";", "return", "products", ";", "}" ]
Adds current date to product added date when smashing into DB
[ "Adds", "current", "date", "to", "product", "added", "date", "when", "smashing", "into", "DB" ]
0b6071b6d963d786684fb9cfa7d1ccc499c3ce27
https://github.com/mrvautin/expressCart/blob/0b6071b6d963d786684fb9cfa7d1ccc499c3ce27/lib/common.js#L721-L728
3,593
NetEase/pomelo
template/web-server/public/js/lib/build/build.js
mixin
function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; }
javascript
function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; }
[ "function", "mixin", "(", "obj", ")", "{", "for", "(", "var", "key", "in", "Emitter", ".", "prototype", ")", "{", "obj", "[", "key", "]", "=", "Emitter", ".", "prototype", "[", "key", "]", ";", "}", "return", "obj", ";", "}" ]
Mixin the emitter properties. @param {Object} obj @return {Object} @api private
[ "Mixin", "the", "emitter", "properties", "." ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/template/web-server/public/js/lib/build/build.js#L254-L259
3,594
NetEase/pomelo
template/web-server/public/js/lib/build/build.js
encode2UTF8
function encode2UTF8(charCode){ if(charCode <= 0x7f){ return [charCode]; }else if(charCode <= 0x7ff){ return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)]; }else{ return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; } }
javascript
function encode2UTF8(charCode){ if(charCode <= 0x7f){ return [charCode]; }else if(charCode <= 0x7ff){ return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)]; }else{ return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; } }
[ "function", "encode2UTF8", "(", "charCode", ")", "{", "if", "(", "charCode", "<=", "0x7f", ")", "{", "return", "[", "charCode", "]", ";", "}", "else", "if", "(", "charCode", "<=", "0x7ff", ")", "{", "return", "[", "0xc0", "|", "(", "charCode", ">>", "6", ")", ",", "0x80", "|", "(", "charCode", "&", "0x3f", ")", "]", ";", "}", "else", "{", "return", "[", "0xe0", "|", "(", "charCode", ">>", "12", ")", ",", "0x80", "|", "(", "(", "charCode", "&", "0xfc0", ")", ">>", "6", ")", ",", "0x80", "|", "(", "charCode", "&", "0x3f", ")", "]", ";", "}", "}" ]
Encode a unicode16 char code to utf8 bytes
[ "Encode", "a", "unicode16", "char", "code", "to", "utf8", "bytes" ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/template/web-server/public/js/lib/build/build.js#L974-L982
3,595
NetEase/pomelo
lib/common/service/channelService.js
function(app, opts) { opts = opts || {}; this.app = app; this.channels = {}; this.prefix = opts.prefix; this.store = opts.store; this.broadcastFilter = opts.broadcastFilter; this.channelRemote = new ChannelRemote(app); }
javascript
function(app, opts) { opts = opts || {}; this.app = app; this.channels = {}; this.prefix = opts.prefix; this.store = opts.store; this.broadcastFilter = opts.broadcastFilter; this.channelRemote = new ChannelRemote(app); }
[ "function", "(", "app", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "app", "=", "app", ";", "this", ".", "channels", "=", "{", "}", ";", "this", ".", "prefix", "=", "opts", ".", "prefix", ";", "this", ".", "store", "=", "opts", ".", "store", ";", "this", ".", "broadcastFilter", "=", "opts", ".", "broadcastFilter", ";", "this", ".", "channelRemote", "=", "new", "ChannelRemote", "(", "app", ")", ";", "}" ]
Create and maintain channels for server local. ChannelService is created by channel component which is a default loaded component of pomelo and channel service would be accessed by `app.get('channelService')`. @class @constructor
[ "Create", "and", "maintain", "channels", "for", "server", "local", "." ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/channelService.js#L21-L29
3,596
NetEase/pomelo
lib/common/service/channelService.js
function(name, service) { this.name = name; this.groups = {}; // group map for uids. key: sid, value: [uid] this.records = {}; // member records. key: uid this.__channelService__ = service; this.state = ST_INITED; this.userAmount =0; }
javascript
function(name, service) { this.name = name; this.groups = {}; // group map for uids. key: sid, value: [uid] this.records = {}; // member records. key: uid this.__channelService__ = service; this.state = ST_INITED; this.userAmount =0; }
[ "function", "(", "name", ",", "service", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "groups", "=", "{", "}", ";", "// group map for uids. key: sid, value: [uid]", "this", ".", "records", "=", "{", "}", ";", "// member records. key: uid", "this", ".", "__channelService__", "=", "service", ";", "this", ".", "state", "=", "ST_INITED", ";", "this", ".", "userAmount", "=", "0", ";", "}" ]
Channel maintains the receiver collection for a subject. You can add users into a channel and then broadcast message to them by channel. @class channel @constructor
[ "Channel", "maintains", "the", "receiver", "collection", "for", "a", "subject", ".", "You", "can", "add", "users", "into", "a", "channel", "and", "then", "broadcast", "message", "to", "them", "by", "channel", "." ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/channelService.js#L205-L212
3,597
NetEase/pomelo
lib/common/service/channelService.js
function(uid, sid, groups) { if(!sid) { logger.warn('ignore uid %j for sid not specified.', uid); return false; } var group = groups[sid]; if(!group) { group = []; groups[sid] = group; } group.push(uid); return true; }
javascript
function(uid, sid, groups) { if(!sid) { logger.warn('ignore uid %j for sid not specified.', uid); return false; } var group = groups[sid]; if(!group) { group = []; groups[sid] = group; } group.push(uid); return true; }
[ "function", "(", "uid", ",", "sid", ",", "groups", ")", "{", "if", "(", "!", "sid", ")", "{", "logger", ".", "warn", "(", "'ignore uid %j for sid not specified.'", ",", "uid", ")", ";", "return", "false", ";", "}", "var", "group", "=", "groups", "[", "sid", "]", ";", "if", "(", "!", "group", ")", "{", "group", "=", "[", "]", ";", "groups", "[", "sid", "]", "=", "group", ";", "}", "group", ".", "push", "(", "uid", ")", ";", "return", "true", ";", "}" ]
add uid and sid into group. ignore any uid that uid not specified. @param uid user id @param sid server id @param groups {Object} grouped uids, , key: sid, value: [uid]
[ "add", "uid", "and", "sid", "into", "group", ".", "ignore", "any", "uid", "that", "uid", "not", "specified", "." ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/channelService.js#L340-L354
3,598
NetEase/pomelo
lib/common/service/sessionService.js
function(sid, frontendId, socket, service) { EventEmitter.call(this); this.id = sid; // r this.frontendId = frontendId; // r this.uid = null; // r this.settings = {}; // private this.__socket__ = socket; this.__sessionService__ = service; this.__state__ = ST_INITED; }
javascript
function(sid, frontendId, socket, service) { EventEmitter.call(this); this.id = sid; // r this.frontendId = frontendId; // r this.uid = null; // r this.settings = {}; // private this.__socket__ = socket; this.__sessionService__ = service; this.__state__ = ST_INITED; }
[ "function", "(", "sid", ",", "frontendId", ",", "socket", ",", "service", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "id", "=", "sid", ";", "// r", "this", ".", "frontendId", "=", "frontendId", ";", "// r", "this", ".", "uid", "=", "null", ";", "// r", "this", ".", "settings", "=", "{", "}", ";", "// private", "this", ".", "__socket__", "=", "socket", ";", "this", ".", "__sessionService__", "=", "service", ";", "this", ".", "__state__", "=", "ST_INITED", ";", "}" ]
Session maintains the relationship between client connection and user information. There is a session associated with each client connection. And it should bind to a user id after the client passes the identification. Session is created in frontend server and should not be accessed in handler. There is a proxy class called BackendSession in backend servers and FrontendSession in frontend servers.
[ "Session", "maintains", "the", "relationship", "between", "client", "connection", "and", "user", "information", ".", "There", "is", "a", "session", "associated", "with", "each", "client", "connection", ".", "And", "it", "should", "bind", "to", "a", "user", "id", "after", "the", "client", "passes", "the", "identification", "." ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/sessionService.js#L431-L442
3,599
NetEase/pomelo
lib/common/service/sessionService.js
function(session) { EventEmitter.call(this); clone(session, this, FRONTEND_SESSION_FIELDS); // deep copy for settings this.settings = dclone(session.settings); this.__session__ = session; }
javascript
function(session) { EventEmitter.call(this); clone(session, this, FRONTEND_SESSION_FIELDS); // deep copy for settings this.settings = dclone(session.settings); this.__session__ = session; }
[ "function", "(", "session", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "clone", "(", "session", ",", "this", ",", "FRONTEND_SESSION_FIELDS", ")", ";", "// deep copy for settings", "this", ".", "settings", "=", "dclone", "(", "session", ".", "settings", ")", ";", "this", ".", "__session__", "=", "session", ";", "}" ]
Frontend session for frontend server.
[ "Frontend", "session", "for", "frontend", "server", "." ]
defcf019631ed399cc4dad932d3b028a04a039a4
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/sessionService.js#L557-L563