id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
18,000
kriskowal/asap
scripts/gauntlet.js
measure
function measure(test, done) { var start = now(); test(function (error, results) { var stop = now(); done(error, results, stop - start); }); }
javascript
function measure(test, done) { var start = now(); test(function (error, results) { var stop = now(); done(error, results, stop - start); }); }
[ "function", "measure", "(", "test", ",", "done", ")", "{", "var", "start", "=", "now", "(", ")", ";", "test", "(", "function", "(", "error", ",", "results", ")", "{", "var", "stop", "=", "now", "(", ")", ";", "done", "(", "error", ",", "results", ",", "stop", "-", "start", ")", ";", "}", ")", ";", "}" ]
measures the duration of one iteration
[ "measures", "the", "duration", "of", "one", "iteration" ]
3e3d99381444379bb0483cb9216caa39ac67bebb
https://github.com/kriskowal/asap/blob/3e3d99381444379bb0483cb9216caa39ac67bebb/scripts/gauntlet.js#L49-L55
18,001
kriskowal/asap
scripts/gauntlet.js
sample
function sample(test, asap, minDuration, sampleSize, done) { var count = 0; var totalDuration = 0; var sampleDurations = []; next(); function next() { measure(function (done) { test(asap, done); }, function (error, results, duration) { if (error) { done(error); } if (sampleDurations.length < sampleSize) { sampleDurations.push(duration); } else if (Math.random() < 1 / count) { sampleDurations.splice(Math.floor(Math.random() * sampleDurations.length), 1); sampleDurations.push(duration); } totalDuration += duration; count++; if (totalDuration >= minDuration) { done(null, { name: test.name, subjectName: asap.name, count: count, totalDuration: totalDuration, averageFrequency: count / totalDuration, averageDuration: totalDuration / count, averageOpsHz: count / totalDuration, sampleDurations: sampleDurations }); } else { next(); } }); } }
javascript
function sample(test, asap, minDuration, sampleSize, done) { var count = 0; var totalDuration = 0; var sampleDurations = []; next(); function next() { measure(function (done) { test(asap, done); }, function (error, results, duration) { if (error) { done(error); } if (sampleDurations.length < sampleSize) { sampleDurations.push(duration); } else if (Math.random() < 1 / count) { sampleDurations.splice(Math.floor(Math.random() * sampleDurations.length), 1); sampleDurations.push(duration); } totalDuration += duration; count++; if (totalDuration >= minDuration) { done(null, { name: test.name, subjectName: asap.name, count: count, totalDuration: totalDuration, averageFrequency: count / totalDuration, averageDuration: totalDuration / count, averageOpsHz: count / totalDuration, sampleDurations: sampleDurations }); } else { next(); } }); } }
[ "function", "sample", "(", "test", ",", "asap", ",", "minDuration", ",", "sampleSize", ",", "done", ")", "{", "var", "count", "=", "0", ";", "var", "totalDuration", "=", "0", ";", "var", "sampleDurations", "=", "[", "]", ";", "next", "(", ")", ";", "function", "next", "(", ")", "{", "measure", "(", "function", "(", "done", ")", "{", "test", "(", "asap", ",", "done", ")", ";", "}", ",", "function", "(", "error", ",", "results", ",", "duration", ")", "{", "if", "(", "error", ")", "{", "done", "(", "error", ")", ";", "}", "if", "(", "sampleDurations", ".", "length", "<", "sampleSize", ")", "{", "sampleDurations", ".", "push", "(", "duration", ")", ";", "}", "else", "if", "(", "Math", ".", "random", "(", ")", "<", "1", "/", "count", ")", "{", "sampleDurations", ".", "splice", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "sampleDurations", ".", "length", ")", ",", "1", ")", ";", "sampleDurations", ".", "push", "(", "duration", ")", ";", "}", "totalDuration", "+=", "duration", ";", "count", "++", ";", "if", "(", "totalDuration", ">=", "minDuration", ")", "{", "done", "(", "null", ",", "{", "name", ":", "test", ".", "name", ",", "subjectName", ":", "asap", ".", "name", ",", "count", ":", "count", ",", "totalDuration", ":", "totalDuration", ",", "averageFrequency", ":", "count", "/", "totalDuration", ",", "averageDuration", ":", "totalDuration", "/", "count", ",", "averageOpsHz", ":", "count", "/", "totalDuration", ",", "sampleDurations", ":", "sampleDurations", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
measures iterations of the test for a duration, maintaining a representative sample of the measurements up to a given size
[ "measures", "iterations", "of", "the", "test", "for", "a", "duration", "maintaining", "a", "representative", "sample", "of", "the", "measurements", "up", "to", "a", "given", "size" ]
3e3d99381444379bb0483cb9216caa39ac67bebb
https://github.com/kriskowal/asap/blob/3e3d99381444379bb0483cb9216caa39ac67bebb/scripts/gauntlet.js#L59-L95
18,002
vesln/nixt
lib/nixt/expectations.js
assertOut
function assertOut(key, expected, result) { var actual = result[key]; var statement = expected instanceof RegExp ? expected.test(actual) : expected === actual; if (statement !== true) { var message = 'Expected ' + key +' to match "' + expected + '". Actual: "' + actual + '"'; return error(result, message, expected, actual); } }
javascript
function assertOut(key, expected, result) { var actual = result[key]; var statement = expected instanceof RegExp ? expected.test(actual) : expected === actual; if (statement !== true) { var message = 'Expected ' + key +' to match "' + expected + '". Actual: "' + actual + '"'; return error(result, message, expected, actual); } }
[ "function", "assertOut", "(", "key", ",", "expected", ",", "result", ")", "{", "var", "actual", "=", "result", "[", "key", "]", ";", "var", "statement", "=", "expected", "instanceof", "RegExp", "?", "expected", ".", "test", "(", "actual", ")", ":", "expected", "===", "actual", ";", "if", "(", "statement", "!==", "true", ")", "{", "var", "message", "=", "'Expected '", "+", "key", "+", "' to match \"'", "+", "expected", "+", "'\". Actual: \"'", "+", "actual", "+", "'\"'", ";", "return", "error", "(", "result", ",", "message", ",", "expected", ",", "actual", ")", ";", "}", "}" ]
Assert stdout or stderr. @param {String} stdout/stderr @param {Mixed} expected @param {Result} result @returns {AssertionError|null} @api private
[ "Assert", "stdout", "or", "stderr", "." ]
d2075099ecf935c870705fa5d5de437113d4d272
https://github.com/vesln/nixt/blob/d2075099ecf935c870705fa5d5de437113d4d272/lib/nixt/expectations.js#L138-L148
18,003
vesln/nixt
lib/nixt/expectations.js
error
function error(result, message, expected, actual) { var err = new AssertionError('`' + result.cmd + '`: ' + message); err.result = result; if (expected) err.expected = expected; if (actual) err.actual = actual; return err; }
javascript
function error(result, message, expected, actual) { var err = new AssertionError('`' + result.cmd + '`: ' + message); err.result = result; if (expected) err.expected = expected; if (actual) err.actual = actual; return err; }
[ "function", "error", "(", "result", ",", "message", ",", "expected", ",", "actual", ")", "{", "var", "err", "=", "new", "AssertionError", "(", "'`'", "+", "result", ".", "cmd", "+", "'`: '", "+", "message", ")", ";", "err", ".", "result", "=", "result", ";", "if", "(", "expected", ")", "err", ".", "expected", "=", "expected", ";", "if", "(", "actual", ")", "err", ".", "actual", "=", "actual", ";", "return", "err", ";", "}" ]
Create and return a new `AssertionError`. It will assign the given `result` to it, it will also prepend the executed command to the error message. Assertion error is a constructor for test and validation frameworks that implements standardized Assertion Error specification. For more info go visit https://github.com/chaijs/assertion-error @param {Result} result @param {String} error message @returns {AssertionError} @api private
[ "Create", "and", "return", "a", "new", "AssertionError", ".", "It", "will", "assign", "the", "given", "result", "to", "it", "it", "will", "also", "prepend", "the", "executed", "command", "to", "the", "error", "message", "." ]
d2075099ecf935c870705fa5d5de437113d4d272
https://github.com/vesln/nixt/blob/d2075099ecf935c870705fa5d5de437113d4d272/lib/nixt/expectations.js#L166-L172
18,004
vesln/nixt
lib/nixt/result.js
Result
function Result(cmd, code, options) { options = options || {}; this.options = options; this.code = code; this.cmd = cmd; }
javascript
function Result(cmd, code, options) { options = options || {}; this.options = options; this.code = code; this.cmd = cmd; }
[ "function", "Result", "(", "cmd", ",", "code", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "options", "=", "options", ";", "this", ".", "code", "=", "code", ";", "this", ".", "cmd", "=", "cmd", ";", "}" ]
Simple object that contains the result of command executions. @constructor
[ "Simple", "object", "that", "contains", "the", "result", "of", "command", "executions", "." ]
d2075099ecf935c870705fa5d5de437113d4d272
https://github.com/vesln/nixt/blob/d2075099ecf935c870705fa5d5de437113d4d272/lib/nixt/result.js#L8-L13
18,005
vesln/nixt
lib/nixt/runner.js
Runner
function Runner(options) { if (!(this instanceof Runner)) return new Runner(options); options = options || {}; this.options = options; this.batch = new Batch; this.world = new World; this.expectations = []; this.prompts = []; this.responses = []; this.baseCmd = ''; this.standardInput = null; }
javascript
function Runner(options) { if (!(this instanceof Runner)) return new Runner(options); options = options || {}; this.options = options; this.batch = new Batch; this.world = new World; this.expectations = []; this.prompts = []; this.responses = []; this.baseCmd = ''; this.standardInput = null; }
[ "function", "Runner", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Runner", ")", ")", "return", "new", "Runner", "(", "options", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "options", "=", "options", ";", "this", ".", "batch", "=", "new", "Batch", ";", "this", ".", "world", "=", "new", "World", ";", "this", ".", "expectations", "=", "[", "]", ";", "this", ".", "prompts", "=", "[", "]", ";", "this", ".", "responses", "=", "[", "]", ";", "this", ".", "baseCmd", "=", "''", ";", "this", ".", "standardInput", "=", "null", ";", "}" ]
The primary entry point for every Nixt test. It provides public interface that the users will interact with. Every `Runner` instance can be cloned and this way one can build the so called "templates". Options: - colors: default - true, Strip colors from stdout and stderr when `false` - newlines: default - true, Strip new lines from stdout and stderr when `false` Examples: Instantiating the class: nixt() // -> Runner new nixt // -> Runner Simple stdout assertion: nixt({ colors: false, newlines: false }) .exec('todo clear') .exec('todo Buy milk') .run('todo ls') .stdout('Buy milk') .end(fn); Stdout assertion: nixt({ colors: false, newlines: false }) .exec('todo clear') .run('todo') .stderr('Please enter a todo') .end(fn); So repeating "todo clear" is simply ugly. You can avoid this by creating a "template". var todo = nixt().before(clearTodos); Later on: todo.clone().exec... For more examples check the "README" file. @see Batch @param {Object} options @constructor
[ "The", "primary", "entry", "point", "for", "every", "Nixt", "test", ".", "It", "provides", "public", "interface", "that", "the", "users", "will", "interact", "with", ".", "Every", "Runner", "instance", "can", "be", "cloned", "and", "this", "way", "one", "can", "build", "the", "so", "called", "templates", "." ]
d2075099ecf935c870705fa5d5de437113d4d272
https://github.com/vesln/nixt/blob/d2075099ecf935c870705fa5d5de437113d4d272/lib/nixt/runner.js#L70-L81
18,006
vesln/nixt
lib/nixt/world.js
World
function World(env, cwd) { this.env = env || clone(process.env); this.cwd = cwd; this.timeout = null; }
javascript
function World(env, cwd) { this.env = env || clone(process.env); this.cwd = cwd; this.timeout = null; }
[ "function", "World", "(", "env", ",", "cwd", ")", "{", "this", ".", "env", "=", "env", "||", "clone", "(", "process", ".", "env", ")", ";", "this", ".", "cwd", "=", "cwd", ";", "this", ".", "timeout", "=", "null", ";", "}" ]
Contain the environment variables and the current working directory for commands. @param {Object} env @param {String} cwd @constructor
[ "Contain", "the", "environment", "variables", "and", "the", "current", "working", "directory", "for", "commands", "." ]
d2075099ecf935c870705fa5d5de437113d4d272
https://github.com/vesln/nixt/blob/d2075099ecf935c870705fa5d5de437113d4d272/lib/nixt/world.js#L16-L20
18,007
vivliostyle/vivliostyle.js
src/vivliostyle/counters.js
cloneCounterValues
function cloneCounterValues(counters) { const result = {}; Object.keys(counters).forEach(name => { result[name] = Array.from(counters[name]); }); return result; }
javascript
function cloneCounterValues(counters) { const result = {}; Object.keys(counters).forEach(name => { result[name] = Array.from(counters[name]); }); return result; }
[ "function", "cloneCounterValues", "(", "counters", ")", "{", "const", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "counters", ")", ".", "forEach", "(", "name", "=>", "{", "result", "[", "name", "]", "=", "Array", ".", "from", "(", "counters", "[", "name", "]", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Clone counter values. @param {!adapt.csscasc.CounterValues} counters @returns {!adapt.csscasc.CounterValues}
[ "Clone", "counter", "values", "." ]
edad7782d3cf368203fc0ed229bc0bb4585ef8ad
https://github.com/vivliostyle/vivliostyle.js/blob/edad7782d3cf368203fc0ed229bc0bb4585ef8ad/src/vivliostyle/counters.js#L35-L41
18,008
btd/rollup-plugin-visualizer
plugin.js
flattenTree
function flattenTree(root) { let newChildren = []; root.children.forEach(child => { const commonParent = getDeepMoreThenOneChild(child); if (commonParent.children.length === 0) { newChildren.push(commonParent); } else { newChildren = newChildren.concat(commonParent.children); } }); root.children = newChildren; }
javascript
function flattenTree(root) { let newChildren = []; root.children.forEach(child => { const commonParent = getDeepMoreThenOneChild(child); if (commonParent.children.length === 0) { newChildren.push(commonParent); } else { newChildren = newChildren.concat(commonParent.children); } }); root.children = newChildren; }
[ "function", "flattenTree", "(", "root", ")", "{", "let", "newChildren", "=", "[", "]", ";", "root", ".", "children", ".", "forEach", "(", "child", "=>", "{", "const", "commonParent", "=", "getDeepMoreThenOneChild", "(", "child", ")", ";", "if", "(", "commonParent", ".", "children", ".", "length", "===", "0", ")", "{", "newChildren", ".", "push", "(", "commonParent", ")", ";", "}", "else", "{", "newChildren", "=", "newChildren", ".", "concat", "(", "commonParent", ".", "children", ")", ";", "}", "}", ")", ";", "root", ".", "children", "=", "newChildren", ";", "}" ]
if root children have only on child we can flatten this
[ "if", "root", "children", "have", "only", "on", "child", "we", "can", "flatten", "this" ]
a867784a93b191ea4bce174c849b7f89d5c265ae
https://github.com/btd/rollup-plugin-visualizer/blob/a867784a93b191ea4bce174c849b7f89d5c265ae/plugin.js#L129-L140
18,009
alanshaw/david
lib/david.js
normaliseDeps
function normaliseDeps (deps) { if (Array.isArray(deps)) { deps = deps.reduce(function (d, depName) { d[depName] = '*' return d }, {}) } return deps }
javascript
function normaliseDeps (deps) { if (Array.isArray(deps)) { deps = deps.reduce(function (d, depName) { d[depName] = '*' return d }, {}) } return deps }
[ "function", "normaliseDeps", "(", "deps", ")", "{", "if", "(", "Array", ".", "isArray", "(", "deps", ")", ")", "{", "deps", "=", "deps", ".", "reduce", "(", "function", "(", "d", ",", "depName", ")", "{", "d", "[", "depName", "]", "=", "'*'", "return", "d", "}", ",", "{", "}", ")", "}", "return", "deps", "}" ]
Convert dependencies specified as an array to an object
[ "Convert", "dependencies", "specified", "as", "an", "array", "to", "an", "object" ]
008beaf57c661df130d667352147539d0256b46f
https://github.com/alanshaw/david/blob/008beaf57c661df130d667352147539d0256b46f/lib/david.js#L15-L23
18,010
alanshaw/david
bin/david.js
printWarnings
function printWarnings (deps, type) { if (!Object.keys(deps).length) return var warnings = { E404: {title: 'Unregistered', list: []}, ESCM: {title: 'SCM', list: []}, EDEPTYPE: {title: 'Non-string dependency', list: []} } for (var name in deps) { var dep = deps[name] if (dep.warn) { warnings[dep.warn.code].list.push([clc.magenta(name), clc.red(dep.warn.toString())]) } } Object.keys(warnings).forEach(function (warnType) { var warnList = warnings[warnType].list if (!warnList.length) return var table = new Table({head: ['Name', 'Message'], style: {head: ['reset']}}) console.log(clc.underline(warnings[warnType].title + ' ' + (type ? type + 'D' : 'd') + 'ependencies') + '\n') warnList.forEach(function (row) { table.push(row) }) console.log(table.toString() + '\n') }) }
javascript
function printWarnings (deps, type) { if (!Object.keys(deps).length) return var warnings = { E404: {title: 'Unregistered', list: []}, ESCM: {title: 'SCM', list: []}, EDEPTYPE: {title: 'Non-string dependency', list: []} } for (var name in deps) { var dep = deps[name] if (dep.warn) { warnings[dep.warn.code].list.push([clc.magenta(name), clc.red(dep.warn.toString())]) } } Object.keys(warnings).forEach(function (warnType) { var warnList = warnings[warnType].list if (!warnList.length) return var table = new Table({head: ['Name', 'Message'], style: {head: ['reset']}}) console.log(clc.underline(warnings[warnType].title + ' ' + (type ? type + 'D' : 'd') + 'ependencies') + '\n') warnList.forEach(function (row) { table.push(row) }) console.log(table.toString() + '\n') }) }
[ "function", "printWarnings", "(", "deps", ",", "type", ")", "{", "if", "(", "!", "Object", ".", "keys", "(", "deps", ")", ".", "length", ")", "return", "var", "warnings", "=", "{", "E404", ":", "{", "title", ":", "'Unregistered'", ",", "list", ":", "[", "]", "}", ",", "ESCM", ":", "{", "title", ":", "'SCM'", ",", "list", ":", "[", "]", "}", ",", "EDEPTYPE", ":", "{", "title", ":", "'Non-string dependency'", ",", "list", ":", "[", "]", "}", "}", "for", "(", "var", "name", "in", "deps", ")", "{", "var", "dep", "=", "deps", "[", "name", "]", "if", "(", "dep", ".", "warn", ")", "{", "warnings", "[", "dep", ".", "warn", ".", "code", "]", ".", "list", ".", "push", "(", "[", "clc", ".", "magenta", "(", "name", ")", ",", "clc", ".", "red", "(", "dep", ".", "warn", ".", "toString", "(", ")", ")", "]", ")", "}", "}", "Object", ".", "keys", "(", "warnings", ")", ".", "forEach", "(", "function", "(", "warnType", ")", "{", "var", "warnList", "=", "warnings", "[", "warnType", "]", ".", "list", "if", "(", "!", "warnList", ".", "length", ")", "return", "var", "table", "=", "new", "Table", "(", "{", "head", ":", "[", "'Name'", ",", "'Message'", "]", ",", "style", ":", "{", "head", ":", "[", "'reset'", "]", "}", "}", ")", "console", ".", "log", "(", "clc", ".", "underline", "(", "warnings", "[", "warnType", "]", ".", "title", "+", "' '", "+", "(", "type", "?", "type", "+", "'D'", ":", "'d'", ")", "+", "'ependencies'", ")", "+", "'\\n'", ")", "warnList", ".", "forEach", "(", "function", "(", "row", ")", "{", "table", ".", "push", "(", "row", ")", "}", ")", "console", ".", "log", "(", "table", ".", "toString", "(", ")", "+", "'\\n'", ")", "}", ")", "}" ]
Like printDeps, walk the list, but only print dependencies with warnings. @param {Object} deps @param {String} type
[ "Like", "printDeps", "walk", "the", "list", "but", "only", "print", "dependencies", "with", "warnings", "." ]
008beaf57c661df130d667352147539d0256b46f
https://github.com/alanshaw/david/blob/008beaf57c661df130d667352147539d0256b46f/bin/david.js#L40-L68
18,011
alanshaw/david
bin/david.js
getUpdatedDeps
function getUpdatedDeps (pkg, cb) { var opts = { stable: !argv.unstable, loose: true, error: { E404: argv.error404, ESCM: argv.errorSCM, EDEPTYPE: argv.errorDepType }, ignore: argv.ignore || argv.i } if (argv.registry) { opts.npm = {registry: argv.registry} } david.getUpdatedDependencies(pkg, opts, function (err, deps) { if (err) return cb(err) david.getUpdatedDependencies(pkg, xtend(opts, {dev: true}), function (err, devDeps) { if (err) return cb(err) david.getUpdatedDependencies(pkg, xtend(opts, {optional: true}), function (err, optionalDeps) { cb(err, filterDeps(deps), filterDeps(devDeps), filterDeps(optionalDeps)) }) }) }) }
javascript
function getUpdatedDeps (pkg, cb) { var opts = { stable: !argv.unstable, loose: true, error: { E404: argv.error404, ESCM: argv.errorSCM, EDEPTYPE: argv.errorDepType }, ignore: argv.ignore || argv.i } if (argv.registry) { opts.npm = {registry: argv.registry} } david.getUpdatedDependencies(pkg, opts, function (err, deps) { if (err) return cb(err) david.getUpdatedDependencies(pkg, xtend(opts, {dev: true}), function (err, devDeps) { if (err) return cb(err) david.getUpdatedDependencies(pkg, xtend(opts, {optional: true}), function (err, optionalDeps) { cb(err, filterDeps(deps), filterDeps(devDeps), filterDeps(optionalDeps)) }) }) }) }
[ "function", "getUpdatedDeps", "(", "pkg", ",", "cb", ")", "{", "var", "opts", "=", "{", "stable", ":", "!", "argv", ".", "unstable", ",", "loose", ":", "true", ",", "error", ":", "{", "E404", ":", "argv", ".", "error404", ",", "ESCM", ":", "argv", ".", "errorSCM", ",", "EDEPTYPE", ":", "argv", ".", "errorDepType", "}", ",", "ignore", ":", "argv", ".", "ignore", "||", "argv", ".", "i", "}", "if", "(", "argv", ".", "registry", ")", "{", "opts", ".", "npm", "=", "{", "registry", ":", "argv", ".", "registry", "}", "}", "david", ".", "getUpdatedDependencies", "(", "pkg", ",", "opts", ",", "function", "(", "err", ",", "deps", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "david", ".", "getUpdatedDependencies", "(", "pkg", ",", "xtend", "(", "opts", ",", "{", "dev", ":", "true", "}", ")", ",", "function", "(", "err", ",", "devDeps", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "david", ".", "getUpdatedDependencies", "(", "pkg", ",", "xtend", "(", "opts", ",", "{", "optional", ":", "true", "}", ")", ",", "function", "(", "err", ",", "optionalDeps", ")", "{", "cb", "(", "err", ",", "filterDeps", "(", "deps", ")", ",", "filterDeps", "(", "devDeps", ")", ",", "filterDeps", "(", "optionalDeps", ")", ")", "}", ")", "}", ")", "}", ")", "}" ]
Get updated deps, devDeps and optionalDeps
[ "Get", "updated", "deps", "devDeps", "and", "optionalDeps" ]
008beaf57c661df130d667352147539d0256b46f
https://github.com/alanshaw/david/blob/008beaf57c661df130d667352147539d0256b46f/bin/david.js#L132-L159
18,012
alanshaw/david
bin/david.js
installDeps
function installDeps (deps, opts, cb) { opts = opts || {} var depNames = Object.keys(deps) // Nothing to install! if (!depNames.length) { return cb(null) } depNames = depNames.filter(function (depName) { return !deps[depName].warn }) var npmOpts = {global: opts.global} // Avoid warning message from npm for invalid registry url if (opts.registry) { npmOpts.registry = opts.registry } npm.load(npmOpts, function (err) { if (err) return cb(err) if (opts.save) { npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), true) } var installArgs = [depNames.map(function (depName) { return depName + '@' + deps[depName][argv.unstable ? 'latest' : 'stable'] }), function (err) { npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), false) cb(err) }] if (opts.path) { installArgs.unshift(opts.path) } npm.commands.install.apply(npm.commands, installArgs) }) }
javascript
function installDeps (deps, opts, cb) { opts = opts || {} var depNames = Object.keys(deps) // Nothing to install! if (!depNames.length) { return cb(null) } depNames = depNames.filter(function (depName) { return !deps[depName].warn }) var npmOpts = {global: opts.global} // Avoid warning message from npm for invalid registry url if (opts.registry) { npmOpts.registry = opts.registry } npm.load(npmOpts, function (err) { if (err) return cb(err) if (opts.save) { npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), true) } var installArgs = [depNames.map(function (depName) { return depName + '@' + deps[depName][argv.unstable ? 'latest' : 'stable'] }), function (err) { npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), false) cb(err) }] if (opts.path) { installArgs.unshift(opts.path) } npm.commands.install.apply(npm.commands, installArgs) }) }
[ "function", "installDeps", "(", "deps", ",", "opts", ",", "cb", ")", "{", "opts", "=", "opts", "||", "{", "}", "var", "depNames", "=", "Object", ".", "keys", "(", "deps", ")", "// Nothing to install!", "if", "(", "!", "depNames", ".", "length", ")", "{", "return", "cb", "(", "null", ")", "}", "depNames", "=", "depNames", ".", "filter", "(", "function", "(", "depName", ")", "{", "return", "!", "deps", "[", "depName", "]", ".", "warn", "}", ")", "var", "npmOpts", "=", "{", "global", ":", "opts", ".", "global", "}", "// Avoid warning message from npm for invalid registry url", "if", "(", "opts", ".", "registry", ")", "{", "npmOpts", ".", "registry", "=", "opts", ".", "registry", "}", "npm", ".", "load", "(", "npmOpts", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "opts", ".", "save", ")", "{", "npm", ".", "config", ".", "set", "(", "'save'", "+", "(", "opts", ".", "dev", "?", "'-dev'", ":", "opts", ".", "optional", "?", "'-optional'", ":", "''", ")", ",", "true", ")", "}", "var", "installArgs", "=", "[", "depNames", ".", "map", "(", "function", "(", "depName", ")", "{", "return", "depName", "+", "'@'", "+", "deps", "[", "depName", "]", "[", "argv", ".", "unstable", "?", "'latest'", ":", "'stable'", "]", "}", ")", ",", "function", "(", "err", ")", "{", "npm", ".", "config", ".", "set", "(", "'save'", "+", "(", "opts", ".", "dev", "?", "'-dev'", ":", "opts", ".", "optional", "?", "'-optional'", ":", "''", ")", ",", "false", ")", "cb", "(", "err", ")", "}", "]", "if", "(", "opts", ".", "path", ")", "{", "installArgs", ".", "unshift", "(", "opts", ".", "path", ")", "}", "npm", ".", "commands", ".", "install", ".", "apply", "(", "npm", ".", "commands", ",", "installArgs", ")", "}", ")", "}" ]
Install the passed dependencies @param {Object} deps Dependencies to install (result from david) @param {Object} opts Install options @param {Boolean} [opts.global] Install globally @param {Boolean} [opts.save] Save installed dependencies to dependencies/devDependencies/optionalDependencies @param {Boolean} [opts.dev] Provided dependencies are dev dependencies @param {Boolean} [opts.optional] Provided dependencies are optional dependencies @param {String} [opts.registry] The npm registry URL to use @param {Function} cb Callback
[ "Install", "the", "passed", "dependencies" ]
008beaf57c661df130d667352147539d0256b46f
https://github.com/alanshaw/david/blob/008beaf57c661df130d667352147539d0256b46f/bin/david.js#L173-L212
18,013
alanshaw/david
lib/version.js
isScm
function isScm (version) { var scmPrefixes = ['git:', 'git+ssh:', 'https:', 'git+https:'] var blacklisted = scmPrefixes.filter(function (prefix) { return version.indexOf(prefix) === 0 }) return !!blacklisted.length }
javascript
function isScm (version) { var scmPrefixes = ['git:', 'git+ssh:', 'https:', 'git+https:'] var blacklisted = scmPrefixes.filter(function (prefix) { return version.indexOf(prefix) === 0 }) return !!blacklisted.length }
[ "function", "isScm", "(", "version", ")", "{", "var", "scmPrefixes", "=", "[", "'git:'", ",", "'git+ssh:'", ",", "'https:'", ",", "'git+https:'", "]", "var", "blacklisted", "=", "scmPrefixes", ".", "filter", "(", "function", "(", "prefix", ")", "{", "return", "version", ".", "indexOf", "(", "prefix", ")", "===", "0", "}", ")", "return", "!", "!", "blacklisted", ".", "length", "}" ]
Determine if a version is a SCM URL or not. @param {String} version @return {Boolean}
[ "Determine", "if", "a", "version", "is", "a", "SCM", "URL", "or", "not", "." ]
008beaf57c661df130d667352147539d0256b46f
https://github.com/alanshaw/david/blob/008beaf57c661df130d667352147539d0256b46f/lib/version.js#L21-L27
18,014
IceCreamYou/MainLoop.js
src/mainloop.js
function() { if (!started) { // Since the application doesn't start running immediately, track // whether this function was called and use that to keep it from // starting the main loop multiple times. started = true; // In the main loop, draw() is called after update(), so if we // entered the main loop immediately, we would never render the // initial state before any updates occur. Instead, we run one // frame where all we do is draw, and then start the main loop with // the next frame. rafHandle = requestAnimationFrame(function(timestamp) { // Render the initial state before any updates occur. draw(1); // The application isn't considered "running" until the // application starts drawing. running = true; // Reset variables that are used for tracking time so that we // don't simulate time passed while the application was paused. lastFrameTimeMs = timestamp; lastFpsUpdate = timestamp; framesSinceLastFpsUpdate = 0; // Start the main loop. rafHandle = requestAnimationFrame(animate); }); } return this; }
javascript
function() { if (!started) { // Since the application doesn't start running immediately, track // whether this function was called and use that to keep it from // starting the main loop multiple times. started = true; // In the main loop, draw() is called after update(), so if we // entered the main loop immediately, we would never render the // initial state before any updates occur. Instead, we run one // frame where all we do is draw, and then start the main loop with // the next frame. rafHandle = requestAnimationFrame(function(timestamp) { // Render the initial state before any updates occur. draw(1); // The application isn't considered "running" until the // application starts drawing. running = true; // Reset variables that are used for tracking time so that we // don't simulate time passed while the application was paused. lastFrameTimeMs = timestamp; lastFpsUpdate = timestamp; framesSinceLastFpsUpdate = 0; // Start the main loop. rafHandle = requestAnimationFrame(animate); }); } return this; }
[ "function", "(", ")", "{", "if", "(", "!", "started", ")", "{", "// Since the application doesn't start running immediately, track", "// whether this function was called and use that to keep it from", "// starting the main loop multiple times.", "started", "=", "true", ";", "// In the main loop, draw() is called after update(), so if we", "// entered the main loop immediately, we would never render the", "// initial state before any updates occur. Instead, we run one", "// frame where all we do is draw, and then start the main loop with", "// the next frame.", "rafHandle", "=", "requestAnimationFrame", "(", "function", "(", "timestamp", ")", "{", "// Render the initial state before any updates occur.", "draw", "(", "1", ")", ";", "// The application isn't considered \"running\" until the", "// application starts drawing.", "running", "=", "true", ";", "// Reset variables that are used for tracking time so that we", "// don't simulate time passed while the application was paused.", "lastFrameTimeMs", "=", "timestamp", ";", "lastFpsUpdate", "=", "timestamp", ";", "framesSinceLastFpsUpdate", "=", "0", ";", "// Start the main loop.", "rafHandle", "=", "requestAnimationFrame", "(", "animate", ")", ";", "}", ")", ";", "}", "return", "this", ";", "}" ]
Starts the main loop. Note that the application is not considered "running" immediately after this function returns; rather, it is considered "running" after the application draws its first frame. The distinction is that event handlers should remain paused until the application is running, even after `MainLoop.start()` is called. Check `MainLoop.isRunning()` for the current status. To act after the application starts, register a callback with requestAnimationFrame() after calling this function and execute the action in that callback. It is safe to call `MainLoop.start()` multiple times even before the application starts running and without calling `MainLoop.stop()` in between, although there is no reason to do this; the main loop will only start if it is not already started. See also `MainLoop.stop()`.
[ "Starts", "the", "main", "loop", "." ]
8ba83c370dba01e2d38e8daf6a8b285cf475afd5
https://github.com/IceCreamYou/MainLoop.js/blob/8ba83c370dba01e2d38e8daf6a8b285cf475afd5/src/mainloop.js#L495-L526
18,015
IceCreamYou/MainLoop.js
src/mainloop.js
animate
function animate(timestamp) { // Run the loop again the next time the browser is ready to render. // We set rafHandle immediately so that the next frame can be canceled // during the current frame. rafHandle = requestAnimationFrame(animate); // Throttle the frame rate (if minFrameDelay is set to a non-zero value by // `MainLoop.setMaxAllowedFPS()`). if (timestamp < lastFrameTimeMs + minFrameDelay) { return; } // frameDelta is the cumulative amount of in-app time that hasn't been // simulated yet. Add the time since the last frame. We need to track total // not-yet-simulated time (as opposed to just the time elapsed since the // last frame) because not all actually elapsed time is guaranteed to be // simulated each frame. See the comments below for details. frameDelta += timestamp - lastFrameTimeMs; lastFrameTimeMs = timestamp; // Run any updates that are not dependent on time in the simulation. See // `MainLoop.setBegin()` for additional details on how to use this. begin(timestamp, frameDelta); // Update the estimate of the frame rate, `fps`. Approximately every // second, the number of frames that occurred in that second are included // in an exponential moving average of all frames per second. This means // that more recent seconds affect the estimated frame rate more than older // seconds. if (timestamp > lastFpsUpdate + fpsUpdateInterval) { // Compute the new exponential moving average. fps = // Divide the number of frames since the last FPS update by the // amount of time that has passed to get the mean frames per second // over that period. This is necessary because slightly more than a // second has likely passed since the last update. fpsAlpha * framesSinceLastFpsUpdate * 1000 / (timestamp - lastFpsUpdate) + (1 - fpsAlpha) * fps; // Reset the frame counter and last-updated timestamp since their // latest values have now been incorporated into the FPS estimate. lastFpsUpdate = timestamp; framesSinceLastFpsUpdate = 0; } // Count the current frame in the next frames-per-second update. This // happens after the previous section because the previous section // calculates the frames that occur up until `timestamp`, and `timestamp` // refers to a time just before the current frame was delivered. framesSinceLastFpsUpdate++; /* * A naive way to move an object along its X-axis might be to write a main * loop containing the statement `obj.x += 10;` which would move the object * 10 units per frame. This approach suffers from the issue that it is * dependent on the frame rate. In other words, if your application is * running slowly (that is, fewer frames per second), your object will also * appear to move slowly, whereas if your application is running quickly * (that is, more frames per second), your object will appear to move * quickly. This is undesirable, especially in multiplayer/multi-user * applications. * * One solution is to multiply the speed by the amount of time that has * passed between rendering frames. For example, if you want your object to * move 600 units per second, you might write `obj.x += 600 * delta`, where * `delta` is the time passed since the last frame. (For convenience, let's * move this statement to an update() function that takes `delta` as a * parameter.) This way, your object will move a constant distance over * time. However, at low frame rates and high speeds, your object will move * large distances every frame, which can cause it to do strange things * such as move through walls. Additionally, we would like our program to * be deterministic. That is, every time we run the application with the * same input, we would like exactly the same output. If the time between * frames (the `delta`) varies, our output will diverge the longer the * program runs due to accumulated rounding errors, even at normal frame * rates. * * A better solution is to separate the amount of time simulated in each * update() from the amount of time between frames. Our update() function * doesn't need to change; we just need to change the delta we pass to it * so that each update() simulates a fixed amount of time (that is, `delta` * should have the same value each time update() is called). The update() * function can be run multiple times per frame if needed to simulate the * total amount of time passed since the last frame. (If the time that has * passed since the last frame is less than the fixed simulation time, we * just won't run an update() until the the next frame. If there is * unsimulated time left over that is less than our timestep, we'll just * leave it to be simulated during the next frame.) This approach avoids * inconsistent rounding errors and ensures that there are no giant leaps * through walls between frames. * * That is what is done below. It introduces a new problem, but it is a * manageable one: if the amount of time spent simulating is consistently * longer than the amount of time between frames, the application could * freeze and crash in a spiral of death. This won't happen as long as the * fixed simulation time is set to a value that is high enough that * update() calls usually take less time than the amount of time they're * simulating. If it does start to happen anyway, see `MainLoop.setEnd()` * for a discussion of ways to stop it. * * Additionally, see `MainLoop.setUpdate()` for a discussion of performance * considerations. * * Further reading for those interested: * * - http://gameprogrammingpatterns.com/game-loop.html * - http://gafferongames.com/game-physics/fix-your-timestep/ * - https://gamealchemist.wordpress.com/2013/03/16/thoughts-on-the-javascript-game-loop/ * - https://developer.mozilla.org/en-US/docs/Games/Anatomy */ numUpdateSteps = 0; while (frameDelta >= simulationTimestep) { update(simulationTimestep); frameDelta -= simulationTimestep; /* * Sanity check: bail if we run the loop too many times. * * One way this could happen is if update() takes longer to run than * the time it simulates, thereby causing a spiral of death. For ways * to avoid this, see `MainLoop.setEnd()`. Another way this could * happen is if the browser throttles serving frames, which typically * occurs when the tab is in the background or the device battery is * low. An event outside of the main loop such as audio processing or * synchronous resource reads could also cause the application to hang * temporarily and accumulate not-yet-simulated time as a result. * * 240 is chosen because, for any sane value of simulationTimestep, 240 * updates will simulate at least one second, and it will simulate four * seconds with the default value of simulationTimestep. (Safari * notifies users that the script is taking too long to run if it takes * more than five seconds.) * * If there are more updates to run in a frame than this, the * application will appear to slow down to the user until it catches * back up. In networked applications this will usually cause the user * to get out of sync with their peers, but if the updates are taking * this long already, they're probably already out of sync. */ if (++numUpdateSteps >= 240) { panic = true; break; } } /* * Render the screen. We do this regardless of whether update() has run * during this frame because it is possible to interpolate between updates * to make the frame rate appear faster than updates are actually * happening. See `MainLoop.setDraw()` for an explanation of how to do * that. * * We draw after updating because we want the screen to reflect a state of * the application that is as up-to-date as possible. (`MainLoop.start()` * draws the very first frame in the application's initial state, before * any updates have occurred.) Some sources speculate that rendering * earlier in the requestAnimationFrame callback can get the screen painted * faster; this is mostly not true, and even when it is, it's usually just * a trade-off between rendering the current frame sooner and rendering the * next frame later. * * See `MainLoop.setDraw()` for details about draw() itself. */ draw(frameDelta / simulationTimestep); // Run any updates that are not dependent on time in the simulation. See // `MainLoop.setEnd()` for additional details on how to use this. end(fps, panic); panic = false; }
javascript
function animate(timestamp) { // Run the loop again the next time the browser is ready to render. // We set rafHandle immediately so that the next frame can be canceled // during the current frame. rafHandle = requestAnimationFrame(animate); // Throttle the frame rate (if minFrameDelay is set to a non-zero value by // `MainLoop.setMaxAllowedFPS()`). if (timestamp < lastFrameTimeMs + minFrameDelay) { return; } // frameDelta is the cumulative amount of in-app time that hasn't been // simulated yet. Add the time since the last frame. We need to track total // not-yet-simulated time (as opposed to just the time elapsed since the // last frame) because not all actually elapsed time is guaranteed to be // simulated each frame. See the comments below for details. frameDelta += timestamp - lastFrameTimeMs; lastFrameTimeMs = timestamp; // Run any updates that are not dependent on time in the simulation. See // `MainLoop.setBegin()` for additional details on how to use this. begin(timestamp, frameDelta); // Update the estimate of the frame rate, `fps`. Approximately every // second, the number of frames that occurred in that second are included // in an exponential moving average of all frames per second. This means // that more recent seconds affect the estimated frame rate more than older // seconds. if (timestamp > lastFpsUpdate + fpsUpdateInterval) { // Compute the new exponential moving average. fps = // Divide the number of frames since the last FPS update by the // amount of time that has passed to get the mean frames per second // over that period. This is necessary because slightly more than a // second has likely passed since the last update. fpsAlpha * framesSinceLastFpsUpdate * 1000 / (timestamp - lastFpsUpdate) + (1 - fpsAlpha) * fps; // Reset the frame counter and last-updated timestamp since their // latest values have now been incorporated into the FPS estimate. lastFpsUpdate = timestamp; framesSinceLastFpsUpdate = 0; } // Count the current frame in the next frames-per-second update. This // happens after the previous section because the previous section // calculates the frames that occur up until `timestamp`, and `timestamp` // refers to a time just before the current frame was delivered. framesSinceLastFpsUpdate++; /* * A naive way to move an object along its X-axis might be to write a main * loop containing the statement `obj.x += 10;` which would move the object * 10 units per frame. This approach suffers from the issue that it is * dependent on the frame rate. In other words, if your application is * running slowly (that is, fewer frames per second), your object will also * appear to move slowly, whereas if your application is running quickly * (that is, more frames per second), your object will appear to move * quickly. This is undesirable, especially in multiplayer/multi-user * applications. * * One solution is to multiply the speed by the amount of time that has * passed between rendering frames. For example, if you want your object to * move 600 units per second, you might write `obj.x += 600 * delta`, where * `delta` is the time passed since the last frame. (For convenience, let's * move this statement to an update() function that takes `delta` as a * parameter.) This way, your object will move a constant distance over * time. However, at low frame rates and high speeds, your object will move * large distances every frame, which can cause it to do strange things * such as move through walls. Additionally, we would like our program to * be deterministic. That is, every time we run the application with the * same input, we would like exactly the same output. If the time between * frames (the `delta`) varies, our output will diverge the longer the * program runs due to accumulated rounding errors, even at normal frame * rates. * * A better solution is to separate the amount of time simulated in each * update() from the amount of time between frames. Our update() function * doesn't need to change; we just need to change the delta we pass to it * so that each update() simulates a fixed amount of time (that is, `delta` * should have the same value each time update() is called). The update() * function can be run multiple times per frame if needed to simulate the * total amount of time passed since the last frame. (If the time that has * passed since the last frame is less than the fixed simulation time, we * just won't run an update() until the the next frame. If there is * unsimulated time left over that is less than our timestep, we'll just * leave it to be simulated during the next frame.) This approach avoids * inconsistent rounding errors and ensures that there are no giant leaps * through walls between frames. * * That is what is done below. It introduces a new problem, but it is a * manageable one: if the amount of time spent simulating is consistently * longer than the amount of time between frames, the application could * freeze and crash in a spiral of death. This won't happen as long as the * fixed simulation time is set to a value that is high enough that * update() calls usually take less time than the amount of time they're * simulating. If it does start to happen anyway, see `MainLoop.setEnd()` * for a discussion of ways to stop it. * * Additionally, see `MainLoop.setUpdate()` for a discussion of performance * considerations. * * Further reading for those interested: * * - http://gameprogrammingpatterns.com/game-loop.html * - http://gafferongames.com/game-physics/fix-your-timestep/ * - https://gamealchemist.wordpress.com/2013/03/16/thoughts-on-the-javascript-game-loop/ * - https://developer.mozilla.org/en-US/docs/Games/Anatomy */ numUpdateSteps = 0; while (frameDelta >= simulationTimestep) { update(simulationTimestep); frameDelta -= simulationTimestep; /* * Sanity check: bail if we run the loop too many times. * * One way this could happen is if update() takes longer to run than * the time it simulates, thereby causing a spiral of death. For ways * to avoid this, see `MainLoop.setEnd()`. Another way this could * happen is if the browser throttles serving frames, which typically * occurs when the tab is in the background or the device battery is * low. An event outside of the main loop such as audio processing or * synchronous resource reads could also cause the application to hang * temporarily and accumulate not-yet-simulated time as a result. * * 240 is chosen because, for any sane value of simulationTimestep, 240 * updates will simulate at least one second, and it will simulate four * seconds with the default value of simulationTimestep. (Safari * notifies users that the script is taking too long to run if it takes * more than five seconds.) * * If there are more updates to run in a frame than this, the * application will appear to slow down to the user until it catches * back up. In networked applications this will usually cause the user * to get out of sync with their peers, but if the updates are taking * this long already, they're probably already out of sync. */ if (++numUpdateSteps >= 240) { panic = true; break; } } /* * Render the screen. We do this regardless of whether update() has run * during this frame because it is possible to interpolate between updates * to make the frame rate appear faster than updates are actually * happening. See `MainLoop.setDraw()` for an explanation of how to do * that. * * We draw after updating because we want the screen to reflect a state of * the application that is as up-to-date as possible. (`MainLoop.start()` * draws the very first frame in the application's initial state, before * any updates have occurred.) Some sources speculate that rendering * earlier in the requestAnimationFrame callback can get the screen painted * faster; this is mostly not true, and even when it is, it's usually just * a trade-off between rendering the current frame sooner and rendering the * next frame later. * * See `MainLoop.setDraw()` for details about draw() itself. */ draw(frameDelta / simulationTimestep); // Run any updates that are not dependent on time in the simulation. See // `MainLoop.setEnd()` for additional details on how to use this. end(fps, panic); panic = false; }
[ "function", "animate", "(", "timestamp", ")", "{", "// Run the loop again the next time the browser is ready to render.", "// We set rafHandle immediately so that the next frame can be canceled", "// during the current frame.", "rafHandle", "=", "requestAnimationFrame", "(", "animate", ")", ";", "// Throttle the frame rate (if minFrameDelay is set to a non-zero value by", "// `MainLoop.setMaxAllowedFPS()`).", "if", "(", "timestamp", "<", "lastFrameTimeMs", "+", "minFrameDelay", ")", "{", "return", ";", "}", "// frameDelta is the cumulative amount of in-app time that hasn't been", "// simulated yet. Add the time since the last frame. We need to track total", "// not-yet-simulated time (as opposed to just the time elapsed since the", "// last frame) because not all actually elapsed time is guaranteed to be", "// simulated each frame. See the comments below for details.", "frameDelta", "+=", "timestamp", "-", "lastFrameTimeMs", ";", "lastFrameTimeMs", "=", "timestamp", ";", "// Run any updates that are not dependent on time in the simulation. See", "// `MainLoop.setBegin()` for additional details on how to use this.", "begin", "(", "timestamp", ",", "frameDelta", ")", ";", "// Update the estimate of the frame rate, `fps`. Approximately every", "// second, the number of frames that occurred in that second are included", "// in an exponential moving average of all frames per second. This means", "// that more recent seconds affect the estimated frame rate more than older", "// seconds.", "if", "(", "timestamp", ">", "lastFpsUpdate", "+", "fpsUpdateInterval", ")", "{", "// Compute the new exponential moving average.", "fps", "=", "// Divide the number of frames since the last FPS update by the", "// amount of time that has passed to get the mean frames per second", "// over that period. This is necessary because slightly more than a", "// second has likely passed since the last update.", "fpsAlpha", "*", "framesSinceLastFpsUpdate", "*", "1000", "/", "(", "timestamp", "-", "lastFpsUpdate", ")", "+", "(", "1", "-", "fpsAlpha", ")", "*", "fps", ";", "// Reset the frame counter and last-updated timestamp since their", "// latest values have now been incorporated into the FPS estimate.", "lastFpsUpdate", "=", "timestamp", ";", "framesSinceLastFpsUpdate", "=", "0", ";", "}", "// Count the current frame in the next frames-per-second update. This", "// happens after the previous section because the previous section", "// calculates the frames that occur up until `timestamp`, and `timestamp`", "// refers to a time just before the current frame was delivered.", "framesSinceLastFpsUpdate", "++", ";", "/*\n * A naive way to move an object along its X-axis might be to write a main\n * loop containing the statement `obj.x += 10;` which would move the object\n * 10 units per frame. This approach suffers from the issue that it is\n * dependent on the frame rate. In other words, if your application is\n * running slowly (that is, fewer frames per second), your object will also\n * appear to move slowly, whereas if your application is running quickly\n * (that is, more frames per second), your object will appear to move\n * quickly. This is undesirable, especially in multiplayer/multi-user\n * applications.\n *\n * One solution is to multiply the speed by the amount of time that has\n * passed between rendering frames. For example, if you want your object to\n * move 600 units per second, you might write `obj.x += 600 * delta`, where\n * `delta` is the time passed since the last frame. (For convenience, let's\n * move this statement to an update() function that takes `delta` as a\n * parameter.) This way, your object will move a constant distance over\n * time. However, at low frame rates and high speeds, your object will move\n * large distances every frame, which can cause it to do strange things\n * such as move through walls. Additionally, we would like our program to\n * be deterministic. That is, every time we run the application with the\n * same input, we would like exactly the same output. If the time between\n * frames (the `delta`) varies, our output will diverge the longer the\n * program runs due to accumulated rounding errors, even at normal frame\n * rates.\n *\n * A better solution is to separate the amount of time simulated in each\n * update() from the amount of time between frames. Our update() function\n * doesn't need to change; we just need to change the delta we pass to it\n * so that each update() simulates a fixed amount of time (that is, `delta`\n * should have the same value each time update() is called). The update()\n * function can be run multiple times per frame if needed to simulate the\n * total amount of time passed since the last frame. (If the time that has\n * passed since the last frame is less than the fixed simulation time, we\n * just won't run an update() until the the next frame. If there is\n * unsimulated time left over that is less than our timestep, we'll just\n * leave it to be simulated during the next frame.) This approach avoids\n * inconsistent rounding errors and ensures that there are no giant leaps\n * through walls between frames.\n *\n * That is what is done below. It introduces a new problem, but it is a\n * manageable one: if the amount of time spent simulating is consistently\n * longer than the amount of time between frames, the application could\n * freeze and crash in a spiral of death. This won't happen as long as the\n * fixed simulation time is set to a value that is high enough that\n * update() calls usually take less time than the amount of time they're\n * simulating. If it does start to happen anyway, see `MainLoop.setEnd()`\n * for a discussion of ways to stop it.\n *\n * Additionally, see `MainLoop.setUpdate()` for a discussion of performance\n * considerations.\n *\n * Further reading for those interested:\n *\n * - http://gameprogrammingpatterns.com/game-loop.html\n * - http://gafferongames.com/game-physics/fix-your-timestep/\n * - https://gamealchemist.wordpress.com/2013/03/16/thoughts-on-the-javascript-game-loop/\n * - https://developer.mozilla.org/en-US/docs/Games/Anatomy\n */", "numUpdateSteps", "=", "0", ";", "while", "(", "frameDelta", ">=", "simulationTimestep", ")", "{", "update", "(", "simulationTimestep", ")", ";", "frameDelta", "-=", "simulationTimestep", ";", "/*\n * Sanity check: bail if we run the loop too many times.\n *\n * One way this could happen is if update() takes longer to run than\n * the time it simulates, thereby causing a spiral of death. For ways\n * to avoid this, see `MainLoop.setEnd()`. Another way this could\n * happen is if the browser throttles serving frames, which typically\n * occurs when the tab is in the background or the device battery is\n * low. An event outside of the main loop such as audio processing or\n * synchronous resource reads could also cause the application to hang\n * temporarily and accumulate not-yet-simulated time as a result.\n *\n * 240 is chosen because, for any sane value of simulationTimestep, 240\n * updates will simulate at least one second, and it will simulate four\n * seconds with the default value of simulationTimestep. (Safari\n * notifies users that the script is taking too long to run if it takes\n * more than five seconds.)\n *\n * If there are more updates to run in a frame than this, the\n * application will appear to slow down to the user until it catches\n * back up. In networked applications this will usually cause the user\n * to get out of sync with their peers, but if the updates are taking\n * this long already, they're probably already out of sync.\n */", "if", "(", "++", "numUpdateSteps", ">=", "240", ")", "{", "panic", "=", "true", ";", "break", ";", "}", "}", "/*\n * Render the screen. We do this regardless of whether update() has run\n * during this frame because it is possible to interpolate between updates\n * to make the frame rate appear faster than updates are actually\n * happening. See `MainLoop.setDraw()` for an explanation of how to do\n * that.\n *\n * We draw after updating because we want the screen to reflect a state of\n * the application that is as up-to-date as possible. (`MainLoop.start()`\n * draws the very first frame in the application's initial state, before\n * any updates have occurred.) Some sources speculate that rendering\n * earlier in the requestAnimationFrame callback can get the screen painted\n * faster; this is mostly not true, and even when it is, it's usually just\n * a trade-off between rendering the current frame sooner and rendering the\n * next frame later.\n *\n * See `MainLoop.setDraw()` for details about draw() itself.\n */", "draw", "(", "frameDelta", "/", "simulationTimestep", ")", ";", "// Run any updates that are not dependent on time in the simulation. See", "// `MainLoop.setEnd()` for additional details on how to use this.", "end", "(", "fps", ",", "panic", ")", ";", "panic", "=", "false", ";", "}" ]
The main loop that runs updates and rendering. @param {DOMHighResTimeStamp} timestamp The current timestamp. In practice this is supplied by requestAnimationFrame at the time that it starts to fire callbacks. This should only be used for comparison to other timestamps because the epoch (i.e. the "zero" time) depends on the engine running this code. In engines that support `DOMHighResTimeStamp` (all modern browsers except iOS Safari 8) the epoch is the time the page started loading, specifically `performance.timing.navigationStart`. Everywhere else, including node.js, the epoch is the Unix epoch (1970-01-01T00:00:00Z). @ignore
[ "The", "main", "loop", "that", "runs", "updates", "and", "rendering", "." ]
8ba83c370dba01e2d38e8daf6a8b285cf475afd5
https://github.com/IceCreamYou/MainLoop.js/blob/8ba83c370dba01e2d38e8daf6a8b285cf475afd5/src/mainloop.js#L576-L745
18,016
TooTallNate/plist.js
lib/build.js
build
function build (obj, opts) { var XMLHDR = { version: '1.0', encoding: 'UTF-8' }; var XMLDTD = { pubid: '-//Apple//DTD PLIST 1.0//EN', sysid: 'http://www.apple.com/DTDs/PropertyList-1.0.dtd' }; var doc = xmlbuilder.create('plist'); doc.dec(XMLHDR.version, XMLHDR.encoding, XMLHDR.standalone); doc.dtd(XMLDTD.pubid, XMLDTD.sysid); doc.att('version', '1.0'); walk_obj(obj, doc); if (!opts) opts = {}; // default `pretty` to `true` opts.pretty = opts.pretty !== false; return doc.end(opts); }
javascript
function build (obj, opts) { var XMLHDR = { version: '1.0', encoding: 'UTF-8' }; var XMLDTD = { pubid: '-//Apple//DTD PLIST 1.0//EN', sysid: 'http://www.apple.com/DTDs/PropertyList-1.0.dtd' }; var doc = xmlbuilder.create('plist'); doc.dec(XMLHDR.version, XMLHDR.encoding, XMLHDR.standalone); doc.dtd(XMLDTD.pubid, XMLDTD.sysid); doc.att('version', '1.0'); walk_obj(obj, doc); if (!opts) opts = {}; // default `pretty` to `true` opts.pretty = opts.pretty !== false; return doc.end(opts); }
[ "function", "build", "(", "obj", ",", "opts", ")", "{", "var", "XMLHDR", "=", "{", "version", ":", "'1.0'", ",", "encoding", ":", "'UTF-8'", "}", ";", "var", "XMLDTD", "=", "{", "pubid", ":", "'-//Apple//DTD PLIST 1.0//EN'", ",", "sysid", ":", "'http://www.apple.com/DTDs/PropertyList-1.0.dtd'", "}", ";", "var", "doc", "=", "xmlbuilder", ".", "create", "(", "'plist'", ")", ";", "doc", ".", "dec", "(", "XMLHDR", ".", "version", ",", "XMLHDR", ".", "encoding", ",", "XMLHDR", ".", "standalone", ")", ";", "doc", ".", "dtd", "(", "XMLDTD", ".", "pubid", ",", "XMLDTD", ".", "sysid", ")", ";", "doc", ".", "att", "(", "'version'", ",", "'1.0'", ")", ";", "walk_obj", "(", "obj", ",", "doc", ")", ";", "if", "(", "!", "opts", ")", "opts", "=", "{", "}", ";", "// default `pretty` to `true`", "opts", ".", "pretty", "=", "opts", ".", "pretty", "!==", "false", ";", "return", "doc", ".", "end", "(", "opts", ")", ";", "}" ]
Generate an XML plist string from the input object `obj`. @param {Object} obj - the object to convert @param {Object} [opts] - optional options object @returns {String} converted plist XML string @api public
[ "Generate", "an", "XML", "plist", "string", "from", "the", "input", "object", "obj", "." ]
1628c6ecc5462be367ac203225af3b55ed5e564c
https://github.com/TooTallNate/plist.js/blob/1628c6ecc5462be367ac203225af3b55ed5e564c/lib/build.js#L58-L81
18,017
TooTallNate/plist.js
lib/build.js
walk_obj
function walk_obj(next, next_child) { var tag_type, i, prop; var name = type(next); if ('Undefined' == name) { return; } else if (Array.isArray(next)) { next_child = next_child.ele('array'); for (i = 0; i < next.length; i++) { walk_obj(next[i], next_child); } } else if (Buffer.isBuffer(next)) { next_child.ele('data').raw(next.toString('base64')); } else if ('Object' == name) { next_child = next_child.ele('dict'); for (prop in next) { if (next.hasOwnProperty(prop)) { next_child.ele('key').txt(prop); walk_obj(next[prop], next_child); } } } else if ('Number' == name) { // detect if this is an integer or real // TODO: add an ability to force one way or another via a "cast" tag_type = (next % 1 === 0) ? 'integer' : 'real'; next_child.ele(tag_type).txt(next.toString()); } else if ('Date' == name) { next_child.ele('date').txt(ISODateString(new Date(next))); } else if ('Boolean' == name) { next_child.ele(next ? 'true' : 'false'); } else if ('String' == name) { next_child.ele('string').txt(next); } else if ('ArrayBuffer' == name) { next_child.ele('data').raw(base64.fromByteArray(next)); } else if (next && next.buffer && 'ArrayBuffer' == type(next.buffer)) { // a typed array next_child.ele('data').raw(base64.fromByteArray(new Uint8Array(next.buffer), next_child)); } }
javascript
function walk_obj(next, next_child) { var tag_type, i, prop; var name = type(next); if ('Undefined' == name) { return; } else if (Array.isArray(next)) { next_child = next_child.ele('array'); for (i = 0; i < next.length; i++) { walk_obj(next[i], next_child); } } else if (Buffer.isBuffer(next)) { next_child.ele('data').raw(next.toString('base64')); } else if ('Object' == name) { next_child = next_child.ele('dict'); for (prop in next) { if (next.hasOwnProperty(prop)) { next_child.ele('key').txt(prop); walk_obj(next[prop], next_child); } } } else if ('Number' == name) { // detect if this is an integer or real // TODO: add an ability to force one way or another via a "cast" tag_type = (next % 1 === 0) ? 'integer' : 'real'; next_child.ele(tag_type).txt(next.toString()); } else if ('Date' == name) { next_child.ele('date').txt(ISODateString(new Date(next))); } else if ('Boolean' == name) { next_child.ele(next ? 'true' : 'false'); } else if ('String' == name) { next_child.ele('string').txt(next); } else if ('ArrayBuffer' == name) { next_child.ele('data').raw(base64.fromByteArray(next)); } else if (next && next.buffer && 'ArrayBuffer' == type(next.buffer)) { // a typed array next_child.ele('data').raw(base64.fromByteArray(new Uint8Array(next.buffer), next_child)); } }
[ "function", "walk_obj", "(", "next", ",", "next_child", ")", "{", "var", "tag_type", ",", "i", ",", "prop", ";", "var", "name", "=", "type", "(", "next", ")", ";", "if", "(", "'Undefined'", "==", "name", ")", "{", "return", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "next", ")", ")", "{", "next_child", "=", "next_child", ".", "ele", "(", "'array'", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "next", ".", "length", ";", "i", "++", ")", "{", "walk_obj", "(", "next", "[", "i", "]", ",", "next_child", ")", ";", "}", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "next", ")", ")", "{", "next_child", ".", "ele", "(", "'data'", ")", ".", "raw", "(", "next", ".", "toString", "(", "'base64'", ")", ")", ";", "}", "else", "if", "(", "'Object'", "==", "name", ")", "{", "next_child", "=", "next_child", ".", "ele", "(", "'dict'", ")", ";", "for", "(", "prop", "in", "next", ")", "{", "if", "(", "next", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "next_child", ".", "ele", "(", "'key'", ")", ".", "txt", "(", "prop", ")", ";", "walk_obj", "(", "next", "[", "prop", "]", ",", "next_child", ")", ";", "}", "}", "}", "else", "if", "(", "'Number'", "==", "name", ")", "{", "// detect if this is an integer or real", "// TODO: add an ability to force one way or another via a \"cast\"", "tag_type", "=", "(", "next", "%", "1", "===", "0", ")", "?", "'integer'", ":", "'real'", ";", "next_child", ".", "ele", "(", "tag_type", ")", ".", "txt", "(", "next", ".", "toString", "(", ")", ")", ";", "}", "else", "if", "(", "'Date'", "==", "name", ")", "{", "next_child", ".", "ele", "(", "'date'", ")", ".", "txt", "(", "ISODateString", "(", "new", "Date", "(", "next", ")", ")", ")", ";", "}", "else", "if", "(", "'Boolean'", "==", "name", ")", "{", "next_child", ".", "ele", "(", "next", "?", "'true'", ":", "'false'", ")", ";", "}", "else", "if", "(", "'String'", "==", "name", ")", "{", "next_child", ".", "ele", "(", "'string'", ")", ".", "txt", "(", "next", ")", ";", "}", "else", "if", "(", "'ArrayBuffer'", "==", "name", ")", "{", "next_child", ".", "ele", "(", "'data'", ")", ".", "raw", "(", "base64", ".", "fromByteArray", "(", "next", ")", ")", ";", "}", "else", "if", "(", "next", "&&", "next", ".", "buffer", "&&", "'ArrayBuffer'", "==", "type", "(", "next", ".", "buffer", ")", ")", "{", "// a typed array", "next_child", ".", "ele", "(", "'data'", ")", ".", "raw", "(", "base64", ".", "fromByteArray", "(", "new", "Uint8Array", "(", "next", ".", "buffer", ")", ",", "next_child", ")", ")", ";", "}", "}" ]
depth first, recursive traversal of a javascript object. when complete, next_child contains a reference to the build XML object. @api private
[ "depth", "first", "recursive", "traversal", "of", "a", "javascript", "object", ".", "when", "complete", "next_child", "contains", "a", "reference", "to", "the", "build", "XML", "object", "." ]
1628c6ecc5462be367ac203225af3b55ed5e564c
https://github.com/TooTallNate/plist.js/blob/1628c6ecc5462be367ac203225af3b55ed5e564c/lib/build.js#L90-L137
18,018
parro-it/electron-localshortcut
index.js
disableAll
function disableAll(win) { debug(`Disabling all shortcuts on window ${title(win)}`); const wc = win.webContents; const shortcutsOfWindow = windowsWithShortcuts.get(wc); for (const shortcut of shortcutsOfWindow) { shortcut.enabled = false; } }
javascript
function disableAll(win) { debug(`Disabling all shortcuts on window ${title(win)}`); const wc = win.webContents; const shortcutsOfWindow = windowsWithShortcuts.get(wc); for (const shortcut of shortcutsOfWindow) { shortcut.enabled = false; } }
[ "function", "disableAll", "(", "win", ")", "{", "debug", "(", "`", "${", "title", "(", "win", ")", "}", "`", ")", ";", "const", "wc", "=", "win", ".", "webContents", ";", "const", "shortcutsOfWindow", "=", "windowsWithShortcuts", ".", "get", "(", "wc", ")", ";", "for", "(", "const", "shortcut", "of", "shortcutsOfWindow", ")", "{", "shortcut", ".", "enabled", "=", "false", ";", "}", "}" ]
Disable all of the shortcuts registered on the BrowserWindow instance. Registered shortcuts no more works on the `window` instance, but the module keep a reference on them. You can reactivate them later by calling `enableAll` method on the same window instance. @param {BrowserWindow} win BrowserWindow instance @return {Undefined}
[ "Disable", "all", "of", "the", "shortcuts", "registered", "on", "the", "BrowserWindow", "instance", ".", "Registered", "shortcuts", "no", "more", "works", "on", "the", "window", "instance", "but", "the", "module", "keep", "a", "reference", "on", "them", ".", "You", "can", "reactivate", "them", "later", "by", "calling", "enableAll", "method", "on", "the", "same", "window", "instance", "." ]
3fbd63a6b3ca22368b218ecd39081c0d77d51ddc
https://github.com/parro-it/electron-localshortcut/blob/3fbd63a6b3ca22368b218ecd39081c0d77d51ddc/index.js#L50-L58
18,019
parro-it/electron-localshortcut
index.js
enableAll
function enableAll(win) { debug(`Enabling all shortcuts on window ${title(win)}`); const wc = win.webContents; const shortcutsOfWindow = windowsWithShortcuts.get(wc); for (const shortcut of shortcutsOfWindow) { shortcut.enabled = true; } }
javascript
function enableAll(win) { debug(`Enabling all shortcuts on window ${title(win)}`); const wc = win.webContents; const shortcutsOfWindow = windowsWithShortcuts.get(wc); for (const shortcut of shortcutsOfWindow) { shortcut.enabled = true; } }
[ "function", "enableAll", "(", "win", ")", "{", "debug", "(", "`", "${", "title", "(", "win", ")", "}", "`", ")", ";", "const", "wc", "=", "win", ".", "webContents", ";", "const", "shortcutsOfWindow", "=", "windowsWithShortcuts", ".", "get", "(", "wc", ")", ";", "for", "(", "const", "shortcut", "of", "shortcutsOfWindow", ")", "{", "shortcut", ".", "enabled", "=", "true", ";", "}", "}" ]
Enable all of the shortcuts registered on the BrowserWindow instance that you had previously disabled calling `disableAll` method. @param {BrowserWindow} win BrowserWindow instance @return {Undefined}
[ "Enable", "all", "of", "the", "shortcuts", "registered", "on", "the", "BrowserWindow", "instance", "that", "you", "had", "previously", "disabled", "calling", "disableAll", "method", "." ]
3fbd63a6b3ca22368b218ecd39081c0d77d51ddc
https://github.com/parro-it/electron-localshortcut/blob/3fbd63a6b3ca22368b218ecd39081c0d77d51ddc/index.js#L66-L74
18,020
parro-it/electron-localshortcut
index.js
unregisterAll
function unregisterAll(win) { debug(`Unregistering all shortcuts on window ${title(win)}`); const wc = win.webContents; const shortcutsOfWindow = windowsWithShortcuts.get(wc); // Remove listener from window shortcutsOfWindow.removeListener(); windowsWithShortcuts.delete(wc); }
javascript
function unregisterAll(win) { debug(`Unregistering all shortcuts on window ${title(win)}`); const wc = win.webContents; const shortcutsOfWindow = windowsWithShortcuts.get(wc); // Remove listener from window shortcutsOfWindow.removeListener(); windowsWithShortcuts.delete(wc); }
[ "function", "unregisterAll", "(", "win", ")", "{", "debug", "(", "`", "${", "title", "(", "win", ")", "}", "`", ")", ";", "const", "wc", "=", "win", ".", "webContents", ";", "const", "shortcutsOfWindow", "=", "windowsWithShortcuts", ".", "get", "(", "wc", ")", ";", "// Remove listener from window", "shortcutsOfWindow", ".", "removeListener", "(", ")", ";", "windowsWithShortcuts", ".", "delete", "(", "wc", ")", ";", "}" ]
Unregisters all of the shortcuts registered on any focused BrowserWindow instance. This method does not unregister any shortcut you registered on a particular window instance. @param {BrowserWindow} win BrowserWindow instance @return {Undefined}
[ "Unregisters", "all", "of", "the", "shortcuts", "registered", "on", "any", "focused", "BrowserWindow", "instance", ".", "This", "method", "does", "not", "unregister", "any", "shortcut", "you", "registered", "on", "a", "particular", "window", "instance", "." ]
3fbd63a6b3ca22368b218ecd39081c0d77d51ddc
https://github.com/parro-it/electron-localshortcut/blob/3fbd63a6b3ca22368b218ecd39081c0d77d51ddc/index.js#L83-L92
18,021
parro-it/electron-localshortcut
index.js
register
function register(win, accelerator, callback) { let wc; if (typeof callback === 'undefined') { wc = ANY_WINDOW; callback = accelerator; accelerator = win; } else { wc = win.webContents; } if (Array.isArray(accelerator) === true) { accelerator.forEach(accelerator => { if (typeof accelerator === 'string') { register(win, accelerator, callback); } }); return; } debug(`Registering callback for ${accelerator} on window ${title(win)}`); _checkAccelerator(accelerator); debug(`${accelerator} seems a valid shortcut sequence.`); let shortcutsOfWindow; if (windowsWithShortcuts.has(wc)) { debug(`Window has others shortcuts registered.`); shortcutsOfWindow = windowsWithShortcuts.get(wc); } else { debug(`This is the first shortcut of the window.`); shortcutsOfWindow = []; windowsWithShortcuts.set(wc, shortcutsOfWindow); if (wc === ANY_WINDOW) { const keyHandler = _onBeforeInput(shortcutsOfWindow); const enableAppShortcuts = (e, win) => { const wc = win.webContents; wc.on('before-input-event', keyHandler); wc.once('closed', () => wc.removeListener('before-input-event', keyHandler) ); }; // Enable shortcut on current windows const windows = BrowserWindow.getAllWindows(); windows.forEach(win => enableAppShortcuts(null, win)); // Enable shortcut on future windows app.on('browser-window-created', enableAppShortcuts); shortcutsOfWindow.removeListener = () => { const windows = BrowserWindow.getAllWindows(); windows.forEach(win => win.webContents.removeListener('before-input-event', keyHandler) ); app.removeListener('browser-window-created', enableAppShortcuts); }; } else { const keyHandler = _onBeforeInput(shortcutsOfWindow); wc.on('before-input-event', keyHandler); // Save a reference to allow remove of listener from elsewhere shortcutsOfWindow.removeListener = () => wc.removeListener('before-input-event', keyHandler); wc.once('closed', shortcutsOfWindow.removeListener); } } debug(`Adding shortcut to window set.`); const eventStamp = toKeyEvent(accelerator); shortcutsOfWindow.push({ eventStamp, callback, enabled: true }); debug(`Shortcut registered.`); }
javascript
function register(win, accelerator, callback) { let wc; if (typeof callback === 'undefined') { wc = ANY_WINDOW; callback = accelerator; accelerator = win; } else { wc = win.webContents; } if (Array.isArray(accelerator) === true) { accelerator.forEach(accelerator => { if (typeof accelerator === 'string') { register(win, accelerator, callback); } }); return; } debug(`Registering callback for ${accelerator} on window ${title(win)}`); _checkAccelerator(accelerator); debug(`${accelerator} seems a valid shortcut sequence.`); let shortcutsOfWindow; if (windowsWithShortcuts.has(wc)) { debug(`Window has others shortcuts registered.`); shortcutsOfWindow = windowsWithShortcuts.get(wc); } else { debug(`This is the first shortcut of the window.`); shortcutsOfWindow = []; windowsWithShortcuts.set(wc, shortcutsOfWindow); if (wc === ANY_WINDOW) { const keyHandler = _onBeforeInput(shortcutsOfWindow); const enableAppShortcuts = (e, win) => { const wc = win.webContents; wc.on('before-input-event', keyHandler); wc.once('closed', () => wc.removeListener('before-input-event', keyHandler) ); }; // Enable shortcut on current windows const windows = BrowserWindow.getAllWindows(); windows.forEach(win => enableAppShortcuts(null, win)); // Enable shortcut on future windows app.on('browser-window-created', enableAppShortcuts); shortcutsOfWindow.removeListener = () => { const windows = BrowserWindow.getAllWindows(); windows.forEach(win => win.webContents.removeListener('before-input-event', keyHandler) ); app.removeListener('browser-window-created', enableAppShortcuts); }; } else { const keyHandler = _onBeforeInput(shortcutsOfWindow); wc.on('before-input-event', keyHandler); // Save a reference to allow remove of listener from elsewhere shortcutsOfWindow.removeListener = () => wc.removeListener('before-input-event', keyHandler); wc.once('closed', shortcutsOfWindow.removeListener); } } debug(`Adding shortcut to window set.`); const eventStamp = toKeyEvent(accelerator); shortcutsOfWindow.push({ eventStamp, callback, enabled: true }); debug(`Shortcut registered.`); }
[ "function", "register", "(", "win", ",", "accelerator", ",", "callback", ")", "{", "let", "wc", ";", "if", "(", "typeof", "callback", "===", "'undefined'", ")", "{", "wc", "=", "ANY_WINDOW", ";", "callback", "=", "accelerator", ";", "accelerator", "=", "win", ";", "}", "else", "{", "wc", "=", "win", ".", "webContents", ";", "}", "if", "(", "Array", ".", "isArray", "(", "accelerator", ")", "===", "true", ")", "{", "accelerator", ".", "forEach", "(", "accelerator", "=>", "{", "if", "(", "typeof", "accelerator", "===", "'string'", ")", "{", "register", "(", "win", ",", "accelerator", ",", "callback", ")", ";", "}", "}", ")", ";", "return", ";", "}", "debug", "(", "`", "${", "accelerator", "}", "${", "title", "(", "win", ")", "}", "`", ")", ";", "_checkAccelerator", "(", "accelerator", ")", ";", "debug", "(", "`", "${", "accelerator", "}", "`", ")", ";", "let", "shortcutsOfWindow", ";", "if", "(", "windowsWithShortcuts", ".", "has", "(", "wc", ")", ")", "{", "debug", "(", "`", "`", ")", ";", "shortcutsOfWindow", "=", "windowsWithShortcuts", ".", "get", "(", "wc", ")", ";", "}", "else", "{", "debug", "(", "`", "`", ")", ";", "shortcutsOfWindow", "=", "[", "]", ";", "windowsWithShortcuts", ".", "set", "(", "wc", ",", "shortcutsOfWindow", ")", ";", "if", "(", "wc", "===", "ANY_WINDOW", ")", "{", "const", "keyHandler", "=", "_onBeforeInput", "(", "shortcutsOfWindow", ")", ";", "const", "enableAppShortcuts", "=", "(", "e", ",", "win", ")", "=>", "{", "const", "wc", "=", "win", ".", "webContents", ";", "wc", ".", "on", "(", "'before-input-event'", ",", "keyHandler", ")", ";", "wc", ".", "once", "(", "'closed'", ",", "(", ")", "=>", "wc", ".", "removeListener", "(", "'before-input-event'", ",", "keyHandler", ")", ")", ";", "}", ";", "// Enable shortcut on current windows", "const", "windows", "=", "BrowserWindow", ".", "getAllWindows", "(", ")", ";", "windows", ".", "forEach", "(", "win", "=>", "enableAppShortcuts", "(", "null", ",", "win", ")", ")", ";", "// Enable shortcut on future windows", "app", ".", "on", "(", "'browser-window-created'", ",", "enableAppShortcuts", ")", ";", "shortcutsOfWindow", ".", "removeListener", "=", "(", ")", "=>", "{", "const", "windows", "=", "BrowserWindow", ".", "getAllWindows", "(", ")", ";", "windows", ".", "forEach", "(", "win", "=>", "win", ".", "webContents", ".", "removeListener", "(", "'before-input-event'", ",", "keyHandler", ")", ")", ";", "app", ".", "removeListener", "(", "'browser-window-created'", ",", "enableAppShortcuts", ")", ";", "}", ";", "}", "else", "{", "const", "keyHandler", "=", "_onBeforeInput", "(", "shortcutsOfWindow", ")", ";", "wc", ".", "on", "(", "'before-input-event'", ",", "keyHandler", ")", ";", "// Save a reference to allow remove of listener from elsewhere", "shortcutsOfWindow", ".", "removeListener", "=", "(", ")", "=>", "wc", ".", "removeListener", "(", "'before-input-event'", ",", "keyHandler", ")", ";", "wc", ".", "once", "(", "'closed'", ",", "shortcutsOfWindow", ".", "removeListener", ")", ";", "}", "}", "debug", "(", "`", "`", ")", ";", "const", "eventStamp", "=", "toKeyEvent", "(", "accelerator", ")", ";", "shortcutsOfWindow", ".", "push", "(", "{", "eventStamp", ",", "callback", ",", "enabled", ":", "true", "}", ")", ";", "debug", "(", "`", "`", ")", ";", "}" ]
Registers the shortcut `accelerator`on the BrowserWindow instance. @param {BrowserWindow} win - BrowserWindow instance to register. This argument could be omitted, in this case the function register the shortcut on all app windows. @param {String|Array<String>} accelerator - the shortcut to register @param {Function} callback This function is called when the shortcut is pressed and the window is focused and not minimized. @return {Undefined}
[ "Registers", "the", "shortcut", "accelerator", "on", "the", "BrowserWindow", "instance", "." ]
3fbd63a6b3ca22368b218ecd39081c0d77d51ddc
https://github.com/parro-it/electron-localshortcut/blob/3fbd63a6b3ca22368b218ecd39081c0d77d51ddc/index.js#L152-L231
18,022
parro-it/electron-localshortcut
index.js
unregister
function unregister(win, accelerator) { let wc; if (typeof accelerator === 'undefined') { wc = ANY_WINDOW; accelerator = win; } else { if (win.isDestroyed()) { debug(`Early return because window is destroyed.`); return; } wc = win.webContents; } if (Array.isArray(accelerator) === true) { accelerator.forEach(accelerator => { if (typeof accelerator === 'string') { unregister(win, accelerator); } }); return; } debug(`Unregistering callback for ${accelerator} on window ${title(win)}`); _checkAccelerator(accelerator); debug(`${accelerator} seems a valid shortcut sequence.`); if (!windowsWithShortcuts.has(wc)) { debug(`Early return because window has never had shortcuts registered.`); return; } const shortcutsOfWindow = windowsWithShortcuts.get(wc); const eventStamp = toKeyEvent(accelerator); const shortcutIdx = _findShortcut(eventStamp, shortcutsOfWindow); if (shortcutIdx === -1) { return; } shortcutsOfWindow.splice(shortcutIdx, 1); // If the window has no more shortcuts, // we remove it early from the WeakMap // and unregistering the event listener if (shortcutsOfWindow.length === 0) { // Remove listener from window shortcutsOfWindow.removeListener(); // Remove window from shortcuts catalog windowsWithShortcuts.delete(wc); } }
javascript
function unregister(win, accelerator) { let wc; if (typeof accelerator === 'undefined') { wc = ANY_WINDOW; accelerator = win; } else { if (win.isDestroyed()) { debug(`Early return because window is destroyed.`); return; } wc = win.webContents; } if (Array.isArray(accelerator) === true) { accelerator.forEach(accelerator => { if (typeof accelerator === 'string') { unregister(win, accelerator); } }); return; } debug(`Unregistering callback for ${accelerator} on window ${title(win)}`); _checkAccelerator(accelerator); debug(`${accelerator} seems a valid shortcut sequence.`); if (!windowsWithShortcuts.has(wc)) { debug(`Early return because window has never had shortcuts registered.`); return; } const shortcutsOfWindow = windowsWithShortcuts.get(wc); const eventStamp = toKeyEvent(accelerator); const shortcutIdx = _findShortcut(eventStamp, shortcutsOfWindow); if (shortcutIdx === -1) { return; } shortcutsOfWindow.splice(shortcutIdx, 1); // If the window has no more shortcuts, // we remove it early from the WeakMap // and unregistering the event listener if (shortcutsOfWindow.length === 0) { // Remove listener from window shortcutsOfWindow.removeListener(); // Remove window from shortcuts catalog windowsWithShortcuts.delete(wc); } }
[ "function", "unregister", "(", "win", ",", "accelerator", ")", "{", "let", "wc", ";", "if", "(", "typeof", "accelerator", "===", "'undefined'", ")", "{", "wc", "=", "ANY_WINDOW", ";", "accelerator", "=", "win", ";", "}", "else", "{", "if", "(", "win", ".", "isDestroyed", "(", ")", ")", "{", "debug", "(", "`", "`", ")", ";", "return", ";", "}", "wc", "=", "win", ".", "webContents", ";", "}", "if", "(", "Array", ".", "isArray", "(", "accelerator", ")", "===", "true", ")", "{", "accelerator", ".", "forEach", "(", "accelerator", "=>", "{", "if", "(", "typeof", "accelerator", "===", "'string'", ")", "{", "unregister", "(", "win", ",", "accelerator", ")", ";", "}", "}", ")", ";", "return", ";", "}", "debug", "(", "`", "${", "accelerator", "}", "${", "title", "(", "win", ")", "}", "`", ")", ";", "_checkAccelerator", "(", "accelerator", ")", ";", "debug", "(", "`", "${", "accelerator", "}", "`", ")", ";", "if", "(", "!", "windowsWithShortcuts", ".", "has", "(", "wc", ")", ")", "{", "debug", "(", "`", "`", ")", ";", "return", ";", "}", "const", "shortcutsOfWindow", "=", "windowsWithShortcuts", ".", "get", "(", "wc", ")", ";", "const", "eventStamp", "=", "toKeyEvent", "(", "accelerator", ")", ";", "const", "shortcutIdx", "=", "_findShortcut", "(", "eventStamp", ",", "shortcutsOfWindow", ")", ";", "if", "(", "shortcutIdx", "===", "-", "1", ")", "{", "return", ";", "}", "shortcutsOfWindow", ".", "splice", "(", "shortcutIdx", ",", "1", ")", ";", "// If the window has no more shortcuts,", "// we remove it early from the WeakMap", "// and unregistering the event listener", "if", "(", "shortcutsOfWindow", ".", "length", "===", "0", ")", "{", "// Remove listener from window", "shortcutsOfWindow", ".", "removeListener", "(", ")", ";", "// Remove window from shortcuts catalog", "windowsWithShortcuts", ".", "delete", "(", "wc", ")", ";", "}", "}" ]
Unregisters the shortcut of `accelerator` registered on the BrowserWindow instance. @param {BrowserWindow} win - BrowserWindow instance to unregister. This argument could be omitted, in this case the function unregister the shortcut on all app windows. If you registered the shortcut on a particular window instance, it will do nothing. @param {String|Array<String>} accelerator - the shortcut to unregister @return {Undefined}
[ "Unregisters", "the", "shortcut", "of", "accelerator", "registered", "on", "the", "BrowserWindow", "instance", "." ]
3fbd63a6b3ca22368b218ecd39081c0d77d51ddc
https://github.com/parro-it/electron-localshortcut/blob/3fbd63a6b3ca22368b218ecd39081c0d77d51ddc/index.js#L241-L293
18,023
weexteam/weex-vue-render
src/mixins/base.js
watchAppearForScrollables
function watchAppearForScrollables (tagName, context) { // when this is a scroller/list/waterfall if (scrollableTypes.indexOf(tagName) > -1) { const sd = context.scrollDirection if (!sd || sd !== 'horizontal') { appearWatched = context watchAppear(context, true) } } }
javascript
function watchAppearForScrollables (tagName, context) { // when this is a scroller/list/waterfall if (scrollableTypes.indexOf(tagName) > -1) { const sd = context.scrollDirection if (!sd || sd !== 'horizontal') { appearWatched = context watchAppear(context, true) } } }
[ "function", "watchAppearForScrollables", "(", "tagName", ",", "context", ")", "{", "// when this is a scroller/list/waterfall", "if", "(", "scrollableTypes", ".", "indexOf", "(", "tagName", ")", ">", "-", "1", ")", "{", "const", "sd", "=", "context", ".", "scrollDirection", "if", "(", "!", "sd", "||", "sd", "!==", "'horizontal'", ")", "{", "appearWatched", "=", "context", "watchAppear", "(", "context", ",", "true", ")", "}", "}", "}" ]
if it's a scrollable tag, then watch appear events for it.
[ "if", "it", "s", "a", "scrollable", "tag", "then", "watch", "appear", "events", "for", "it", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/mixins/base.js#L64-L73
18,024
weexteam/weex-vue-render
src/core/node.js
bindEvents
function bindEvents (ctx, evts, attrs, tag, appearAttached) { for (const key in evts) { const appearEvtName = appearEventsMap[key] if (appearEvtName) { attrs[`data-evt-${appearEvtName}`] = '' if (!appearAttached.value) { appearAttached.value = true attrs['weex-appear'] = '' } } else { attrs[`data-evt-${key}`] = '' if (key !== 'click') { // should stop propagation by default. // TODO: should test inBubble first. const handler = evts[key] if (isArray(evts[key])) { handler.unshift(ctx.$stopPropagation) } else { evts[key] = [ctx.$stopPropagation, handler] } } } } if (evts.click) { evts.weex$tap = evts.click evts.click = ctx.$stopOuterA } if (evts.scroll) { evts.weex$scroll = evts.scroll delete evts.scroll } }
javascript
function bindEvents (ctx, evts, attrs, tag, appearAttached) { for (const key in evts) { const appearEvtName = appearEventsMap[key] if (appearEvtName) { attrs[`data-evt-${appearEvtName}`] = '' if (!appearAttached.value) { appearAttached.value = true attrs['weex-appear'] = '' } } else { attrs[`data-evt-${key}`] = '' if (key !== 'click') { // should stop propagation by default. // TODO: should test inBubble first. const handler = evts[key] if (isArray(evts[key])) { handler.unshift(ctx.$stopPropagation) } else { evts[key] = [ctx.$stopPropagation, handler] } } } } if (evts.click) { evts.weex$tap = evts.click evts.click = ctx.$stopOuterA } if (evts.scroll) { evts.weex$scroll = evts.scroll delete evts.scroll } }
[ "function", "bindEvents", "(", "ctx", ",", "evts", ",", "attrs", ",", "tag", ",", "appearAttached", ")", "{", "for", "(", "const", "key", "in", "evts", ")", "{", "const", "appearEvtName", "=", "appearEventsMap", "[", "key", "]", "if", "(", "appearEvtName", ")", "{", "attrs", "[", "`", "${", "appearEvtName", "}", "`", "]", "=", "''", "if", "(", "!", "appearAttached", ".", "value", ")", "{", "appearAttached", ".", "value", "=", "true", "attrs", "[", "'weex-appear'", "]", "=", "''", "}", "}", "else", "{", "attrs", "[", "`", "${", "key", "}", "`", "]", "=", "''", "if", "(", "key", "!==", "'click'", ")", "{", "// should stop propagation by default.", "// TODO: should test inBubble first.", "const", "handler", "=", "evts", "[", "key", "]", "if", "(", "isArray", "(", "evts", "[", "key", "]", ")", ")", "{", "handler", ".", "unshift", "(", "ctx", ".", "$stopPropagation", ")", "}", "else", "{", "evts", "[", "key", "]", "=", "[", "ctx", ".", "$stopPropagation", ",", "handler", "]", "}", "}", "}", "}", "if", "(", "evts", ".", "click", ")", "{", "evts", ".", "weex$tap", "=", "evts", ".", "click", "evts", ".", "click", "=", "ctx", ".", "$stopOuterA", "}", "if", "(", "evts", ".", "scroll", ")", "{", "evts", ".", "weex$scroll", "=", "evts", ".", "scroll", "delete", "evts", ".", "scroll", "}", "}" ]
Tell whether a element is contained in a element who has a attribute 'bubble'=true. @param {HTMLElement} el function inBubble (el) { if (typeof el._inBubble === 'boolean') { return el._inBubble } const parents = [] let parent = el.parentElement let inBubble while (parent && parent !== document.body) { if (typeof parent._inBubble === 'boolean') { inBubble = parent._inBubble break } const attr = parent.getAttribute('bubble') if (attr !== '') { inBubble = attr === true || attr === 'true' break } parents.push(parent) parent = parent.parentElement } el._inBubble = inBubble for (let i = 0, l = parents.length; i < l; i++) { parents[i]._inBubble = inBubble } return inBubble }
[ "Tell", "whether", "a", "element", "is", "contained", "in", "a", "element", "who", "has", "a", "attribute", "bubble", "=", "true", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/core/node.js#L186-L219
18,025
weexteam/weex-vue-render
src/weex/viewport.js
setRootFont
function setRootFont (width, viewportWidth, force) { const doc = window.document const rem = width * 750 / viewportWidth / 10 if (!doc.documentElement) { return } const rootFontSize = doc.documentElement.style.fontSize if (!rootFontSize || force) { doc.documentElement.style.fontSize = rem + 'px' } info.rem = rem info.rootValue = viewportWidth / 10 }
javascript
function setRootFont (width, viewportWidth, force) { const doc = window.document const rem = width * 750 / viewportWidth / 10 if (!doc.documentElement) { return } const rootFontSize = doc.documentElement.style.fontSize if (!rootFontSize || force) { doc.documentElement.style.fontSize = rem + 'px' } info.rem = rem info.rootValue = viewportWidth / 10 }
[ "function", "setRootFont", "(", "width", ",", "viewportWidth", ",", "force", ")", "{", "const", "doc", "=", "window", ".", "document", "const", "rem", "=", "width", "*", "750", "/", "viewportWidth", "/", "10", "if", "(", "!", "doc", ".", "documentElement", ")", "{", "return", "}", "const", "rootFontSize", "=", "doc", ".", "documentElement", ".", "style", ".", "fontSize", "if", "(", "!", "rootFontSize", "||", "force", ")", "{", "doc", ".", "documentElement", ".", "style", ".", "fontSize", "=", "rem", "+", "'px'", "}", "info", ".", "rem", "=", "rem", "info", ".", "rootValue", "=", "viewportWidth", "/", "10", "}" ]
set root font-size for rem units. If already been set, just skip this.
[ "set", "root", "font", "-", "size", "for", "rem", "units", ".", "If", "already", "been", "set", "just", "skip", "this", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/weex/viewport.js#L63-L73
18,026
weexteam/weex-vue-render
src/lib/gesture.js
getCommonAncestor
function getCommonAncestor(el1, el2) { var el = el1 while (el) { if (el.contains(el2) || el == el2) { return el } el = el.parentNode } return null }
javascript
function getCommonAncestor(el1, el2) { var el = el1 while (el) { if (el.contains(el2) || el == el2) { return el } el = el.parentNode } return null }
[ "function", "getCommonAncestor", "(", "el1", ",", "el2", ")", "{", "var", "el", "=", "el1", "while", "(", "el", ")", "{", "if", "(", "el", ".", "contains", "(", "el2", ")", "||", "el", "==", "el2", ")", "{", "return", "el", "}", "el", "=", "el", ".", "parentNode", "}", "return", "null", "}" ]
find the closest common ancestor if there's no one, return null @param {Element} el1 first element @param {Element} el2 second element @return {Element} common ancestor
[ "find", "the", "closest", "common", "ancestor", "if", "there", "s", "no", "one", "return", "null" ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/lib/gesture.js#L53-L62
18,027
weexteam/weex-vue-render
src/lib/gesture.js
fireEvent
function fireEvent(element, type, extra) { var event = doc.createEvent('HTMLEvents') event.initEvent(type, true, true) if (typeof extra === 'object') { for (var p in extra) { event[p] = extra[p] } } /** * A flag to distinguish with other events with the same name generated * by another library in the same page. */ event._for = 'weex' element.dispatchEvent(event) }
javascript
function fireEvent(element, type, extra) { var event = doc.createEvent('HTMLEvents') event.initEvent(type, true, true) if (typeof extra === 'object') { for (var p in extra) { event[p] = extra[p] } } /** * A flag to distinguish with other events with the same name generated * by another library in the same page. */ event._for = 'weex' element.dispatchEvent(event) }
[ "function", "fireEvent", "(", "element", ",", "type", ",", "extra", ")", "{", "var", "event", "=", "doc", ".", "createEvent", "(", "'HTMLEvents'", ")", "event", ".", "initEvent", "(", "type", ",", "true", ",", "true", ")", "if", "(", "typeof", "extra", "===", "'object'", ")", "{", "for", "(", "var", "p", "in", "extra", ")", "{", "event", "[", "p", "]", "=", "extra", "[", "p", "]", "}", "}", "/**\n * A flag to distinguish with other events with the same name generated\n * by another library in the same page.\n */", "event", ".", "_for", "=", "'weex'", "element", ".", "dispatchEvent", "(", "event", ")", "}" ]
fire a HTMLEvent @param {Element} element which element to fire a event on @param {string} type type of event @param {object} extra extra data for the event object
[ "fire", "a", "HTMLEvent" ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/lib/gesture.js#L71-L88
18,028
weexteam/weex-vue-render
src/modules/storage.js
function (key, value, callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } if (!key || (!value && value !== 0)) { sender.performCallback(callbackId, { result: 'failed', data: INVALID_PARAM }) return } try { localStorage.setItem(key, value) sender.performCallback(callbackId, { result: SUCCESS, data: UNDEFINED }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
javascript
function (key, value, callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } if (!key || (!value && value !== 0)) { sender.performCallback(callbackId, { result: 'failed', data: INVALID_PARAM }) return } try { localStorage.setItem(key, value) sender.performCallback(callbackId, { result: SUCCESS, data: UNDEFINED }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
[ "function", "(", "key", ",", "value", ",", "callbackId", ")", "{", "const", "sender", "=", "this", ".", "sender", "if", "(", "!", "supportLocalStorage", ")", "{", "return", "callNotSupportFail", "(", "sender", ",", "callbackId", ")", "}", "if", "(", "!", "key", "||", "(", "!", "value", "&&", "value", "!==", "0", ")", ")", "{", "sender", ".", "performCallback", "(", "callbackId", ",", "{", "result", ":", "'failed'", ",", "data", ":", "INVALID_PARAM", "}", ")", "return", "}", "try", "{", "localStorage", ".", "setItem", "(", "key", ",", "value", ")", "sender", ".", "performCallback", "(", "callbackId", ",", "{", "result", ":", "SUCCESS", ",", "data", ":", "UNDEFINED", "}", ")", "}", "catch", "(", "e", ")", "{", "// accept any exception thrown during a storage attempt as a quota error", "callFail", "(", "sender", ",", "callbackId", ")", "}", "}" ]
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists. @param {string} key @param {string} value not null nor undifined,but 0 works. @param {function} callbackId
[ "When", "passed", "a", "key", "name", "and", "value", "will", "add", "that", "key", "to", "the", "storage", "or", "update", "that", "key", "s", "value", "if", "it", "already", "exists", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/modules/storage.js#L59-L82
18,029
weexteam/weex-vue-render
src/modules/storage.js
function (key, callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } if (!key) { sender.performCallback(callbackId, { result: FAILED, data: INVALID_PARAM }) return } try { const val = localStorage.getItem(key) sender.performCallback(callbackId, { result: val ? SUCCESS : FAILED, data: val || UNDEFINED }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
javascript
function (key, callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } if (!key) { sender.performCallback(callbackId, { result: FAILED, data: INVALID_PARAM }) return } try { const val = localStorage.getItem(key) sender.performCallback(callbackId, { result: val ? SUCCESS : FAILED, data: val || UNDEFINED }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
[ "function", "(", "key", ",", "callbackId", ")", "{", "const", "sender", "=", "this", ".", "sender", "if", "(", "!", "supportLocalStorage", ")", "{", "return", "callNotSupportFail", "(", "sender", ",", "callbackId", ")", "}", "if", "(", "!", "key", ")", "{", "sender", ".", "performCallback", "(", "callbackId", ",", "{", "result", ":", "FAILED", ",", "data", ":", "INVALID_PARAM", "}", ")", "return", "}", "try", "{", "const", "val", "=", "localStorage", ".", "getItem", "(", "key", ")", "sender", ".", "performCallback", "(", "callbackId", ",", "{", "result", ":", "val", "?", "SUCCESS", ":", "FAILED", ",", "data", ":", "val", "||", "UNDEFINED", "}", ")", "}", "catch", "(", "e", ")", "{", "// accept any exception thrown during a storage attempt as a quota error", "callFail", "(", "sender", ",", "callbackId", ")", "}", "}" ]
When passed a key name, will return that key's value. @param {string} key @param {function} callbackId
[ "When", "passed", "a", "key", "name", "will", "return", "that", "key", "s", "value", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/modules/storage.js#L89-L112
18,030
weexteam/weex-vue-render
src/modules/storage.js
function (callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } try { const len = localStorage.length sender.performCallback(callbackId, { result: SUCCESS, data: len }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
javascript
function (callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } try { const len = localStorage.length sender.performCallback(callbackId, { result: SUCCESS, data: len }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
[ "function", "(", "callbackId", ")", "{", "const", "sender", "=", "this", ".", "sender", "if", "(", "!", "supportLocalStorage", ")", "{", "return", "callNotSupportFail", "(", "sender", ",", "callbackId", ")", "}", "try", "{", "const", "len", "=", "localStorage", ".", "length", "sender", ".", "performCallback", "(", "callbackId", ",", "{", "result", ":", "SUCCESS", ",", "data", ":", "len", "}", ")", "}", "catch", "(", "e", ")", "{", "// accept any exception thrown during a storage attempt as a quota error", "callFail", "(", "sender", ",", "callbackId", ")", "}", "}" ]
Returns an integer representing the number of data items stored in the Storage object. @param {function} callbackId
[ "Returns", "an", "integer", "representing", "the", "number", "of", "data", "items", "stored", "in", "the", "Storage", "object", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/modules/storage.js#L148-L164
18,031
weexteam/weex-vue-render
src/modules/storage.js
function (callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } try { const _arr = [] for (let i = 0; i < localStorage.length; i++) { _arr.push(localStorage.key(i)) } sender.performCallback(callbackId, { result: SUCCESS, data: _arr }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
javascript
function (callbackId) { const sender = this.sender if (!supportLocalStorage) { return callNotSupportFail(sender, callbackId) } try { const _arr = [] for (let i = 0; i < localStorage.length; i++) { _arr.push(localStorage.key(i)) } sender.performCallback(callbackId, { result: SUCCESS, data: _arr }) } catch (e) { // accept any exception thrown during a storage attempt as a quota error callFail(sender, callbackId) } }
[ "function", "(", "callbackId", ")", "{", "const", "sender", "=", "this", ".", "sender", "if", "(", "!", "supportLocalStorage", ")", "{", "return", "callNotSupportFail", "(", "sender", ",", "callbackId", ")", "}", "try", "{", "const", "_arr", "=", "[", "]", "for", "(", "let", "i", "=", "0", ";", "i", "<", "localStorage", ".", "length", ";", "i", "++", ")", "{", "_arr", ".", "push", "(", "localStorage", ".", "key", "(", "i", ")", ")", "}", "sender", ".", "performCallback", "(", "callbackId", ",", "{", "result", ":", "SUCCESS", ",", "data", ":", "_arr", "}", ")", "}", "catch", "(", "e", ")", "{", "// accept any exception thrown during a storage attempt as a quota error", "callFail", "(", "sender", ",", "callbackId", ")", "}", "}" ]
Returns an array that contains all keys stored in Storage object. @param {function} callbackId
[ "Returns", "an", "array", "that", "contains", "all", "keys", "stored", "in", "Storage", "object", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/src/modules/storage.js#L170-L189
18,032
weexteam/weex-vue-render
public/assets/phantom-limb.js
createMouseEvent
function createMouseEvent(eventName, originalEvent, finger) { var e = document.createEvent('MouseEvent'); e.initMouseEvent(eventName, true, true, originalEvent.view, originalEvent.detail, finger.x || originalEvent.screenX, finger.y || originalEvent.screenY, finger.x || originalEvent.clientX, finger.y || originalEvent.clientY, originalEvent.ctrlKey, originalEvent.shiftKey, originalEvent.altKey, originalEvent.metaKey, originalEvent.button, finger.target || originalEvent.relatedTarget ); e.synthetic = true; // Set this so we can match shared targets later. e._finger = finger; return e; }
javascript
function createMouseEvent(eventName, originalEvent, finger) { var e = document.createEvent('MouseEvent'); e.initMouseEvent(eventName, true, true, originalEvent.view, originalEvent.detail, finger.x || originalEvent.screenX, finger.y || originalEvent.screenY, finger.x || originalEvent.clientX, finger.y || originalEvent.clientY, originalEvent.ctrlKey, originalEvent.shiftKey, originalEvent.altKey, originalEvent.metaKey, originalEvent.button, finger.target || originalEvent.relatedTarget ); e.synthetic = true; // Set this so we can match shared targets later. e._finger = finger; return e; }
[ "function", "createMouseEvent", "(", "eventName", ",", "originalEvent", ",", "finger", ")", "{", "var", "e", "=", "document", ".", "createEvent", "(", "'MouseEvent'", ")", ";", "e", ".", "initMouseEvent", "(", "eventName", ",", "true", ",", "true", ",", "originalEvent", ".", "view", ",", "originalEvent", ".", "detail", ",", "finger", ".", "x", "||", "originalEvent", ".", "screenX", ",", "finger", ".", "y", "||", "originalEvent", ".", "screenY", ",", "finger", ".", "x", "||", "originalEvent", ".", "clientX", ",", "finger", ".", "y", "||", "originalEvent", ".", "clientY", ",", "originalEvent", ".", "ctrlKey", ",", "originalEvent", ".", "shiftKey", ",", "originalEvent", ".", "altKey", ",", "originalEvent", ".", "metaKey", ",", "originalEvent", ".", "button", ",", "finger", ".", "target", "||", "originalEvent", ".", "relatedTarget", ")", ";", "e", ".", "synthetic", "=", "true", ";", "// Set this so we can match shared targets later.", "e", ".", "_finger", "=", "finger", ";", "return", "e", ";", "}" ]
Create a synthetic event from a real event and a finger.
[ "Create", "a", "synthetic", "event", "from", "a", "real", "event", "and", "a", "finger", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/public/assets/phantom-limb.js#L74-L92
18,033
weexteam/weex-vue-render
public/assets/phantom-limb.js
phantomTouchStart
function phantomTouchStart(e) { if (e.synthetic) return; mouseIsDown = true; e.preventDefault(); e.stopPropagation(); fireTouchEvents('touchstart', e); }
javascript
function phantomTouchStart(e) { if (e.synthetic) return; mouseIsDown = true; e.preventDefault(); e.stopPropagation(); fireTouchEvents('touchstart', e); }
[ "function", "phantomTouchStart", "(", "e", ")", "{", "if", "(", "e", ".", "synthetic", ")", "return", ";", "mouseIsDown", "=", "true", ";", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "fireTouchEvents", "(", "'touchstart'", ",", "e", ")", ";", "}" ]
Prevent all mousedown event from doing anything. We'll fire one manually at touchend.
[ "Prevent", "all", "mousedown", "event", "from", "doing", "anything", ".", "We", "ll", "fire", "one", "manually", "at", "touchend", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/public/assets/phantom-limb.js#L183-L192
18,034
weexteam/weex-vue-render
public/assets/phantom-limb.js
moveFingers
function moveFingers(e) { // We'll use this if the second is locked with the first. var changeX = e.clientX - fingers[0].x || 0; var changeY = e.clientY - fingers[0].y || 0; // The first finger just follows the mouse. fingers[0].move(e.clientX, e.clientY); // TODO: Determine modifier keys independent of mouse movement. if (e.altKey) { // Reset the center. if (!centerX && !centerY) { centerX = innerWidth / 2; centerY = innerHeight / 2; } // Lock the center with the first finger. if (e.shiftKey) { centerX += changeX; centerY += changeY; } var secondX = centerX + (centerX - e.clientX); var secondY = centerY + (centerY - e.clientY); fingers[1].move(secondX, secondY); } else { // Disengage the second finger. fingers[1].move(NaN, NaN); // Reset the center next time the alt key is held. centerX = NaN; centerY = NaN; } }
javascript
function moveFingers(e) { // We'll use this if the second is locked with the first. var changeX = e.clientX - fingers[0].x || 0; var changeY = e.clientY - fingers[0].y || 0; // The first finger just follows the mouse. fingers[0].move(e.clientX, e.clientY); // TODO: Determine modifier keys independent of mouse movement. if (e.altKey) { // Reset the center. if (!centerX && !centerY) { centerX = innerWidth / 2; centerY = innerHeight / 2; } // Lock the center with the first finger. if (e.shiftKey) { centerX += changeX; centerY += changeY; } var secondX = centerX + (centerX - e.clientX); var secondY = centerY + (centerY - e.clientY); fingers[1].move(secondX, secondY); } else { // Disengage the second finger. fingers[1].move(NaN, NaN); // Reset the center next time the alt key is held. centerX = NaN; centerY = NaN; } }
[ "function", "moveFingers", "(", "e", ")", "{", "// We'll use this if the second is locked with the first.", "var", "changeX", "=", "e", ".", "clientX", "-", "fingers", "[", "0", "]", ".", "x", "||", "0", ";", "var", "changeY", "=", "e", ".", "clientY", "-", "fingers", "[", "0", "]", ".", "y", "||", "0", ";", "// The first finger just follows the mouse.", "fingers", "[", "0", "]", ".", "move", "(", "e", ".", "clientX", ",", "e", ".", "clientY", ")", ";", "// TODO: Determine modifier keys independent of mouse movement.", "if", "(", "e", ".", "altKey", ")", "{", "// Reset the center.", "if", "(", "!", "centerX", "&&", "!", "centerY", ")", "{", "centerX", "=", "innerWidth", "/", "2", ";", "centerY", "=", "innerHeight", "/", "2", ";", "}", "// Lock the center with the first finger.", "if", "(", "e", ".", "shiftKey", ")", "{", "centerX", "+=", "changeX", ";", "centerY", "+=", "changeY", ";", "}", "var", "secondX", "=", "centerX", "+", "(", "centerX", "-", "e", ".", "clientX", ")", ";", "var", "secondY", "=", "centerY", "+", "(", "centerY", "-", "e", ".", "clientY", ")", ";", "fingers", "[", "1", "]", ".", "move", "(", "secondX", ",", "secondY", ")", ";", "}", "else", "{", "// Disengage the second finger.", "fingers", "[", "1", "]", ".", "move", "(", "NaN", ",", "NaN", ")", ";", "// Reset the center next time the alt key is held.", "centerX", "=", "NaN", ";", "centerY", "=", "NaN", ";", "}", "}" ]
Set each finger's position target. Pressing alt engages the second finger. Pressing shift locks the second finger's position relative to the first's.
[ "Set", "each", "finger", "s", "position", "target", ".", "Pressing", "alt", "engages", "the", "second", "finger", ".", "Pressing", "shift", "locks", "the", "second", "finger", "s", "position", "relative", "to", "the", "first", "s", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/public/assets/phantom-limb.js#L201-L236
18,035
weexteam/weex-vue-render
public/assets/phantom-limb.js
phantomTouchEnd
function phantomTouchEnd(e) { if (e.synthetic) return; mouseIsDown = false; e.preventDefault(); e.stopPropagation(); fireTouchEvents('touchend', e); fingers.forEach(function(finger) { if (!finger.target) return; // Mobile Safari moves all the mouse event to fire after the touchend event. finger.target.dispatchEvent(createMouseEvent('mouseover', e, finger)); finger.target.dispatchEvent(createMouseEvent('mousemove', e, finger)); finger.target.dispatchEvent(createMouseEvent('mousedown', e, finger)); // TODO: These two only fire if content didn't change. How can we tell? finger.target.dispatchEvent(createMouseEvent('mouseup', e, finger)); finger.target.dispatchEvent(createMouseEvent('click', e, finger)); }); }
javascript
function phantomTouchEnd(e) { if (e.synthetic) return; mouseIsDown = false; e.preventDefault(); e.stopPropagation(); fireTouchEvents('touchend', e); fingers.forEach(function(finger) { if (!finger.target) return; // Mobile Safari moves all the mouse event to fire after the touchend event. finger.target.dispatchEvent(createMouseEvent('mouseover', e, finger)); finger.target.dispatchEvent(createMouseEvent('mousemove', e, finger)); finger.target.dispatchEvent(createMouseEvent('mousedown', e, finger)); // TODO: These two only fire if content didn't change. How can we tell? finger.target.dispatchEvent(createMouseEvent('mouseup', e, finger)); finger.target.dispatchEvent(createMouseEvent('click', e, finger)); }); }
[ "function", "phantomTouchEnd", "(", "e", ")", "{", "if", "(", "e", ".", "synthetic", ")", "return", ";", "mouseIsDown", "=", "false", ";", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "fireTouchEvents", "(", "'touchend'", ",", "e", ")", ";", "fingers", ".", "forEach", "(", "function", "(", "finger", ")", "{", "if", "(", "!", "finger", ".", "target", ")", "return", ";", "// Mobile Safari moves all the mouse event to fire after the touchend event.", "finger", ".", "target", ".", "dispatchEvent", "(", "createMouseEvent", "(", "'mouseover'", ",", "e", ",", "finger", ")", ")", ";", "finger", ".", "target", ".", "dispatchEvent", "(", "createMouseEvent", "(", "'mousemove'", ",", "e", ",", "finger", ")", ")", ";", "finger", ".", "target", ".", "dispatchEvent", "(", "createMouseEvent", "(", "'mousedown'", ",", "e", ",", "finger", ")", ")", ";", "// TODO: These two only fire if content didn't change. How can we tell?", "finger", ".", "target", ".", "dispatchEvent", "(", "createMouseEvent", "(", "'mouseup'", ",", "e", ",", "finger", ")", ")", ";", "finger", ".", "target", ".", "dispatchEvent", "(", "createMouseEvent", "(", "'click'", ",", "e", ",", "finger", ")", ")", ";", "}", ")", ";", "}" ]
Prevent all mouseup events from firing. We'll fire one manually at touchend.
[ "Prevent", "all", "mouseup", "events", "from", "firing", ".", "We", "ll", "fire", "one", "manually", "at", "touchend", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/public/assets/phantom-limb.js#L255-L277
18,036
weexteam/weex-vue-render
public/assets/phantom-limb.js
phantomKeyUp
function phantomKeyUp(e) { if (e.keyCode === 27) { if (document.documentElement.classList.contains('_phantom-limb')) { stop(); } else { start(); } } }
javascript
function phantomKeyUp(e) { if (e.keyCode === 27) { if (document.documentElement.classList.contains('_phantom-limb')) { stop(); } else { start(); } } }
[ "function", "phantomKeyUp", "(", "e", ")", "{", "if", "(", "e", ".", "keyCode", "===", "27", ")", "{", "if", "(", "document", ".", "documentElement", ".", "classList", ".", "contains", "(", "'_phantom-limb'", ")", ")", "{", "stop", "(", ")", ";", "}", "else", "{", "start", "(", ")", ";", "}", "}", "}" ]
Detect keyup, exit when esc.
[ "Detect", "keyup", "exit", "when", "esc", "." ]
8464b64d54538f7b274c488e5fdc83a64e9dc74c
https://github.com/weexteam/weex-vue-render/blob/8464b64d54538f7b274c488e5fdc83a64e9dc74c/public/assets/phantom-limb.js#L340-L348
18,037
Netflix/ember-nf-graph
addon/utils/nf/svg-dom.js
inlineAllStyles
function inlineAllStyles(element) { let styles = getComputedStyle(element); for(let key in styles) { if(styles.hasOwnProperty(key)) { element.style[key] = styles[key]; } } for(let i = 0; i < element.childNodes.length; i++) { let node = element.childNodes[i]; if(node.nodeType === 1) { inlineAllStyles(node); } } }
javascript
function inlineAllStyles(element) { let styles = getComputedStyle(element); for(let key in styles) { if(styles.hasOwnProperty(key)) { element.style[key] = styles[key]; } } for(let i = 0; i < element.childNodes.length; i++) { let node = element.childNodes[i]; if(node.nodeType === 1) { inlineAllStyles(node); } } }
[ "function", "inlineAllStyles", "(", "element", ")", "{", "let", "styles", "=", "getComputedStyle", "(", "element", ")", ";", "for", "(", "let", "key", "in", "styles", ")", "{", "if", "(", "styles", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "element", ".", "style", "[", "key", "]", "=", "styles", "[", "key", "]", ";", "}", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "element", ".", "childNodes", ".", "length", ";", "i", "++", ")", "{", "let", "node", "=", "element", ".", "childNodes", "[", "i", "]", ";", "if", "(", "node", ".", "nodeType", "===", "1", ")", "{", "inlineAllStyles", "(", "node", ")", ";", "}", "}", "}" ]
Traverses an element and all of its descendants, setting their inline style property to whatever the computed style is. @method inlineAllStyles @param element {Element} the dom element to traverse. @private
[ "Traverses", "an", "element", "and", "all", "of", "its", "descendants", "setting", "their", "inline", "style", "property", "to", "whatever", "the", "computed", "style", "is", "." ]
851b63edc9690501d01b8fb87c3346bc5dac9959
https://github.com/Netflix/ember-nf-graph/blob/851b63edc9690501d01b8fb87c3346bc5dac9959/addon/utils/nf/svg-dom.js#L11-L25
18,038
molnarg/node-http2
lib/protocol/compressor.js
cut
function cut(buffer, size) { var chunks = []; var cursor = 0; do { var chunkSize = Math.min(size, buffer.length - cursor); chunks.push(buffer.slice(cursor, cursor + chunkSize)); cursor += chunkSize; } while(cursor < buffer.length); return chunks; }
javascript
function cut(buffer, size) { var chunks = []; var cursor = 0; do { var chunkSize = Math.min(size, buffer.length - cursor); chunks.push(buffer.slice(cursor, cursor + chunkSize)); cursor += chunkSize; } while(cursor < buffer.length); return chunks; }
[ "function", "cut", "(", "buffer", ",", "size", ")", "{", "var", "chunks", "=", "[", "]", ";", "var", "cursor", "=", "0", ";", "do", "{", "var", "chunkSize", "=", "Math", ".", "min", "(", "size", ",", "buffer", ".", "length", "-", "cursor", ")", ";", "chunks", ".", "push", "(", "buffer", ".", "slice", "(", "cursor", ",", "cursor", "+", "chunkSize", ")", ")", ";", "cursor", "+=", "chunkSize", ";", "}", "while", "(", "cursor", "<", "buffer", ".", "length", ")", ";", "return", "chunks", ";", "}" ]
Cut `buffer` into chunks not larger than `size`
[ "Cut", "buffer", "into", "chunks", "not", "larger", "than", "size" ]
c0fde1842f12604228c2b40895521397b015ae71
https://github.com/molnarg/node-http2/blob/c0fde1842f12604228c2b40895521397b015ae71/lib/protocol/compressor.js#L1353-L1362
18,039
molnarg/node-http2
example/server.js
onRequest
function onRequest(request, response) { var filename = path.join(__dirname, request.url); // Serving server.js from cache. Useful for microbenchmarks. if (request.url === cachedUrl) { if (response.push) { // Also push down the client js, since it's possible if the requester wants // one, they want both. var push = response.push('/client.js'); push.writeHead(200); fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push); } response.end(cachedFile); } // Reading file from disk if it exists and is safe. else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) { response.writeHead(200); var fileStream = fs.createReadStream(filename); fileStream.pipe(response); fileStream.on('finish',response.end); } // Example for testing large (boundary-sized) frames. else if (request.url === "/largeframe") { response.writeHead(200); var body = 'a'; for (var i = 0; i < 14; i++) { body += body; } body = body + 'a'; response.end(body); } // Otherwise responding with 404. else { response.writeHead(404); response.end(); } }
javascript
function onRequest(request, response) { var filename = path.join(__dirname, request.url); // Serving server.js from cache. Useful for microbenchmarks. if (request.url === cachedUrl) { if (response.push) { // Also push down the client js, since it's possible if the requester wants // one, they want both. var push = response.push('/client.js'); push.writeHead(200); fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push); } response.end(cachedFile); } // Reading file from disk if it exists and is safe. else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) { response.writeHead(200); var fileStream = fs.createReadStream(filename); fileStream.pipe(response); fileStream.on('finish',response.end); } // Example for testing large (boundary-sized) frames. else if (request.url === "/largeframe") { response.writeHead(200); var body = 'a'; for (var i = 0; i < 14; i++) { body += body; } body = body + 'a'; response.end(body); } // Otherwise responding with 404. else { response.writeHead(404); response.end(); } }
[ "function", "onRequest", "(", "request", ",", "response", ")", "{", "var", "filename", "=", "path", ".", "join", "(", "__dirname", ",", "request", ".", "url", ")", ";", "// Serving server.js from cache. Useful for microbenchmarks.", "if", "(", "request", ".", "url", "===", "cachedUrl", ")", "{", "if", "(", "response", ".", "push", ")", "{", "// Also push down the client js, since it's possible if the requester wants", "// one, they want both.", "var", "push", "=", "response", ".", "push", "(", "'/client.js'", ")", ";", "push", ".", "writeHead", "(", "200", ")", ";", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "__dirname", ",", "'/client.js'", ")", ")", ".", "pipe", "(", "push", ")", ";", "}", "response", ".", "end", "(", "cachedFile", ")", ";", "}", "// Reading file from disk if it exists and is safe.", "else", "if", "(", "(", "filename", ".", "indexOf", "(", "__dirname", ")", "===", "0", ")", "&&", "fs", ".", "existsSync", "(", "filename", ")", "&&", "fs", ".", "statSync", "(", "filename", ")", ".", "isFile", "(", ")", ")", "{", "response", ".", "writeHead", "(", "200", ")", ";", "var", "fileStream", "=", "fs", ".", "createReadStream", "(", "filename", ")", ";", "fileStream", ".", "pipe", "(", "response", ")", ";", "fileStream", ".", "on", "(", "'finish'", ",", "response", ".", "end", ")", ";", "}", "// Example for testing large (boundary-sized) frames.", "else", "if", "(", "request", ".", "url", "===", "\"/largeframe\"", ")", "{", "response", ".", "writeHead", "(", "200", ")", ";", "var", "body", "=", "'a'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "14", ";", "i", "++", ")", "{", "body", "+=", "body", ";", "}", "body", "=", "body", "+", "'a'", ";", "response", ".", "end", "(", "body", ")", ";", "}", "// Otherwise responding with 404.", "else", "{", "response", ".", "writeHead", "(", "404", ")", ";", "response", ".", "end", "(", ")", ";", "}", "}" ]
The callback to handle requests
[ "The", "callback", "to", "handle", "requests" ]
c0fde1842f12604228c2b40895521397b015ae71
https://github.com/molnarg/node-http2/blob/c0fde1842f12604228c2b40895521397b015ae71/example/server.js#L10-L49
18,040
expressjs/serve-favicon
index.js
favicon
function favicon (path, options) { var opts = options || {} var icon // favicon cache var maxAge = calcMaxAge(opts.maxAge) if (!path) { throw new TypeError('path to favicon.ico is required') } if (Buffer.isBuffer(path)) { icon = createIcon(Buffer.from(path), maxAge) } else if (typeof path === 'string') { path = resolveSync(path) } else { throw new TypeError('path to favicon.ico must be string or buffer') } return function favicon (req, res, next) { if (getPathname(req) !== '/favicon.ico') { next() return } if (req.method !== 'GET' && req.method !== 'HEAD') { res.statusCode = req.method === 'OPTIONS' ? 200 : 405 res.setHeader('Allow', 'GET, HEAD, OPTIONS') res.setHeader('Content-Length', '0') res.end() return } if (icon) { send(req, res, icon) return } fs.readFile(path, function (err, buf) { if (err) return next(err) icon = createIcon(buf, maxAge) send(req, res, icon) }) } }
javascript
function favicon (path, options) { var opts = options || {} var icon // favicon cache var maxAge = calcMaxAge(opts.maxAge) if (!path) { throw new TypeError('path to favicon.ico is required') } if (Buffer.isBuffer(path)) { icon = createIcon(Buffer.from(path), maxAge) } else if (typeof path === 'string') { path = resolveSync(path) } else { throw new TypeError('path to favicon.ico must be string or buffer') } return function favicon (req, res, next) { if (getPathname(req) !== '/favicon.ico') { next() return } if (req.method !== 'GET' && req.method !== 'HEAD') { res.statusCode = req.method === 'OPTIONS' ? 200 : 405 res.setHeader('Allow', 'GET, HEAD, OPTIONS') res.setHeader('Content-Length', '0') res.end() return } if (icon) { send(req, res, icon) return } fs.readFile(path, function (err, buf) { if (err) return next(err) icon = createIcon(buf, maxAge) send(req, res, icon) }) } }
[ "function", "favicon", "(", "path", ",", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", "var", "icon", "// favicon cache", "var", "maxAge", "=", "calcMaxAge", "(", "opts", ".", "maxAge", ")", "if", "(", "!", "path", ")", "{", "throw", "new", "TypeError", "(", "'path to favicon.ico is required'", ")", "}", "if", "(", "Buffer", ".", "isBuffer", "(", "path", ")", ")", "{", "icon", "=", "createIcon", "(", "Buffer", ".", "from", "(", "path", ")", ",", "maxAge", ")", "}", "else", "if", "(", "typeof", "path", "===", "'string'", ")", "{", "path", "=", "resolveSync", "(", "path", ")", "}", "else", "{", "throw", "new", "TypeError", "(", "'path to favicon.ico must be string or buffer'", ")", "}", "return", "function", "favicon", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "getPathname", "(", "req", ")", "!==", "'/favicon.ico'", ")", "{", "next", "(", ")", "return", "}", "if", "(", "req", ".", "method", "!==", "'GET'", "&&", "req", ".", "method", "!==", "'HEAD'", ")", "{", "res", ".", "statusCode", "=", "req", ".", "method", "===", "'OPTIONS'", "?", "200", ":", "405", "res", ".", "setHeader", "(", "'Allow'", ",", "'GET, HEAD, OPTIONS'", ")", "res", ".", "setHeader", "(", "'Content-Length'", ",", "'0'", ")", "res", ".", "end", "(", ")", "return", "}", "if", "(", "icon", ")", "{", "send", "(", "req", ",", "res", ",", "icon", ")", "return", "}", "fs", ".", "readFile", "(", "path", ",", "function", "(", "err", ",", "buf", ")", "{", "if", "(", "err", ")", "return", "next", "(", "err", ")", "icon", "=", "createIcon", "(", "buf", ",", "maxAge", ")", "send", "(", "req", ",", "res", ",", "icon", ")", "}", ")", "}", "}" ]
Serves the favicon located by the given `path`. @public @param {String|Buffer} path @param {Object} [options] @return {Function} middleware
[ "Serves", "the", "favicon", "located", "by", "the", "given", "path", "." ]
15fe5e3837cef1e88cb4d1112bc2a23674b4834b
https://github.com/expressjs/serve-favicon/blob/15fe5e3837cef1e88cb4d1112bc2a23674b4834b/index.js#L48-L91
18,041
expressjs/serve-favicon
index.js
calcMaxAge
function calcMaxAge (val) { var num = typeof val === 'string' ? ms(val) : val return num != null ? Math.min(Math.max(0, num), ONE_YEAR_MS) : ONE_YEAR_MS }
javascript
function calcMaxAge (val) { var num = typeof val === 'string' ? ms(val) : val return num != null ? Math.min(Math.max(0, num), ONE_YEAR_MS) : ONE_YEAR_MS }
[ "function", "calcMaxAge", "(", "val", ")", "{", "var", "num", "=", "typeof", "val", "===", "'string'", "?", "ms", "(", "val", ")", ":", "val", "return", "num", "!=", "null", "?", "Math", ".", "min", "(", "Math", ".", "max", "(", "0", ",", "num", ")", ",", "ONE_YEAR_MS", ")", ":", "ONE_YEAR_MS", "}" ]
Calculate the max-age from a configured value. @private @param {string|number} val @return {number}
[ "Calculate", "the", "max", "-", "age", "from", "a", "configured", "value", "." ]
15fe5e3837cef1e88cb4d1112bc2a23674b4834b
https://github.com/expressjs/serve-favicon/blob/15fe5e3837cef1e88cb4d1112bc2a23674b4834b/index.js#L101-L109
18,042
expressjs/serve-favicon
index.js
createIcon
function createIcon (buf, maxAge) { return { body: buf, headers: { 'Cache-Control': 'public, max-age=' + Math.floor(maxAge / 1000), 'ETag': etag(buf) } } }
javascript
function createIcon (buf, maxAge) { return { body: buf, headers: { 'Cache-Control': 'public, max-age=' + Math.floor(maxAge / 1000), 'ETag': etag(buf) } } }
[ "function", "createIcon", "(", "buf", ",", "maxAge", ")", "{", "return", "{", "body", ":", "buf", ",", "headers", ":", "{", "'Cache-Control'", ":", "'public, max-age='", "+", "Math", ".", "floor", "(", "maxAge", "/", "1000", ")", ",", "'ETag'", ":", "etag", "(", "buf", ")", "}", "}", "}" ]
Create icon data from Buffer and max-age. @private @param {Buffer} buf @param {number} maxAge @return {object}
[ "Create", "icon", "data", "from", "Buffer", "and", "max", "-", "age", "." ]
15fe5e3837cef1e88cb4d1112bc2a23674b4834b
https://github.com/expressjs/serve-favicon/blob/15fe5e3837cef1e88cb4d1112bc2a23674b4834b/index.js#L120-L128
18,043
expressjs/serve-favicon
index.js
createIsDirError
function createIsDirError (path) { var error = new Error('EISDIR, illegal operation on directory \'' + path + '\'') error.code = 'EISDIR' error.errno = 28 error.path = path error.syscall = 'open' return error }
javascript
function createIsDirError (path) { var error = new Error('EISDIR, illegal operation on directory \'' + path + '\'') error.code = 'EISDIR' error.errno = 28 error.path = path error.syscall = 'open' return error }
[ "function", "createIsDirError", "(", "path", ")", "{", "var", "error", "=", "new", "Error", "(", "'EISDIR, illegal operation on directory \\''", "+", "path", "+", "'\\''", ")", "error", ".", "code", "=", "'EISDIR'", "error", ".", "errno", "=", "28", "error", ".", "path", "=", "path", "error", ".", "syscall", "=", "'open'", "return", "error", "}" ]
Create EISDIR error. @private @param {string} path @return {Error}
[ "Create", "EISDIR", "error", "." ]
15fe5e3837cef1e88cb4d1112bc2a23674b4834b
https://github.com/expressjs/serve-favicon/blob/15fe5e3837cef1e88cb4d1112bc2a23674b4834b/index.js#L138-L145
18,044
expressjs/serve-favicon
index.js
isFresh
function isFresh (req, res) { return fresh(req.headers, { 'etag': res.getHeader('ETag'), 'last-modified': res.getHeader('Last-Modified') }) }
javascript
function isFresh (req, res) { return fresh(req.headers, { 'etag': res.getHeader('ETag'), 'last-modified': res.getHeader('Last-Modified') }) }
[ "function", "isFresh", "(", "req", ",", "res", ")", "{", "return", "fresh", "(", "req", ".", "headers", ",", "{", "'etag'", ":", "res", ".", "getHeader", "(", "'ETag'", ")", ",", "'last-modified'", ":", "res", ".", "getHeader", "(", "'Last-Modified'", ")", "}", ")", "}" ]
Determine if the cached representation is fresh. @param {object} req @param {object} res @return {boolean} @private
[ "Determine", "if", "the", "cached", "representation", "is", "fresh", "." ]
15fe5e3837cef1e88cb4d1112bc2a23674b4834b
https://github.com/expressjs/serve-favicon/blob/15fe5e3837cef1e88cb4d1112bc2a23674b4834b/index.js#L171-L176
18,045
expressjs/serve-favicon
index.js
resolveSync
function resolveSync (iconPath) { var path = resolve(iconPath) var stat = fs.statSync(path) if (stat.isDirectory()) { throw createIsDirError(path) } return path }
javascript
function resolveSync (iconPath) { var path = resolve(iconPath) var stat = fs.statSync(path) if (stat.isDirectory()) { throw createIsDirError(path) } return path }
[ "function", "resolveSync", "(", "iconPath", ")", "{", "var", "path", "=", "resolve", "(", "iconPath", ")", "var", "stat", "=", "fs", ".", "statSync", "(", "path", ")", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "throw", "createIsDirError", "(", "path", ")", "}", "return", "path", "}" ]
Resolve the path to icon. @param {string} iconPath @private
[ "Resolve", "the", "path", "to", "icon", "." ]
15fe5e3837cef1e88cb4d1112bc2a23674b4834b
https://github.com/expressjs/serve-favicon/blob/15fe5e3837cef1e88cb4d1112bc2a23674b4834b/index.js#L185-L194
18,046
auth0/node-wsfed
lib/metadata.js
metadataMiddleware
function metadataMiddleware (options) { //claimTypes, issuer, pem, endpointPath options = options || {}; if(!options.issuer) { throw new Error('options.issuer is required'); } if(!options.cert) { throw new Error('options.cert is required'); } var claimTypes = (options.profileMapper || PassportProfileMapper).prototype.metadata; var issuer = options.issuer; var pem = encoders.removeHeaders(options.cert); return function (req, res) { var endpoint = getEndpointAddress(req, options.endpointPath); var mexEndpoint = options.mexEndpoint ? getEndpointAddress(req, options.mexEndpoint) : ''; res.set('Content-Type', 'application/xml'); res.send(templates.metadata({ claimTypes: claimTypes, pem: pem, issuer: issuer, endpoint: endpoint, mexEndpoint: mexEndpoint }).replace(/\n/g, '')); }; }
javascript
function metadataMiddleware (options) { //claimTypes, issuer, pem, endpointPath options = options || {}; if(!options.issuer) { throw new Error('options.issuer is required'); } if(!options.cert) { throw new Error('options.cert is required'); } var claimTypes = (options.profileMapper || PassportProfileMapper).prototype.metadata; var issuer = options.issuer; var pem = encoders.removeHeaders(options.cert); return function (req, res) { var endpoint = getEndpointAddress(req, options.endpointPath); var mexEndpoint = options.mexEndpoint ? getEndpointAddress(req, options.mexEndpoint) : ''; res.set('Content-Type', 'application/xml'); res.send(templates.metadata({ claimTypes: claimTypes, pem: pem, issuer: issuer, endpoint: endpoint, mexEndpoint: mexEndpoint }).replace(/\n/g, '')); }; }
[ "function", "metadataMiddleware", "(", "options", ")", "{", "//claimTypes, issuer, pem, endpointPath", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "options", ".", "issuer", ")", "{", "throw", "new", "Error", "(", "'options.issuer is required'", ")", ";", "}", "if", "(", "!", "options", ".", "cert", ")", "{", "throw", "new", "Error", "(", "'options.cert is required'", ")", ";", "}", "var", "claimTypes", "=", "(", "options", ".", "profileMapper", "||", "PassportProfileMapper", ")", ".", "prototype", ".", "metadata", ";", "var", "issuer", "=", "options", ".", "issuer", ";", "var", "pem", "=", "encoders", ".", "removeHeaders", "(", "options", ".", "cert", ")", ";", "return", "function", "(", "req", ",", "res", ")", "{", "var", "endpoint", "=", "getEndpointAddress", "(", "req", ",", "options", ".", "endpointPath", ")", ";", "var", "mexEndpoint", "=", "options", ".", "mexEndpoint", "?", "getEndpointAddress", "(", "req", ",", "options", ".", "mexEndpoint", ")", ":", "''", ";", "res", ".", "set", "(", "'Content-Type'", ",", "'application/xml'", ")", ";", "res", ".", "send", "(", "templates", ".", "metadata", "(", "{", "claimTypes", ":", "claimTypes", ",", "pem", ":", "pem", ",", "issuer", ":", "issuer", ",", "endpoint", ":", "endpoint", ",", "mexEndpoint", ":", "mexEndpoint", "}", ")", ".", "replace", "(", "/", "\\n", "/", "g", ",", "''", ")", ")", ";", "}", ";", "}" ]
WSFederation metadata endpoint This endpoint returns a wsfederation metadata document. You should expose this endpoint in an address like: 'https://your-wsfederation-server.com/FederationMetadata/2007-06/FederationMetadata.xml options: - issuer string - cert the public certificate - profileMapper a function that given a user returns a claim based identity, also contains the metadata. By default maps from Passport.js user schema (PassportProfile). - endpointPath optional, defaults to the root of the fed metadata document. - mexEndpoint optional, url of the wsfederation MEX endpoint metadata document. @param {[type]} options [description] @return {[type]} [description]
[ "WSFederation", "metadata", "endpoint" ]
31fae4e6df6e13d31b2c86f754ececf7c7089bd3
https://github.com/auth0/node-wsfed/blob/31fae4e6df6e13d31b2c86f754ececf7c7089bd3/lib/metadata.js#L33-L63
18,047
fingerpich/jalali-moment
jalali-moment.js
leftZeroFill
function leftZeroFill(number, targetLength) { var output = number + ""; while (output.length < targetLength){ output = "0" + output; } return output; }
javascript
function leftZeroFill(number, targetLength) { var output = number + ""; while (output.length < targetLength){ output = "0" + output; } return output; }
[ "function", "leftZeroFill", "(", "number", ",", "targetLength", ")", "{", "var", "output", "=", "number", "+", "\"\"", ";", "while", "(", "output", ".", "length", "<", "targetLength", ")", "{", "output", "=", "\"0\"", "+", "output", ";", "}", "return", "output", ";", "}" ]
return a string which length is as much as you need @param {number} number input @param {number} targetLength expected length @example leftZeroFill(5,2) => 05
[ "return", "a", "string", "which", "length", "is", "as", "much", "as", "you", "need" ]
2f0442745b0b7b79b6ca1153b73f35de4e0b93d5
https://github.com/fingerpich/jalali-moment/blob/2f0442745b0b7b79b6ca1153b73f35de4e0b93d5/jalali-moment.js#L117-L123
18,048
fingerpich/jalali-moment
jalali-moment.js
toJalaliFormat
function toJalaliFormat(format) { for (var i = 0; i < format.length; i++) { if(!i || (format[i-1] !== "j" && format[i-1] !== format[i])) { if (format[i] === "Y" || format[i] === "M" || format[i] === "D" || format[i] === "g") { format = format.slice(0, i) + "j" + format.slice(i); } } } return format; }
javascript
function toJalaliFormat(format) { for (var i = 0; i < format.length; i++) { if(!i || (format[i-1] !== "j" && format[i-1] !== format[i])) { if (format[i] === "Y" || format[i] === "M" || format[i] === "D" || format[i] === "g") { format = format.slice(0, i) + "j" + format.slice(i); } } } return format; }
[ "function", "toJalaliFormat", "(", "format", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "format", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "i", "||", "(", "format", "[", "i", "-", "1", "]", "!==", "\"j\"", "&&", "format", "[", "i", "-", "1", "]", "!==", "format", "[", "i", "]", ")", ")", "{", "if", "(", "format", "[", "i", "]", "===", "\"Y\"", "||", "format", "[", "i", "]", "===", "\"M\"", "||", "format", "[", "i", "]", "===", "\"D\"", "||", "format", "[", "i", "]", "===", "\"g\"", ")", "{", "format", "=", "format", ".", "slice", "(", "0", ",", "i", ")", "+", "\"j\"", "+", "format", ".", "slice", "(", "i", ")", ";", "}", "}", "}", "return", "format", ";", "}" ]
Changes any moment Gregorian format to Jalali system format @param {string} format @example toJalaliFormat("YYYY/MMM/DD") => "jYYYY/jMMM/jDD"
[ "Changes", "any", "moment", "Gregorian", "format", "to", "Jalali", "system", "format" ]
2f0442745b0b7b79b6ca1153b73f35de4e0b93d5
https://github.com/fingerpich/jalali-moment/blob/2f0442745b0b7b79b6ca1153b73f35de4e0b93d5/jalali-moment.js#L138-L147
18,049
fingerpich/jalali-moment
jalali-moment.js
normalizeUnits
function normalizeUnits(units, momentObj) { if (isJalali(momentObj)) { units = toJalaliUnit(units); } if (units) { var lowered = units.toLowerCase(); units = unitAliases[lowered] || lowered; } // TODO : add unit test if (units === "jday") units = "day"; else if (units === "jd") units = "d"; return units; }
javascript
function normalizeUnits(units, momentObj) { if (isJalali(momentObj)) { units = toJalaliUnit(units); } if (units) { var lowered = units.toLowerCase(); units = unitAliases[lowered] || lowered; } // TODO : add unit test if (units === "jday") units = "day"; else if (units === "jd") units = "d"; return units; }
[ "function", "normalizeUnits", "(", "units", ",", "momentObj", ")", "{", "if", "(", "isJalali", "(", "momentObj", ")", ")", "{", "units", "=", "toJalaliUnit", "(", "units", ")", ";", "}", "if", "(", "units", ")", "{", "var", "lowered", "=", "units", ".", "toLowerCase", "(", ")", ";", "units", "=", "unitAliases", "[", "lowered", "]", "||", "lowered", ";", "}", "// TODO : add unit test", "if", "(", "units", "===", "\"jday\"", ")", "units", "=", "\"day\"", ";", "else", "if", "(", "units", "===", "\"jd\"", ")", "units", "=", "\"d\"", ";", "return", "units", ";", "}" ]
normalize units to be comparable @param {string} units
[ "normalize", "units", "to", "be", "comparable" ]
2f0442745b0b7b79b6ca1153b73f35de4e0b93d5
https://github.com/fingerpich/jalali-moment/blob/2f0442745b0b7b79b6ca1153b73f35de4e0b93d5/jalali-moment.js#L170-L182
18,050
fingerpich/jalali-moment
jalali-moment.js
setDate
function setDate(momentInstance, year, month, day) { var d = momentInstance._d; if (momentInstance._isUTC) { /*eslint-disable new-cap*/ momentInstance._d = new Date(Date.UTC(year, month, day, d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())); /*eslint-enable new-cap*/ } else { momentInstance._d = new Date(year, month, day, d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()); } }
javascript
function setDate(momentInstance, year, month, day) { var d = momentInstance._d; if (momentInstance._isUTC) { /*eslint-disable new-cap*/ momentInstance._d = new Date(Date.UTC(year, month, day, d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())); /*eslint-enable new-cap*/ } else { momentInstance._d = new Date(year, month, day, d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()); } }
[ "function", "setDate", "(", "momentInstance", ",", "year", ",", "month", ",", "day", ")", "{", "var", "d", "=", "momentInstance", ".", "_d", ";", "if", "(", "momentInstance", ".", "_isUTC", ")", "{", "/*eslint-disable new-cap*/", "momentInstance", ".", "_d", "=", "new", "Date", "(", "Date", ".", "UTC", "(", "year", ",", "month", ",", "day", ",", "d", ".", "getUTCHours", "(", ")", ",", "d", ".", "getUTCMinutes", "(", ")", ",", "d", ".", "getUTCSeconds", "(", ")", ",", "d", ".", "getUTCMilliseconds", "(", ")", ")", ")", ";", "/*eslint-enable new-cap*/", "}", "else", "{", "momentInstance", ".", "_d", "=", "new", "Date", "(", "year", ",", "month", ",", "day", ",", "d", ".", "getHours", "(", ")", ",", "d", ".", "getMinutes", "(", ")", ",", "d", ".", "getSeconds", "(", ")", ",", "d", ".", "getMilliseconds", "(", ")", ")", ";", "}", "}" ]
set a gregorian date to moment object @param {string} momentInstance @param {string} year in gregorian system @param {string} month in gregorian system @param {string} day in gregorian system
[ "set", "a", "gregorian", "date", "to", "moment", "object" ]
2f0442745b0b7b79b6ca1153b73f35de4e0b93d5
https://github.com/fingerpich/jalali-moment/blob/2f0442745b0b7b79b6ca1153b73f35de4e0b93d5/jalali-moment.js#L191-L202
18,051
jgranstrom/sass-extract
src/importer.js
findImportedPath
function findImportedPath(url, prev, includedFilesMap, includedPaths) { let candidateFromPaths; if(prev !== 'stdin') { const prevPath = path.posix.dirname(prev); candidateFromPaths = [prevPath, ...includedPaths]; } else { candidateFromPaths = [...includedPaths]; } for(let i = 0; i < candidateFromPaths.length; i++) { let candidatePath; let candidateFromPath = normalizePath(makeAbsolute(candidateFromPaths[i])); if (path.isAbsolute(url)) { candidatePath = normalizePath(url); } else { // Get normalize absolute candidate from path candidatePath = path.posix.join(candidateFromPath, url); } if(includedFilesMap[candidatePath]) { return candidatePath; } else { let urlBasename = path.posix.basename(url); let indexOfBasename = url.lastIndexOf(urlBasename); let partialUrl = `${url.substring(0, indexOfBasename)}_${urlBasename}`; if (path.isAbsolute(partialUrl)) { candidatePath = normalizePath(partialUrl); } else { candidatePath = path.posix.join(candidateFromPath, partialUrl); } if(includedFilesMap[candidatePath]) { return candidatePath; } } } return null; }
javascript
function findImportedPath(url, prev, includedFilesMap, includedPaths) { let candidateFromPaths; if(prev !== 'stdin') { const prevPath = path.posix.dirname(prev); candidateFromPaths = [prevPath, ...includedPaths]; } else { candidateFromPaths = [...includedPaths]; } for(let i = 0; i < candidateFromPaths.length; i++) { let candidatePath; let candidateFromPath = normalizePath(makeAbsolute(candidateFromPaths[i])); if (path.isAbsolute(url)) { candidatePath = normalizePath(url); } else { // Get normalize absolute candidate from path candidatePath = path.posix.join(candidateFromPath, url); } if(includedFilesMap[candidatePath]) { return candidatePath; } else { let urlBasename = path.posix.basename(url); let indexOfBasename = url.lastIndexOf(urlBasename); let partialUrl = `${url.substring(0, indexOfBasename)}_${urlBasename}`; if (path.isAbsolute(partialUrl)) { candidatePath = normalizePath(partialUrl); } else { candidatePath = path.posix.join(candidateFromPath, partialUrl); } if(includedFilesMap[candidatePath]) { return candidatePath; } } } return null; }
[ "function", "findImportedPath", "(", "url", ",", "prev", ",", "includedFilesMap", ",", "includedPaths", ")", "{", "let", "candidateFromPaths", ";", "if", "(", "prev", "!==", "'stdin'", ")", "{", "const", "prevPath", "=", "path", ".", "posix", ".", "dirname", "(", "prev", ")", ";", "candidateFromPaths", "=", "[", "prevPath", ",", "...", "includedPaths", "]", ";", "}", "else", "{", "candidateFromPaths", "=", "[", "...", "includedPaths", "]", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "candidateFromPaths", ".", "length", ";", "i", "++", ")", "{", "let", "candidatePath", ";", "let", "candidateFromPath", "=", "normalizePath", "(", "makeAbsolute", "(", "candidateFromPaths", "[", "i", "]", ")", ")", ";", "if", "(", "path", ".", "isAbsolute", "(", "url", ")", ")", "{", "candidatePath", "=", "normalizePath", "(", "url", ")", ";", "}", "else", "{", "// Get normalize absolute candidate from path", "candidatePath", "=", "path", ".", "posix", ".", "join", "(", "candidateFromPath", ",", "url", ")", ";", "}", "if", "(", "includedFilesMap", "[", "candidatePath", "]", ")", "{", "return", "candidatePath", ";", "}", "else", "{", "let", "urlBasename", "=", "path", ".", "posix", ".", "basename", "(", "url", ")", ";", "let", "indexOfBasename", "=", "url", ".", "lastIndexOf", "(", "urlBasename", ")", ";", "let", "partialUrl", "=", "`", "${", "url", ".", "substring", "(", "0", ",", "indexOfBasename", ")", "}", "${", "urlBasename", "}", "`", ";", "if", "(", "path", ".", "isAbsolute", "(", "partialUrl", ")", ")", "{", "candidatePath", "=", "normalizePath", "(", "partialUrl", ")", ";", "}", "else", "{", "candidatePath", "=", "path", ".", "posix", ".", "join", "(", "candidateFromPath", ",", "partialUrl", ")", ";", "}", "if", "(", "includedFilesMap", "[", "candidatePath", "]", ")", "{", "return", "candidatePath", ";", "}", "}", "}", "return", "null", ";", "}" ]
Search for the imported file in order of included paths
[ "Search", "for", "the", "imported", "file", "in", "order", "of", "included", "paths" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/importer.js#L8-L48
18,052
jgranstrom/sass-extract
src/importer.js
getImportAbsolutePath
function getImportAbsolutePath(url, prev, includedFilesMap, includedPaths = []) { // Ensure that both @import 'file' and @import 'file.scss' is mapped correctly let extension = path.posix.extname(prev); if(path.posix.extname(url) !== extension) { url += extension; } const absolutePath = findImportedPath(url, prev, includedFilesMap, includedPaths); if(!absolutePath) { throw new Error(`Can not determine imported file for url '${url}' imported in ${prev}`); } return absolutePath; }
javascript
function getImportAbsolutePath(url, prev, includedFilesMap, includedPaths = []) { // Ensure that both @import 'file' and @import 'file.scss' is mapped correctly let extension = path.posix.extname(prev); if(path.posix.extname(url) !== extension) { url += extension; } const absolutePath = findImportedPath(url, prev, includedFilesMap, includedPaths); if(!absolutePath) { throw new Error(`Can not determine imported file for url '${url}' imported in ${prev}`); } return absolutePath; }
[ "function", "getImportAbsolutePath", "(", "url", ",", "prev", ",", "includedFilesMap", ",", "includedPaths", "=", "[", "]", ")", "{", "// Ensure that both @import 'file' and @import 'file.scss' is mapped correctly", "let", "extension", "=", "path", ".", "posix", ".", "extname", "(", "prev", ")", ";", "if", "(", "path", ".", "posix", ".", "extname", "(", "url", ")", "!==", "extension", ")", "{", "url", "+=", "extension", ";", "}", "const", "absolutePath", "=", "findImportedPath", "(", "url", ",", "prev", ",", "includedFilesMap", ",", "includedPaths", ")", ";", "if", "(", "!", "absolutePath", ")", "{", "throw", "new", "Error", "(", "`", "${", "url", "}", "${", "prev", "}", "`", ")", ";", "}", "return", "absolutePath", ";", "}" ]
Get the absolute file path for a relative @import like './sub/file.scsss' If the @import is made from a raw data section a best guess path is returned
[ "Get", "the", "absolute", "file", "path", "for", "a", "relative" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/importer.js#L54-L68
18,053
jgranstrom/sass-extract
src/importer.js
getImportResult
function getImportResult(extractions, url, prev, includedFilesMap, includedPaths) { const absolutePath = getImportAbsolutePath(url, prev, includedFilesMap, includedPaths); const contents = extractions[absolutePath].injectedData; return { file: absolutePath, contents }; }
javascript
function getImportResult(extractions, url, prev, includedFilesMap, includedPaths) { const absolutePath = getImportAbsolutePath(url, prev, includedFilesMap, includedPaths); const contents = extractions[absolutePath].injectedData; return { file: absolutePath, contents }; }
[ "function", "getImportResult", "(", "extractions", ",", "url", ",", "prev", ",", "includedFilesMap", ",", "includedPaths", ")", "{", "const", "absolutePath", "=", "getImportAbsolutePath", "(", "url", ",", "prev", ",", "includedFilesMap", ",", "includedPaths", ")", ";", "const", "contents", "=", "extractions", "[", "absolutePath", "]", ".", "injectedData", ";", "return", "{", "file", ":", "absolutePath", ",", "contents", "}", ";", "}" ]
Get the resulting source and path for a given @import request
[ "Get", "the", "resulting", "source", "and", "path", "for", "a", "given" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/importer.js#L73-L78
18,054
jgranstrom/sass-extract
src/parse.js
getDeclarationDeps
function getDeclarationDeps($ast, declaration, scope) { if(scope !== SCOPE_EXPLICIT) { return {}; } const depParentNodes = $ast(declaration).parents(node => { if(node.node.type === 'mixin') { return true; } else if(node.node.type === 'atrule') { const atruleIdentNode = $ast(node).children('atkeyword').children('ident'); return atruleIdentNode.length() > 0 && atruleIdentNode.first().value() === 'function' } else { return false; } }); if(depParentNodes.length() === 0) { return {}; } const depParentNode = depParentNodes.last(); const depKeywordNode = depParentNode.children('atkeyword').children('ident'); if(depKeywordNode.length() === 0) { return {}; } const atKeyword = depKeywordNode.first().value(); if(!DEP_HOST[atKeyword]) { return {}; } const depHostNode = DEP_HOST[atKeyword](depParentNode); const atKeywordIdentifierNode = depHostNode.children('ident'); if(atKeywordIdentifierNode.length() === 0) { return {}; } const atIdentifier = atKeywordIdentifierNode.first().value(); const argumentsNode = depHostNode.children('arguments'); // Count arguments to mixin/function @atrule const requiredArgsCount = argumentsNode.children('variable').length(); const optionalArgsCount = argumentsNode.children('declaration').length(); const totalArgsCount = requiredArgsCount + optionalArgsCount; if(!DEP_KEYWORDS[atKeyword]) { return {}; } return { [DEP_KEYWORDS[atKeyword]]: { name: atIdentifier, argsCount: { total: totalArgsCount, required: requiredArgsCount, optional: optionalArgsCount, }, }, }; }
javascript
function getDeclarationDeps($ast, declaration, scope) { if(scope !== SCOPE_EXPLICIT) { return {}; } const depParentNodes = $ast(declaration).parents(node => { if(node.node.type === 'mixin') { return true; } else if(node.node.type === 'atrule') { const atruleIdentNode = $ast(node).children('atkeyword').children('ident'); return atruleIdentNode.length() > 0 && atruleIdentNode.first().value() === 'function' } else { return false; } }); if(depParentNodes.length() === 0) { return {}; } const depParentNode = depParentNodes.last(); const depKeywordNode = depParentNode.children('atkeyword').children('ident'); if(depKeywordNode.length() === 0) { return {}; } const atKeyword = depKeywordNode.first().value(); if(!DEP_HOST[atKeyword]) { return {}; } const depHostNode = DEP_HOST[atKeyword](depParentNode); const atKeywordIdentifierNode = depHostNode.children('ident'); if(atKeywordIdentifierNode.length() === 0) { return {}; } const atIdentifier = atKeywordIdentifierNode.first().value(); const argumentsNode = depHostNode.children('arguments'); // Count arguments to mixin/function @atrule const requiredArgsCount = argumentsNode.children('variable').length(); const optionalArgsCount = argumentsNode.children('declaration').length(); const totalArgsCount = requiredArgsCount + optionalArgsCount; if(!DEP_KEYWORDS[atKeyword]) { return {}; } return { [DEP_KEYWORDS[atKeyword]]: { name: atIdentifier, argsCount: { total: totalArgsCount, required: requiredArgsCount, optional: optionalArgsCount, }, }, }; }
[ "function", "getDeclarationDeps", "(", "$ast", ",", "declaration", ",", "scope", ")", "{", "if", "(", "scope", "!==", "SCOPE_EXPLICIT", ")", "{", "return", "{", "}", ";", "}", "const", "depParentNodes", "=", "$ast", "(", "declaration", ")", ".", "parents", "(", "node", "=>", "{", "if", "(", "node", ".", "node", ".", "type", "===", "'mixin'", ")", "{", "return", "true", ";", "}", "else", "if", "(", "node", ".", "node", ".", "type", "===", "'atrule'", ")", "{", "const", "atruleIdentNode", "=", "$ast", "(", "node", ")", ".", "children", "(", "'atkeyword'", ")", ".", "children", "(", "'ident'", ")", ";", "return", "atruleIdentNode", ".", "length", "(", ")", ">", "0", "&&", "atruleIdentNode", ".", "first", "(", ")", ".", "value", "(", ")", "===", "'function'", "}", "else", "{", "return", "false", ";", "}", "}", ")", ";", "if", "(", "depParentNodes", ".", "length", "(", ")", "===", "0", ")", "{", "return", "{", "}", ";", "}", "const", "depParentNode", "=", "depParentNodes", ".", "last", "(", ")", ";", "const", "depKeywordNode", "=", "depParentNode", ".", "children", "(", "'atkeyword'", ")", ".", "children", "(", "'ident'", ")", ";", "if", "(", "depKeywordNode", ".", "length", "(", ")", "===", "0", ")", "{", "return", "{", "}", ";", "}", "const", "atKeyword", "=", "depKeywordNode", ".", "first", "(", ")", ".", "value", "(", ")", ";", "if", "(", "!", "DEP_HOST", "[", "atKeyword", "]", ")", "{", "return", "{", "}", ";", "}", "const", "depHostNode", "=", "DEP_HOST", "[", "atKeyword", "]", "(", "depParentNode", ")", ";", "const", "atKeywordIdentifierNode", "=", "depHostNode", ".", "children", "(", "'ident'", ")", ";", "if", "(", "atKeywordIdentifierNode", ".", "length", "(", ")", "===", "0", ")", "{", "return", "{", "}", ";", "}", "const", "atIdentifier", "=", "atKeywordIdentifierNode", ".", "first", "(", ")", ".", "value", "(", ")", ";", "const", "argumentsNode", "=", "depHostNode", ".", "children", "(", "'arguments'", ")", ";", "// Count arguments to mixin/function @atrule", "const", "requiredArgsCount", "=", "argumentsNode", ".", "children", "(", "'variable'", ")", ".", "length", "(", ")", ";", "const", "optionalArgsCount", "=", "argumentsNode", ".", "children", "(", "'declaration'", ")", ".", "length", "(", ")", ";", "const", "totalArgsCount", "=", "requiredArgsCount", "+", "optionalArgsCount", ";", "if", "(", "!", "DEP_KEYWORDS", "[", "atKeyword", "]", ")", "{", "return", "{", "}", ";", "}", "return", "{", "[", "DEP_KEYWORDS", "[", "atKeyword", "]", "]", ":", "{", "name", ":", "atIdentifier", ",", "argsCount", ":", "{", "total", ":", "totalArgsCount", ",", "required", ":", "requiredArgsCount", ",", "optional", ":", "optionalArgsCount", ",", "}", ",", "}", ",", "}", ";", "}" ]
Get dependencies required to extract variables such as mixins or function invocations
[ "Get", "dependencies", "required", "to", "extract", "variables", "such", "as", "mixins", "or", "function", "invocations" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/parse.js#L54-L116
18,055
jgranstrom/sass-extract
src/parse.js
parseDeclaration
function parseDeclaration($ast, declaration, scope) { const variable = {}; const propertyNode = $ast(declaration) .children('property'); variable.declarationClean = propertyNode.value(); variable.position = propertyNode.get(0).start; variable.declaration = `$${variable.declarationClean}`; variable.expression = parseExpression($ast, declaration); variable.flags = { default: isDefaultDeclaration($ast, declaration), global: isExplicitGlobalDeclaration($ast, declaration), }; variable.deps = getDeclarationDeps($ast, declaration, scope); return variable; }
javascript
function parseDeclaration($ast, declaration, scope) { const variable = {}; const propertyNode = $ast(declaration) .children('property'); variable.declarationClean = propertyNode.value(); variable.position = propertyNode.get(0).start; variable.declaration = `$${variable.declarationClean}`; variable.expression = parseExpression($ast, declaration); variable.flags = { default: isDefaultDeclaration($ast, declaration), global: isExplicitGlobalDeclaration($ast, declaration), }; variable.deps = getDeclarationDeps($ast, declaration, scope); return variable; }
[ "function", "parseDeclaration", "(", "$ast", ",", "declaration", ",", "scope", ")", "{", "const", "variable", "=", "{", "}", ";", "const", "propertyNode", "=", "$ast", "(", "declaration", ")", ".", "children", "(", "'property'", ")", ";", "variable", ".", "declarationClean", "=", "propertyNode", ".", "value", "(", ")", ";", "variable", ".", "position", "=", "propertyNode", ".", "get", "(", "0", ")", ".", "start", ";", "variable", ".", "declaration", "=", "`", "${", "variable", ".", "declarationClean", "}", "`", ";", "variable", ".", "expression", "=", "parseExpression", "(", "$ast", ",", "declaration", ")", ";", "variable", ".", "flags", "=", "{", "default", ":", "isDefaultDeclaration", "(", "$ast", ",", "declaration", ")", ",", "global", ":", "isExplicitGlobalDeclaration", "(", "$ast", ",", "declaration", ")", ",", "}", ";", "variable", ".", "deps", "=", "getDeclarationDeps", "(", "$ast", ",", "declaration", ",", "scope", ")", ";", "return", "variable", ";", "}" ]
Parse declaration node into declaration object
[ "Parse", "declaration", "node", "into", "declaration", "object" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/parse.js#L121-L141
18,056
jgranstrom/sass-extract
src/process.js
processFile
function processFile(idx, count, filename, data, parsedDeclarations, pluggable) { const declarations = parsedDeclarations.files[filename]; // Inject dependent declaration extraction to last file const dependentDeclarations = idx === count - 1 ? parsedDeclarations.dependentDeclarations : []; const variables = { global: {} }; const globalDeclarationResultHandler = (declaration, value, sassValue) => { if(!variables.global[declaration.declaration]) { variables.global[declaration.declaration] = []; } const variableValue = pluggable.run(Pluggable.POST_VALUE, { value, sassValue }).value; variables.global[declaration.declaration].push({ declaration, value: variableValue }); } const fileId = getFileId(filename); const injection = injectExtractionFunctions(fileId, declarations, dependentDeclarations, { globalDeclarationResultHandler }); const injectedData = `${data}\n\n${injection.injectedData}`; const injectedFunctions = injection.injectedFunctions; return { fileId, declarations, variables, injectedData, injectedFunctions, }; }
javascript
function processFile(idx, count, filename, data, parsedDeclarations, pluggable) { const declarations = parsedDeclarations.files[filename]; // Inject dependent declaration extraction to last file const dependentDeclarations = idx === count - 1 ? parsedDeclarations.dependentDeclarations : []; const variables = { global: {} }; const globalDeclarationResultHandler = (declaration, value, sassValue) => { if(!variables.global[declaration.declaration]) { variables.global[declaration.declaration] = []; } const variableValue = pluggable.run(Pluggable.POST_VALUE, { value, sassValue }).value; variables.global[declaration.declaration].push({ declaration, value: variableValue }); } const fileId = getFileId(filename); const injection = injectExtractionFunctions(fileId, declarations, dependentDeclarations, { globalDeclarationResultHandler }); const injectedData = `${data}\n\n${injection.injectedData}`; const injectedFunctions = injection.injectedFunctions; return { fileId, declarations, variables, injectedData, injectedFunctions, }; }
[ "function", "processFile", "(", "idx", ",", "count", ",", "filename", ",", "data", ",", "parsedDeclarations", ",", "pluggable", ")", "{", "const", "declarations", "=", "parsedDeclarations", ".", "files", "[", "filename", "]", ";", "// Inject dependent declaration extraction to last file", "const", "dependentDeclarations", "=", "idx", "===", "count", "-", "1", "?", "parsedDeclarations", ".", "dependentDeclarations", ":", "[", "]", ";", "const", "variables", "=", "{", "global", ":", "{", "}", "}", ";", "const", "globalDeclarationResultHandler", "=", "(", "declaration", ",", "value", ",", "sassValue", ")", "=>", "{", "if", "(", "!", "variables", ".", "global", "[", "declaration", ".", "declaration", "]", ")", "{", "variables", ".", "global", "[", "declaration", ".", "declaration", "]", "=", "[", "]", ";", "}", "const", "variableValue", "=", "pluggable", ".", "run", "(", "Pluggable", ".", "POST_VALUE", ",", "{", "value", ",", "sassValue", "}", ")", ".", "value", ";", "variables", ".", "global", "[", "declaration", ".", "declaration", "]", ".", "push", "(", "{", "declaration", ",", "value", ":", "variableValue", "}", ")", ";", "}", "const", "fileId", "=", "getFileId", "(", "filename", ")", ";", "const", "injection", "=", "injectExtractionFunctions", "(", "fileId", ",", "declarations", ",", "dependentDeclarations", ",", "{", "globalDeclarationResultHandler", "}", ")", ";", "const", "injectedData", "=", "`", "${", "data", "}", "\\n", "\\n", "${", "injection", ".", "injectedData", "}", "`", ";", "const", "injectedFunctions", "=", "injection", ".", "injectedFunctions", ";", "return", "{", "fileId", ",", "declarations", ",", "variables", ",", "injectedData", ",", "injectedFunctions", ",", "}", ";", "}" ]
Process a single sass files to get declarations, injected source and functions
[ "Process", "a", "single", "sass", "files", "to", "get", "declarations", "injected", "source", "and", "functions" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/process.js#L32-L58
18,057
jgranstrom/sass-extract
src/extract.js
getRenderedStats
function getRenderedStats(rendered, compileOptions) { return { entryFilename: normalizePath(rendered.stats.entry), includedFiles: rendered.stats.includedFiles.map(f => normalizePath(makeAbsolute(f))), includedPaths: (compileOptions.includePaths || []).map(normalizePath), }; }
javascript
function getRenderedStats(rendered, compileOptions) { return { entryFilename: normalizePath(rendered.stats.entry), includedFiles: rendered.stats.includedFiles.map(f => normalizePath(makeAbsolute(f))), includedPaths: (compileOptions.includePaths || []).map(normalizePath), }; }
[ "function", "getRenderedStats", "(", "rendered", ",", "compileOptions", ")", "{", "return", "{", "entryFilename", ":", "normalizePath", "(", "rendered", ".", "stats", ".", "entry", ")", ",", "includedFiles", ":", "rendered", ".", "stats", ".", "includedFiles", ".", "map", "(", "f", "=>", "normalizePath", "(", "makeAbsolute", "(", "f", ")", ")", ")", ",", "includedPaths", ":", "(", "compileOptions", ".", "includePaths", "||", "[", "]", ")", ".", "map", "(", "normalizePath", ")", ",", "}", ";", "}" ]
Get rendered stats required for extraction
[ "Get", "rendered", "stats", "required", "for", "extraction" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/extract.js#L14-L20
18,058
jgranstrom/sass-extract
src/extract.js
makeExtractionCompileOptions
function makeExtractionCompileOptions(compileOptions, entryFilename, extractions, importer) { const extractionCompileOptions = Object.assign({}, compileOptions); const extractionFunctions = {}; // Copy all extraction function for each file into one object for compilation Object.keys(extractions).forEach(extractionKey => { Object.assign(extractionFunctions, extractions[extractionKey].injectedFunctions); }); extractionCompileOptions.functions = Object.assign(extractionFunctions, compileOptions.functions); extractionCompileOptions.data = extractions[entryFilename].injectedData; if(!makeExtractionCompileOptions.imported) { extractionCompileOptions.importer = importer; } return extractionCompileOptions; }
javascript
function makeExtractionCompileOptions(compileOptions, entryFilename, extractions, importer) { const extractionCompileOptions = Object.assign({}, compileOptions); const extractionFunctions = {}; // Copy all extraction function for each file into one object for compilation Object.keys(extractions).forEach(extractionKey => { Object.assign(extractionFunctions, extractions[extractionKey].injectedFunctions); }); extractionCompileOptions.functions = Object.assign(extractionFunctions, compileOptions.functions); extractionCompileOptions.data = extractions[entryFilename].injectedData; if(!makeExtractionCompileOptions.imported) { extractionCompileOptions.importer = importer; } return extractionCompileOptions; }
[ "function", "makeExtractionCompileOptions", "(", "compileOptions", ",", "entryFilename", ",", "extractions", ",", "importer", ")", "{", "const", "extractionCompileOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "compileOptions", ")", ";", "const", "extractionFunctions", "=", "{", "}", ";", "// Copy all extraction function for each file into one object for compilation", "Object", ".", "keys", "(", "extractions", ")", ".", "forEach", "(", "extractionKey", "=>", "{", "Object", ".", "assign", "(", "extractionFunctions", ",", "extractions", "[", "extractionKey", "]", ".", "injectedFunctions", ")", ";", "}", ")", ";", "extractionCompileOptions", ".", "functions", "=", "Object", ".", "assign", "(", "extractionFunctions", ",", "compileOptions", ".", "functions", ")", ";", "extractionCompileOptions", ".", "data", "=", "extractions", "[", "entryFilename", "]", ".", "injectedData", ";", "if", "(", "!", "makeExtractionCompileOptions", ".", "imported", ")", "{", "extractionCompileOptions", ".", "importer", "=", "importer", ";", "}", "return", "extractionCompileOptions", ";", "}" ]
Make the compilation option for the extraction rendering Set the data to be rendered to the injected source Add compilation functions and custom importer for injected sources
[ "Make", "the", "compilation", "option", "for", "the", "extraction", "rendering", "Set", "the", "data", "to", "be", "rendered", "to", "the", "injected", "source", "Add", "compilation", "functions", "and", "custom", "importer", "for", "injected", "sources" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/extract.js#L27-L43
18,059
jgranstrom/sass-extract
src/extract.js
compileExtractionResult
function compileExtractionResult(orderedFiles, extractions) { const extractedVariables = { global: {} }; orderedFiles.map(filename => { const globalFileVariables = extractions[filename].variables.global; Object.keys(globalFileVariables).map(variableKey => { globalFileVariables[variableKey].forEach(extractedVariable => { let variable = extractedVariables.global[variableKey]; let currentVariableSources = []; let currentVariableDeclarations = []; if(variable) { currentVariableSources = variable.sources; currentVariableDeclarations = variable.declarations; } const hasOnlyDefaults = currentVariableDeclarations.every(declaration => declaration.flags.default); const currentIsDefault = extractedVariable.declaration.flags.default; if(currentVariableDeclarations.length === 0 || !currentIsDefault || hasOnlyDefaults) { variable = extractedVariables.global[variableKey] = Object.assign({}, extractedVariable.value); } variable.sources = currentVariableSources.indexOf(filename) < 0 ? [...currentVariableSources, filename] : currentVariableSources; variable.declarations = [...currentVariableDeclarations, { expression: extractedVariable.declaration.expression, flags: extractedVariable.declaration.flags, in: filename, position: extractedVariable.declaration.position, }]; }); }); }); return extractedVariables; }
javascript
function compileExtractionResult(orderedFiles, extractions) { const extractedVariables = { global: {} }; orderedFiles.map(filename => { const globalFileVariables = extractions[filename].variables.global; Object.keys(globalFileVariables).map(variableKey => { globalFileVariables[variableKey].forEach(extractedVariable => { let variable = extractedVariables.global[variableKey]; let currentVariableSources = []; let currentVariableDeclarations = []; if(variable) { currentVariableSources = variable.sources; currentVariableDeclarations = variable.declarations; } const hasOnlyDefaults = currentVariableDeclarations.every(declaration => declaration.flags.default); const currentIsDefault = extractedVariable.declaration.flags.default; if(currentVariableDeclarations.length === 0 || !currentIsDefault || hasOnlyDefaults) { variable = extractedVariables.global[variableKey] = Object.assign({}, extractedVariable.value); } variable.sources = currentVariableSources.indexOf(filename) < 0 ? [...currentVariableSources, filename] : currentVariableSources; variable.declarations = [...currentVariableDeclarations, { expression: extractedVariable.declaration.expression, flags: extractedVariable.declaration.flags, in: filename, position: extractedVariable.declaration.position, }]; }); }); }); return extractedVariables; }
[ "function", "compileExtractionResult", "(", "orderedFiles", ",", "extractions", ")", "{", "const", "extractedVariables", "=", "{", "global", ":", "{", "}", "}", ";", "orderedFiles", ".", "map", "(", "filename", "=>", "{", "const", "globalFileVariables", "=", "extractions", "[", "filename", "]", ".", "variables", ".", "global", ";", "Object", ".", "keys", "(", "globalFileVariables", ")", ".", "map", "(", "variableKey", "=>", "{", "globalFileVariables", "[", "variableKey", "]", ".", "forEach", "(", "extractedVariable", "=>", "{", "let", "variable", "=", "extractedVariables", ".", "global", "[", "variableKey", "]", ";", "let", "currentVariableSources", "=", "[", "]", ";", "let", "currentVariableDeclarations", "=", "[", "]", ";", "if", "(", "variable", ")", "{", "currentVariableSources", "=", "variable", ".", "sources", ";", "currentVariableDeclarations", "=", "variable", ".", "declarations", ";", "}", "const", "hasOnlyDefaults", "=", "currentVariableDeclarations", ".", "every", "(", "declaration", "=>", "declaration", ".", "flags", ".", "default", ")", ";", "const", "currentIsDefault", "=", "extractedVariable", ".", "declaration", ".", "flags", ".", "default", ";", "if", "(", "currentVariableDeclarations", ".", "length", "===", "0", "||", "!", "currentIsDefault", "||", "hasOnlyDefaults", ")", "{", "variable", "=", "extractedVariables", ".", "global", "[", "variableKey", "]", "=", "Object", ".", "assign", "(", "{", "}", ",", "extractedVariable", ".", "value", ")", ";", "}", "variable", ".", "sources", "=", "currentVariableSources", ".", "indexOf", "(", "filename", ")", "<", "0", "?", "[", "...", "currentVariableSources", ",", "filename", "]", ":", "currentVariableSources", ";", "variable", ".", "declarations", "=", "[", "...", "currentVariableDeclarations", ",", "{", "expression", ":", "extractedVariable", ".", "declaration", ".", "expression", ",", "flags", ":", "extractedVariable", ".", "declaration", ".", "flags", ",", "in", ":", "filename", ",", "position", ":", "extractedVariable", ".", "declaration", ".", "position", ",", "}", "]", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "extractedVariables", ";", "}" ]
Compile extracted variables per file into a complete result object
[ "Compile", "extracted", "variables", "per", "file", "into", "a", "complete", "result", "object" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/extract.js#L48-L83
18,060
jgranstrom/sass-extract
src/plugins/compact.js
isColor
function isColor(value) { return value.r != null && value.g != null && value.b != null && value.a != null && value.hex != null; }
javascript
function isColor(value) { return value.r != null && value.g != null && value.b != null && value.a != null && value.hex != null; }
[ "function", "isColor", "(", "value", ")", "{", "return", "value", ".", "r", "!=", "null", "&&", "value", ".", "g", "!=", "null", "&&", "value", ".", "b", "!=", "null", "&&", "value", ".", "a", "!=", "null", "&&", "value", ".", "hex", "!=", "null", ";", "}" ]
Use duck typing to distinguish between map and color objects
[ "Use", "duck", "typing", "to", "distinguish", "between", "map", "and", "color", "objects" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/plugins/compact.js#L8-L14
18,061
jgranstrom/sass-extract
src/serialize.js
serializeValue
function serializeValue(sassValue, isInList) { switch(sassValue.constructor) { case sass.types.String: case sass.types.Boolean: return `${sassValue.getValue()}`; case sass.types.Number: return `${sassValue.getValue()}${sassValue.getUnit()}`; case sass.types.Color: return serializeColor(sassValue); case sass.types.Null: return `null`; case sass.types.List: const listLength = sassValue.getLength(); const listElement = []; const hasSeparator = sassValue.getSeparator(); for(let i = 0; i < listLength; i++) { listElement.push(serialize(sassValue.getValue(i), true)); } // Make sure nested lists are serialized with surrounding parenthesis if(isInList) { return `(${listElement.join(hasSeparator ? ',' : ' ')})`; } else { return `${listElement.join(hasSeparator ? ',' : ' ')}`; } case sass.types.Map: const mapLength = sassValue.getLength(); const mapValue = {}; for(let i = 0; i < mapLength; i++) { const key = serialize(sassValue.getKey(i)); const value = serialize(sassValue.getValue(i)); mapValue[key] = value; } const serializedMapValues = Object.keys(mapValue).map(key => `${key}: ${mapValue[key]}`); return `(${serializedMapValues})`; default: throw new Error(`Unsupported sass variable type '${sassValue.constructor.name}'`) }; }
javascript
function serializeValue(sassValue, isInList) { switch(sassValue.constructor) { case sass.types.String: case sass.types.Boolean: return `${sassValue.getValue()}`; case sass.types.Number: return `${sassValue.getValue()}${sassValue.getUnit()}`; case sass.types.Color: return serializeColor(sassValue); case sass.types.Null: return `null`; case sass.types.List: const listLength = sassValue.getLength(); const listElement = []; const hasSeparator = sassValue.getSeparator(); for(let i = 0; i < listLength; i++) { listElement.push(serialize(sassValue.getValue(i), true)); } // Make sure nested lists are serialized with surrounding parenthesis if(isInList) { return `(${listElement.join(hasSeparator ? ',' : ' ')})`; } else { return `${listElement.join(hasSeparator ? ',' : ' ')}`; } case sass.types.Map: const mapLength = sassValue.getLength(); const mapValue = {}; for(let i = 0; i < mapLength; i++) { const key = serialize(sassValue.getKey(i)); const value = serialize(sassValue.getValue(i)); mapValue[key] = value; } const serializedMapValues = Object.keys(mapValue).map(key => `${key}: ${mapValue[key]}`); return `(${serializedMapValues})`; default: throw new Error(`Unsupported sass variable type '${sassValue.constructor.name}'`) }; }
[ "function", "serializeValue", "(", "sassValue", ",", "isInList", ")", "{", "switch", "(", "sassValue", ".", "constructor", ")", "{", "case", "sass", ".", "types", ".", "String", ":", "case", "sass", ".", "types", ".", "Boolean", ":", "return", "`", "${", "sassValue", ".", "getValue", "(", ")", "}", "`", ";", "case", "sass", ".", "types", ".", "Number", ":", "return", "`", "${", "sassValue", ".", "getValue", "(", ")", "}", "${", "sassValue", ".", "getUnit", "(", ")", "}", "`", ";", "case", "sass", ".", "types", ".", "Color", ":", "return", "serializeColor", "(", "sassValue", ")", ";", "case", "sass", ".", "types", ".", "Null", ":", "return", "`", "`", ";", "case", "sass", ".", "types", ".", "List", ":", "const", "listLength", "=", "sassValue", ".", "getLength", "(", ")", ";", "const", "listElement", "=", "[", "]", ";", "const", "hasSeparator", "=", "sassValue", ".", "getSeparator", "(", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "listLength", ";", "i", "++", ")", "{", "listElement", ".", "push", "(", "serialize", "(", "sassValue", ".", "getValue", "(", "i", ")", ",", "true", ")", ")", ";", "}", "// Make sure nested lists are serialized with surrounding parenthesis", "if", "(", "isInList", ")", "{", "return", "`", "${", "listElement", ".", "join", "(", "hasSeparator", "?", "','", ":", "' '", ")", "}", "`", ";", "}", "else", "{", "return", "`", "${", "listElement", ".", "join", "(", "hasSeparator", "?", "','", ":", "' '", ")", "}", "`", ";", "}", "case", "sass", ".", "types", ".", "Map", ":", "const", "mapLength", "=", "sassValue", ".", "getLength", "(", ")", ";", "const", "mapValue", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "mapLength", ";", "i", "++", ")", "{", "const", "key", "=", "serialize", "(", "sassValue", ".", "getKey", "(", "i", ")", ")", ";", "const", "value", "=", "serialize", "(", "sassValue", ".", "getValue", "(", "i", ")", ")", ";", "mapValue", "[", "key", "]", "=", "value", ";", "}", "const", "serializedMapValues", "=", "Object", ".", "keys", "(", "mapValue", ")", ".", "map", "(", "key", "=>", "`", "${", "key", "}", "${", "mapValue", "[", "key", "]", "}", "`", ")", ";", "return", "`", "${", "serializedMapValues", "}", "`", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "sassValue", ".", "constructor", ".", "name", "}", "`", ")", "}", ";", "}" ]
Transform a SassValue into a serialized string
[ "Transform", "a", "SassValue", "into", "a", "serialized", "string" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/serialize.js#L31-L74
18,062
jgranstrom/sass-extract
src/inject.js
createInjection
function createInjection(fileId, categoryPrefix, declaration, idx, declarationResultHandler) { const fnName = `${FN_PREFIX}_${fileId}_${categoryPrefix}_${declaration.declarationClean}_${idx}`; const injectedFunction = function(sassValue) { const value = createStructuredValue(sassValue); declarationResultHandler(declaration, value, sassValue); return sassValue; }; let injectedCode = `@if global_variable_exists('${declaration.declarationClean}') { $${fnName}: ${fnName}(${declaration.declaration}); }\n` return { fnName, injectedFunction, injectedCode }; }
javascript
function createInjection(fileId, categoryPrefix, declaration, idx, declarationResultHandler) { const fnName = `${FN_PREFIX}_${fileId}_${categoryPrefix}_${declaration.declarationClean}_${idx}`; const injectedFunction = function(sassValue) { const value = createStructuredValue(sassValue); declarationResultHandler(declaration, value, sassValue); return sassValue; }; let injectedCode = `@if global_variable_exists('${declaration.declarationClean}') { $${fnName}: ${fnName}(${declaration.declaration}); }\n` return { fnName, injectedFunction, injectedCode }; }
[ "function", "createInjection", "(", "fileId", ",", "categoryPrefix", ",", "declaration", ",", "idx", ",", "declarationResultHandler", ")", "{", "const", "fnName", "=", "`", "${", "FN_PREFIX", "}", "${", "fileId", "}", "${", "categoryPrefix", "}", "${", "declaration", ".", "declarationClean", "}", "${", "idx", "}", "`", ";", "const", "injectedFunction", "=", "function", "(", "sassValue", ")", "{", "const", "value", "=", "createStructuredValue", "(", "sassValue", ")", ";", "declarationResultHandler", "(", "declaration", ",", "value", ",", "sassValue", ")", ";", "return", "sassValue", ";", "}", ";", "let", "injectedCode", "=", "`", "${", "declaration", ".", "declarationClean", "}", "${", "fnName", "}", "${", "fnName", "}", "${", "declaration", ".", "declaration", "}", "\\n", "`", "return", "{", "fnName", ",", "injectedFunction", ",", "injectedCode", "}", ";", "}" ]
Create injection function and source for a file, category, declaration and result handler
[ "Create", "injection", "function", "and", "source", "for", "a", "file", "category", "declaration", "and", "result", "handler" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/inject.js#L12-L26
18,063
jgranstrom/sass-extract
src/load.js
includeRawDataFile
function includeRawDataFile(includedFiles, files, entryFilename, data) { let orderedFiles = includedFiles; if(entryFilename === RAW_DATA_FILE && data) { files[RAW_DATA_FILE] = data; orderedFiles = [...orderedFiles, RAW_DATA_FILE]; } else if(orderedFiles.length > 0) { orderedFiles = [...orderedFiles.slice(1), orderedFiles[0]]; } return { compiledFiles: files, orderedFiles, }; }
javascript
function includeRawDataFile(includedFiles, files, entryFilename, data) { let orderedFiles = includedFiles; if(entryFilename === RAW_DATA_FILE && data) { files[RAW_DATA_FILE] = data; orderedFiles = [...orderedFiles, RAW_DATA_FILE]; } else if(orderedFiles.length > 0) { orderedFiles = [...orderedFiles.slice(1), orderedFiles[0]]; } return { compiledFiles: files, orderedFiles, }; }
[ "function", "includeRawDataFile", "(", "includedFiles", ",", "files", ",", "entryFilename", ",", "data", ")", "{", "let", "orderedFiles", "=", "includedFiles", ";", "if", "(", "entryFilename", "===", "RAW_DATA_FILE", "&&", "data", ")", "{", "files", "[", "RAW_DATA_FILE", "]", "=", "data", ";", "orderedFiles", "=", "[", "...", "orderedFiles", ",", "RAW_DATA_FILE", "]", ";", "}", "else", "if", "(", "orderedFiles", ".", "length", ">", "0", ")", "{", "orderedFiles", "=", "[", "...", "orderedFiles", ".", "slice", "(", "1", ")", ",", "orderedFiles", "[", "0", "]", "]", ";", "}", "return", "{", "compiledFiles", ":", "files", ",", "orderedFiles", ",", "}", ";", "}" ]
Include any raw compilation data as a 'data' file
[ "Include", "any", "raw", "compilation", "data", "as", "a", "data", "file" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/load.js#L11-L25
18,064
jgranstrom/sass-extract
src/struct.js
makeValue
function makeValue(sassValue) { switch(sassValue.constructor) { case sass.types.String: case sass.types.Boolean: return { value: sassValue.getValue() }; case sass.types.Number: return { value: sassValue.getValue(), unit: sassValue.getUnit() }; case sass.types.Color: const r = Math.round(sassValue.getR()); const g = Math.round(sassValue.getG()); const b = Math.round(sassValue.getB()); return { value: { r, g, b, a: sassValue.getA(), hex: `#${toColorHex(r)}${toColorHex(g)}${toColorHex(b)}` }, }; case sass.types.Null: return { value: null }; case sass.types.List: const listLength = sassValue.getLength(); const listValue = []; for(let i = 0; i < listLength; i++) { listValue.push(createStructuredValue(sassValue.getValue(i))); } return { value: listValue, separator: sassValue.getSeparator() ? ',' : ' ' }; case sass.types.Map: const mapLength = sassValue.getLength(); const mapValue = {}; for(let i = 0; i < mapLength; i++) { // Serialize map keys of arbitrary type for extracted struct const serializedKey = serialize(sassValue.getKey(i)); mapValue[serializedKey] = createStructuredValue(sassValue.getValue(i)); } return { value: mapValue }; default: throw new Error(`Unsupported sass variable type '${sassValue.constructor.name}'`) }; }
javascript
function makeValue(sassValue) { switch(sassValue.constructor) { case sass.types.String: case sass.types.Boolean: return { value: sassValue.getValue() }; case sass.types.Number: return { value: sassValue.getValue(), unit: sassValue.getUnit() }; case sass.types.Color: const r = Math.round(sassValue.getR()); const g = Math.round(sassValue.getG()); const b = Math.round(sassValue.getB()); return { value: { r, g, b, a: sassValue.getA(), hex: `#${toColorHex(r)}${toColorHex(g)}${toColorHex(b)}` }, }; case sass.types.Null: return { value: null }; case sass.types.List: const listLength = sassValue.getLength(); const listValue = []; for(let i = 0; i < listLength; i++) { listValue.push(createStructuredValue(sassValue.getValue(i))); } return { value: listValue, separator: sassValue.getSeparator() ? ',' : ' ' }; case sass.types.Map: const mapLength = sassValue.getLength(); const mapValue = {}; for(let i = 0; i < mapLength; i++) { // Serialize map keys of arbitrary type for extracted struct const serializedKey = serialize(sassValue.getKey(i)); mapValue[serializedKey] = createStructuredValue(sassValue.getValue(i)); } return { value: mapValue }; default: throw new Error(`Unsupported sass variable type '${sassValue.constructor.name}'`) }; }
[ "function", "makeValue", "(", "sassValue", ")", "{", "switch", "(", "sassValue", ".", "constructor", ")", "{", "case", "sass", ".", "types", ".", "String", ":", "case", "sass", ".", "types", ".", "Boolean", ":", "return", "{", "value", ":", "sassValue", ".", "getValue", "(", ")", "}", ";", "case", "sass", ".", "types", ".", "Number", ":", "return", "{", "value", ":", "sassValue", ".", "getValue", "(", ")", ",", "unit", ":", "sassValue", ".", "getUnit", "(", ")", "}", ";", "case", "sass", ".", "types", ".", "Color", ":", "const", "r", "=", "Math", ".", "round", "(", "sassValue", ".", "getR", "(", ")", ")", ";", "const", "g", "=", "Math", ".", "round", "(", "sassValue", ".", "getG", "(", ")", ")", ";", "const", "b", "=", "Math", ".", "round", "(", "sassValue", ".", "getB", "(", ")", ")", ";", "return", "{", "value", ":", "{", "r", ",", "g", ",", "b", ",", "a", ":", "sassValue", ".", "getA", "(", ")", ",", "hex", ":", "`", "${", "toColorHex", "(", "r", ")", "}", "${", "toColorHex", "(", "g", ")", "}", "${", "toColorHex", "(", "b", ")", "}", "`", "}", ",", "}", ";", "case", "sass", ".", "types", ".", "Null", ":", "return", "{", "value", ":", "null", "}", ";", "case", "sass", ".", "types", ".", "List", ":", "const", "listLength", "=", "sassValue", ".", "getLength", "(", ")", ";", "const", "listValue", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "listLength", ";", "i", "++", ")", "{", "listValue", ".", "push", "(", "createStructuredValue", "(", "sassValue", ".", "getValue", "(", "i", ")", ")", ")", ";", "}", "return", "{", "value", ":", "listValue", ",", "separator", ":", "sassValue", ".", "getSeparator", "(", ")", "?", "','", ":", "' '", "}", ";", "case", "sass", ".", "types", ".", "Map", ":", "const", "mapLength", "=", "sassValue", ".", "getLength", "(", ")", ";", "const", "mapValue", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "mapLength", ";", "i", "++", ")", "{", "// Serialize map keys of arbitrary type for extracted struct", "const", "serializedKey", "=", "serialize", "(", "sassValue", ".", "getKey", "(", "i", ")", ")", ";", "mapValue", "[", "serializedKey", "]", "=", "createStructuredValue", "(", "sassValue", ".", "getValue", "(", "i", ")", ")", ";", "}", "return", "{", "value", ":", "mapValue", "}", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "sassValue", ".", "constructor", ".", "name", "}", "`", ")", "}", ";", "}" ]
Transform a sassValue into a structured value based on the value type
[ "Transform", "a", "sassValue", "into", "a", "structured", "value", "based", "on", "the", "value", "type" ]
a2b0b3d513bf88c3adb9b6b444ff81c18738b0be
https://github.com/jgranstrom/sass-extract/blob/a2b0b3d513bf88c3adb9b6b444ff81c18738b0be/src/struct.js#L8-L54
18,065
adobe-photoshop/generator-assets
lib/assetmanager.js
AssetManager
function AssetManager(generator, config, logger, document, renderManager) { events.EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; this._document = document; this._metaDataRoot = config["meta-data-root"] || META_PLUGIN_ID; this._renderManager = renderManager; this._fileManager = new FileManager(generator, config, logger); this._errorManager = new ErrorManager(generator, config, logger, this._fileManager); this._handleChange = this._handleChange.bind(this); this._handleCompsChange = this._handleCompsChange.bind(this); }
javascript
function AssetManager(generator, config, logger, document, renderManager) { events.EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; this._document = document; this._metaDataRoot = config["meta-data-root"] || META_PLUGIN_ID; this._renderManager = renderManager; this._fileManager = new FileManager(generator, config, logger); this._errorManager = new ErrorManager(generator, config, logger, this._fileManager); this._handleChange = this._handleChange.bind(this); this._handleCompsChange = this._handleCompsChange.bind(this); }
[ "function", "AssetManager", "(", "generator", ",", "config", ",", "logger", ",", "document", ",", "renderManager", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_generator", "=", "generator", ";", "this", ".", "_config", "=", "config", ";", "this", ".", "_logger", "=", "logger", ";", "this", ".", "_document", "=", "document", ";", "this", ".", "_metaDataRoot", "=", "config", "[", "\"meta-data-root\"", "]", "||", "META_PLUGIN_ID", ";", "this", ".", "_renderManager", "=", "renderManager", ";", "this", ".", "_fileManager", "=", "new", "FileManager", "(", "generator", ",", "config", ",", "logger", ")", ";", "this", ".", "_errorManager", "=", "new", "ErrorManager", "(", "generator", ",", "config", ",", "logger", ",", "this", ".", "_fileManager", ")", ";", "this", ".", "_handleChange", "=", "this", ".", "_handleChange", ".", "bind", "(", "this", ")", ";", "this", ".", "_handleCompsChange", "=", "this", ".", "_handleCompsChange", ".", "bind", "(", "this", ")", ";", "}" ]
The asset manager maintains a set of assets for a given document. On initialization, it parses the layers' names into a set of components, requests renderings of each of those components from the render manager, and organizes the rendered assets into the appropriate files and folders. When the document changes, it requests that the appropriate components be re-rendered or moved into the right place. It also manages error reporting. @constructor @param {Generator} generator @param {object} config @param {Logger} logger @param {Document} document @param {RenderManager} renderManager
[ "The", "asset", "manager", "maintains", "a", "set", "of", "assets", "for", "a", "given", "document", ".", "On", "initialization", "it", "parses", "the", "layers", "names", "into", "a", "set", "of", "components", "requests", "renderings", "of", "each", "of", "those", "components", "from", "the", "render", "manager", "and", "organizes", "the", "rendered", "assets", "into", "the", "appropriate", "files", "and", "folders", ".", "When", "the", "document", "changes", "it", "requests", "that", "the", "appropriate", "components", "be", "re", "-", "rendered", "or", "moved", "into", "the", "right", "place", ".", "It", "also", "manages", "error", "reporting", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/assetmanager.js#L68-L83
18,066
adobe-photoshop/generator-assets
lib/rendermanager.js
RenderManager
function RenderManager(generator, config, logger) { events.EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; this._svgRenderers = {}; this._pixmapRenderers = {}; this._componentsByDocument = {}; this._pending = {}; this._working = {}; this._renderedAssetCount = 0; }
javascript
function RenderManager(generator, config, logger) { events.EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; this._svgRenderers = {}; this._pixmapRenderers = {}; this._componentsByDocument = {}; this._pending = {}; this._working = {}; this._renderedAssetCount = 0; }
[ "function", "RenderManager", "(", "generator", ",", "config", ",", "logger", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_generator", "=", "generator", ";", "this", ".", "_config", "=", "config", ";", "this", ".", "_logger", "=", "logger", ";", "this", ".", "_svgRenderers", "=", "{", "}", ";", "this", ".", "_pixmapRenderers", "=", "{", "}", ";", "this", ".", "_componentsByDocument", "=", "{", "}", ";", "this", ".", "_pending", "=", "{", "}", ";", "this", ".", "_working", "=", "{", "}", ";", "this", ".", "_renderedAssetCount", "=", "0", ";", "}" ]
Manages asynchonous rendering jobs across all active documents. @constructor @param {Generator} generator @param {object} config @param {Logger} logger
[ "Manages", "asynchonous", "rendering", "jobs", "across", "all", "active", "documents", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/rendermanager.js#L49-L64
18,067
adobe-photoshop/generator-assets
main.js
_pauseAssetGeneration
function _pauseAssetGeneration(id) { if (_waitingDocuments.hasOwnProperty(id)) { _canceledDocuments[id] = true; } else if (_assetManagers.hasOwnProperty(id)) { _assetManagers[id].stop(); } }
javascript
function _pauseAssetGeneration(id) { if (_waitingDocuments.hasOwnProperty(id)) { _canceledDocuments[id] = true; } else if (_assetManagers.hasOwnProperty(id)) { _assetManagers[id].stop(); } }
[ "function", "_pauseAssetGeneration", "(", "id", ")", "{", "if", "(", "_waitingDocuments", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "_canceledDocuments", "[", "id", "]", "=", "true", ";", "}", "else", "if", "(", "_assetManagers", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "_assetManagers", "[", "id", "]", ".", "stop", "(", ")", ";", "}", "}" ]
Disable asset generation for the given Document ID, halting any asset rending in progress. @private @param {!number} id The document ID for which asset generation should be disabled.
[ "Disable", "asset", "generation", "for", "the", "given", "Document", "ID", "halting", "any", "asset", "rending", "in", "progress", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L57-L63
18,068
adobe-photoshop/generator-assets
main.js
_handleFileChange
function _handleFileChange(id, change) { // If the filename changed but the saved state didn't change, then the file must have been renamed if (change.previous && !change.hasOwnProperty("previousSaved")) { _stopAssetGeneration(id); _stateManager.deactivate(id); } }
javascript
function _handleFileChange(id, change) { // If the filename changed but the saved state didn't change, then the file must have been renamed if (change.previous && !change.hasOwnProperty("previousSaved")) { _stopAssetGeneration(id); _stateManager.deactivate(id); } }
[ "function", "_handleFileChange", "(", "id", ",", "change", ")", "{", "// If the filename changed but the saved state didn't change, then the file must have been renamed", "if", "(", "change", ".", "previous", "&&", "!", "change", ".", "hasOwnProperty", "(", "\"previousSaved\"", ")", ")", "{", "_stopAssetGeneration", "(", "id", ")", ";", "_stateManager", ".", "deactivate", "(", "id", ")", ";", "}", "}" ]
Handler for a the "file" change event fired by Document objects. Disables asset generation after Save As is performed on an an already-saved file. @private @param {number} id The ID of the Document that changed @param {{previous: string=, previousSaved: boolean=}} change The file change event emitted by the Document
[ "Handler", "for", "a", "the", "file", "change", "event", "fired", "by", "Document", "objects", ".", "Disables", "asset", "generation", "after", "Save", "As", "is", "performed", "on", "an", "an", "already", "-", "saved", "file", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L89-L95
18,069
adobe-photoshop/generator-assets
main.js
_getChangedSettings
function _getChangedSettings(settings) { if (settings && typeof(settings) === "object") { return _generator.extractDocumentSettings({generatorSettings: settings}, PLUGIN_ID); } return null; }
javascript
function _getChangedSettings(settings) { if (settings && typeof(settings) === "object") { return _generator.extractDocumentSettings({generatorSettings: settings}, PLUGIN_ID); } return null; }
[ "function", "_getChangedSettings", "(", "settings", ")", "{", "if", "(", "settings", "&&", "typeof", "(", "settings", ")", "===", "\"object\"", ")", "{", "return", "_generator", ".", "extractDocumentSettings", "(", "{", "generatorSettings", ":", "settings", "}", ",", "PLUGIN_ID", ")", ";", "}", "return", "null", ";", "}" ]
Extract generator settings from the "current" or "previous" property of a generatorSettings change event. If the supplied value is not actually a settings object, returns null. @private @param {object} settings Settings json object. @return {object} Settings object from generator or null.
[ "Extract", "generator", "settings", "from", "the", "current", "or", "previous", "property", "of", "a", "generatorSettings", "change", "event", ".", "If", "the", "supplied", "value", "is", "not", "actually", "a", "settings", "object", "returns", "null", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L105-L110
18,070
adobe-photoshop/generator-assets
main.js
_handleDocGeneratorSettingsChange
function _handleDocGeneratorSettingsChange(id, change) { var curSettings = _getChangedSettings(change.current), prevSettings = _getChangedSettings(change.previous), curEnabled = !!(curSettings && curSettings.enabled), prevEnabled = !!(prevSettings && prevSettings.enabled); if (prevEnabled !== curEnabled) { if (curEnabled) { _stateManager.activate(id); } else { _stateManager.deactivate(id); } } }
javascript
function _handleDocGeneratorSettingsChange(id, change) { var curSettings = _getChangedSettings(change.current), prevSettings = _getChangedSettings(change.previous), curEnabled = !!(curSettings && curSettings.enabled), prevEnabled = !!(prevSettings && prevSettings.enabled); if (prevEnabled !== curEnabled) { if (curEnabled) { _stateManager.activate(id); } else { _stateManager.deactivate(id); } } }
[ "function", "_handleDocGeneratorSettingsChange", "(", "id", ",", "change", ")", "{", "var", "curSettings", "=", "_getChangedSettings", "(", "change", ".", "current", ")", ",", "prevSettings", "=", "_getChangedSettings", "(", "change", ".", "previous", ")", ",", "curEnabled", "=", "!", "!", "(", "curSettings", "&&", "curSettings", ".", "enabled", ")", ",", "prevEnabled", "=", "!", "!", "(", "prevSettings", "&&", "prevSettings", ".", "enabled", ")", ";", "if", "(", "prevEnabled", "!==", "curEnabled", ")", "{", "if", "(", "curEnabled", ")", "{", "_stateManager", ".", "activate", "(", "id", ")", ";", "}", "else", "{", "_stateManager", ".", "deactivate", "(", "id", ")", ";", "}", "}", "}" ]
Handler for a the "generatorSettings" change event fired by Document objects. Updates the state manger based on the current doc setting if the enable settings actually changed @private @param {number} id The ID of the Document that changed @param {{previous: settings=, current: settings=}} change The previous and current document settings
[ "Handler", "for", "a", "the", "generatorSettings", "change", "event", "fired", "by", "Document", "objects", ".", "Updates", "the", "state", "manger", "based", "on", "the", "current", "doc", "setting", "if", "the", "enable", "settings", "actually", "changed" ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L122-L135
18,071
adobe-photoshop/generator-assets
main.js
_handleOpenDocumentsChanged
function _handleOpenDocumentsChanged(all, opened) { var open = opened || all; open.forEach(function (id) { _documentManager.getDocument(id).done(function (document) { document.on("generatorSettings", _handleDocGeneratorSettingsChange.bind(undefined, id)); }, function (error) { _logger.warning("Error getting document during a document changed event, " + "document was likely closed.", error); }); }); }
javascript
function _handleOpenDocumentsChanged(all, opened) { var open = opened || all; open.forEach(function (id) { _documentManager.getDocument(id).done(function (document) { document.on("generatorSettings", _handleDocGeneratorSettingsChange.bind(undefined, id)); }, function (error) { _logger.warning("Error getting document during a document changed event, " + "document was likely closed.", error); }); }); }
[ "function", "_handleOpenDocumentsChanged", "(", "all", ",", "opened", ")", "{", "var", "open", "=", "opened", "||", "all", ";", "open", ".", "forEach", "(", "function", "(", "id", ")", "{", "_documentManager", ".", "getDocument", "(", "id", ")", ".", "done", "(", "function", "(", "document", ")", "{", "document", ".", "on", "(", "\"generatorSettings\"", ",", "_handleDocGeneratorSettingsChange", ".", "bind", "(", "undefined", ",", "id", ")", ")", ";", "}", ",", "function", "(", "error", ")", "{", "_logger", ".", "warning", "(", "\"Error getting document during a document changed event, \"", "+", "\"document was likely closed.\"", ",", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Handler for a the "openDocumentsChanged" event emitted by the DocumentManager. Registers a generatorSettings change to update the StateManager appropiately @private @param {Array.<number>} all The complete set of open document IDs @param {Array.<number>=} opened The set of newly opened document IDs
[ "Handler", "for", "a", "the", "openDocumentsChanged", "event", "emitted", "by", "the", "DocumentManager", ".", "Registers", "a", "generatorSettings", "change", "to", "update", "the", "StateManager", "appropiately" ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L145-L156
18,072
adobe-photoshop/generator-assets
main.js
_startAssetGeneration
function _startAssetGeneration(id) { if (_waitingDocuments.hasOwnProperty(id)) { return; } var documentPromise = _documentManager.getDocument(id); _waitingDocuments[id] = documentPromise; documentPromise.done(function (document) { delete _waitingDocuments[id]; if (_canceledDocuments.hasOwnProperty(id)) { delete _canceledDocuments[id]; } else { if (!_assetManagers.hasOwnProperty(id)) { _assetManagers[id] = new AssetManager(_generator, _config, _logger, document, _renderManager); document.on("closed", _stopAssetGeneration.bind(undefined, id)); document.on("end", _restartAssetGeneration.bind(undefined, id)); document.on("file", _handleFileChange.bind(undefined, id)); } _assetManagers[id].start(); } }); }
javascript
function _startAssetGeneration(id) { if (_waitingDocuments.hasOwnProperty(id)) { return; } var documentPromise = _documentManager.getDocument(id); _waitingDocuments[id] = documentPromise; documentPromise.done(function (document) { delete _waitingDocuments[id]; if (_canceledDocuments.hasOwnProperty(id)) { delete _canceledDocuments[id]; } else { if (!_assetManagers.hasOwnProperty(id)) { _assetManagers[id] = new AssetManager(_generator, _config, _logger, document, _renderManager); document.on("closed", _stopAssetGeneration.bind(undefined, id)); document.on("end", _restartAssetGeneration.bind(undefined, id)); document.on("file", _handleFileChange.bind(undefined, id)); } _assetManagers[id].start(); } }); }
[ "function", "_startAssetGeneration", "(", "id", ")", "{", "if", "(", "_waitingDocuments", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "return", ";", "}", "var", "documentPromise", "=", "_documentManager", ".", "getDocument", "(", "id", ")", ";", "_waitingDocuments", "[", "id", "]", "=", "documentPromise", ";", "documentPromise", ".", "done", "(", "function", "(", "document", ")", "{", "delete", "_waitingDocuments", "[", "id", "]", ";", "if", "(", "_canceledDocuments", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "delete", "_canceledDocuments", "[", "id", "]", ";", "}", "else", "{", "if", "(", "!", "_assetManagers", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "_assetManagers", "[", "id", "]", "=", "new", "AssetManager", "(", "_generator", ",", "_config", ",", "_logger", ",", "document", ",", "_renderManager", ")", ";", "document", ".", "on", "(", "\"closed\"", ",", "_stopAssetGeneration", ".", "bind", "(", "undefined", ",", "id", ")", ")", ";", "document", ".", "on", "(", "\"end\"", ",", "_restartAssetGeneration", ".", "bind", "(", "undefined", ",", "id", ")", ")", ";", "document", ".", "on", "(", "\"file\"", ",", "_handleFileChange", ".", "bind", "(", "undefined", ",", "id", ")", ")", ";", "}", "_assetManagers", "[", "id", "]", ".", "start", "(", ")", ";", "}", "}", ")", ";", "}" ]
Enable asset generation for the given Document ID, causing all annotated assets in the given document to be regenerated. @private @param {!number} id The document ID for which asset generation should be enabled.
[ "Enable", "asset", "generation", "for", "the", "given", "Document", "ID", "causing", "all", "annotated", "assets", "in", "the", "given", "document", "to", "be", "regenerated", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L165-L190
18,073
adobe-photoshop/generator-assets
main.js
_getConfig
function _getConfig() { var copy = {}, property; for (property in _config) { if (_config.hasOwnProperty(property)) { copy[property] = _config[property]; } } return copy; }
javascript
function _getConfig() { var copy = {}, property; for (property in _config) { if (_config.hasOwnProperty(property)) { copy[property] = _config[property]; } } return copy; }
[ "function", "_getConfig", "(", ")", "{", "var", "copy", "=", "{", "}", ",", "property", ";", "for", "(", "property", "in", "_config", ")", "{", "if", "(", "_config", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "copy", "[", "property", "]", "=", "_config", "[", "property", "]", ";", "}", "}", "return", "copy", ";", "}" ]
Get a copy of the plugin's config object. For automated testing only. @private @return {object}
[ "Get", "a", "copy", "of", "the", "plugin", "s", "config", "object", ".", "For", "automated", "testing", "only", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L211-L222
18,074
adobe-photoshop/generator-assets
main.js
_setConfig
function _setConfig(config, keepExisting) { var property; // optionally clean out the existing properties first if (!keepExisting) { for (property in _config) { if (_config.hasOwnProperty(property)) { delete _config[property]; } } } // add in the new properties for (property in config) { if (config.hasOwnProperty(property)) { _config[property] = config[property]; } } }
javascript
function _setConfig(config, keepExisting) { var property; // optionally clean out the existing properties first if (!keepExisting) { for (property in _config) { if (_config.hasOwnProperty(property)) { delete _config[property]; } } } // add in the new properties for (property in config) { if (config.hasOwnProperty(property)) { _config[property] = config[property]; } } }
[ "function", "_setConfig", "(", "config", ",", "keepExisting", ")", "{", "var", "property", ";", "// optionally clean out the existing properties first", "if", "(", "!", "keepExisting", ")", "{", "for", "(", "property", "in", "_config", ")", "{", "if", "(", "_config", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "delete", "_config", "[", "property", "]", ";", "}", "}", "}", "// add in the new properties", "for", "(", "property", "in", "config", ")", "{", "if", "(", "config", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "_config", "[", "property", "]", "=", "config", "[", "property", "]", ";", "}", "}", "}" ]
Set the plugin's config object. This mutates the referenced object, not the reference. For automated testing only. @private @param {object} config @param {boolean=} keepExisting if true then don't delete previous configs first. default: false
[ "Set", "the", "plugin", "s", "config", "object", ".", "This", "mutates", "the", "referenced", "object", "not", "the", "reference", ".", "For", "automated", "testing", "only", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L232-L250
18,075
adobe-photoshop/generator-assets
main.js
init
function init(generator, config, logger) { _generator = generator; _config = config; _logger = logger; _documentManager = new DocumentManager(generator, config, logger); _stateManager = new StateManager(generator, config, logger, _documentManager); _renderManager = new RenderManager(generator, config, logger); if (!!_config["css-enabled"]) { var SONToCSS = require("./lib/css/sontocss.js"); _SONToCSSConverter = new SONToCSS(generator, config, logger, _documentManager); } // For automated tests exports._renderManager = _renderManager; exports._stateManager = _stateManager; exports._assetManagers = _assetManagers; exports._layerNameParse = require("./lib/parser").parse; _stateManager.on("enabled", _startAssetGeneration); _stateManager.on("disabled", _pauseAssetGeneration); _documentManager.on("openDocumentsChanged", _handleOpenDocumentsChanged); Headlights.init(generator, logger, _stateManager, _renderManager); }
javascript
function init(generator, config, logger) { _generator = generator; _config = config; _logger = logger; _documentManager = new DocumentManager(generator, config, logger); _stateManager = new StateManager(generator, config, logger, _documentManager); _renderManager = new RenderManager(generator, config, logger); if (!!_config["css-enabled"]) { var SONToCSS = require("./lib/css/sontocss.js"); _SONToCSSConverter = new SONToCSS(generator, config, logger, _documentManager); } // For automated tests exports._renderManager = _renderManager; exports._stateManager = _stateManager; exports._assetManagers = _assetManagers; exports._layerNameParse = require("./lib/parser").parse; _stateManager.on("enabled", _startAssetGeneration); _stateManager.on("disabled", _pauseAssetGeneration); _documentManager.on("openDocumentsChanged", _handleOpenDocumentsChanged); Headlights.init(generator, logger, _stateManager, _renderManager); }
[ "function", "init", "(", "generator", ",", "config", ",", "logger", ")", "{", "_generator", "=", "generator", ";", "_config", "=", "config", ";", "_logger", "=", "logger", ";", "_documentManager", "=", "new", "DocumentManager", "(", "generator", ",", "config", ",", "logger", ")", ";", "_stateManager", "=", "new", "StateManager", "(", "generator", ",", "config", ",", "logger", ",", "_documentManager", ")", ";", "_renderManager", "=", "new", "RenderManager", "(", "generator", ",", "config", ",", "logger", ")", ";", "if", "(", "!", "!", "_config", "[", "\"css-enabled\"", "]", ")", "{", "var", "SONToCSS", "=", "require", "(", "\"./lib/css/sontocss.js\"", ")", ";", "_SONToCSSConverter", "=", "new", "SONToCSS", "(", "generator", ",", "config", ",", "logger", ",", "_documentManager", ")", ";", "}", "// For automated tests", "exports", ".", "_renderManager", "=", "_renderManager", ";", "exports", ".", "_stateManager", "=", "_stateManager", ";", "exports", ".", "_assetManagers", "=", "_assetManagers", ";", "exports", ".", "_layerNameParse", "=", "require", "(", "\"./lib/parser\"", ")", ".", "parse", ";", "_stateManager", ".", "on", "(", "\"enabled\"", ",", "_startAssetGeneration", ")", ";", "_stateManager", ".", "on", "(", "\"disabled\"", ",", "_pauseAssetGeneration", ")", ";", "_documentManager", ".", "on", "(", "\"openDocumentsChanged\"", ",", "_handleOpenDocumentsChanged", ")", ";", "Headlights", ".", "init", "(", "generator", ",", "logger", ",", "_stateManager", ",", "_renderManager", ")", ";", "}" ]
Initialize the Assets plugin. @param {Generator} generator The Generator instance for this plugin. @param {object} config Configuration options for this plugin. @param {Logger} logger The Logger instance for this plugin.
[ "Initialize", "the", "Assets", "plugin", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/main.js#L260-L285
18,076
adobe-photoshop/generator-assets
lib/renderer.js
BaseRenderer
function BaseRenderer(generator, config, logger, document) { this._generator = generator; this._document = document; this._logger = logger; if (config.hasOwnProperty("use-jpg-encoding")) { this._useJPGEncoding = config["use-jpg-encoding"]; } if (config.hasOwnProperty("use-smart-scaling")) { this._useSmartScaling = !!config["use-smart-scaling"]; } if (config.hasOwnProperty("include-ancestor-masks")) { this._includeAncestorMasks = !!config["include-ancestor-masks"]; } if (config.hasOwnProperty("convert-color-space")) { this._convertColorSpace = !!config["convert-color-space"]; } if (config.hasOwnProperty("icc-profile")) { this._useICCProfile = config["icc-profile"]; } if (config.hasOwnProperty("embed-icc-profile")) { this._embedICCProfile = config["embed-icc-profile"]; } if (config.hasOwnProperty("allow-dither")) { this._allowDither = !!config["allow-dither"]; } if (config.hasOwnProperty("use-psd-smart-object-pixel-scaling")) { this._forceSmartPSDPixelScaling = !!config["use-psd-smart-object-pixel-scaling"]; } if (config.hasOwnProperty("use-pngquant")) { this._usePngquant = !!config["use-pngquant"]; } if (config.hasOwnProperty("use-flite")) { this._useFlite = !!config["use-flite"]; } if (config.hasOwnProperty("webp-lossless")) { this._webpLossless = !!config["webp-lossless"]; } if (config.hasOwnProperty("clip-all-images-to-document-bounds")) { this._clipAllImagesToDocumentBounds = !!config["clip-all-images-to-document-bounds"]; } if (config.hasOwnProperty("clip-all-images-to-artboard-bounds")) { this._clipAllImagesToArtboardBounds = !!config["clip-all-images-to-artboard-bounds"]; } if (config.hasOwnProperty("mask-adds-padding")) { this._masksAddPadding = !!config["mask-adds-padding"]; } if (config.hasOwnProperty("expand-max-dimensions")) { this._expandMaxDimensions = !!config["expand-max-dimensions"]; } }
javascript
function BaseRenderer(generator, config, logger, document) { this._generator = generator; this._document = document; this._logger = logger; if (config.hasOwnProperty("use-jpg-encoding")) { this._useJPGEncoding = config["use-jpg-encoding"]; } if (config.hasOwnProperty("use-smart-scaling")) { this._useSmartScaling = !!config["use-smart-scaling"]; } if (config.hasOwnProperty("include-ancestor-masks")) { this._includeAncestorMasks = !!config["include-ancestor-masks"]; } if (config.hasOwnProperty("convert-color-space")) { this._convertColorSpace = !!config["convert-color-space"]; } if (config.hasOwnProperty("icc-profile")) { this._useICCProfile = config["icc-profile"]; } if (config.hasOwnProperty("embed-icc-profile")) { this._embedICCProfile = config["embed-icc-profile"]; } if (config.hasOwnProperty("allow-dither")) { this._allowDither = !!config["allow-dither"]; } if (config.hasOwnProperty("use-psd-smart-object-pixel-scaling")) { this._forceSmartPSDPixelScaling = !!config["use-psd-smart-object-pixel-scaling"]; } if (config.hasOwnProperty("use-pngquant")) { this._usePngquant = !!config["use-pngquant"]; } if (config.hasOwnProperty("use-flite")) { this._useFlite = !!config["use-flite"]; } if (config.hasOwnProperty("webp-lossless")) { this._webpLossless = !!config["webp-lossless"]; } if (config.hasOwnProperty("clip-all-images-to-document-bounds")) { this._clipAllImagesToDocumentBounds = !!config["clip-all-images-to-document-bounds"]; } if (config.hasOwnProperty("clip-all-images-to-artboard-bounds")) { this._clipAllImagesToArtboardBounds = !!config["clip-all-images-to-artboard-bounds"]; } if (config.hasOwnProperty("mask-adds-padding")) { this._masksAddPadding = !!config["mask-adds-padding"]; } if (config.hasOwnProperty("expand-max-dimensions")) { this._expandMaxDimensions = !!config["expand-max-dimensions"]; } }
[ "function", "BaseRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", "{", "this", ".", "_generator", "=", "generator", ";", "this", ".", "_document", "=", "document", ";", "this", ".", "_logger", "=", "logger", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "\"use-jpg-encoding\"", ")", ")", "{", "this", ".", "_useJPGEncoding", "=", "config", "[", "\"use-jpg-encoding\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"use-smart-scaling\"", ")", ")", "{", "this", ".", "_useSmartScaling", "=", "!", "!", "config", "[", "\"use-smart-scaling\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"include-ancestor-masks\"", ")", ")", "{", "this", ".", "_includeAncestorMasks", "=", "!", "!", "config", "[", "\"include-ancestor-masks\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"convert-color-space\"", ")", ")", "{", "this", ".", "_convertColorSpace", "=", "!", "!", "config", "[", "\"convert-color-space\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"icc-profile\"", ")", ")", "{", "this", ".", "_useICCProfile", "=", "config", "[", "\"icc-profile\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"embed-icc-profile\"", ")", ")", "{", "this", ".", "_embedICCProfile", "=", "config", "[", "\"embed-icc-profile\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"allow-dither\"", ")", ")", "{", "this", ".", "_allowDither", "=", "!", "!", "config", "[", "\"allow-dither\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"use-psd-smart-object-pixel-scaling\"", ")", ")", "{", "this", ".", "_forceSmartPSDPixelScaling", "=", "!", "!", "config", "[", "\"use-psd-smart-object-pixel-scaling\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"use-pngquant\"", ")", ")", "{", "this", ".", "_usePngquant", "=", "!", "!", "config", "[", "\"use-pngquant\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"use-flite\"", ")", ")", "{", "this", ".", "_useFlite", "=", "!", "!", "config", "[", "\"use-flite\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"webp-lossless\"", ")", ")", "{", "this", ".", "_webpLossless", "=", "!", "!", "config", "[", "\"webp-lossless\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"clip-all-images-to-document-bounds\"", ")", ")", "{", "this", ".", "_clipAllImagesToDocumentBounds", "=", "!", "!", "config", "[", "\"clip-all-images-to-document-bounds\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"clip-all-images-to-artboard-bounds\"", ")", ")", "{", "this", ".", "_clipAllImagesToArtboardBounds", "=", "!", "!", "config", "[", "\"clip-all-images-to-artboard-bounds\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"mask-adds-padding\"", ")", ")", "{", "this", ".", "_masksAddPadding", "=", "!", "!", "config", "[", "\"mask-adds-padding\"", "]", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "\"expand-max-dimensions\"", ")", ")", "{", "this", ".", "_expandMaxDimensions", "=", "!", "!", "config", "[", "\"expand-max-dimensions\"", "]", ";", "}", "}" ]
Abstract renderer class for a given document. Converts components to assets on disk. @constructor @param {Generator} generator @param {object} config @param {Logger} logger @param {Document} document
[ "Abstract", "renderer", "class", "for", "a", "given", "document", ".", "Converts", "components", "to", "assets", "on", "disk", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/renderer.js#L57-L121
18,077
adobe-photoshop/generator-assets
lib/renderer.js
SVGRenderer
function SVGRenderer(generator, config, logger, document) { BaseRenderer.call(this, generator, config, logger, document); if (config.hasOwnProperty("svgomg-enabled")) { this._useSVGOMG = !!config["svgomg-enabled"]; } }
javascript
function SVGRenderer(generator, config, logger, document) { BaseRenderer.call(this, generator, config, logger, document); if (config.hasOwnProperty("svgomg-enabled")) { this._useSVGOMG = !!config["svgomg-enabled"]; } }
[ "function", "SVGRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", "{", "BaseRenderer", ".", "call", "(", "this", ",", "generator", ",", "config", ",", "logger", ",", "document", ")", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "\"svgomg-enabled\"", ")", ")", "{", "this", ".", "_useSVGOMG", "=", "!", "!", "config", "[", "\"svgomg-enabled\"", "]", ";", "}", "}" ]
SVG asset renderer. @constructor @extends BaseRenderer
[ "SVG", "asset", "renderer", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/renderer.js#L436-L442
18,078
adobe-photoshop/generator-assets
lib/renderer.js
createSVGRenderer
function createSVGRenderer(generator, config, logger, document) { return new SVGRenderer(generator, config, logger, document); }
javascript
function createSVGRenderer(generator, config, logger, document) { return new SVGRenderer(generator, config, logger, document); }
[ "function", "createSVGRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", "{", "return", "new", "SVGRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", ";", "}" ]
Return a new SVGRenderer object.
[ "Return", "a", "new", "SVGRenderer", "object", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/renderer.js#L641-L643
18,079
adobe-photoshop/generator-assets
lib/renderer.js
PixmapRenderer
function PixmapRenderer(generator, config, logger, document) { BaseRenderer.call(this, generator, config, logger, document); if (config.hasOwnProperty("interpolation-type")) { this._interpolationType = config["interpolation-type"]; } }
javascript
function PixmapRenderer(generator, config, logger, document) { BaseRenderer.call(this, generator, config, logger, document); if (config.hasOwnProperty("interpolation-type")) { this._interpolationType = config["interpolation-type"]; } }
[ "function", "PixmapRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", "{", "BaseRenderer", ".", "call", "(", "this", ",", "generator", ",", "config", ",", "logger", ",", "document", ")", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "\"interpolation-type\"", ")", ")", "{", "this", ".", "_interpolationType", "=", "config", "[", "\"interpolation-type\"", "]", ";", "}", "}" ]
Pixmap asset renderer. @constructor @extends BaseRenderer
[ "Pixmap", "asset", "renderer", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/renderer.js#L651-L657
18,080
adobe-photoshop/generator-assets
lib/renderer.js
createPixmapRenderer
function createPixmapRenderer(generator, config, logger, document) { return new PixmapRenderer(generator, config, logger, document); }
javascript
function createPixmapRenderer(generator, config, logger, document) { return new PixmapRenderer(generator, config, logger, document); }
[ "function", "createPixmapRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", "{", "return", "new", "PixmapRenderer", "(", "generator", ",", "config", ",", "logger", ",", "document", ")", ";", "}" ]
Return a new PixmapRenderer object.
[ "Return", "a", "new", "PixmapRenderer", "object", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/renderer.js#L1486-L1488
18,081
adobe-photoshop/generator-assets
lib/componentmanager.js
_shallowCopy
function _shallowCopy(component) { var clone = {}, property; for (property in component) { if (component.hasOwnProperty(property)) { clone[property] = component[property]; } } return clone; }
javascript
function _shallowCopy(component) { var clone = {}, property; for (property in component) { if (component.hasOwnProperty(property)) { clone[property] = component[property]; } } return clone; }
[ "function", "_shallowCopy", "(", "component", ")", "{", "var", "clone", "=", "{", "}", ",", "property", ";", "for", "(", "property", "in", "component", ")", "{", "if", "(", "component", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "clone", "[", "property", "]", "=", "component", "[", "property", "]", ";", "}", "}", "return", "clone", ";", "}" ]
Create a shallow copy of a component. @param {Component} component @return {Component}
[ "Create", "a", "shallow", "copy", "of", "a", "component", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/componentmanager.js#L57-L68
18,082
adobe-photoshop/generator-assets
lib/componentmanager.js
_deriveComponent
function _deriveComponent(def, basic) { var derived = _shallowCopy(basic); if (def.hasOwnProperty("folder")) { if (derived.hasOwnProperty("folder")) { var folder = def.folder.concat(basic.folder); derived.folder = folder; } else { derived.folder = def.folder; } } if (def.hasOwnProperty("suffix")) { var index = basic.file.lastIndexOf("."), filename = basic.file.substring(0, index), extension = basic.file.substring(index); derived.file = filename + def.suffix + extension; } if (def.hasOwnProperty("scale") || def.hasOwnProperty("width") || def.hasOwnProperty("height")) { if (!derived.hasOwnProperty("scale") && !derived.hasOwnProperty("width") && !derived.hasOwnProperty("height")) { if (def.hasOwnProperty("scale")) { derived.scale = def.scale; } if (def.hasOwnProperty("width")) { derived.width = def.width; } if (def.hasOwnProperty("height")) { derived.height = def.height; } } } if (def.hasOwnProperty("canvasWidth") || def.hasOwnProperty("canvasHeight") || def.hasOwnProperty("canvasOffsetX") || def.hasOwnProperty("canvasOffsetY")) { if (!derived.hasOwnProperty("canvasWidth") && !derived.hasOwnProperty("canvasHeight") && !derived.hasOwnProperty("canvasOffsetX") && !derived.hasOwnProperty("canvasOffsetY")) { if (def.hasOwnProperty("canvasWidth")) { derived.canvasWidth = def.canvasWidth; } if (def.hasOwnProperty("canvasHeight")) { derived.canvasHeight = def.canvasHeight; } if (def.hasOwnProperty("canvasOffsetX")) { derived.canvasOffsetX = def.canvasOffsetX; } if (def.hasOwnProperty("canvasOffsetY")) { derived.canvasOffsetY = def.canvasOffsetY; } } } if (def.hasOwnProperty("quality")) { if (!derived.hasOwnProperty("quality")) { derived.quality = def.quality; } } derived.id = def.id + ":" + basic.id; derived.assetPath = _getAssetPath(derived); derived.default = def; return derived; }
javascript
function _deriveComponent(def, basic) { var derived = _shallowCopy(basic); if (def.hasOwnProperty("folder")) { if (derived.hasOwnProperty("folder")) { var folder = def.folder.concat(basic.folder); derived.folder = folder; } else { derived.folder = def.folder; } } if (def.hasOwnProperty("suffix")) { var index = basic.file.lastIndexOf("."), filename = basic.file.substring(0, index), extension = basic.file.substring(index); derived.file = filename + def.suffix + extension; } if (def.hasOwnProperty("scale") || def.hasOwnProperty("width") || def.hasOwnProperty("height")) { if (!derived.hasOwnProperty("scale") && !derived.hasOwnProperty("width") && !derived.hasOwnProperty("height")) { if (def.hasOwnProperty("scale")) { derived.scale = def.scale; } if (def.hasOwnProperty("width")) { derived.width = def.width; } if (def.hasOwnProperty("height")) { derived.height = def.height; } } } if (def.hasOwnProperty("canvasWidth") || def.hasOwnProperty("canvasHeight") || def.hasOwnProperty("canvasOffsetX") || def.hasOwnProperty("canvasOffsetY")) { if (!derived.hasOwnProperty("canvasWidth") && !derived.hasOwnProperty("canvasHeight") && !derived.hasOwnProperty("canvasOffsetX") && !derived.hasOwnProperty("canvasOffsetY")) { if (def.hasOwnProperty("canvasWidth")) { derived.canvasWidth = def.canvasWidth; } if (def.hasOwnProperty("canvasHeight")) { derived.canvasHeight = def.canvasHeight; } if (def.hasOwnProperty("canvasOffsetX")) { derived.canvasOffsetX = def.canvasOffsetX; } if (def.hasOwnProperty("canvasOffsetY")) { derived.canvasOffsetY = def.canvasOffsetY; } } } if (def.hasOwnProperty("quality")) { if (!derived.hasOwnProperty("quality")) { derived.quality = def.quality; } } derived.id = def.id + ":" + basic.id; derived.assetPath = _getAssetPath(derived); derived.default = def; return derived; }
[ "function", "_deriveComponent", "(", "def", ",", "basic", ")", "{", "var", "derived", "=", "_shallowCopy", "(", "basic", ")", ";", "if", "(", "def", ".", "hasOwnProperty", "(", "\"folder\"", ")", ")", "{", "if", "(", "derived", ".", "hasOwnProperty", "(", "\"folder\"", ")", ")", "{", "var", "folder", "=", "def", ".", "folder", ".", "concat", "(", "basic", ".", "folder", ")", ";", "derived", ".", "folder", "=", "folder", ";", "}", "else", "{", "derived", ".", "folder", "=", "def", ".", "folder", ";", "}", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"suffix\"", ")", ")", "{", "var", "index", "=", "basic", ".", "file", ".", "lastIndexOf", "(", "\".\"", ")", ",", "filename", "=", "basic", ".", "file", ".", "substring", "(", "0", ",", "index", ")", ",", "extension", "=", "basic", ".", "file", ".", "substring", "(", "index", ")", ";", "derived", ".", "file", "=", "filename", "+", "def", ".", "suffix", "+", "extension", ";", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"scale\"", ")", "||", "def", ".", "hasOwnProperty", "(", "\"width\"", ")", "||", "def", ".", "hasOwnProperty", "(", "\"height\"", ")", ")", "{", "if", "(", "!", "derived", ".", "hasOwnProperty", "(", "\"scale\"", ")", "&&", "!", "derived", ".", "hasOwnProperty", "(", "\"width\"", ")", "&&", "!", "derived", ".", "hasOwnProperty", "(", "\"height\"", ")", ")", "{", "if", "(", "def", ".", "hasOwnProperty", "(", "\"scale\"", ")", ")", "{", "derived", ".", "scale", "=", "def", ".", "scale", ";", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"width\"", ")", ")", "{", "derived", ".", "width", "=", "def", ".", "width", ";", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"height\"", ")", ")", "{", "derived", ".", "height", "=", "def", ".", "height", ";", "}", "}", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"canvasWidth\"", ")", "||", "def", ".", "hasOwnProperty", "(", "\"canvasHeight\"", ")", "||", "def", ".", "hasOwnProperty", "(", "\"canvasOffsetX\"", ")", "||", "def", ".", "hasOwnProperty", "(", "\"canvasOffsetY\"", ")", ")", "{", "if", "(", "!", "derived", ".", "hasOwnProperty", "(", "\"canvasWidth\"", ")", "&&", "!", "derived", ".", "hasOwnProperty", "(", "\"canvasHeight\"", ")", "&&", "!", "derived", ".", "hasOwnProperty", "(", "\"canvasOffsetX\"", ")", "&&", "!", "derived", ".", "hasOwnProperty", "(", "\"canvasOffsetY\"", ")", ")", "{", "if", "(", "def", ".", "hasOwnProperty", "(", "\"canvasWidth\"", ")", ")", "{", "derived", ".", "canvasWidth", "=", "def", ".", "canvasWidth", ";", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"canvasHeight\"", ")", ")", "{", "derived", ".", "canvasHeight", "=", "def", ".", "canvasHeight", ";", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"canvasOffsetX\"", ")", ")", "{", "derived", ".", "canvasOffsetX", "=", "def", ".", "canvasOffsetX", ";", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"canvasOffsetY\"", ")", ")", "{", "derived", ".", "canvasOffsetY", "=", "def", ".", "canvasOffsetY", ";", "}", "}", "}", "if", "(", "def", ".", "hasOwnProperty", "(", "\"quality\"", ")", ")", "{", "if", "(", "!", "derived", ".", "hasOwnProperty", "(", "\"quality\"", ")", ")", "{", "derived", ".", "quality", "=", "def", ".", "quality", ";", "}", "}", "derived", ".", "id", "=", "def", ".", "id", "+", "\":\"", "+", "basic", ".", "id", ";", "derived", ".", "assetPath", "=", "_getAssetPath", "(", "derived", ")", ";", "derived", ".", "default", "=", "def", ";", "return", "derived", ";", "}" ]
Create a single derived component from a given default component and basic component. @private @param {Component} def A default component @param {Component} basic A basic component @return {Component} The derived component
[ "Create", "a", "single", "derived", "component", "from", "a", "given", "default", "component", "and", "basic", "component", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/componentmanager.js#L79-L159
18,083
adobe-photoshop/generator-assets
lib/componentmanager.js
ComponentManager
function ComponentManager(generator, config) { this._parserManager = new ParserManager(config); this._config = config || {}; this._allComponents = {}; this._componentsForLayer = {}; this._componentsForComp = {}; this._componentsForDocument = {}; this._paths = {}; this._defaultLayerId = null; this._metaDefaultComponents = []; this._metaDataRoot = config["meta-data-root"] || META_PLUGIN_ID; }
javascript
function ComponentManager(generator, config) { this._parserManager = new ParserManager(config); this._config = config || {}; this._allComponents = {}; this._componentsForLayer = {}; this._componentsForComp = {}; this._componentsForDocument = {}; this._paths = {}; this._defaultLayerId = null; this._metaDefaultComponents = []; this._metaDataRoot = config["meta-data-root"] || META_PLUGIN_ID; }
[ "function", "ComponentManager", "(", "generator", ",", "config", ")", "{", "this", ".", "_parserManager", "=", "new", "ParserManager", "(", "config", ")", ";", "this", ".", "_config", "=", "config", "||", "{", "}", ";", "this", ".", "_allComponents", "=", "{", "}", ";", "this", ".", "_componentsForLayer", "=", "{", "}", ";", "this", ".", "_componentsForComp", "=", "{", "}", ";", "this", ".", "_componentsForDocument", "=", "{", "}", ";", "this", ".", "_paths", "=", "{", "}", ";", "this", ".", "_defaultLayerId", "=", "null", ";", "this", ".", "_metaDefaultComponents", "=", "[", "]", ";", "this", ".", "_metaDataRoot", "=", "config", "[", "\"meta-data-root\"", "]", "||", "META_PLUGIN_ID", ";", "}" ]
ComponentManagers manage a set of Component objects. @constructor
[ "ComponentManagers", "manage", "a", "set", "of", "Component", "objects", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/componentmanager.js#L166-L177
18,084
adobe-photoshop/generator-assets
lib/parsermanager.js
ParserManager
function ParserManager(config) { this._config = config || {}; this._supportedUnits = { "in": true, "cm": true, "px": true, "mm": true }; this._supportedExtensions = { "jpg": true, "png": true, "gif": true, "svg": this._config.hasOwnProperty("svg-enabled") ? !!this._config["svg-enabled"] : true, "webp": !!this._config["webp-enabled"] }; }
javascript
function ParserManager(config) { this._config = config || {}; this._supportedUnits = { "in": true, "cm": true, "px": true, "mm": true }; this._supportedExtensions = { "jpg": true, "png": true, "gif": true, "svg": this._config.hasOwnProperty("svg-enabled") ? !!this._config["svg-enabled"] : true, "webp": !!this._config["webp-enabled"] }; }
[ "function", "ParserManager", "(", "config", ")", "{", "this", ".", "_config", "=", "config", "||", "{", "}", ";", "this", ".", "_supportedUnits", "=", "{", "\"in\"", ":", "true", ",", "\"cm\"", ":", "true", ",", "\"px\"", ":", "true", ",", "\"mm\"", ":", "true", "}", ";", "this", ".", "_supportedExtensions", "=", "{", "\"jpg\"", ":", "true", ",", "\"png\"", ":", "true", ",", "\"gif\"", ":", "true", ",", "\"svg\"", ":", "this", ".", "_config", ".", "hasOwnProperty", "(", "\"svg-enabled\"", ")", "?", "!", "!", "this", ".", "_config", "[", "\"svg-enabled\"", "]", ":", "true", ",", "\"webp\"", ":", "!", "!", "this", ".", "_config", "[", "\"webp-enabled\"", "]", "}", ";", "}" ]
The ParserManager manages parsing, normalization and analysis of layer names into asset specifications. The config parameter can be used to enable svg and webp parsing if the "svg-enabled" and "webp-enabled" parameters are set, resp. @constructor @param {object} config
[ "The", "ParserManager", "manages", "parsing", "normalization", "and", "analysis", "of", "layer", "names", "into", "asset", "specifications", ".", "The", "config", "parameter", "can", "be", "used", "to", "enable", "svg", "and", "webp", "parsing", "if", "the", "svg", "-", "enabled", "and", "webp", "-", "enabled", "parameters", "are", "set", "resp", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/parsermanager.js#L38-L55
18,085
adobe-photoshop/generator-assets
lib/filemanager.js
FileManager
function FileManager(generator, config, logger) { this._generator = generator; this._config = config; this._logger = logger; this._queue = new AsyncQueue(); this._queue.pause(); this._queue.on("error", function (err) { this._logger.error(err); }.bind(this)); }
javascript
function FileManager(generator, config, logger) { this._generator = generator; this._config = config; this._logger = logger; this._queue = new AsyncQueue(); this._queue.pause(); this._queue.on("error", function (err) { this._logger.error(err); }.bind(this)); }
[ "function", "FileManager", "(", "generator", ",", "config", ",", "logger", ")", "{", "this", ".", "_generator", "=", "generator", ";", "this", ".", "_config", "=", "config", ";", "this", ".", "_logger", "=", "logger", ";", "this", ".", "_queue", "=", "new", "AsyncQueue", "(", ")", ";", "this", ".", "_queue", ".", "pause", "(", ")", ";", "this", ".", "_queue", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "this", ".", "_logger", ".", "error", "(", "err", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Manage a collection of files, specified with relative paths, under a given base path, specified absolutely. @constructor @param {Generator} generator @param {object} config @param {Logger} logger
[ "Manage", "a", "collection", "of", "files", "specified", "with", "relative", "paths", "under", "a", "given", "base", "path", "specified", "absolutely", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/filemanager.js#L50-L60
18,086
adobe-photoshop/generator-assets
lib/documentmanager.js
DocumentManager
function DocumentManager(generator, config, logger, options) { EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; options = options || {}; this._getDocumentInfoFlags = options.getDocumentInfoFlags; this._clearCacheOnChange = options.clearCacheOnChange; this._documents = {}; this._documentDeferreds = {}; this._documentChanges = {}; this._openDocumentIds = {}; this._newOpenDocumentIds = {}; this._newClosedDocumentIds = {}; this._initActiveDocumentID(); this._resetOpenDocumentIDs() .then(function () { // make sure that openDocumentsChanged fires once on startup, even // if there are no open documents this._handleOpenDocumentsChange(); }.bind(this)) .done(); generator.onPhotoshopEvent("imageChanged", this._handleImageChanged.bind(this)); }
javascript
function DocumentManager(generator, config, logger, options) { EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; options = options || {}; this._getDocumentInfoFlags = options.getDocumentInfoFlags; this._clearCacheOnChange = options.clearCacheOnChange; this._documents = {}; this._documentDeferreds = {}; this._documentChanges = {}; this._openDocumentIds = {}; this._newOpenDocumentIds = {}; this._newClosedDocumentIds = {}; this._initActiveDocumentID(); this._resetOpenDocumentIDs() .then(function () { // make sure that openDocumentsChanged fires once on startup, even // if there are no open documents this._handleOpenDocumentsChange(); }.bind(this)) .done(); generator.onPhotoshopEvent("imageChanged", this._handleImageChanged.bind(this)); }
[ "function", "DocumentManager", "(", "generator", ",", "config", ",", "logger", ",", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_generator", "=", "generator", ";", "this", ".", "_config", "=", "config", ";", "this", ".", "_logger", "=", "logger", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_getDocumentInfoFlags", "=", "options", ".", "getDocumentInfoFlags", ";", "this", ".", "_clearCacheOnChange", "=", "options", ".", "clearCacheOnChange", ";", "this", ".", "_documents", "=", "{", "}", ";", "this", ".", "_documentDeferreds", "=", "{", "}", ";", "this", ".", "_documentChanges", "=", "{", "}", ";", "this", ".", "_openDocumentIds", "=", "{", "}", ";", "this", ".", "_newOpenDocumentIds", "=", "{", "}", ";", "this", ".", "_newClosedDocumentIds", "=", "{", "}", ";", "this", ".", "_initActiveDocumentID", "(", ")", ";", "this", ".", "_resetOpenDocumentIDs", "(", ")", ".", "then", "(", "function", "(", ")", "{", "// make sure that openDocumentsChanged fires once on startup, even", "// if there are no open documents", "this", ".", "_handleOpenDocumentsChange", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ".", "done", "(", ")", ";", "generator", ".", "onPhotoshopEvent", "(", "\"imageChanged\"", ",", "this", ".", "_handleImageChanged", ".", "bind", "(", "this", ")", ")", ";", "}" ]
The DocumentManager provides a simple interface for requesting and maintaining up-to-date Document objects from Photoshop. Emits "openDocumentsChanged" event when the set of open documents changes with the following parameters: 1. @param {Array.<number>} IDs for the set of currently open documents 2. @param {Array.<number>} IDs for the set of recently opened documents 3. @param {Array.<number>} IDs for the set of recently closed documents Emits "activeDocumentChanged" event when the currently active document changes with the follwing parameter: 1. @param {?number} ID of the currently active document, or null if there is none @constructor @param {Generator} generator @param {object} config @param {Logger} logger @param {object*} options runtime options: getDocumentInfoFlags: object, key documented at getDocumentInfo clearCacheOnChange: bool, removes the document from the cache on change instead of updating it and sending a change event
[ "The", "DocumentManager", "provides", "a", "simple", "interface", "for", "requesting", "and", "maintaining", "up", "-", "to", "-", "date", "Document", "objects", "from", "Photoshop", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/documentmanager.js#L73-L103
18,087
adobe-photoshop/generator-assets
lib/dom/document.js
Document
function Document(generator, config, logger, raw) { if (DEBUG_TO_RAW_CONVERSION) { debugLogObject("raw", raw); } events.EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; var property; for (property in raw) { if (raw.hasOwnProperty(property)) { switch (property) { case "id": this._id = raw.id; break; case "count": this._count = raw.count; break; case "timeStamp": this._timeStamp = raw.timeStamp; break; case "version": this._version = raw.version; break; case "file": this._setFile(raw.file); break; case "bounds": this._setBounds(raw.bounds); break; case "selection": // Resolving the selection depends on the layers; set it in a later pass break; case "resolution": this._setResolution(raw.resolution); break; case "globalLight": this._setGlobalLight(raw.globalLight); break; case "generatorSettings": this._setGeneratorSettings(raw.generatorSettings); break; case "layers": this._setLayers(raw.layers); break; case "comps": this._setComps(raw.comps); break; case "placed": this._setPlaced(raw.placed); break; case "mode": this._setMode(raw.mode); break; case "profile": case "depth": // Do nothing for these properties // TODO could profile be helpful for embedding color profile? break; default: this._logger.warn("Unhandled property in raw constructor:", property, raw[property]); } } } if (raw.hasOwnProperty("selection")) { this._setSelection(raw.selection); } if (DEBUG_TO_RAW_CONVERSION) { debugLogObject("document.toRaw", this.toRaw()); } }
javascript
function Document(generator, config, logger, raw) { if (DEBUG_TO_RAW_CONVERSION) { debugLogObject("raw", raw); } events.EventEmitter.call(this); this._generator = generator; this._config = config; this._logger = logger; var property; for (property in raw) { if (raw.hasOwnProperty(property)) { switch (property) { case "id": this._id = raw.id; break; case "count": this._count = raw.count; break; case "timeStamp": this._timeStamp = raw.timeStamp; break; case "version": this._version = raw.version; break; case "file": this._setFile(raw.file); break; case "bounds": this._setBounds(raw.bounds); break; case "selection": // Resolving the selection depends on the layers; set it in a later pass break; case "resolution": this._setResolution(raw.resolution); break; case "globalLight": this._setGlobalLight(raw.globalLight); break; case "generatorSettings": this._setGeneratorSettings(raw.generatorSettings); break; case "layers": this._setLayers(raw.layers); break; case "comps": this._setComps(raw.comps); break; case "placed": this._setPlaced(raw.placed); break; case "mode": this._setMode(raw.mode); break; case "profile": case "depth": // Do nothing for these properties // TODO could profile be helpful for embedding color profile? break; default: this._logger.warn("Unhandled property in raw constructor:", property, raw[property]); } } } if (raw.hasOwnProperty("selection")) { this._setSelection(raw.selection); } if (DEBUG_TO_RAW_CONVERSION) { debugLogObject("document.toRaw", this.toRaw()); } }
[ "function", "Document", "(", "generator", ",", "config", ",", "logger", ",", "raw", ")", "{", "if", "(", "DEBUG_TO_RAW_CONVERSION", ")", "{", "debugLogObject", "(", "\"raw\"", ",", "raw", ")", ";", "}", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_generator", "=", "generator", ";", "this", ".", "_config", "=", "config", ";", "this", ".", "_logger", "=", "logger", ";", "var", "property", ";", "for", "(", "property", "in", "raw", ")", "{", "if", "(", "raw", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "switch", "(", "property", ")", "{", "case", "\"id\"", ":", "this", ".", "_id", "=", "raw", ".", "id", ";", "break", ";", "case", "\"count\"", ":", "this", ".", "_count", "=", "raw", ".", "count", ";", "break", ";", "case", "\"timeStamp\"", ":", "this", ".", "_timeStamp", "=", "raw", ".", "timeStamp", ";", "break", ";", "case", "\"version\"", ":", "this", ".", "_version", "=", "raw", ".", "version", ";", "break", ";", "case", "\"file\"", ":", "this", ".", "_setFile", "(", "raw", ".", "file", ")", ";", "break", ";", "case", "\"bounds\"", ":", "this", ".", "_setBounds", "(", "raw", ".", "bounds", ")", ";", "break", ";", "case", "\"selection\"", ":", "// Resolving the selection depends on the layers; set it in a later pass", "break", ";", "case", "\"resolution\"", ":", "this", ".", "_setResolution", "(", "raw", ".", "resolution", ")", ";", "break", ";", "case", "\"globalLight\"", ":", "this", ".", "_setGlobalLight", "(", "raw", ".", "globalLight", ")", ";", "break", ";", "case", "\"generatorSettings\"", ":", "this", ".", "_setGeneratorSettings", "(", "raw", ".", "generatorSettings", ")", ";", "break", ";", "case", "\"layers\"", ":", "this", ".", "_setLayers", "(", "raw", ".", "layers", ")", ";", "break", ";", "case", "\"comps\"", ":", "this", ".", "_setComps", "(", "raw", ".", "comps", ")", ";", "break", ";", "case", "\"placed\"", ":", "this", ".", "_setPlaced", "(", "raw", ".", "placed", ")", ";", "break", ";", "case", "\"mode\"", ":", "this", ".", "_setMode", "(", "raw", ".", "mode", ")", ";", "break", ";", "case", "\"profile\"", ":", "case", "\"depth\"", ":", "// Do nothing for these properties", "// TODO could profile be helpful for embedding color profile?", "break", ";", "default", ":", "this", ".", "_logger", ".", "warn", "(", "\"Unhandled property in raw constructor:\"", ",", "property", ",", "raw", "[", "property", "]", ")", ";", "}", "}", "}", "if", "(", "raw", ".", "hasOwnProperty", "(", "\"selection\"", ")", ")", "{", "this", ".", "_setSelection", "(", "raw", ".", "selection", ")", ";", "}", "if", "(", "DEBUG_TO_RAW_CONVERSION", ")", "{", "debugLogObject", "(", "\"document.toRaw\"", ",", "this", ".", "toRaw", "(", ")", ")", ";", "}", "}" ]
Model of a Photoshop document. @constructor @param {Generator} generator @param {object} config @param {Logger} logger @param {object} raw Raw description of the document
[ "Model", "of", "a", "Photoshop", "document", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/dom/document.js#L58-L134
18,088
adobe-photoshop/generator-assets
lib/dom/layer.js
BaseLayer
function BaseLayer(document, group, raw) { this._document = document; this._logger = document._logger; if (group) { this._setGroup(group); } var handledProperties = this._handledProperties || {}, property; for (property in raw) { if (raw.hasOwnProperty(property) && !handledProperties.hasOwnProperty(property)) { switch (property) { case "id": this._id = raw.id; break; case "name": this._setName(raw.name); break; case "bounds": this._setBounds(raw.bounds); break; case "artboard": this._setArtboard(raw.artboard); break; case "boundsWithFX": this._setBoundsWithFX(raw.boundsWithFX); break; case "visible": this._setVisible(raw.visible); break; case "clipped": this._setClipped(raw.clipped); break; case "mask": this._setMask(raw.mask); break; case "layerEffects": this._setLayerEffects(raw.layerEffects); break; case "generatorSettings": this._setGeneratorSettings(raw.generatorSettings); break; case "blendOptions": this._setBlendOptions(raw.blendOptions); break; case "protection": this._setProtection(raw.protection); break; case "path": this._setPath(raw.path); break; case "type": this._setType(raw.type); break; case "index": case "added": // ignore these properties break; default: this._logger.warn("Unhandled property in raw constructor:", property, raw[property]); } } } }
javascript
function BaseLayer(document, group, raw) { this._document = document; this._logger = document._logger; if (group) { this._setGroup(group); } var handledProperties = this._handledProperties || {}, property; for (property in raw) { if (raw.hasOwnProperty(property) && !handledProperties.hasOwnProperty(property)) { switch (property) { case "id": this._id = raw.id; break; case "name": this._setName(raw.name); break; case "bounds": this._setBounds(raw.bounds); break; case "artboard": this._setArtboard(raw.artboard); break; case "boundsWithFX": this._setBoundsWithFX(raw.boundsWithFX); break; case "visible": this._setVisible(raw.visible); break; case "clipped": this._setClipped(raw.clipped); break; case "mask": this._setMask(raw.mask); break; case "layerEffects": this._setLayerEffects(raw.layerEffects); break; case "generatorSettings": this._setGeneratorSettings(raw.generatorSettings); break; case "blendOptions": this._setBlendOptions(raw.blendOptions); break; case "protection": this._setProtection(raw.protection); break; case "path": this._setPath(raw.path); break; case "type": this._setType(raw.type); break; case "index": case "added": // ignore these properties break; default: this._logger.warn("Unhandled property in raw constructor:", property, raw[property]); } } } }
[ "function", "BaseLayer", "(", "document", ",", "group", ",", "raw", ")", "{", "this", ".", "_document", "=", "document", ";", "this", ".", "_logger", "=", "document", ".", "_logger", ";", "if", "(", "group", ")", "{", "this", ".", "_setGroup", "(", "group", ")", ";", "}", "var", "handledProperties", "=", "this", ".", "_handledProperties", "||", "{", "}", ",", "property", ";", "for", "(", "property", "in", "raw", ")", "{", "if", "(", "raw", ".", "hasOwnProperty", "(", "property", ")", "&&", "!", "handledProperties", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "switch", "(", "property", ")", "{", "case", "\"id\"", ":", "this", ".", "_id", "=", "raw", ".", "id", ";", "break", ";", "case", "\"name\"", ":", "this", ".", "_setName", "(", "raw", ".", "name", ")", ";", "break", ";", "case", "\"bounds\"", ":", "this", ".", "_setBounds", "(", "raw", ".", "bounds", ")", ";", "break", ";", "case", "\"artboard\"", ":", "this", ".", "_setArtboard", "(", "raw", ".", "artboard", ")", ";", "break", ";", "case", "\"boundsWithFX\"", ":", "this", ".", "_setBoundsWithFX", "(", "raw", ".", "boundsWithFX", ")", ";", "break", ";", "case", "\"visible\"", ":", "this", ".", "_setVisible", "(", "raw", ".", "visible", ")", ";", "break", ";", "case", "\"clipped\"", ":", "this", ".", "_setClipped", "(", "raw", ".", "clipped", ")", ";", "break", ";", "case", "\"mask\"", ":", "this", ".", "_setMask", "(", "raw", ".", "mask", ")", ";", "break", ";", "case", "\"layerEffects\"", ":", "this", ".", "_setLayerEffects", "(", "raw", ".", "layerEffects", ")", ";", "break", ";", "case", "\"generatorSettings\"", ":", "this", ".", "_setGeneratorSettings", "(", "raw", ".", "generatorSettings", ")", ";", "break", ";", "case", "\"blendOptions\"", ":", "this", ".", "_setBlendOptions", "(", "raw", ".", "blendOptions", ")", ";", "break", ";", "case", "\"protection\"", ":", "this", ".", "_setProtection", "(", "raw", ".", "protection", ")", ";", "break", ";", "case", "\"path\"", ":", "this", ".", "_setPath", "(", "raw", ".", "path", ")", ";", "break", ";", "case", "\"type\"", ":", "this", ".", "_setType", "(", "raw", ".", "type", ")", ";", "break", ";", "case", "\"index\"", ":", "case", "\"added\"", ":", "// ignore these properties", "break", ";", "default", ":", "this", ".", "_logger", ".", "warn", "(", "\"Unhandled property in raw constructor:\"", ",", "property", ",", "raw", "[", "property", "]", ")", ";", "}", "}", "}", "}" ]
Abstract base class for representing layers in a document. This should not be instantiated directly. @constructor @private @param {Document} document @param {?LayerGroup} group The parent layer group of this layer. Null if the layer is directly contained by the Document. @param {object} raw Raw description of the layer.
[ "Abstract", "base", "class", "for", "representing", "layers", "in", "a", "document", ".", "This", "should", "not", "be", "instantiated", "directly", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/dom/layer.js#L77-L142
18,089
adobe-photoshop/generator-assets
lib/dom/layer.js
createLayer
function createLayer(document, parent, rawLayer) { if (!parent && !rawLayer.hasOwnProperty("type")) { return new LayerGroup(document, null, rawLayer); } switch (rawLayer.type) { case "layerSection": case "artboardSection": case "framedGroupSection": return new LayerGroup(document, parent, rawLayer); case "layer": return new Layer(document, parent, rawLayer); case "shapeLayer": return new ShapeLayer(document, parent, rawLayer); case "textLayer": return new TextLayer(document, parent, rawLayer); case "adjustmentLayer": return new AdjustmentLayer(document, parent, rawLayer); case "smartObjectLayer": return new SmartObjectLayer(document, parent, rawLayer); case "backgroundLayer": return new BackgroundLayer(document, parent, rawLayer); default: throw new Error("Unknown layer type:", rawLayer.type); } }
javascript
function createLayer(document, parent, rawLayer) { if (!parent && !rawLayer.hasOwnProperty("type")) { return new LayerGroup(document, null, rawLayer); } switch (rawLayer.type) { case "layerSection": case "artboardSection": case "framedGroupSection": return new LayerGroup(document, parent, rawLayer); case "layer": return new Layer(document, parent, rawLayer); case "shapeLayer": return new ShapeLayer(document, parent, rawLayer); case "textLayer": return new TextLayer(document, parent, rawLayer); case "adjustmentLayer": return new AdjustmentLayer(document, parent, rawLayer); case "smartObjectLayer": return new SmartObjectLayer(document, parent, rawLayer); case "backgroundLayer": return new BackgroundLayer(document, parent, rawLayer); default: throw new Error("Unknown layer type:", rawLayer.type); } }
[ "function", "createLayer", "(", "document", ",", "parent", ",", "rawLayer", ")", "{", "if", "(", "!", "parent", "&&", "!", "rawLayer", ".", "hasOwnProperty", "(", "\"type\"", ")", ")", "{", "return", "new", "LayerGroup", "(", "document", ",", "null", ",", "rawLayer", ")", ";", "}", "switch", "(", "rawLayer", ".", "type", ")", "{", "case", "\"layerSection\"", ":", "case", "\"artboardSection\"", ":", "case", "\"framedGroupSection\"", ":", "return", "new", "LayerGroup", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "case", "\"layer\"", ":", "return", "new", "Layer", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "case", "\"shapeLayer\"", ":", "return", "new", "ShapeLayer", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "case", "\"textLayer\"", ":", "return", "new", "TextLayer", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "case", "\"adjustmentLayer\"", ":", "return", "new", "AdjustmentLayer", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "case", "\"smartObjectLayer\"", ":", "return", "new", "SmartObjectLayer", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "case", "\"backgroundLayer\"", ":", "return", "new", "BackgroundLayer", "(", "document", ",", "parent", ",", "rawLayer", ")", ";", "default", ":", "throw", "new", "Error", "(", "\"Unknown layer type:\"", ",", "rawLayer", ".", "type", ")", ";", "}", "}" ]
Create a new layer object of the appropriate type for the given raw description. The new layer is not attached to its parent layer. @param {Document} document The parent document for the new layer @param {?BaseLayer} parent The parent layer for the new layer @param {object} rawLayer The raw description of the new layer @return {BaseLayer} A subtype of the abstract BaseLayer class.
[ "Create", "a", "new", "layer", "object", "of", "the", "appropriate", "type", "for", "the", "given", "raw", "description", ".", "The", "new", "layer", "is", "not", "attached", "to", "its", "parent", "layer", "." ]
87878b2d3cb979578d471f1ecc3eba906c6d17d4
https://github.com/adobe-photoshop/generator-assets/blob/87878b2d3cb979578d471f1ecc3eba906c6d17d4/lib/dom/layer.js#L1114-L1139
18,090
archilogic-com/3dio-js
src/scene/structure/to-aframe-elements.js
getAframeElementsFromSceneStructure
function getAframeElementsFromSceneStructure(sceneStructure, parent) { var collection = parent ? null : [] // use collection or parent sceneStructure.forEach(function(element3d) { // check if type is supported in aframe if (validTypes.indexOf(element3d.type) > -1) { // get html attributes from element3d objects var el = addEntity({ attributes: getAttributes(element3d), parent: parent }) // the level scene might be baked if (element3d.type === 'level') { createBakedElement(el, element3d) } // recursively proceed through sceneStructure if (element3d.children && element3d.children.length) getAframeElementsFromSceneStructure(element3d.children, el) if (collection) collection.push(el) } }) return collection }
javascript
function getAframeElementsFromSceneStructure(sceneStructure, parent) { var collection = parent ? null : [] // use collection or parent sceneStructure.forEach(function(element3d) { // check if type is supported in aframe if (validTypes.indexOf(element3d.type) > -1) { // get html attributes from element3d objects var el = addEntity({ attributes: getAttributes(element3d), parent: parent }) // the level scene might be baked if (element3d.type === 'level') { createBakedElement(el, element3d) } // recursively proceed through sceneStructure if (element3d.children && element3d.children.length) getAframeElementsFromSceneStructure(element3d.children, el) if (collection) collection.push(el) } }) return collection }
[ "function", "getAframeElementsFromSceneStructure", "(", "sceneStructure", ",", "parent", ")", "{", "var", "collection", "=", "parent", "?", "null", ":", "[", "]", "// use collection or parent", "sceneStructure", ".", "forEach", "(", "function", "(", "element3d", ")", "{", "// check if type is supported in aframe", "if", "(", "validTypes", ".", "indexOf", "(", "element3d", ".", "type", ")", ">", "-", "1", ")", "{", "// get html attributes from element3d objects", "var", "el", "=", "addEntity", "(", "{", "attributes", ":", "getAttributes", "(", "element3d", ")", ",", "parent", ":", "parent", "}", ")", "// the level scene might be baked", "if", "(", "element3d", ".", "type", "===", "'level'", ")", "{", "createBakedElement", "(", "el", ",", "element3d", ")", "}", "// recursively proceed through sceneStructure", "if", "(", "element3d", ".", "children", "&&", "element3d", ".", "children", ".", "length", ")", "getAframeElementsFromSceneStructure", "(", "element3d", ".", "children", ",", "el", ")", "if", "(", "collection", ")", "collection", ".", "push", "(", "el", ")", "}", "}", ")", "return", "collection", "}" ]
recursive parsing through sceneStructre
[ "recursive", "parsing", "through", "sceneStructre" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/scene/structure/to-aframe-elements.js#L54-L75
18,091
archilogic-com/3dio-js
src/scene/structure/to-aframe-elements.js
createBakedElement
function createBakedElement(parentElem, element3d) { // we might have a scene that has no baked level if (!element3d.bakedModelUrl && !element3d.bakePreviewStatusFileKey) { console.warn('Level without bakedModelUrl: ', element3d) return } // set data3d.buffer file key var attributes = { 'io3d-data3d': 'key: ' + element3d.bakedModelUrl, shadow: 'cast: false; receive: true' } // set lightmap settings if (element3d.lightMapIntensity) { attributes['io3d-data3d'] += '; lightMapIntensity: ' + element3d.lightMapIntensity + '; lightMapExposure: ' + element3d.lightMapCenter } var bakedElem = addEntity({ attributes: attributes, parent: parentElem }) if (element3d.bakeRegularStatusFileKey || element3d.bakePreviewStatusFileKey) { updateOnBake(bakedElem, element3d) } }
javascript
function createBakedElement(parentElem, element3d) { // we might have a scene that has no baked level if (!element3d.bakedModelUrl && !element3d.bakePreviewStatusFileKey) { console.warn('Level without bakedModelUrl: ', element3d) return } // set data3d.buffer file key var attributes = { 'io3d-data3d': 'key: ' + element3d.bakedModelUrl, shadow: 'cast: false; receive: true' } // set lightmap settings if (element3d.lightMapIntensity) { attributes['io3d-data3d'] += '; lightMapIntensity: ' + element3d.lightMapIntensity + '; lightMapExposure: ' + element3d.lightMapCenter } var bakedElem = addEntity({ attributes: attributes, parent: parentElem }) if (element3d.bakeRegularStatusFileKey || element3d.bakePreviewStatusFileKey) { updateOnBake(bakedElem, element3d) } }
[ "function", "createBakedElement", "(", "parentElem", ",", "element3d", ")", "{", "// we might have a scene that has no baked level", "if", "(", "!", "element3d", ".", "bakedModelUrl", "&&", "!", "element3d", ".", "bakePreviewStatusFileKey", ")", "{", "console", ".", "warn", "(", "'Level without bakedModelUrl: '", ",", "element3d", ")", "return", "}", "// set data3d.buffer file key", "var", "attributes", "=", "{", "'io3d-data3d'", ":", "'key: '", "+", "element3d", ".", "bakedModelUrl", ",", "shadow", ":", "'cast: false; receive: true'", "}", "// set lightmap settings", "if", "(", "element3d", ".", "lightMapIntensity", ")", "{", "attributes", "[", "'io3d-data3d'", "]", "+=", "'; lightMapIntensity: '", "+", "element3d", ".", "lightMapIntensity", "+", "'; lightMapExposure: '", "+", "element3d", ".", "lightMapCenter", "}", "var", "bakedElem", "=", "addEntity", "(", "{", "attributes", ":", "attributes", ",", "parent", ":", "parentElem", "}", ")", "if", "(", "element3d", ".", "bakeRegularStatusFileKey", "||", "element3d", ".", "bakePreviewStatusFileKey", ")", "{", "updateOnBake", "(", "bakedElem", ",", "element3d", ")", "}", "}" ]
creates a child for a baked model in the current element
[ "creates", "a", "child", "for", "a", "baked", "model", "in", "the", "current", "element" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/scene/structure/to-aframe-elements.js#L183-L208
18,092
archilogic-com/3dio-js
src/aframe/component/gblock.js
GBlockLoader
function GBlockLoader () { this.manager = THREE.DefaultLoadingManager this.path = THREE.Loader.prototype.extractUrlBase( url ) }
javascript
function GBlockLoader () { this.manager = THREE.DefaultLoadingManager this.path = THREE.Loader.prototype.extractUrlBase( url ) }
[ "function", "GBlockLoader", "(", ")", "{", "this", ".", "manager", "=", "THREE", ".", "DefaultLoadingManager", "this", ".", "path", "=", "THREE", ".", "Loader", ".", "prototype", ".", "extractUrlBase", "(", "url", ")", "}" ]
create unviresal GLTF loader for google blocks this one will inherit methods from GLTF V1 or V2 based on file version
[ "create", "unviresal", "GLTF", "loader", "for", "google", "blocks", "this", "one", "will", "inherit", "methods", "from", "GLTF", "V1", "or", "V2", "based", "on", "file", "version" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/aframe/component/gblock.js#L116-L119
18,093
archilogic-com/3dio-js
src/scene/structure/parametric-objects/kitchen.js
getElementPos
function getElementPos(pos) { var l = 0 for (var i = 0; i < pos - 1; i++) { l += elements[i] } return l }
javascript
function getElementPos(pos) { var l = 0 for (var i = 0; i < pos - 1; i++) { l += elements[i] } return l }
[ "function", "getElementPos", "(", "pos", ")", "{", "var", "l", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pos", "-", "1", ";", "i", "++", ")", "{", "l", "+=", "elements", "[", "i", "]", "}", "return", "l", "}" ]
get x coordinate for element index
[ "get", "x", "coordinate", "for", "element", "index" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/scene/structure/parametric-objects/kitchen.js#L193-L197
18,094
archilogic-com/3dio-js
src/utils/image/scale-down-image.js
normaliseScale
function normaliseScale(s) { if (s>1) throw('s must be <1'); s = 0 | (1/s); var l = log2(s); var mask = 1 << l; var accuracy = 4; while(accuracy && l) { l--; mask |= 1<<l; accuracy--; } return 1 / ( s & mask ); }
javascript
function normaliseScale(s) { if (s>1) throw('s must be <1'); s = 0 | (1/s); var l = log2(s); var mask = 1 << l; var accuracy = 4; while(accuracy && l) { l--; mask |= 1<<l; accuracy--; } return 1 / ( s & mask ); }
[ "function", "normaliseScale", "(", "s", ")", "{", "if", "(", "s", ">", "1", ")", "throw", "(", "'s must be <1'", ")", ";", "s", "=", "0", "|", "(", "1", "/", "s", ")", ";", "var", "l", "=", "log2", "(", "s", ")", ";", "var", "mask", "=", "1", "<<", "l", ";", "var", "accuracy", "=", "4", ";", "while", "(", "accuracy", "&&", "l", ")", "{", "l", "--", ";", "mask", "|=", "1", "<<", "l", ";", "accuracy", "--", ";", "}", "return", "1", "/", "(", "s", "&", "mask", ")", ";", "}" ]
normalize a scale <1 to avoid some rounding issue with js numbers
[ "normalize", "a", "scale", "<1", "to", "avoid", "some", "rounding", "issue", "with", "js", "numbers" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/utils/image/scale-down-image.js#L230-L238
18,095
archilogic-com/3dio-js
examples-browser/offline-data/sw.js
fromCache
function fromCache(request) { return caches.open(CACHE).then(function (cache) { return cache.match(request).then(function (matching) { return matching || Promise.reject('no-match'); }); }); }
javascript
function fromCache(request) { return caches.open(CACHE).then(function (cache) { return cache.match(request).then(function (matching) { return matching || Promise.reject('no-match'); }); }); }
[ "function", "fromCache", "(", "request", ")", "{", "return", "caches", ".", "open", "(", "CACHE", ")", ".", "then", "(", "function", "(", "cache", ")", "{", "return", "cache", ".", "match", "(", "request", ")", ".", "then", "(", "function", "(", "matching", ")", "{", "return", "matching", "||", "Promise", ".", "reject", "(", "'no-match'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Open the cache where the assets were stored and search for the requested resource. Notice that in case of no matching, the promise still resolves but it does with `undefined` as value.
[ "Open", "the", "cache", "where", "the", "assets", "were", "stored", "and", "search", "for", "the", "requested", "resource", ".", "Notice", "that", "in", "case", "of", "no", "matching", "the", "promise", "still", "resolves", "but", "it", "does", "with", "undefined", "as", "value", "." ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/examples-browser/offline-data/sw.js#L46-L52
18,096
archilogic-com/3dio-js
examples-browser/offline-data/sw.js
update
function update(request) { // don't automatically put 3D models in the cache if(request.url.match(/https:\/\/storage.3d.io/)) return fetch(request); return caches.open(CACHE).then(function (cache) { return fetch(request).then(function (response) { return cache.put(request, response); }); }); }
javascript
function update(request) { // don't automatically put 3D models in the cache if(request.url.match(/https:\/\/storage.3d.io/)) return fetch(request); return caches.open(CACHE).then(function (cache) { return fetch(request).then(function (response) { return cache.put(request, response); }); }); }
[ "function", "update", "(", "request", ")", "{", "// don't automatically put 3D models in the cache", "if", "(", "request", ".", "url", ".", "match", "(", "/", "https:\\/\\/storage.3d.io", "/", ")", ")", "return", "fetch", "(", "request", ")", ";", "return", "caches", ".", "open", "(", "CACHE", ")", ".", "then", "(", "function", "(", "cache", ")", "{", "return", "fetch", "(", "request", ")", ".", "then", "(", "function", "(", "response", ")", "{", "return", "cache", ".", "put", "(", "request", ",", "response", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update consists in opening the cache, performing a network request and storing the new response data.
[ "Update", "consists", "in", "opening", "the", "cache", "performing", "a", "network", "request", "and", "storing", "the", "new", "response", "data", "." ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/examples-browser/offline-data/sw.js#L56-L65
18,097
archilogic-com/3dio-js
src/aframe/component/tour.js
getNormalizeRotations
function getNormalizeRotations(start, end) { // normalize both rotations var normStart = normalizeRotation(start) var normEnd = normalizeRotation(end) // find the shortest arc for each rotation Object.keys(start).forEach(function(axis) { if (normEnd[axis] - normStart[axis] > 180) normEnd[axis] -= 360 }) return { start: normStart, end: normEnd } }
javascript
function getNormalizeRotations(start, end) { // normalize both rotations var normStart = normalizeRotation(start) var normEnd = normalizeRotation(end) // find the shortest arc for each rotation Object.keys(start).forEach(function(axis) { if (normEnd[axis] - normStart[axis] > 180) normEnd[axis] -= 360 }) return { start: normStart, end: normEnd } }
[ "function", "getNormalizeRotations", "(", "start", ",", "end", ")", "{", "// normalize both rotations", "var", "normStart", "=", "normalizeRotation", "(", "start", ")", "var", "normEnd", "=", "normalizeRotation", "(", "end", ")", "// find the shortest arc for each rotation", "Object", ".", "keys", "(", "start", ")", ".", "forEach", "(", "function", "(", "axis", ")", "{", "if", "(", "normEnd", "[", "axis", "]", "-", "normStart", "[", "axis", "]", ">", "180", ")", "normEnd", "[", "axis", "]", "-=", "360", "}", ")", "return", "{", "start", ":", "normStart", ",", "end", ":", "normEnd", "}", "}" ]
we want to prevent excessive spinning in rotations
[ "we", "want", "to", "prevent", "excessive", "spinning", "in", "rotations" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/aframe/component/tour.js#L235-L244
18,098
archilogic-com/3dio-js
src/utils/data3d/buffer/triangulate-2d.js
eliminateHoles
function eliminateHoles (data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim end = i < len - 1 ? holeIndices[i + 1] * dim : data.length list = linkedList(data, start, end, dim, false) if (list === list.next) { list.steiner = true } list = filterPoints(data, list) if (list) { queue.push(getLeftmost(data, list)) } } queue.sort(function (a, b) { return data[a.i] - data[b.i] }) // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(data, queue[i], outerNode) outerNode = filterPoints(data, outerNode, outerNode.next) } return outerNode }
javascript
function eliminateHoles (data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim end = i < len - 1 ? holeIndices[i + 1] * dim : data.length list = linkedList(data, start, end, dim, false) if (list === list.next) { list.steiner = true } list = filterPoints(data, list) if (list) { queue.push(getLeftmost(data, list)) } } queue.sort(function (a, b) { return data[a.i] - data[b.i] }) // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(data, queue[i], outerNode) outerNode = filterPoints(data, outerNode, outerNode.next) } return outerNode }
[ "function", "eliminateHoles", "(", "data", ",", "holeIndices", ",", "outerNode", ",", "dim", ")", "{", "var", "queue", "=", "[", "]", ",", "i", ",", "len", ",", "start", ",", "end", ",", "list", "for", "(", "i", "=", "0", ",", "len", "=", "holeIndices", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "start", "=", "holeIndices", "[", "i", "]", "*", "dim", "end", "=", "i", "<", "len", "-", "1", "?", "holeIndices", "[", "i", "+", "1", "]", "*", "dim", ":", "data", ".", "length", "list", "=", "linkedList", "(", "data", ",", "start", ",", "end", ",", "dim", ",", "false", ")", "if", "(", "list", "===", "list", ".", "next", ")", "{", "list", ".", "steiner", "=", "true", "}", "list", "=", "filterPoints", "(", "data", ",", "list", ")", "if", "(", "list", ")", "{", "queue", ".", "push", "(", "getLeftmost", "(", "data", ",", "list", ")", ")", "}", "}", "queue", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "data", "[", "a", ".", "i", "]", "-", "data", "[", "b", ".", "i", "]", "}", ")", "// process holes from left to right", "for", "(", "i", "=", "0", ";", "i", "<", "queue", ".", "length", ";", "i", "++", ")", "{", "eliminateHole", "(", "data", ",", "queue", "[", "i", "]", ",", "outerNode", ")", "outerNode", "=", "filterPoints", "(", "data", ",", "outerNode", ",", "outerNode", ".", "next", ")", "}", "return", "outerNode", "}" ]
link every hole into the outer loop, producing a single-ring polygon without holes
[ "link", "every", "hole", "into", "the", "outer", "loop", "producing", "a", "single", "-", "ring", "polygon", "without", "holes" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/utils/data3d/buffer/triangulate-2d.js#L379-L407
18,099
archilogic-com/3dio-js
src/utils/data3d/buffer/triangulate-2d.js
orient
function orient (data, p, q, r) { var o = (data[q + 1] - data[p + 1]) * (data[r] - data[q]) - (data[q] - data[p]) * (data[r + 1] - data[q + 1]) return o > 0 ? 1 : o < 0 ? -1 : 0 }
javascript
function orient (data, p, q, r) { var o = (data[q + 1] - data[p + 1]) * (data[r] - data[q]) - (data[q] - data[p]) * (data[r + 1] - data[q + 1]) return o > 0 ? 1 : o < 0 ? -1 : 0 }
[ "function", "orient", "(", "data", ",", "p", ",", "q", ",", "r", ")", "{", "var", "o", "=", "(", "data", "[", "q", "+", "1", "]", "-", "data", "[", "p", "+", "1", "]", ")", "*", "(", "data", "[", "r", "]", "-", "data", "[", "q", "]", ")", "-", "(", "data", "[", "q", "]", "-", "data", "[", "p", "]", ")", "*", "(", "data", "[", "r", "+", "1", "]", "-", "data", "[", "q", "+", "1", "]", ")", "return", "o", ">", "0", "?", "1", ":", "o", "<", "0", "?", "-", "1", ":", "0", "}" ]
winding order of triangle formed by 3 given points
[ "winding", "order", "of", "triangle", "formed", "by", "3", "given", "points" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/utils/data3d/buffer/triangulate-2d.js#L620-L623