id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
8,300 | jenkinsci/blueocean-plugin | bin/pretty.js | splitFilesIntoBatches | function splitFilesIntoBatches(files, config) {
// We need to specifiy a different parser for TS files
const configTS = Object.assign({}, config);
configTS.parser = 'typescript';
const batches = [];
batches.push({
files: files.filter(fileName => fileMatchesExtension(fileName, EXTENSIONS.js)),
config: config,
});
batches.push({
files: files.filter(fileName => fileMatchesExtension(fileName, EXTENSIONS.ts)),
config: configTS,
});
return batches;
} | javascript | function splitFilesIntoBatches(files, config) {
// We need to specifiy a different parser for TS files
const configTS = Object.assign({}, config);
configTS.parser = 'typescript';
const batches = [];
batches.push({
files: files.filter(fileName => fileMatchesExtension(fileName, EXTENSIONS.js)),
config: config,
});
batches.push({
files: files.filter(fileName => fileMatchesExtension(fileName, EXTENSIONS.ts)),
config: configTS,
});
return batches;
} | [
"function",
"splitFilesIntoBatches",
"(",
"files",
",",
"config",
")",
"{",
"// We need to specifiy a different parser for TS files",
"const",
"configTS",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"config",
")",
";",
"configTS",
".",
"parser",
"=",
"'typescript'",
";",
"const",
"batches",
"=",
"[",
"]",
";",
"batches",
".",
"push",
"(",
"{",
"files",
":",
"files",
".",
"filter",
"(",
"fileName",
"=>",
"fileMatchesExtension",
"(",
"fileName",
",",
"EXTENSIONS",
".",
"js",
")",
")",
",",
"config",
":",
"config",
",",
"}",
")",
";",
"batches",
".",
"push",
"(",
"{",
"files",
":",
"files",
".",
"filter",
"(",
"fileName",
"=>",
"fileMatchesExtension",
"(",
"fileName",
",",
"EXTENSIONS",
".",
"ts",
")",
")",
",",
"config",
":",
"configTS",
",",
"}",
")",
";",
"return",
"batches",
";",
"}"
] | Takes a list of files and initial config, and splits into two batches, each consisting of a subset of files and
the specific config for that batch. | [
"Takes",
"a",
"list",
"of",
"files",
"and",
"initial",
"config",
"and",
"splits",
"into",
"two",
"batches",
"each",
"consisting",
"of",
"a",
"subset",
"of",
"files",
"and",
"the",
"specific",
"config",
"for",
"that",
"batch",
"."
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/bin/pretty.js#L157-L175 |
8,301 | jenkinsci/blueocean-plugin | bin/pretty.js | prettifyBatches | function prettifyBatches(batches) {
return Promise.all(batches.map(({ files, config }) => prettifyFiles(files, config)));
} | javascript | function prettifyBatches(batches) {
return Promise.all(batches.map(({ files, config }) => prettifyFiles(files, config)));
} | [
"function",
"prettifyBatches",
"(",
"batches",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"batches",
".",
"map",
"(",
"(",
"{",
"files",
",",
"config",
"}",
")",
"=>",
"prettifyFiles",
"(",
"files",
",",
"config",
")",
")",
")",
";",
"}"
] | Runs prettifyFiles for each batch. | [
"Runs",
"prettifyFiles",
"for",
"each",
"batch",
"."
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/bin/pretty.js#L219-L221 |
8,302 | jenkinsci/blueocean-plugin | bin/pretty.js | mergeBatchResults | function mergeBatchResults(batches) {
let files = [];
let unformattedFiles = [];
let formattedFiles = [];
let errors = [];
batches.forEach(batch => {
files.push(...batch.files);
unformattedFiles.push(...batch.unformattedFiles);
formattedFiles.push(...batch.formattedFiles);
errors.push(...batch.errors);
});
return { files, formattedFiles, unformattedFiles, errors };
} | javascript | function mergeBatchResults(batches) {
let files = [];
let unformattedFiles = [];
let formattedFiles = [];
let errors = [];
batches.forEach(batch => {
files.push(...batch.files);
unformattedFiles.push(...batch.unformattedFiles);
formattedFiles.push(...batch.formattedFiles);
errors.push(...batch.errors);
});
return { files, formattedFiles, unformattedFiles, errors };
} | [
"function",
"mergeBatchResults",
"(",
"batches",
")",
"{",
"let",
"files",
"=",
"[",
"]",
";",
"let",
"unformattedFiles",
"=",
"[",
"]",
";",
"let",
"formattedFiles",
"=",
"[",
"]",
";",
"let",
"errors",
"=",
"[",
"]",
";",
"batches",
".",
"forEach",
"(",
"batch",
"=>",
"{",
"files",
".",
"push",
"(",
"...",
"batch",
".",
"files",
")",
";",
"unformattedFiles",
".",
"push",
"(",
"...",
"batch",
".",
"unformattedFiles",
")",
";",
"formattedFiles",
".",
"push",
"(",
"...",
"batch",
".",
"formattedFiles",
")",
";",
"errors",
".",
"push",
"(",
"...",
"batch",
".",
"errors",
")",
";",
"}",
")",
";",
"return",
"{",
"files",
",",
"formattedFiles",
",",
"unformattedFiles",
",",
"errors",
"}",
";",
"}"
] | Merge the results from each batch into a single result of the same format | [
"Merge",
"the",
"results",
"from",
"each",
"batch",
"into",
"a",
"single",
"result",
"of",
"the",
"same",
"format"
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/bin/pretty.js#L226-L240 |
8,303 | jenkinsci/blueocean-plugin | bin/pretty.js | showResults | function showResults(files, formattedFiles, unformattedFiles, errors) {
const formattedCount = formattedFiles.length;
const unformattedCount = unformattedFiles.length;
const errorCount = errors.length;
const filesCount = files.length;
const okCount = filesCount - formattedCount - unformattedCount - errorCount;
if (okCount > 0 && !simplifyOutput) {
console.log(okCount + ' of ' + filesCount + ' files already correct.');
}
if (formattedCount > 0) {
if (!simplifyOutput) {
console.log('Formatted ' + formattedCount + ' of ' + filesCount + ' files:');
}
for (const sourcePath of formattedFiles) {
if (simplifyOutput) {
console.log(sourcePath);
} else {
console.log(' - ' + sourcePath);
}
}
}
if (unformattedCount > 0) {
// Should only happen when !fixMode
console.error(unformattedCount + ' of ' + filesCount + ' files need formatting:');
for (const sourcePath of unformattedFiles) {
console.error(' - ' + sourcePath);
}
process.exitCode = 1;
}
if (errorCount > 0) {
console.error('\x1b[32mErrors occured processing ' + errorCount + ' of ' + filesCount + ' files.\x1b[m');
process.exitCode = -1;
}
return { formattedFiles, unformattedFiles };
} | javascript | function showResults(files, formattedFiles, unformattedFiles, errors) {
const formattedCount = formattedFiles.length;
const unformattedCount = unformattedFiles.length;
const errorCount = errors.length;
const filesCount = files.length;
const okCount = filesCount - formattedCount - unformattedCount - errorCount;
if (okCount > 0 && !simplifyOutput) {
console.log(okCount + ' of ' + filesCount + ' files already correct.');
}
if (formattedCount > 0) {
if (!simplifyOutput) {
console.log('Formatted ' + formattedCount + ' of ' + filesCount + ' files:');
}
for (const sourcePath of formattedFiles) {
if (simplifyOutput) {
console.log(sourcePath);
} else {
console.log(' - ' + sourcePath);
}
}
}
if (unformattedCount > 0) {
// Should only happen when !fixMode
console.error(unformattedCount + ' of ' + filesCount + ' files need formatting:');
for (const sourcePath of unformattedFiles) {
console.error(' - ' + sourcePath);
}
process.exitCode = 1;
}
if (errorCount > 0) {
console.error('\x1b[32mErrors occured processing ' + errorCount + ' of ' + filesCount + ' files.\x1b[m');
process.exitCode = -1;
}
return { formattedFiles, unformattedFiles };
} | [
"function",
"showResults",
"(",
"files",
",",
"formattedFiles",
",",
"unformattedFiles",
",",
"errors",
")",
"{",
"const",
"formattedCount",
"=",
"formattedFiles",
".",
"length",
";",
"const",
"unformattedCount",
"=",
"unformattedFiles",
".",
"length",
";",
"const",
"errorCount",
"=",
"errors",
".",
"length",
";",
"const",
"filesCount",
"=",
"files",
".",
"length",
";",
"const",
"okCount",
"=",
"filesCount",
"-",
"formattedCount",
"-",
"unformattedCount",
"-",
"errorCount",
";",
"if",
"(",
"okCount",
">",
"0",
"&&",
"!",
"simplifyOutput",
")",
"{",
"console",
".",
"log",
"(",
"okCount",
"+",
"' of '",
"+",
"filesCount",
"+",
"' files already correct.'",
")",
";",
"}",
"if",
"(",
"formattedCount",
">",
"0",
")",
"{",
"if",
"(",
"!",
"simplifyOutput",
")",
"{",
"console",
".",
"log",
"(",
"'Formatted '",
"+",
"formattedCount",
"+",
"' of '",
"+",
"filesCount",
"+",
"' files:'",
")",
";",
"}",
"for",
"(",
"const",
"sourcePath",
"of",
"formattedFiles",
")",
"{",
"if",
"(",
"simplifyOutput",
")",
"{",
"console",
".",
"log",
"(",
"sourcePath",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"' - '",
"+",
"sourcePath",
")",
";",
"}",
"}",
"}",
"if",
"(",
"unformattedCount",
">",
"0",
")",
"{",
"// Should only happen when !fixMode",
"console",
".",
"error",
"(",
"unformattedCount",
"+",
"' of '",
"+",
"filesCount",
"+",
"' files need formatting:'",
")",
";",
"for",
"(",
"const",
"sourcePath",
"of",
"unformattedFiles",
")",
"{",
"console",
".",
"error",
"(",
"' - '",
"+",
"sourcePath",
")",
";",
"}",
"process",
".",
"exitCode",
"=",
"1",
";",
"}",
"if",
"(",
"errorCount",
">",
"0",
")",
"{",
"console",
".",
"error",
"(",
"'\\x1b[32mErrors occured processing '",
"+",
"errorCount",
"+",
"' of '",
"+",
"filesCount",
"+",
"' files.\\x1b[m'",
")",
";",
"process",
".",
"exitCode",
"=",
"-",
"1",
";",
"}",
"return",
"{",
"formattedFiles",
",",
"unformattedFiles",
"}",
";",
"}"
] | Display results to user | [
"Display",
"results",
"to",
"user"
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/bin/pretty.js#L243-L282 |
8,304 | jenkinsci/blueocean-plugin | blueocean-dashboard/src/main/js/util/PromiseDelayUtils.js | delayReject | function delayReject(delay = 1000) {
const begin = time();
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (promise.payload) {
reject(promise.payload);
}
}, delay);
});
return function proceed(error) {
// if we haven't reached the delay yet, stash the payload
// so the setTimeout above will resolve it later
if (time() - begin < delay) {
promise.payload = error;
return promise;
}
throw error;
};
} | javascript | function delayReject(delay = 1000) {
const begin = time();
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (promise.payload) {
reject(promise.payload);
}
}, delay);
});
return function proceed(error) {
// if we haven't reached the delay yet, stash the payload
// so the setTimeout above will resolve it later
if (time() - begin < delay) {
promise.payload = error;
return promise;
}
throw error;
};
} | [
"function",
"delayReject",
"(",
"delay",
"=",
"1000",
")",
"{",
"const",
"begin",
"=",
"time",
"(",
")",
";",
"const",
"promise",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"promise",
".",
"payload",
")",
"{",
"reject",
"(",
"promise",
".",
"payload",
")",
";",
"}",
"}",
",",
"delay",
")",
";",
"}",
")",
";",
"return",
"function",
"proceed",
"(",
"error",
")",
"{",
"// if we haven't reached the delay yet, stash the payload",
"// so the setTimeout above will resolve it later",
"if",
"(",
"time",
"(",
")",
"-",
"begin",
"<",
"delay",
")",
"{",
"promise",
".",
"payload",
"=",
"error",
";",
"return",
"promise",
";",
"}",
"throw",
"error",
";",
"}",
";",
"}"
] | Returns a function that should be chained to a promise to reject it after the delay.
@param {number} [delay] millis to delay
@returns {function} rejection function to pass to 'then()' | [
"Returns",
"a",
"function",
"that",
"should",
"be",
"chained",
"to",
"a",
"promise",
"to",
"reject",
"it",
"after",
"the",
"delay",
"."
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/blueocean-dashboard/src/main/js/util/PromiseDelayUtils.js#L63-L84 |
8,305 | jenkinsci/blueocean-plugin | js-extensions/src/ExtensionUtils.js | sortByOrdinal | function sortByOrdinal(extensions, done) {
const sorted = extensions.sort((a, b) => {
if (a.ordinal || b.ordinal) {
if (!a.ordinal) return 1;
if (!b.ordinal) return -1;
if (a.ordinal < b.ordinal) return -1;
return 1;
}
return a.pluginId.localeCompare(b.pluginId);
});
if (done) {
done(sorted);
}
return sorted;
} | javascript | function sortByOrdinal(extensions, done) {
const sorted = extensions.sort((a, b) => {
if (a.ordinal || b.ordinal) {
if (!a.ordinal) return 1;
if (!b.ordinal) return -1;
if (a.ordinal < b.ordinal) return -1;
return 1;
}
return a.pluginId.localeCompare(b.pluginId);
});
if (done) {
done(sorted);
}
return sorted;
} | [
"function",
"sortByOrdinal",
"(",
"extensions",
",",
"done",
")",
"{",
"const",
"sorted",
"=",
"extensions",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"a",
".",
"ordinal",
"||",
"b",
".",
"ordinal",
")",
"{",
"if",
"(",
"!",
"a",
".",
"ordinal",
")",
"return",
"1",
";",
"if",
"(",
"!",
"b",
".",
"ordinal",
")",
"return",
"-",
"1",
";",
"if",
"(",
"a",
".",
"ordinal",
"<",
"b",
".",
"ordinal",
")",
"return",
"-",
"1",
";",
"return",
"1",
";",
"}",
"return",
"a",
".",
"pluginId",
".",
"localeCompare",
"(",
"b",
".",
"pluginId",
")",
";",
"}",
")",
";",
"if",
"(",
"done",
")",
"{",
"done",
"(",
"sorted",
")",
";",
"}",
"return",
"sorted",
";",
"}"
] | Sort extensions by ordinal if defined, then fallback to pluginId.
@param extensions
@param [done] | [
"Sort",
"extensions",
"by",
"ordinal",
"if",
"defined",
"then",
"fallback",
"to",
"pluginId",
"."
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/js-extensions/src/ExtensionUtils.js#L6-L22 |
8,306 | jenkinsci/blueocean-plugin | blueocean-core-js/src/js/parameter/rest/ParameterApi.js | prepareOptions | function prepareOptions(body) {
const fetchOptions = Object.assign({}, fetchOptionsCommon);
if (body) {
try {
fetchOptions.body = JSON.stringify(body);
} catch (e) {
console.warn('The form body are not added. Could not extract data from the body element', body);
}
}
return fetchOptions;
} | javascript | function prepareOptions(body) {
const fetchOptions = Object.assign({}, fetchOptionsCommon);
if (body) {
try {
fetchOptions.body = JSON.stringify(body);
} catch (e) {
console.warn('The form body are not added. Could not extract data from the body element', body);
}
}
return fetchOptions;
} | [
"function",
"prepareOptions",
"(",
"body",
")",
"{",
"const",
"fetchOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"fetchOptionsCommon",
")",
";",
"if",
"(",
"body",
")",
"{",
"try",
"{",
"fetchOptions",
".",
"body",
"=",
"JSON",
".",
"stringify",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"warn",
"(",
"'The form body are not added. Could not extract data from the body element'",
",",
"body",
")",
";",
"}",
"}",
"return",
"fetchOptions",
";",
"}"
] | Helper method to clone and prepare the body if attached
@param body - JSON object that we want to sent to the server
@returns {*} fetchOptions | [
"Helper",
"method",
"to",
"clone",
"and",
"prepare",
"the",
"body",
"if",
"attached"
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/blueocean-core-js/src/js/parameter/rest/ParameterApi.js#L18-L28 |
8,307 | jenkinsci/blueocean-plugin | jenkins-design-language/bin/import-material-icons.js | validateSourcePath | function validateSourcePath(sourcePath) {
const materialPackageJSONPath = pathUtils.resolve(sourcePath, 'package.json');
return fs.readFileAsync(materialPackageJSONPath, { encoding: 'UTF8' })
.then(materialPackageJSONString => {
const package = JSON.parse(materialPackageJSONString);
if (package.name !== sourcePackageName) {
throw new Error(`Source path ${sourcePath} does not appear to be a clone of https://github.com/callemall/material-ui`);
}
return sourcePath;
});
} | javascript | function validateSourcePath(sourcePath) {
const materialPackageJSONPath = pathUtils.resolve(sourcePath, 'package.json');
return fs.readFileAsync(materialPackageJSONPath, { encoding: 'UTF8' })
.then(materialPackageJSONString => {
const package = JSON.parse(materialPackageJSONString);
if (package.name !== sourcePackageName) {
throw new Error(`Source path ${sourcePath} does not appear to be a clone of https://github.com/callemall/material-ui`);
}
return sourcePath;
});
} | [
"function",
"validateSourcePath",
"(",
"sourcePath",
")",
"{",
"const",
"materialPackageJSONPath",
"=",
"pathUtils",
".",
"resolve",
"(",
"sourcePath",
",",
"'package.json'",
")",
";",
"return",
"fs",
".",
"readFileAsync",
"(",
"materialPackageJSONPath",
",",
"{",
"encoding",
":",
"'UTF8'",
"}",
")",
".",
"then",
"(",
"materialPackageJSONString",
"=>",
"{",
"const",
"package",
"=",
"JSON",
".",
"parse",
"(",
"materialPackageJSONString",
")",
";",
"if",
"(",
"package",
".",
"name",
"!==",
"sourcePackageName",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"sourcePath",
"}",
"`",
")",
";",
"}",
"return",
"sourcePath",
";",
"}",
")",
";",
"}"
] | Make sure the source path is correct in that it exists and appears to point to the root of the repo we want. | [
"Make",
"sure",
"the",
"source",
"path",
"is",
"correct",
"in",
"that",
"it",
"exists",
"and",
"appears",
"to",
"point",
"to",
"the",
"root",
"of",
"the",
"repo",
"we",
"want",
"."
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/jenkins-design-language/bin/import-material-icons.js#L119-L130 |
8,308 | jenkinsci/blueocean-plugin | jenkins-design-language/bin/import-material-icons.js | findSourceFiles | function findSourceFiles(sourceIconsRoot) {
let visitedDirectories = [];
let allSourceFiles = [];
function recurseDir(dir, depth) {
// Don't get in any loops
if (visitedDirectories.indexOf(dir) !== -1) {
return;
}
if (depth > 3) {
throw new Error('findSourceFiles() - directory tree too deep');
}
visitedDirectories.push(dir);
return fs.readdirAsync(dir)
.then(filenames => {
// Turn the list of filenames into paths
const paths = filenames
.filter(filename => filename[0] !== '.' && filename !== 'index.js') // Ignore index, hidden, '.' and '..'
.map(filename => pathUtils.resolve(dir, filename));
// For each path...
const statPromises = paths.map(filePath => {
return fs.statAsync(filePath) // ... get stats
.then(stats => ({ filePath, stats })); // ... and associate with path
});
// Turn the array of promises into a promise of arrays.
return Promise.all(statPromises);
})
.then(filePathsAndStats => {
// Pick out all the JS files in dir, while collecting the list of subdirectories
let subDirPaths = [];
for (const { filePath, stats } of filePathsAndStats) {
if (stats.isDirectory()) {
subDirPaths.push(filePath);
}
else if (stats.isFile() && pathUtils.extname(filePath).toLowerCase() === '.js') {
allSourceFiles.push(filePath);
}
}
if (subDirPaths.length === 0) {
return;
}
// Recurse
return Promise.all(subDirPaths.map(path => recurseDir(path, depth + 1)));
});
}
return recurseDir(sourceIconsRoot, 0).then(() => allSourceFiles);
} | javascript | function findSourceFiles(sourceIconsRoot) {
let visitedDirectories = [];
let allSourceFiles = [];
function recurseDir(dir, depth) {
// Don't get in any loops
if (visitedDirectories.indexOf(dir) !== -1) {
return;
}
if (depth > 3) {
throw new Error('findSourceFiles() - directory tree too deep');
}
visitedDirectories.push(dir);
return fs.readdirAsync(dir)
.then(filenames => {
// Turn the list of filenames into paths
const paths = filenames
.filter(filename => filename[0] !== '.' && filename !== 'index.js') // Ignore index, hidden, '.' and '..'
.map(filename => pathUtils.resolve(dir, filename));
// For each path...
const statPromises = paths.map(filePath => {
return fs.statAsync(filePath) // ... get stats
.then(stats => ({ filePath, stats })); // ... and associate with path
});
// Turn the array of promises into a promise of arrays.
return Promise.all(statPromises);
})
.then(filePathsAndStats => {
// Pick out all the JS files in dir, while collecting the list of subdirectories
let subDirPaths = [];
for (const { filePath, stats } of filePathsAndStats) {
if (stats.isDirectory()) {
subDirPaths.push(filePath);
}
else if (stats.isFile() && pathUtils.extname(filePath).toLowerCase() === '.js') {
allSourceFiles.push(filePath);
}
}
if (subDirPaths.length === 0) {
return;
}
// Recurse
return Promise.all(subDirPaths.map(path => recurseDir(path, depth + 1)));
});
}
return recurseDir(sourceIconsRoot, 0).then(() => allSourceFiles);
} | [
"function",
"findSourceFiles",
"(",
"sourceIconsRoot",
")",
"{",
"let",
"visitedDirectories",
"=",
"[",
"]",
";",
"let",
"allSourceFiles",
"=",
"[",
"]",
";",
"function",
"recurseDir",
"(",
"dir",
",",
"depth",
")",
"{",
"// Don't get in any loops",
"if",
"(",
"visitedDirectories",
".",
"indexOf",
"(",
"dir",
")",
"!==",
"-",
"1",
")",
"{",
"return",
";",
"}",
"if",
"(",
"depth",
">",
"3",
")",
"{",
"throw",
"new",
"Error",
"(",
"'findSourceFiles() - directory tree too deep'",
")",
";",
"}",
"visitedDirectories",
".",
"push",
"(",
"dir",
")",
";",
"return",
"fs",
".",
"readdirAsync",
"(",
"dir",
")",
".",
"then",
"(",
"filenames",
"=>",
"{",
"// Turn the list of filenames into paths",
"const",
"paths",
"=",
"filenames",
".",
"filter",
"(",
"filename",
"=>",
"filename",
"[",
"0",
"]",
"!==",
"'.'",
"&&",
"filename",
"!==",
"'index.js'",
")",
"// Ignore index, hidden, '.' and '..'",
".",
"map",
"(",
"filename",
"=>",
"pathUtils",
".",
"resolve",
"(",
"dir",
",",
"filename",
")",
")",
";",
"// For each path...",
"const",
"statPromises",
"=",
"paths",
".",
"map",
"(",
"filePath",
"=>",
"{",
"return",
"fs",
".",
"statAsync",
"(",
"filePath",
")",
"// ... get stats",
".",
"then",
"(",
"stats",
"=>",
"(",
"{",
"filePath",
",",
"stats",
"}",
")",
")",
";",
"// ... and associate with path",
"}",
")",
";",
"// Turn the array of promises into a promise of arrays.",
"return",
"Promise",
".",
"all",
"(",
"statPromises",
")",
";",
"}",
")",
".",
"then",
"(",
"filePathsAndStats",
"=>",
"{",
"// Pick out all the JS files in dir, while collecting the list of subdirectories",
"let",
"subDirPaths",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"{",
"filePath",
",",
"stats",
"}",
"of",
"filePathsAndStats",
")",
"{",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"subDirPaths",
".",
"push",
"(",
"filePath",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
"&&",
"pathUtils",
".",
"extname",
"(",
"filePath",
")",
".",
"toLowerCase",
"(",
")",
"===",
"'.js'",
")",
"{",
"allSourceFiles",
".",
"push",
"(",
"filePath",
")",
";",
"}",
"}",
"if",
"(",
"subDirPaths",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"// Recurse",
"return",
"Promise",
".",
"all",
"(",
"subDirPaths",
".",
"map",
"(",
"path",
"=>",
"recurseDir",
"(",
"path",
",",
"depth",
"+",
"1",
")",
")",
")",
";",
"}",
")",
";",
"}",
"return",
"recurseDir",
"(",
"sourceIconsRoot",
",",
"0",
")",
".",
"then",
"(",
"(",
")",
"=>",
"allSourceFiles",
")",
";",
"}"
] | Traverse the tree starting at sourcePath, and find all the .js files.
Only goes 3 levels deep, will throw if it gives up due to tree depth.
Kind of ugly, but better than pulling in some npm module with 45 transitive dependencies. Please let me know if
there's a nicer way to do this! - JM | [
"Traverse",
"the",
"tree",
"starting",
"at",
"sourcePath",
"and",
"find",
"all",
"the",
".",
"js",
"files",
"."
] | 6e87cc0e76449669a942d66a9391cd7a46a943e0 | https://github.com/jenkinsci/blueocean-plugin/blob/6e87cc0e76449669a942d66a9391cd7a46a943e0/jenkins-design-language/bin/import-material-icons.js#L140-L196 |
8,309 | toji/gl-matrix | spec/helpers/spec-helper.js | function(a, epsilon) {
if(epsilon == undefined) epsilon = EPSILON;
let allSignsFlipped = false;
if (e.length != a.length)
expected(e, "to have the same length as", a);
for (let i = 0; i < e.length; i++) {
if (isNaN(e[i]) !== isNaN(a[i]))
expected(e, "to be equalish to", a);
if (allSignsFlipped) {
if (Math.abs(e[i] - (-a[i])) >= epsilon)
expected(e, "to be equalish to", a);
} else {
if (Math.abs(e[i] - a[i]) >= epsilon) {
allSignsFlipped = true;
i = 0;
}
}
}
} | javascript | function(a, epsilon) {
if(epsilon == undefined) epsilon = EPSILON;
let allSignsFlipped = false;
if (e.length != a.length)
expected(e, "to have the same length as", a);
for (let i = 0; i < e.length; i++) {
if (isNaN(e[i]) !== isNaN(a[i]))
expected(e, "to be equalish to", a);
if (allSignsFlipped) {
if (Math.abs(e[i] - (-a[i])) >= epsilon)
expected(e, "to be equalish to", a);
} else {
if (Math.abs(e[i] - a[i]) >= epsilon) {
allSignsFlipped = true;
i = 0;
}
}
}
} | [
"function",
"(",
"a",
",",
"epsilon",
")",
"{",
"if",
"(",
"epsilon",
"==",
"undefined",
")",
"epsilon",
"=",
"EPSILON",
";",
"let",
"allSignsFlipped",
"=",
"false",
";",
"if",
"(",
"e",
".",
"length",
"!=",
"a",
".",
"length",
")",
"expected",
"(",
"e",
",",
"\"to have the same length as\"",
",",
"a",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"e",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isNaN",
"(",
"e",
"[",
"i",
"]",
")",
"!==",
"isNaN",
"(",
"a",
"[",
"i",
"]",
")",
")",
"expected",
"(",
"e",
",",
"\"to be equalish to\"",
",",
"a",
")",
";",
"if",
"(",
"allSignsFlipped",
")",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"e",
"[",
"i",
"]",
"-",
"(",
"-",
"a",
"[",
"i",
"]",
")",
")",
">=",
"epsilon",
")",
"expected",
"(",
"e",
",",
"\"to be equalish to\"",
",",
"a",
")",
";",
"}",
"else",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"e",
"[",
"i",
"]",
"-",
"a",
"[",
"i",
"]",
")",
">=",
"epsilon",
")",
"{",
"allSignsFlipped",
"=",
"true",
";",
"i",
"=",
"0",
";",
"}",
"}",
"}",
"}"
] | Dual quaternions are very special & unique snowflakes | [
"Dual",
"quaternions",
"are",
"very",
"special",
"&",
"unique",
"snowflakes"
] | 9ea87effc0ca32feb8511a01685ee596c6160fcc | https://github.com/toji/gl-matrix/blob/9ea87effc0ca32feb8511a01685ee596c6160fcc/spec/helpers/spec-helper.js#L86-L106 |
|
8,310 | optimizely/nuclear-js | examples/rest-api/src/modules/rest-api/create-api-actions.js | onDeleteSuccess | function onDeleteSuccess(model, params, result) {
Flux.dispatch(actionTypes.API_DELETE_SUCCESS, {
model: model,
params: params,
result: result,
})
return result
} | javascript | function onDeleteSuccess(model, params, result) {
Flux.dispatch(actionTypes.API_DELETE_SUCCESS, {
model: model,
params: params,
result: result,
})
return result
} | [
"function",
"onDeleteSuccess",
"(",
"model",
",",
"params",
",",
"result",
")",
"{",
"Flux",
".",
"dispatch",
"(",
"actionTypes",
".",
"API_DELETE_SUCCESS",
",",
"{",
"model",
":",
"model",
",",
"params",
":",
"params",
",",
"result",
":",
"result",
",",
"}",
")",
"return",
"result",
"}"
] | Handler for API delete success, dispatches flux action to remove the instance from the stores
@param {Model} model
@param {*} params used to call the `model.delete(params)`
@param {Object} result
@return {Object} | [
"Handler",
"for",
"API",
"delete",
"success",
"dispatches",
"flux",
"action",
"to",
"remove",
"the",
"instance",
"from",
"the",
"stores"
] | 102fe399c8730375dece7711c66f1d46c860f5ae | https://github.com/optimizely/nuclear-js/blob/102fe399c8730375dece7711c66f1d46c860f5ae/examples/rest-api/src/modules/rest-api/create-api-actions.js#L140-L147 |
8,311 | optimizely/nuclear-js | examples/rest-api/src/modules/rest-api/create-api-actions.js | onDeleteFail | function onDeleteFail(model, params, reason) {
Flux.dispatch(actionTypes.API_DELETE_FAIL, {
model: model,
params: params,
reason: reason,
})
return Promise.reject(reason)
} | javascript | function onDeleteFail(model, params, reason) {
Flux.dispatch(actionTypes.API_DELETE_FAIL, {
model: model,
params: params,
reason: reason,
})
return Promise.reject(reason)
} | [
"function",
"onDeleteFail",
"(",
"model",
",",
"params",
",",
"reason",
")",
"{",
"Flux",
".",
"dispatch",
"(",
"actionTypes",
".",
"API_DELETE_FAIL",
",",
"{",
"model",
":",
"model",
",",
"params",
":",
"params",
",",
"reason",
":",
"reason",
",",
"}",
")",
"return",
"Promise",
".",
"reject",
"(",
"reason",
")",
"}"
] | Handler for API delete fail
@param {Model} model
@param {*} params used to call the `model.delete(params)`
@param {Object} result
@return {Object} | [
"Handler",
"for",
"API",
"delete",
"fail"
] | 102fe399c8730375dece7711c66f1d46c860f5ae | https://github.com/optimizely/nuclear-js/blob/102fe399c8730375dece7711c66f1d46c860f5ae/examples/rest-api/src/modules/rest-api/create-api-actions.js#L156-L163 |
8,312 | optimizely/nuclear-js | src/getter.js | getFlattenedDeps | function getFlattenedDeps(getter, existing) {
if (!existing) {
existing = Immutable.Set()
}
const toAdd = Immutable.Set().withMutations(set => {
if (!isGetter(getter)) {
throw new Error('getFlattenedDeps must be passed a Getter')
}
getDeps(getter).forEach(dep => {
if (isKeyPath(dep)) {
set.add(List(dep))
} else if (isGetter(dep)) {
set.union(getFlattenedDeps(dep))
} else {
throw new Error('Invalid getter, each dependency must be a KeyPath or Getter')
}
})
})
return existing.union(toAdd)
} | javascript | function getFlattenedDeps(getter, existing) {
if (!existing) {
existing = Immutable.Set()
}
const toAdd = Immutable.Set().withMutations(set => {
if (!isGetter(getter)) {
throw new Error('getFlattenedDeps must be passed a Getter')
}
getDeps(getter).forEach(dep => {
if (isKeyPath(dep)) {
set.add(List(dep))
} else if (isGetter(dep)) {
set.union(getFlattenedDeps(dep))
} else {
throw new Error('Invalid getter, each dependency must be a KeyPath or Getter')
}
})
})
return existing.union(toAdd)
} | [
"function",
"getFlattenedDeps",
"(",
"getter",
",",
"existing",
")",
"{",
"if",
"(",
"!",
"existing",
")",
"{",
"existing",
"=",
"Immutable",
".",
"Set",
"(",
")",
"}",
"const",
"toAdd",
"=",
"Immutable",
".",
"Set",
"(",
")",
".",
"withMutations",
"(",
"set",
"=>",
"{",
"if",
"(",
"!",
"isGetter",
"(",
"getter",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'getFlattenedDeps must be passed a Getter'",
")",
"}",
"getDeps",
"(",
"getter",
")",
".",
"forEach",
"(",
"dep",
"=>",
"{",
"if",
"(",
"isKeyPath",
"(",
"dep",
")",
")",
"{",
"set",
".",
"add",
"(",
"List",
"(",
"dep",
")",
")",
"}",
"else",
"if",
"(",
"isGetter",
"(",
"dep",
")",
")",
"{",
"set",
".",
"union",
"(",
"getFlattenedDeps",
"(",
"dep",
")",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid getter, each dependency must be a KeyPath or Getter'",
")",
"}",
"}",
")",
"}",
")",
"return",
"existing",
".",
"union",
"(",
"toAdd",
")",
"}"
] | Returns an array of deps from a getter and all its deps
@param {Getter} getter
@param {Immutable.Set} existing
@return {Immutable.Set} | [
"Returns",
"an",
"array",
"of",
"deps",
"from",
"a",
"getter",
"and",
"all",
"its",
"deps"
] | 102fe399c8730375dece7711c66f1d46c860f5ae | https://github.com/optimizely/nuclear-js/blob/102fe399c8730375dece7711c66f1d46c860f5ae/src/getter.js#L45-L67 |
8,313 | optimizely/nuclear-js | src/reactor/fns.js | createCacheEntry | function createCacheEntry(reactorState, getter) {
// evaluate dependencies
const args = getDeps(getter).map(dep => evaluate(reactorState, dep).result)
const value = getComputeFn(getter).apply(null, args)
const storeDeps = getStoreDeps(getter)
const storeStates = toImmutable({}).withMutations(map => {
storeDeps.forEach(storeId => {
const stateId = reactorState.getIn(['storeStates', storeId])
map.set(storeId, stateId)
})
})
return CacheEntry({
value: value,
storeStates: storeStates,
dispatchId: reactorState.get('dispatchId'),
})
} | javascript | function createCacheEntry(reactorState, getter) {
// evaluate dependencies
const args = getDeps(getter).map(dep => evaluate(reactorState, dep).result)
const value = getComputeFn(getter).apply(null, args)
const storeDeps = getStoreDeps(getter)
const storeStates = toImmutable({}).withMutations(map => {
storeDeps.forEach(storeId => {
const stateId = reactorState.getIn(['storeStates', storeId])
map.set(storeId, stateId)
})
})
return CacheEntry({
value: value,
storeStates: storeStates,
dispatchId: reactorState.get('dispatchId'),
})
} | [
"function",
"createCacheEntry",
"(",
"reactorState",
",",
"getter",
")",
"{",
"// evaluate dependencies",
"const",
"args",
"=",
"getDeps",
"(",
"getter",
")",
".",
"map",
"(",
"dep",
"=>",
"evaluate",
"(",
"reactorState",
",",
"dep",
")",
".",
"result",
")",
"const",
"value",
"=",
"getComputeFn",
"(",
"getter",
")",
".",
"apply",
"(",
"null",
",",
"args",
")",
"const",
"storeDeps",
"=",
"getStoreDeps",
"(",
"getter",
")",
"const",
"storeStates",
"=",
"toImmutable",
"(",
"{",
"}",
")",
".",
"withMutations",
"(",
"map",
"=>",
"{",
"storeDeps",
".",
"forEach",
"(",
"storeId",
"=>",
"{",
"const",
"stateId",
"=",
"reactorState",
".",
"getIn",
"(",
"[",
"'storeStates'",
",",
"storeId",
"]",
")",
"map",
".",
"set",
"(",
"storeId",
",",
"stateId",
")",
"}",
")",
"}",
")",
"return",
"CacheEntry",
"(",
"{",
"value",
":",
"value",
",",
"storeStates",
":",
"storeStates",
",",
"dispatchId",
":",
"reactorState",
".",
"get",
"(",
"'dispatchId'",
")",
",",
"}",
")",
"}"
] | Evaluates getter for given reactorState and returns CacheEntry
@param {ReactorState} reactorState
@param {Getter} getter
@return {CacheEntry} | [
"Evaluates",
"getter",
"for",
"given",
"reactorState",
"and",
"returns",
"CacheEntry"
] | 102fe399c8730375dece7711c66f1d46c860f5ae | https://github.com/optimizely/nuclear-js/blob/102fe399c8730375dece7711c66f1d46c860f5ae/src/reactor/fns.js#L408-L426 |
8,314 | optimizely/nuclear-js | examples/flux-chat/js/modules/chat/stores/thread-store.js | setMessagesRead | function setMessagesRead(state, { threadID }) {
return state.updateIn([threadID, 'messages'], messages => {
return messages.map(msg => msg.set('isRead', true))
})
} | javascript | function setMessagesRead(state, { threadID }) {
return state.updateIn([threadID, 'messages'], messages => {
return messages.map(msg => msg.set('isRead', true))
})
} | [
"function",
"setMessagesRead",
"(",
"state",
",",
"{",
"threadID",
"}",
")",
"{",
"return",
"state",
".",
"updateIn",
"(",
"[",
"threadID",
",",
"'messages'",
"]",
",",
"messages",
"=>",
"{",
"return",
"messages",
".",
"map",
"(",
"msg",
"=>",
"msg",
".",
"set",
"(",
"'isRead'",
",",
"true",
")",
")",
"}",
")",
"}"
] | Mark all messages for a thread as "read"
@param {Immutable.Map}
@param {Object} payload
@param {GUID} payload.threadID | [
"Mark",
"all",
"messages",
"for",
"a",
"thread",
"as",
"read"
] | 102fe399c8730375dece7711c66f1d46c860f5ae | https://github.com/optimizely/nuclear-js/blob/102fe399c8730375dece7711c66f1d46c860f5ae/examples/flux-chat/js/modules/chat/stores/thread-store.js#L66-L70 |
8,315 | mipengine/mip2 | packages/mip/src/performance.js | removeFsElement | function removeFsElement (element) {
let index = fsElements.indexOf(element)
if (index !== -1) {
fsElements.splice(index, 1)
}
} | javascript | function removeFsElement (element) {
let index = fsElements.indexOf(element)
if (index !== -1) {
fsElements.splice(index, 1)
}
} | [
"function",
"removeFsElement",
"(",
"element",
")",
"{",
"let",
"index",
"=",
"fsElements",
".",
"indexOf",
"(",
"element",
")",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"fsElements",
".",
"splice",
"(",
"index",
",",
"1",
")",
"}",
"}"
] | Remove element from fsElements.
@param {HTMLElement} element html element | [
"Remove",
"element",
"from",
"fsElements",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/performance.js#L66-L71 |
8,316 | mipengine/mip2 | packages/mip/src/performance.js | getTiming | function getTiming () {
let nativeTiming
let performance = window.performance
if (performance && performance.timing) {
nativeTiming = performance.timing.toJSON
? performance.timing.toJSON()
: util.fn.extend({}, performance.timing)
} else {
nativeTiming = {}
}
return util.fn.extend(nativeTiming, recorder)
} | javascript | function getTiming () {
let nativeTiming
let performance = window.performance
if (performance && performance.timing) {
nativeTiming = performance.timing.toJSON
? performance.timing.toJSON()
: util.fn.extend({}, performance.timing)
} else {
nativeTiming = {}
}
return util.fn.extend(nativeTiming, recorder)
} | [
"function",
"getTiming",
"(",
")",
"{",
"let",
"nativeTiming",
"let",
"performance",
"=",
"window",
".",
"performance",
"if",
"(",
"performance",
"&&",
"performance",
".",
"timing",
")",
"{",
"nativeTiming",
"=",
"performance",
".",
"timing",
".",
"toJSON",
"?",
"performance",
".",
"timing",
".",
"toJSON",
"(",
")",
":",
"util",
".",
"fn",
".",
"extend",
"(",
"{",
"}",
",",
"performance",
".",
"timing",
")",
"}",
"else",
"{",
"nativeTiming",
"=",
"{",
"}",
"}",
"return",
"util",
".",
"fn",
".",
"extend",
"(",
"nativeTiming",
",",
"recorder",
")",
"}"
] | Get the timings.
@return {Object} | [
"Get",
"the",
"timings",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/performance.js#L78-L89 |
8,317 | mipengine/mip2 | packages/mip/src/performance.js | recordTiming | function recordTiming (name, timing) {
recorder[name] = parseInt(timing, 10) || Date.now()
performanceEvent.trigger('update', getTiming())
} | javascript | function recordTiming (name, timing) {
recorder[name] = parseInt(timing, 10) || Date.now()
performanceEvent.trigger('update', getTiming())
} | [
"function",
"recordTiming",
"(",
"name",
",",
"timing",
")",
"{",
"recorder",
"[",
"name",
"]",
"=",
"parseInt",
"(",
"timing",
",",
"10",
")",
"||",
"Date",
".",
"now",
"(",
")",
"performanceEvent",
".",
"trigger",
"(",
"'update'",
",",
"getTiming",
"(",
")",
")",
"}"
] | Record timing by name.
@param {string} name Name of the timing.
@param {?number} timing timing | [
"Record",
"timing",
"by",
"name",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/performance.js#L97-L100 |
8,318 | mipengine/mip2 | packages/mip/src/performance.js | lockFirstScreen | function lockFirstScreen () {
// when is prerendering, iframe container display none,
// all elements are not in viewport.
if (prerender.isPrerendering) {
return
}
let viewportRect = viewport.getRect()
fsElements = fsElements.filter((element) => {
if (prerender.isPrerendered) {
return element._resources.isInViewport(element, viewportRect)
}
return element.inViewport()
}).map((element) => {
element.setAttribute('mip-firstscreen-element', '')
return element
})
fsElementsLocked = true
tryRecordFirstScreen()
!prerender.isPrerendered && firstScreenLabel.sendLog()
} | javascript | function lockFirstScreen () {
// when is prerendering, iframe container display none,
// all elements are not in viewport.
if (prerender.isPrerendering) {
return
}
let viewportRect = viewport.getRect()
fsElements = fsElements.filter((element) => {
if (prerender.isPrerendered) {
return element._resources.isInViewport(element, viewportRect)
}
return element.inViewport()
}).map((element) => {
element.setAttribute('mip-firstscreen-element', '')
return element
})
fsElementsLocked = true
tryRecordFirstScreen()
!prerender.isPrerendered && firstScreenLabel.sendLog()
} | [
"function",
"lockFirstScreen",
"(",
")",
"{",
"// when is prerendering, iframe container display none,",
"// all elements are not in viewport.",
"if",
"(",
"prerender",
".",
"isPrerendering",
")",
"{",
"return",
"}",
"let",
"viewportRect",
"=",
"viewport",
".",
"getRect",
"(",
")",
"fsElements",
"=",
"fsElements",
".",
"filter",
"(",
"(",
"element",
")",
"=>",
"{",
"if",
"(",
"prerender",
".",
"isPrerendered",
")",
"{",
"return",
"element",
".",
"_resources",
".",
"isInViewport",
"(",
"element",
",",
"viewportRect",
")",
"}",
"return",
"element",
".",
"inViewport",
"(",
")",
"}",
")",
".",
"map",
"(",
"(",
"element",
")",
"=>",
"{",
"element",
".",
"setAttribute",
"(",
"'mip-firstscreen-element'",
",",
"''",
")",
"return",
"element",
"}",
")",
"fsElementsLocked",
"=",
"true",
"tryRecordFirstScreen",
"(",
")",
"!",
"prerender",
".",
"isPrerendered",
"&&",
"firstScreenLabel",
".",
"sendLog",
"(",
")",
"}"
] | Lock the fsElements. No longer add fsElements. | [
"Lock",
"the",
"fsElements",
".",
"No",
"longer",
"add",
"fsElements",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/performance.js#L115-L134 |
8,319 | mipengine/mip2 | packages/mip/src/register-element.js | loadCss | function loadCss (css, name) {
if (css) {
cssLoader.insertStyleElement(document, document.head, css, name, false)
}
} | javascript | function loadCss (css, name) {
if (css) {
cssLoader.insertStyleElement(document, document.head, css, name, false)
}
} | [
"function",
"loadCss",
"(",
"css",
",",
"name",
")",
"{",
"if",
"(",
"css",
")",
"{",
"cssLoader",
".",
"insertStyleElement",
"(",
"document",
",",
"document",
".",
"head",
",",
"css",
",",
"name",
",",
"false",
")",
"}",
"}"
] | Add a style tag to head by csstext
@param {string} css Css code
@param {string} name name | [
"Add",
"a",
"style",
"tag",
"to",
"head",
"by",
"csstext"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/register-element.js#L16-L20 |
8,320 | mipengine/mip2 | packages/mip/src/util/hash.js | ssEnabled | function ssEnabled () {
let support = false
try {
window.sessionStorage.setItem('_t', 1)
window.sessionStorage.removeItem('_t')
support = true
} catch (e) {}
return support
} | javascript | function ssEnabled () {
let support = false
try {
window.sessionStorage.setItem('_t', 1)
window.sessionStorage.removeItem('_t')
support = true
} catch (e) {}
return support
} | [
"function",
"ssEnabled",
"(",
")",
"{",
"let",
"support",
"=",
"false",
"try",
"{",
"window",
".",
"sessionStorage",
".",
"setItem",
"(",
"'_t'",
",",
"1",
")",
"window",
".",
"sessionStorage",
".",
"removeItem",
"(",
"'_t'",
")",
"support",
"=",
"true",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"support",
"}"
] | test ss is available
@return {boolean} whether enabled or not | [
"test",
"ss",
"is",
"available"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/hash.js#L150-L159 |
8,321 | mipengine/mip2 | packages/mip/src/vue/core/observer/index.js | dependArray | function dependArray (value) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
} | javascript | function dependArray (value) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
} | [
"function",
"dependArray",
"(",
"value",
")",
"{",
"for",
"(",
"let",
"e",
",",
"i",
"=",
"0",
",",
"l",
"=",
"value",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"e",
"=",
"value",
"[",
"i",
"]",
"e",
"&&",
"e",
".",
"__ob__",
"&&",
"e",
".",
"__ob__",
".",
"dep",
".",
"depend",
"(",
")",
"if",
"(",
"Array",
".",
"isArray",
"(",
"e",
")",
")",
"{",
"dependArray",
"(",
"e",
")",
"}",
"}",
"}"
] | Collect dependencies on array elements when the array is touched, since
we cannot intercept array element access like property getters. | [
"Collect",
"dependencies",
"on",
"array",
"elements",
"when",
"the",
"array",
"is",
"touched",
"since",
"we",
"cannot",
"intercept",
"array",
"element",
"access",
"like",
"property",
"getters",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/vue/core/observer/index.js#L268-L276 |
8,322 | mipengine/mip2 | packages/mip/src/mip1-polyfill/customElement.js | function () {
function impl (element) {
customElement.call(this, element)
}
impl.prototype = Object.create(customElement.prototype)
return impl
} | javascript | function () {
function impl (element) {
customElement.call(this, element)
}
impl.prototype = Object.create(customElement.prototype)
return impl
} | [
"function",
"(",
")",
"{",
"function",
"impl",
"(",
"element",
")",
"{",
"customElement",
".",
"call",
"(",
"this",
",",
"element",
")",
"}",
"impl",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"customElement",
".",
"prototype",
")",
"return",
"impl",
"}"
] | Create a class of a new type mip element
@return {Function} | [
"Create",
"a",
"class",
"of",
"a",
"new",
"type",
"mip",
"element"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/mip1-polyfill/customElement.js#L155-L161 |
|
8,323 | mipengine/mip2 | packages/mip/src/components/mip-shell/switchPage.js | forwardTransitionAndCreate | function forwardTransitionAndCreate (shell, options) {
let {sourcePageId, targetPageId, targetPageMeta, onComplete} = options
let loading = getLoading(targetPageMeta, {transitionContainsHeader: shell.transitionContainsHeader})
loading.classList.add('slide-enter', 'slide-enter-active')
css(loading, 'display', 'block')
let headerLogoTitle
let fadeHeader
if (!shell.transitionContainsHeader) {
headerLogoTitle = document.querySelector('.mip-shell-header-wrapper .mip-shell-header-logo-title')
headerLogoTitle && headerLogoTitle.classList.add('fade-out')
fadeHeader = getFadeHeader(targetPageMeta)
fadeHeader.classList.add('fade-enter', 'fade-enter-active')
css(fadeHeader, 'display', 'block')
}
whenTransitionEnds(loading, 'transition', () => {
loading.classList.remove('slide-enter-to', 'slide-enter-active')
if (!shell.transitionContainsHeader) {
fadeHeader.classList.remove('fade-enter-to', 'fade-enter-active')
}
hideAllIFrames()
fixRootPageScroll(shell, {sourcePageId, targetPageId})
onComplete && onComplete()
let iframe = getIFrame(targetPageId)
css(iframe, 'z-index', activeZIndex++)
shell.afterSwitchPage(options)
})
nextFrame(() => {
loading.classList.add('slide-enter-to')
loading.classList.remove('slide-enter')
if (!shell.transitionContainsHeader) {
fadeHeader.classList.add('fade-enter-to')
fadeHeader.classList.remove('fade-enter')
}
})
} | javascript | function forwardTransitionAndCreate (shell, options) {
let {sourcePageId, targetPageId, targetPageMeta, onComplete} = options
let loading = getLoading(targetPageMeta, {transitionContainsHeader: shell.transitionContainsHeader})
loading.classList.add('slide-enter', 'slide-enter-active')
css(loading, 'display', 'block')
let headerLogoTitle
let fadeHeader
if (!shell.transitionContainsHeader) {
headerLogoTitle = document.querySelector('.mip-shell-header-wrapper .mip-shell-header-logo-title')
headerLogoTitle && headerLogoTitle.classList.add('fade-out')
fadeHeader = getFadeHeader(targetPageMeta)
fadeHeader.classList.add('fade-enter', 'fade-enter-active')
css(fadeHeader, 'display', 'block')
}
whenTransitionEnds(loading, 'transition', () => {
loading.classList.remove('slide-enter-to', 'slide-enter-active')
if (!shell.transitionContainsHeader) {
fadeHeader.classList.remove('fade-enter-to', 'fade-enter-active')
}
hideAllIFrames()
fixRootPageScroll(shell, {sourcePageId, targetPageId})
onComplete && onComplete()
let iframe = getIFrame(targetPageId)
css(iframe, 'z-index', activeZIndex++)
shell.afterSwitchPage(options)
})
nextFrame(() => {
loading.classList.add('slide-enter-to')
loading.classList.remove('slide-enter')
if (!shell.transitionContainsHeader) {
fadeHeader.classList.add('fade-enter-to')
fadeHeader.classList.remove('fade-enter')
}
})
} | [
"function",
"forwardTransitionAndCreate",
"(",
"shell",
",",
"options",
")",
"{",
"let",
"{",
"sourcePageId",
",",
"targetPageId",
",",
"targetPageMeta",
",",
"onComplete",
"}",
"=",
"options",
"let",
"loading",
"=",
"getLoading",
"(",
"targetPageMeta",
",",
"{",
"transitionContainsHeader",
":",
"shell",
".",
"transitionContainsHeader",
"}",
")",
"loading",
".",
"classList",
".",
"add",
"(",
"'slide-enter'",
",",
"'slide-enter-active'",
")",
"css",
"(",
"loading",
",",
"'display'",
",",
"'block'",
")",
"let",
"headerLogoTitle",
"let",
"fadeHeader",
"if",
"(",
"!",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"headerLogoTitle",
"=",
"document",
".",
"querySelector",
"(",
"'.mip-shell-header-wrapper .mip-shell-header-logo-title'",
")",
"headerLogoTitle",
"&&",
"headerLogoTitle",
".",
"classList",
".",
"add",
"(",
"'fade-out'",
")",
"fadeHeader",
"=",
"getFadeHeader",
"(",
"targetPageMeta",
")",
"fadeHeader",
".",
"classList",
".",
"add",
"(",
"'fade-enter'",
",",
"'fade-enter-active'",
")",
"css",
"(",
"fadeHeader",
",",
"'display'",
",",
"'block'",
")",
"}",
"whenTransitionEnds",
"(",
"loading",
",",
"'transition'",
",",
"(",
")",
"=>",
"{",
"loading",
".",
"classList",
".",
"remove",
"(",
"'slide-enter-to'",
",",
"'slide-enter-active'",
")",
"if",
"(",
"!",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"fadeHeader",
".",
"classList",
".",
"remove",
"(",
"'fade-enter-to'",
",",
"'fade-enter-active'",
")",
"}",
"hideAllIFrames",
"(",
")",
"fixRootPageScroll",
"(",
"shell",
",",
"{",
"sourcePageId",
",",
"targetPageId",
"}",
")",
"onComplete",
"&&",
"onComplete",
"(",
")",
"let",
"iframe",
"=",
"getIFrame",
"(",
"targetPageId",
")",
"css",
"(",
"iframe",
",",
"'z-index'",
",",
"activeZIndex",
"++",
")",
"shell",
".",
"afterSwitchPage",
"(",
"options",
")",
"}",
")",
"nextFrame",
"(",
"(",
")",
"=>",
"{",
"loading",
".",
"classList",
".",
"add",
"(",
"'slide-enter-to'",
")",
"loading",
".",
"classList",
".",
"remove",
"(",
"'slide-enter'",
")",
"if",
"(",
"!",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"fadeHeader",
".",
"classList",
".",
"add",
"(",
"'fade-enter-to'",
")",
"fadeHeader",
".",
"classList",
".",
"remove",
"(",
"'fade-enter'",
")",
"}",
"}",
")",
"}"
] | Forward transition and create new iframe
@param {Object} shell shell instance
@param {Object} options
@param {string} options.targetPageId targetPageId
@param {Object} options.targetPageMeta pageMeta of target page
@param {string} options.sourcePageId sourcePageId
@param {Object} options.sourcePageMeta pageMeta of source page
@param {boolean} options.newPage whether a new iframe should be created (true)
@param {boolean} options.isForward whether transition direction is forward (true)
@param {Function} options.onComplete complete callback | [
"Forward",
"transition",
"and",
"create",
"new",
"iframe"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/components/mip-shell/switchPage.js#L72-L112 |
8,324 | mipengine/mip2 | packages/mip/src/components/mip-shell/switchPage.js | backwardTransitionAndCreate | function backwardTransitionAndCreate (shell, options) {
let {
targetPageId,
targetPageMeta,
sourcePageId,
sourcePageMeta,
onComplete
} = options
// Goto root page, resume scroll position (Only appears in backward)
let rootPageScrollPosition = 0
fixRootPageScroll(shell, {targetPageId})
if (targetPageId === window.MIP.viewer.page.pageId) {
rootPageScrollPosition = shell.rootPageScrollPosition
}
let iframe = getIFrame(sourcePageId)
// If source page is root page, skip transition
if (!iframe) {
document.documentElement.classList.add('mip-no-scroll')
window.MIP.viewer.page.getElementsInRootPage().forEach(e => e.classList.add('hide'))
onComplete && onComplete()
let targetIFrame = getIFrame(targetPageId)
if (targetIFrame) {
activeZIndex -= 2
css(targetIFrame, 'z-index', activeZIndex++)
}
shell.afterSwitchPage(options)
return
}
// Moving out only needs header, not loading body
let loading = getLoading(sourcePageMeta, {
onlyHeader: true,
transitionContainsHeader: shell.transitionContainsHeader
})
let headerLogoTitle
let fadeHeader
if (shell.transitionContainsHeader) {
css(loading, 'display', 'block')
} else {
headerLogoTitle = document.querySelector('.mip-shell-header-wrapper .mip-shell-header-logo-title')
headerLogoTitle && headerLogoTitle.classList.add('fade-out')
fadeHeader = getFadeHeader(targetPageMeta, sourcePageMeta)
css(fadeHeader, 'display', 'block')
}
iframe.classList.add('slide-leave', 'slide-leave-active')
if (shell.transitionContainsHeader) {
loading.classList.add('slide-leave', 'slide-leave-active')
} else {
fadeHeader.classList.add('fade-enter', 'fade-enter-active')
}
// trigger layout and move current iframe to correct position
/* eslint-disable no-unused-expressions */
css(iframe, {
opacity: 1,
top: rootPageScrollPosition + 'px'
})
/* eslint-enable no-unused-expressions */
whenTransitionEnds(iframe, 'transition', () => {
css(iframe, {
display: 'none',
'z-index': 10000,
top: 0
})
iframe.classList.remove('slide-leave-to', 'slide-leave-active')
if (shell.transitionContainsHeader) {
loading.classList.remove('slide-leave-to', 'slide-leave-active')
css(loading, 'display', 'none')
} else {
fadeHeader.classList.remove('fade-enter-to', 'fade-enter')
}
onComplete && onComplete()
let targetIFrame = getIFrame(targetPageId)
if (targetIFrame) {
activeZIndex -= 2
css(targetIFrame, 'z-index', activeZIndex++)
}
shell.afterSwitchPage(options)
})
nextFrame(() => {
iframe.classList.add('slide-leave-to')
iframe.classList.remove('slide-leave')
if (shell.transitionContainsHeader) {
loading.classList.add('slide-leave-to')
loading.classList.remove('slide-leave')
} else {
fadeHeader.classList.add('fade-enter-to')
fadeHeader.classList.remove('fade-enter')
}
})
} | javascript | function backwardTransitionAndCreate (shell, options) {
let {
targetPageId,
targetPageMeta,
sourcePageId,
sourcePageMeta,
onComplete
} = options
// Goto root page, resume scroll position (Only appears in backward)
let rootPageScrollPosition = 0
fixRootPageScroll(shell, {targetPageId})
if (targetPageId === window.MIP.viewer.page.pageId) {
rootPageScrollPosition = shell.rootPageScrollPosition
}
let iframe = getIFrame(sourcePageId)
// If source page is root page, skip transition
if (!iframe) {
document.documentElement.classList.add('mip-no-scroll')
window.MIP.viewer.page.getElementsInRootPage().forEach(e => e.classList.add('hide'))
onComplete && onComplete()
let targetIFrame = getIFrame(targetPageId)
if (targetIFrame) {
activeZIndex -= 2
css(targetIFrame, 'z-index', activeZIndex++)
}
shell.afterSwitchPage(options)
return
}
// Moving out only needs header, not loading body
let loading = getLoading(sourcePageMeta, {
onlyHeader: true,
transitionContainsHeader: shell.transitionContainsHeader
})
let headerLogoTitle
let fadeHeader
if (shell.transitionContainsHeader) {
css(loading, 'display', 'block')
} else {
headerLogoTitle = document.querySelector('.mip-shell-header-wrapper .mip-shell-header-logo-title')
headerLogoTitle && headerLogoTitle.classList.add('fade-out')
fadeHeader = getFadeHeader(targetPageMeta, sourcePageMeta)
css(fadeHeader, 'display', 'block')
}
iframe.classList.add('slide-leave', 'slide-leave-active')
if (shell.transitionContainsHeader) {
loading.classList.add('slide-leave', 'slide-leave-active')
} else {
fadeHeader.classList.add('fade-enter', 'fade-enter-active')
}
// trigger layout and move current iframe to correct position
/* eslint-disable no-unused-expressions */
css(iframe, {
opacity: 1,
top: rootPageScrollPosition + 'px'
})
/* eslint-enable no-unused-expressions */
whenTransitionEnds(iframe, 'transition', () => {
css(iframe, {
display: 'none',
'z-index': 10000,
top: 0
})
iframe.classList.remove('slide-leave-to', 'slide-leave-active')
if (shell.transitionContainsHeader) {
loading.classList.remove('slide-leave-to', 'slide-leave-active')
css(loading, 'display', 'none')
} else {
fadeHeader.classList.remove('fade-enter-to', 'fade-enter')
}
onComplete && onComplete()
let targetIFrame = getIFrame(targetPageId)
if (targetIFrame) {
activeZIndex -= 2
css(targetIFrame, 'z-index', activeZIndex++)
}
shell.afterSwitchPage(options)
})
nextFrame(() => {
iframe.classList.add('slide-leave-to')
iframe.classList.remove('slide-leave')
if (shell.transitionContainsHeader) {
loading.classList.add('slide-leave-to')
loading.classList.remove('slide-leave')
} else {
fadeHeader.classList.add('fade-enter-to')
fadeHeader.classList.remove('fade-enter')
}
})
} | [
"function",
"backwardTransitionAndCreate",
"(",
"shell",
",",
"options",
")",
"{",
"let",
"{",
"targetPageId",
",",
"targetPageMeta",
",",
"sourcePageId",
",",
"sourcePageMeta",
",",
"onComplete",
"}",
"=",
"options",
"// Goto root page, resume scroll position (Only appears in backward)",
"let",
"rootPageScrollPosition",
"=",
"0",
"fixRootPageScroll",
"(",
"shell",
",",
"{",
"targetPageId",
"}",
")",
"if",
"(",
"targetPageId",
"===",
"window",
".",
"MIP",
".",
"viewer",
".",
"page",
".",
"pageId",
")",
"{",
"rootPageScrollPosition",
"=",
"shell",
".",
"rootPageScrollPosition",
"}",
"let",
"iframe",
"=",
"getIFrame",
"(",
"sourcePageId",
")",
"// If source page is root page, skip transition",
"if",
"(",
"!",
"iframe",
")",
"{",
"document",
".",
"documentElement",
".",
"classList",
".",
"add",
"(",
"'mip-no-scroll'",
")",
"window",
".",
"MIP",
".",
"viewer",
".",
"page",
".",
"getElementsInRootPage",
"(",
")",
".",
"forEach",
"(",
"e",
"=>",
"e",
".",
"classList",
".",
"add",
"(",
"'hide'",
")",
")",
"onComplete",
"&&",
"onComplete",
"(",
")",
"let",
"targetIFrame",
"=",
"getIFrame",
"(",
"targetPageId",
")",
"if",
"(",
"targetIFrame",
")",
"{",
"activeZIndex",
"-=",
"2",
"css",
"(",
"targetIFrame",
",",
"'z-index'",
",",
"activeZIndex",
"++",
")",
"}",
"shell",
".",
"afterSwitchPage",
"(",
"options",
")",
"return",
"}",
"// Moving out only needs header, not loading body",
"let",
"loading",
"=",
"getLoading",
"(",
"sourcePageMeta",
",",
"{",
"onlyHeader",
":",
"true",
",",
"transitionContainsHeader",
":",
"shell",
".",
"transitionContainsHeader",
"}",
")",
"let",
"headerLogoTitle",
"let",
"fadeHeader",
"if",
"(",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"css",
"(",
"loading",
",",
"'display'",
",",
"'block'",
")",
"}",
"else",
"{",
"headerLogoTitle",
"=",
"document",
".",
"querySelector",
"(",
"'.mip-shell-header-wrapper .mip-shell-header-logo-title'",
")",
"headerLogoTitle",
"&&",
"headerLogoTitle",
".",
"classList",
".",
"add",
"(",
"'fade-out'",
")",
"fadeHeader",
"=",
"getFadeHeader",
"(",
"targetPageMeta",
",",
"sourcePageMeta",
")",
"css",
"(",
"fadeHeader",
",",
"'display'",
",",
"'block'",
")",
"}",
"iframe",
".",
"classList",
".",
"add",
"(",
"'slide-leave'",
",",
"'slide-leave-active'",
")",
"if",
"(",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"loading",
".",
"classList",
".",
"add",
"(",
"'slide-leave'",
",",
"'slide-leave-active'",
")",
"}",
"else",
"{",
"fadeHeader",
".",
"classList",
".",
"add",
"(",
"'fade-enter'",
",",
"'fade-enter-active'",
")",
"}",
"// trigger layout and move current iframe to correct position",
"/* eslint-disable no-unused-expressions */",
"css",
"(",
"iframe",
",",
"{",
"opacity",
":",
"1",
",",
"top",
":",
"rootPageScrollPosition",
"+",
"'px'",
"}",
")",
"/* eslint-enable no-unused-expressions */",
"whenTransitionEnds",
"(",
"iframe",
",",
"'transition'",
",",
"(",
")",
"=>",
"{",
"css",
"(",
"iframe",
",",
"{",
"display",
":",
"'none'",
",",
"'z-index'",
":",
"10000",
",",
"top",
":",
"0",
"}",
")",
"iframe",
".",
"classList",
".",
"remove",
"(",
"'slide-leave-to'",
",",
"'slide-leave-active'",
")",
"if",
"(",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"loading",
".",
"classList",
".",
"remove",
"(",
"'slide-leave-to'",
",",
"'slide-leave-active'",
")",
"css",
"(",
"loading",
",",
"'display'",
",",
"'none'",
")",
"}",
"else",
"{",
"fadeHeader",
".",
"classList",
".",
"remove",
"(",
"'fade-enter-to'",
",",
"'fade-enter'",
")",
"}",
"onComplete",
"&&",
"onComplete",
"(",
")",
"let",
"targetIFrame",
"=",
"getIFrame",
"(",
"targetPageId",
")",
"if",
"(",
"targetIFrame",
")",
"{",
"activeZIndex",
"-=",
"2",
"css",
"(",
"targetIFrame",
",",
"'z-index'",
",",
"activeZIndex",
"++",
")",
"}",
"shell",
".",
"afterSwitchPage",
"(",
"options",
")",
"}",
")",
"nextFrame",
"(",
"(",
")",
"=>",
"{",
"iframe",
".",
"classList",
".",
"add",
"(",
"'slide-leave-to'",
")",
"iframe",
".",
"classList",
".",
"remove",
"(",
"'slide-leave'",
")",
"if",
"(",
"shell",
".",
"transitionContainsHeader",
")",
"{",
"loading",
".",
"classList",
".",
"add",
"(",
"'slide-leave-to'",
")",
"loading",
".",
"classList",
".",
"remove",
"(",
"'slide-leave'",
")",
"}",
"else",
"{",
"fadeHeader",
".",
"classList",
".",
"add",
"(",
"'fade-enter-to'",
")",
"fadeHeader",
".",
"classList",
".",
"remove",
"(",
"'fade-enter'",
")",
"}",
"}",
")",
"}"
] | Backward transition and create new iframe
@param {Object} shell shell instance
@param {Object} options
@param {string} options.targetPageId targetPageId
@param {Object} options.targetPageMeta pageMeta of target page
@param {string} options.sourcePageId sourcePageId
@param {Object} options.sourcePageMeta pageMeta of source page
@param {boolean} options.newPage whether a new iframe should be created (true)
@param {boolean} options.isForward whether transition direction is forward (false)
@param {Function} options.onComplete complete callback | [
"Backward",
"transition",
"and",
"create",
"new",
"iframe"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/components/mip-shell/switchPage.js#L127-L228 |
8,325 | mipengine/mip2 | packages/mip/src/components/mip-shell/switchPage.js | skipTransitionAndCreate | function skipTransitionAndCreate (shell, options) {
let {sourcePageId, targetPageId, onComplete} = options
hideAllIFrames()
fixRootPageScroll(shell, {sourcePageId, targetPageId})
onComplete && onComplete()
let iframe = getIFrame(targetPageId)
css(iframe, 'z-index', activeZIndex++)
shell.afterSwitchPage(options)
} | javascript | function skipTransitionAndCreate (shell, options) {
let {sourcePageId, targetPageId, onComplete} = options
hideAllIFrames()
fixRootPageScroll(shell, {sourcePageId, targetPageId})
onComplete && onComplete()
let iframe = getIFrame(targetPageId)
css(iframe, 'z-index', activeZIndex++)
shell.afterSwitchPage(options)
} | [
"function",
"skipTransitionAndCreate",
"(",
"shell",
",",
"options",
")",
"{",
"let",
"{",
"sourcePageId",
",",
"targetPageId",
",",
"onComplete",
"}",
"=",
"options",
"hideAllIFrames",
"(",
")",
"fixRootPageScroll",
"(",
"shell",
",",
"{",
"sourcePageId",
",",
"targetPageId",
"}",
")",
"onComplete",
"&&",
"onComplete",
"(",
")",
"let",
"iframe",
"=",
"getIFrame",
"(",
"targetPageId",
")",
"css",
"(",
"iframe",
",",
"'z-index'",
",",
"activeZIndex",
"++",
")",
"shell",
".",
"afterSwitchPage",
"(",
"options",
")",
"}"
] | Skip transition and create new iframe
@param {Object} shell shell instance
@param {Object} options
@param {string} options.targetPageId targetPageId
@param {Object} options.targetPageMeta pageMeta of target page
@param {string} options.sourcePageId sourcePageId
@param {Object} options.sourcePageMeta pageMeta of source page
@param {boolean} options.newPage whether a new iframe should be created (false)
@param {boolean} options.isForward whether transition direction is forward (true)
@param {Function} options.onComplete complete callback | [
"Skip",
"transition",
"and",
"create",
"new",
"iframe"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/components/mip-shell/switchPage.js#L418-L429 |
8,326 | mipengine/mip2 | packages/mip/src/mip1-polyfill/element.js | createBaseElementProto | function createBaseElementProto () {
if (baseElementProto) {
return baseElementProto
}
// Base element inherits from HTMLElement
let proto = Object.create(HTMLElement.prototype)
/**
* Created callback of MIPElement. It will initialize the element.
*/
proto.createdCallback = function () {
// get mip1 clazz from custom elements store
let CustomElement = customElementsStore.get(this.tagName, 'mip1')
this.classList.add('mip-element')
/**
* Viewport state
* @private
* @type {boolean}
*/
this._inViewport = false
/**
* Whether the element is into the viewport.
* @private
* @type {boolean}
*/
this._firstInViewport = false
/**
* The resources object.
* @private
* @type {Object}
*/
this._resources = resources
/**
* Instantiated the custom element.
* @type {Object}
* @public
*/
let customElement = this.customElement = new CustomElement(this)
customElement.createdCallback()
// Add first-screen element to performance.
if (customElement.hasResources()) {
performance.addFsElement(this)
}
}
/**
* When the element is inserted into the DOM, initialize the layout and add the element to the '_resources'.
*/
proto.attachedCallback = function () {
// Apply layout for this.
this._layout = applyLayout(this)
this.customElement.attachedCallback()
this._resources.add(this)
}
/**
* When the element is removed from the DOM, remove it from '_resources'.
*/
proto.detachedCallback = function () {
this.customElement.detachedCallback()
this._resources.remove(this)
performance.fsElementLoaded(this)
}
proto.attributeChangedCallback = function (attributeName, oldValue, newValue, namespace) {
let ele = this.customElement
prerender.execute(() => {
ele.attributeChangedCallback(...arguments)
}, this)
}
/**
* Check whether the element is in the viewport.
*
* @return {boolean}
*/
proto.inViewport = function () {
return this._inViewport
}
/**
* Called when the element enter or exit the viewport.
*
* @param {boolean} inViewport whether in viewport or not
* And it will call the firstInviewCallback and viewportCallback of the custom element.
*/
proto.viewportCallback = function (inViewport) {
this._inViewport = inViewport
if (!this._firstInViewport) {
this._firstInViewport = true
this.customElement.firstInviewCallback()
}
this.customElement.viewportCallback(inViewport)
}
/**
* Check whether the building callback has been executed.
*
* @return {boolean}
*/
proto.isBuilt = function () {
return this._built
}
/**
* Check whether the element need to be rendered in advance.
*
* @return {boolean}
*/
proto.prerenderAllowed = function () {
return this.customElement.prerenderAllowed()
}
/**
* Build the element and the custom element.
* This will be executed only once.
*/
proto.build = function () {
if (this.isBuilt()) {
return
}
// Add `try ... catch` avoid the executing build list being interrupted by errors.
try {
this.customElement.build()
this._built = true
customEmit(this, 'build')
} catch (e) {
customEmit(this, 'build-error', e)
console.error(e)
}
}
/**
* Method of executing event actions of the custom Element
*
* @param {Object} action event action
*/
proto.executeEventAction = function (action) {
this.customElement.executeEventAction(action)
}
/**
* Called by customElement. And tell the performance that element is loaded.
* @deprecated
*/
proto.resourcesComplete = function () {
performance.fsElementLoaded(this)
}
baseElementProto = proto
return baseElementProto
} | javascript | function createBaseElementProto () {
if (baseElementProto) {
return baseElementProto
}
// Base element inherits from HTMLElement
let proto = Object.create(HTMLElement.prototype)
/**
* Created callback of MIPElement. It will initialize the element.
*/
proto.createdCallback = function () {
// get mip1 clazz from custom elements store
let CustomElement = customElementsStore.get(this.tagName, 'mip1')
this.classList.add('mip-element')
/**
* Viewport state
* @private
* @type {boolean}
*/
this._inViewport = false
/**
* Whether the element is into the viewport.
* @private
* @type {boolean}
*/
this._firstInViewport = false
/**
* The resources object.
* @private
* @type {Object}
*/
this._resources = resources
/**
* Instantiated the custom element.
* @type {Object}
* @public
*/
let customElement = this.customElement = new CustomElement(this)
customElement.createdCallback()
// Add first-screen element to performance.
if (customElement.hasResources()) {
performance.addFsElement(this)
}
}
/**
* When the element is inserted into the DOM, initialize the layout and add the element to the '_resources'.
*/
proto.attachedCallback = function () {
// Apply layout for this.
this._layout = applyLayout(this)
this.customElement.attachedCallback()
this._resources.add(this)
}
/**
* When the element is removed from the DOM, remove it from '_resources'.
*/
proto.detachedCallback = function () {
this.customElement.detachedCallback()
this._resources.remove(this)
performance.fsElementLoaded(this)
}
proto.attributeChangedCallback = function (attributeName, oldValue, newValue, namespace) {
let ele = this.customElement
prerender.execute(() => {
ele.attributeChangedCallback(...arguments)
}, this)
}
/**
* Check whether the element is in the viewport.
*
* @return {boolean}
*/
proto.inViewport = function () {
return this._inViewport
}
/**
* Called when the element enter or exit the viewport.
*
* @param {boolean} inViewport whether in viewport or not
* And it will call the firstInviewCallback and viewportCallback of the custom element.
*/
proto.viewportCallback = function (inViewport) {
this._inViewport = inViewport
if (!this._firstInViewport) {
this._firstInViewport = true
this.customElement.firstInviewCallback()
}
this.customElement.viewportCallback(inViewport)
}
/**
* Check whether the building callback has been executed.
*
* @return {boolean}
*/
proto.isBuilt = function () {
return this._built
}
/**
* Check whether the element need to be rendered in advance.
*
* @return {boolean}
*/
proto.prerenderAllowed = function () {
return this.customElement.prerenderAllowed()
}
/**
* Build the element and the custom element.
* This will be executed only once.
*/
proto.build = function () {
if (this.isBuilt()) {
return
}
// Add `try ... catch` avoid the executing build list being interrupted by errors.
try {
this.customElement.build()
this._built = true
customEmit(this, 'build')
} catch (e) {
customEmit(this, 'build-error', e)
console.error(e)
}
}
/**
* Method of executing event actions of the custom Element
*
* @param {Object} action event action
*/
proto.executeEventAction = function (action) {
this.customElement.executeEventAction(action)
}
/**
* Called by customElement. And tell the performance that element is loaded.
* @deprecated
*/
proto.resourcesComplete = function () {
performance.fsElementLoaded(this)
}
baseElementProto = proto
return baseElementProto
} | [
"function",
"createBaseElementProto",
"(",
")",
"{",
"if",
"(",
"baseElementProto",
")",
"{",
"return",
"baseElementProto",
"}",
"// Base element inherits from HTMLElement",
"let",
"proto",
"=",
"Object",
".",
"create",
"(",
"HTMLElement",
".",
"prototype",
")",
"/**\n * Created callback of MIPElement. It will initialize the element.\n */",
"proto",
".",
"createdCallback",
"=",
"function",
"(",
")",
"{",
"// get mip1 clazz from custom elements store",
"let",
"CustomElement",
"=",
"customElementsStore",
".",
"get",
"(",
"this",
".",
"tagName",
",",
"'mip1'",
")",
"this",
".",
"classList",
".",
"add",
"(",
"'mip-element'",
")",
"/**\n * Viewport state\n * @private\n * @type {boolean}\n */",
"this",
".",
"_inViewport",
"=",
"false",
"/**\n * Whether the element is into the viewport.\n * @private\n * @type {boolean}\n */",
"this",
".",
"_firstInViewport",
"=",
"false",
"/**\n * The resources object.\n * @private\n * @type {Object}\n */",
"this",
".",
"_resources",
"=",
"resources",
"/**\n * Instantiated the custom element.\n * @type {Object}\n * @public\n */",
"let",
"customElement",
"=",
"this",
".",
"customElement",
"=",
"new",
"CustomElement",
"(",
"this",
")",
"customElement",
".",
"createdCallback",
"(",
")",
"// Add first-screen element to performance.",
"if",
"(",
"customElement",
".",
"hasResources",
"(",
")",
")",
"{",
"performance",
".",
"addFsElement",
"(",
"this",
")",
"}",
"}",
"/**\n * When the element is inserted into the DOM, initialize the layout and add the element to the '_resources'.\n */",
"proto",
".",
"attachedCallback",
"=",
"function",
"(",
")",
"{",
"// Apply layout for this.",
"this",
".",
"_layout",
"=",
"applyLayout",
"(",
"this",
")",
"this",
".",
"customElement",
".",
"attachedCallback",
"(",
")",
"this",
".",
"_resources",
".",
"add",
"(",
"this",
")",
"}",
"/**\n * When the element is removed from the DOM, remove it from '_resources'.\n */",
"proto",
".",
"detachedCallback",
"=",
"function",
"(",
")",
"{",
"this",
".",
"customElement",
".",
"detachedCallback",
"(",
")",
"this",
".",
"_resources",
".",
"remove",
"(",
"this",
")",
"performance",
".",
"fsElementLoaded",
"(",
"this",
")",
"}",
"proto",
".",
"attributeChangedCallback",
"=",
"function",
"(",
"attributeName",
",",
"oldValue",
",",
"newValue",
",",
"namespace",
")",
"{",
"let",
"ele",
"=",
"this",
".",
"customElement",
"prerender",
".",
"execute",
"(",
"(",
")",
"=>",
"{",
"ele",
".",
"attributeChangedCallback",
"(",
"...",
"arguments",
")",
"}",
",",
"this",
")",
"}",
"/**\n * Check whether the element is in the viewport.\n *\n * @return {boolean}\n */",
"proto",
".",
"inViewport",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_inViewport",
"}",
"/**\n * Called when the element enter or exit the viewport.\n *\n * @param {boolean} inViewport whether in viewport or not\n * And it will call the firstInviewCallback and viewportCallback of the custom element.\n */",
"proto",
".",
"viewportCallback",
"=",
"function",
"(",
"inViewport",
")",
"{",
"this",
".",
"_inViewport",
"=",
"inViewport",
"if",
"(",
"!",
"this",
".",
"_firstInViewport",
")",
"{",
"this",
".",
"_firstInViewport",
"=",
"true",
"this",
".",
"customElement",
".",
"firstInviewCallback",
"(",
")",
"}",
"this",
".",
"customElement",
".",
"viewportCallback",
"(",
"inViewport",
")",
"}",
"/**\n * Check whether the building callback has been executed.\n *\n * @return {boolean}\n */",
"proto",
".",
"isBuilt",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_built",
"}",
"/**\n * Check whether the element need to be rendered in advance.\n *\n * @return {boolean}\n */",
"proto",
".",
"prerenderAllowed",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"customElement",
".",
"prerenderAllowed",
"(",
")",
"}",
"/**\n * Build the element and the custom element.\n * This will be executed only once.\n */",
"proto",
".",
"build",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isBuilt",
"(",
")",
")",
"{",
"return",
"}",
"// Add `try ... catch` avoid the executing build list being interrupted by errors.",
"try",
"{",
"this",
".",
"customElement",
".",
"build",
"(",
")",
"this",
".",
"_built",
"=",
"true",
"customEmit",
"(",
"this",
",",
"'build'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"customEmit",
"(",
"this",
",",
"'build-error'",
",",
"e",
")",
"console",
".",
"error",
"(",
"e",
")",
"}",
"}",
"/**\n * Method of executing event actions of the custom Element\n *\n * @param {Object} action event action\n */",
"proto",
".",
"executeEventAction",
"=",
"function",
"(",
"action",
")",
"{",
"this",
".",
"customElement",
".",
"executeEventAction",
"(",
"action",
")",
"}",
"/**\n * Called by customElement. And tell the performance that element is loaded.\n * @deprecated\n */",
"proto",
".",
"resourcesComplete",
"=",
"function",
"(",
")",
"{",
"performance",
".",
"fsElementLoaded",
"(",
"this",
")",
"}",
"baseElementProto",
"=",
"proto",
"return",
"baseElementProto",
"}"
] | Create a basic prototype of mip elements classes
@return {Object} | [
"Create",
"a",
"basic",
"prototype",
"of",
"mip",
"elements",
"classes"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/mip1-polyfill/element.js#L28-L188 |
8,327 | mipengine/mip2 | packages/mip/src/mip1-polyfill/element.js | createMipElementProto | function createMipElementProto (name) {
let proto = Object.create(createBaseElementProto())
proto.name = name
return proto
} | javascript | function createMipElementProto (name) {
let proto = Object.create(createBaseElementProto())
proto.name = name
return proto
} | [
"function",
"createMipElementProto",
"(",
"name",
")",
"{",
"let",
"proto",
"=",
"Object",
".",
"create",
"(",
"createBaseElementProto",
"(",
")",
")",
"proto",
".",
"name",
"=",
"name",
"return",
"proto",
"}"
] | Create a mip element prototype by name
@param {string} name The mip element's name
@return {Object} | [
"Create",
"a",
"mip",
"element",
"prototype",
"by",
"name"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/mip1-polyfill/element.js#L196-L200 |
8,328 | mipengine/mip2 | packages/mip/src/util/custom-storage.js | getErrorMess | function getErrorMess (code, name) {
let mess
switch (code) {
case eCode.siteExceed:
mess = 'storage space need less than 4k'
break
case eCode.lsExceed:
mess = 'Uncaught DOMException: Failed to execute setItem on Storage: Setting the value of ' +
name + ' exceeded the quota at ' + window.location.href
}
return mess
} | javascript | function getErrorMess (code, name) {
let mess
switch (code) {
case eCode.siteExceed:
mess = 'storage space need less than 4k'
break
case eCode.lsExceed:
mess = 'Uncaught DOMException: Failed to execute setItem on Storage: Setting the value of ' +
name + ' exceeded the quota at ' + window.location.href
}
return mess
} | [
"function",
"getErrorMess",
"(",
"code",
",",
"name",
")",
"{",
"let",
"mess",
"switch",
"(",
"code",
")",
"{",
"case",
"eCode",
".",
"siteExceed",
":",
"mess",
"=",
"'storage space need less than 4k'",
"break",
"case",
"eCode",
".",
"lsExceed",
":",
"mess",
"=",
"'Uncaught DOMException: Failed to execute setItem on Storage: Setting the value of '",
"+",
"name",
"+",
"' exceeded the quota at '",
"+",
"window",
".",
"location",
".",
"href",
"}",
"return",
"mess",
"}"
] | Get error message with error code
@param {string} code error code
@param {string} name error name
@return {string} error message | [
"Get",
"error",
"message",
"with",
"error",
"code"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/custom-storage.js#L506-L517 |
8,329 | mipengine/mip2 | packages/mip/src/util/dom/dom.js | matches | function matches (element, selector) {
if (!element || element.nodeType !== 1) {
return false
}
return nativeMatches.call(element, selector)
} | javascript | function matches (element, selector) {
if (!element || element.nodeType !== 1) {
return false
}
return nativeMatches.call(element, selector)
} | [
"function",
"matches",
"(",
"element",
",",
"selector",
")",
"{",
"if",
"(",
"!",
"element",
"||",
"element",
".",
"nodeType",
"!==",
"1",
")",
"{",
"return",
"false",
"}",
"return",
"nativeMatches",
".",
"call",
"(",
"element",
",",
"selector",
")",
"}"
] | Support for matches. Check whether a element matches a selector.
@param {HTMLElement} element target element
@param {string} selector element selector
@return {boolean} | [
"Support",
"for",
"matches",
".",
"Check",
"whether",
"a",
"element",
"matches",
"a",
"selector",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/dom.js#L34-L39 |
8,330 | mipengine/mip2 | packages/mip/src/util/dom/dom.js | closestTo | function closestTo (element, selector, target) {
let closestElement = closest(element, selector)
return contains(target, closestElement) ? closestElement : null
} | javascript | function closestTo (element, selector, target) {
let closestElement = closest(element, selector)
return contains(target, closestElement) ? closestElement : null
} | [
"function",
"closestTo",
"(",
"element",
",",
"selector",
",",
"target",
")",
"{",
"let",
"closestElement",
"=",
"closest",
"(",
"element",
",",
"selector",
")",
"return",
"contains",
"(",
"target",
",",
"closestElement",
")",
"?",
"closestElement",
":",
"null",
"}"
] | Find the nearest element that matches the selector from current element to target element.
@param {HTMLElement} element element
@param {string} selector element selector
@param {HTMLElement} target target element
@return {?HTMLElement} | [
"Find",
"the",
"nearest",
"element",
"that",
"matches",
"the",
"selector",
"from",
"current",
"element",
"to",
"target",
"element",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/dom.js#L92-L95 |
8,331 | mipengine/mip2 | packages/mip/src/util/dom/dom.js | create | function create (str) {
createTmpElement.innerHTML = str
if (!createTmpElement.children.length) {
return null
}
let children = Array.prototype.slice.call(createTmpElement.children)
createTmpElement.innerHTML = ''
return children.length > 1 ? children : children[0]
} | javascript | function create (str) {
createTmpElement.innerHTML = str
if (!createTmpElement.children.length) {
return null
}
let children = Array.prototype.slice.call(createTmpElement.children)
createTmpElement.innerHTML = ''
return children.length > 1 ? children : children[0]
} | [
"function",
"create",
"(",
"str",
")",
"{",
"createTmpElement",
".",
"innerHTML",
"=",
"str",
"if",
"(",
"!",
"createTmpElement",
".",
"children",
".",
"length",
")",
"{",
"return",
"null",
"}",
"let",
"children",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"createTmpElement",
".",
"children",
")",
"createTmpElement",
".",
"innerHTML",
"=",
"''",
"return",
"children",
".",
"length",
">",
"1",
"?",
"children",
":",
"children",
"[",
"0",
"]",
"}"
] | Create a element by string
@param {string} str Html string
@return {HTMLElement} | [
"Create",
"a",
"element",
"by",
"string"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/dom.js#L110-L118 |
8,332 | mipengine/mip2 | packages/mip/src/util/dom/dom.js | onDocumentState | function onDocumentState (doc, stateFn, callback) {
let ready = stateFn(doc)
if (ready) {
callback(doc)
return
}
const readyListener = () => {
if (!stateFn(doc)) {
return
}
if (!ready) {
ready = true
callback(doc)
}
doc.removeEventListener('readystatechange', readyListener)
}
doc.addEventListener('readystatechange', readyListener)
} | javascript | function onDocumentState (doc, stateFn, callback) {
let ready = stateFn(doc)
if (ready) {
callback(doc)
return
}
const readyListener = () => {
if (!stateFn(doc)) {
return
}
if (!ready) {
ready = true
callback(doc)
}
doc.removeEventListener('readystatechange', readyListener)
}
doc.addEventListener('readystatechange', readyListener)
} | [
"function",
"onDocumentState",
"(",
"doc",
",",
"stateFn",
",",
"callback",
")",
"{",
"let",
"ready",
"=",
"stateFn",
"(",
"doc",
")",
"if",
"(",
"ready",
")",
"{",
"callback",
"(",
"doc",
")",
"return",
"}",
"const",
"readyListener",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"stateFn",
"(",
"doc",
")",
")",
"{",
"return",
"}",
"if",
"(",
"!",
"ready",
")",
"{",
"ready",
"=",
"true",
"callback",
"(",
"doc",
")",
"}",
"doc",
".",
"removeEventListener",
"(",
"'readystatechange'",
",",
"readyListener",
")",
"}",
"doc",
".",
"addEventListener",
"(",
"'readystatechange'",
",",
"readyListener",
")",
"}"
] | Calls the callback when document's state satisfies the stateFn.
@param {!Document} doc
@param {(doc: Document) => boolean} stateFn
@param {(doc: Document) => void} callback | [
"Calls",
"the",
"callback",
"when",
"document",
"s",
"state",
"satisfies",
"the",
"stateFn",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/dom.js#L205-L228 |
8,333 | mipengine/mip2 | packages/mip/src/util/dom/dom.js | insert | function insert (parent, children) {
if (!parent || !children) {
return
}
let nodes = Array.prototype.slice.call(children)
if (nodes.length === 0) {
nodes.push(children)
}
for (let i = 0; i < nodes.length; i++) {
if (this.contains(nodes[i], parent)) {
continue
}
if (nodes[i] !== parent && parent.appendChild) {
parent.appendChild(nodes[i])
}
}
} | javascript | function insert (parent, children) {
if (!parent || !children) {
return
}
let nodes = Array.prototype.slice.call(children)
if (nodes.length === 0) {
nodes.push(children)
}
for (let i = 0; i < nodes.length; i++) {
if (this.contains(nodes[i], parent)) {
continue
}
if (nodes[i] !== parent && parent.appendChild) {
parent.appendChild(nodes[i])
}
}
} | [
"function",
"insert",
"(",
"parent",
",",
"children",
")",
"{",
"if",
"(",
"!",
"parent",
"||",
"!",
"children",
")",
"{",
"return",
"}",
"let",
"nodes",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"children",
")",
"if",
"(",
"nodes",
".",
"length",
"===",
"0",
")",
"{",
"nodes",
".",
"push",
"(",
"children",
")",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"this",
".",
"contains",
"(",
"nodes",
"[",
"i",
"]",
",",
"parent",
")",
")",
"{",
"continue",
"}",
"if",
"(",
"nodes",
"[",
"i",
"]",
"!==",
"parent",
"&&",
"parent",
".",
"appendChild",
")",
"{",
"parent",
".",
"appendChild",
"(",
"nodes",
"[",
"i",
"]",
")",
"}",
"}",
"}"
] | Insert dom list to a node
@param {HTMLElement} parent the node will be inserted
@param {Array} children node list which will insert into parent | [
"Insert",
"dom",
"list",
"to",
"a",
"node"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/dom.js#L246-L262 |
8,334 | mipengine/mip2 | packages/mip/src/util/dom/css.js | prefixProperty | function prefixProperty (property) {
property = property.replace(camelReg, (match, first, char) => (first ? char : char.toUpperCase()))
if (prefixCache[property]) {
return prefixCache[property]
}
let prop
if (!(property in supportElement.style)) {
for (let i = 0; i < PREFIX_TYPE.length; i++) {
let prefixedProp = PREFIX_TYPE[i] +
property.charAt(0).toUpperCase() +
property.slice(1)
if (prefixedProp in supportElement.style) {
prop = prefixedProp
break
}
}
}
prefixCache[property] = prop || property
return prefixCache[property]
} | javascript | function prefixProperty (property) {
property = property.replace(camelReg, (match, first, char) => (first ? char : char.toUpperCase()))
if (prefixCache[property]) {
return prefixCache[property]
}
let prop
if (!(property in supportElement.style)) {
for (let i = 0; i < PREFIX_TYPE.length; i++) {
let prefixedProp = PREFIX_TYPE[i] +
property.charAt(0).toUpperCase() +
property.slice(1)
if (prefixedProp in supportElement.style) {
prop = prefixedProp
break
}
}
}
prefixCache[property] = prop || property
return prefixCache[property]
} | [
"function",
"prefixProperty",
"(",
"property",
")",
"{",
"property",
"=",
"property",
".",
"replace",
"(",
"camelReg",
",",
"(",
"match",
",",
"first",
",",
"char",
")",
"=>",
"(",
"first",
"?",
"char",
":",
"char",
".",
"toUpperCase",
"(",
")",
")",
")",
"if",
"(",
"prefixCache",
"[",
"property",
"]",
")",
"{",
"return",
"prefixCache",
"[",
"property",
"]",
"}",
"let",
"prop",
"if",
"(",
"!",
"(",
"property",
"in",
"supportElement",
".",
"style",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"PREFIX_TYPE",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"prefixedProp",
"=",
"PREFIX_TYPE",
"[",
"i",
"]",
"+",
"property",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"property",
".",
"slice",
"(",
"1",
")",
"if",
"(",
"prefixedProp",
"in",
"supportElement",
".",
"style",
")",
"{",
"prop",
"=",
"prefixedProp",
"break",
"}",
"}",
"}",
"prefixCache",
"[",
"property",
"]",
"=",
"prop",
"||",
"property",
"return",
"prefixCache",
"[",
"property",
"]",
"}"
] | Make sure a property is supported by adding prefix.
@param {string} property A property to be checked
@return {string} the property or its prefixed version | [
"Make",
"sure",
"a",
"property",
"is",
"supported",
"by",
"adding",
"prefix",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/css.js#L26-L50 |
8,335 | mipengine/mip2 | packages/mip/src/util/dom/css.js | unitProperty | function unitProperty (property, value) {
if (value !== +value) {
return value
}
if (unitCache[property]) {
return value + unitCache[property]
}
supportElement.style[property] = 0
let propValue = supportElement.style[property]
let match = propValue.match && propValue.match(UNIT_REG)
if (match) {
return value + (unitCache[property] = match[1])
}
return value
} | javascript | function unitProperty (property, value) {
if (value !== +value) {
return value
}
if (unitCache[property]) {
return value + unitCache[property]
}
supportElement.style[property] = 0
let propValue = supportElement.style[property]
let match = propValue.match && propValue.match(UNIT_REG)
if (match) {
return value + (unitCache[property] = match[1])
}
return value
} | [
"function",
"unitProperty",
"(",
"property",
",",
"value",
")",
"{",
"if",
"(",
"value",
"!==",
"+",
"value",
")",
"{",
"return",
"value",
"}",
"if",
"(",
"unitCache",
"[",
"property",
"]",
")",
"{",
"return",
"value",
"+",
"unitCache",
"[",
"property",
"]",
"}",
"supportElement",
".",
"style",
"[",
"property",
"]",
"=",
"0",
"let",
"propValue",
"=",
"supportElement",
".",
"style",
"[",
"property",
"]",
"let",
"match",
"=",
"propValue",
".",
"match",
"&&",
"propValue",
".",
"match",
"(",
"UNIT_REG",
")",
"if",
"(",
"match",
")",
"{",
"return",
"value",
"+",
"(",
"unitCache",
"[",
"property",
"]",
"=",
"match",
"[",
"1",
"]",
")",
"}",
"return",
"value",
"}"
] | Obtain the unit of a property and add it to the value has no unit if exists.
@param {string} property property
@param {(string|number)} value A value maybe needs unit.
@return {(string|number)} | [
"Obtain",
"the",
"unit",
"of",
"a",
"property",
"and",
"add",
"it",
"to",
"the",
"value",
"has",
"no",
"unit",
"if",
"exists",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/css.js#L66-L85 |
8,336 | mipengine/mip2 | packages/mip/src/layout.js | isLayoutSizeDefined | function isLayoutSizeDefined (layout) {
return (
layout === LAYOUT.FIXED ||
layout === LAYOUT.FIXED_HEIGHT ||
layout === LAYOUT.RESPONSIVE ||
layout === LAYOUT.FILL ||
layout === LAYOUT.FLEX_ITEM ||
layout === LAYOUT.INTRINSIC
)
} | javascript | function isLayoutSizeDefined (layout) {
return (
layout === LAYOUT.FIXED ||
layout === LAYOUT.FIXED_HEIGHT ||
layout === LAYOUT.RESPONSIVE ||
layout === LAYOUT.FILL ||
layout === LAYOUT.FLEX_ITEM ||
layout === LAYOUT.INTRINSIC
)
} | [
"function",
"isLayoutSizeDefined",
"(",
"layout",
")",
"{",
"return",
"(",
"layout",
"===",
"LAYOUT",
".",
"FIXED",
"||",
"layout",
"===",
"LAYOUT",
".",
"FIXED_HEIGHT",
"||",
"layout",
"===",
"LAYOUT",
".",
"RESPONSIVE",
"||",
"layout",
"===",
"LAYOUT",
".",
"FILL",
"||",
"layout",
"===",
"LAYOUT",
".",
"FLEX_ITEM",
"||",
"layout",
"===",
"LAYOUT",
".",
"INTRINSIC",
")",
"}"
] | Whether an element with this layout inherently defines the size.
@param {Layout} layout layout name
@return {boolean} | [
"Whether",
"an",
"element",
"with",
"this",
"layout",
"inherently",
"defines",
"the",
"size",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/layout.js#L79-L88 |
8,337 | mipengine/mip2 | packages/mip/src/vue/core/util/options.js | checkComponents | function checkComponents (options) {
for (const key in options.components) {
const lower = key.toLowerCase()
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
)
}
}
} | javascript | function checkComponents (options) {
for (const key in options.components) {
const lower = key.toLowerCase()
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
)
}
}
} | [
"function",
"checkComponents",
"(",
"options",
")",
"{",
"for",
"(",
"const",
"key",
"in",
"options",
".",
"components",
")",
"{",
"const",
"lower",
"=",
"key",
".",
"toLowerCase",
"(",
")",
"if",
"(",
"isBuiltInTag",
"(",
"lower",
")",
"||",
"config",
".",
"isReservedTag",
"(",
"lower",
")",
")",
"{",
"warn",
"(",
"'Do not use built-in or reserved HTML elements as component '",
"+",
"'id: '",
"+",
"key",
")",
"}",
"}",
"}"
] | Validate component names | [
"Validate",
"component",
"names"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/vue/core/util/options.js#L277-L287 |
8,338 | mipengine/mip2 | packages/mip/src/base-element.js | lastChildElement | function lastChildElement (parent, callback) {
for (let child = parent.lastElementChild; child; child = child.previousElementSibling) {
if (callback(child)) {
return child
}
}
return null
} | javascript | function lastChildElement (parent, callback) {
for (let child = parent.lastElementChild; child; child = child.previousElementSibling) {
if (callback(child)) {
return child
}
}
return null
} | [
"function",
"lastChildElement",
"(",
"parent",
",",
"callback",
")",
"{",
"for",
"(",
"let",
"child",
"=",
"parent",
".",
"lastElementChild",
";",
"child",
";",
"child",
"=",
"child",
".",
"previousElementSibling",
")",
"{",
"if",
"(",
"callback",
"(",
"child",
")",
")",
"{",
"return",
"child",
"}",
"}",
"return",
"null",
"}"
] | Finds the last child element that satisfies the callback.
@param {!Element} parent
@param {function(!Element):boolean} callback
@return {?Element} | [
"Finds",
"the",
"last",
"child",
"element",
"that",
"satisfies",
"the",
"callback",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/base-element.js#L26-L33 |
8,339 | mipengine/mip2 | packages/mip/src/base-element.js | isInternalNode | function isInternalNode (node) {
let tagName = (typeof node === 'string') ? node : node.tagName
if (tagName && tagName.toLowerCase().indexOf('mip-i-') === 0) {
return true
}
if (node.tagName && (node.hasAttribute('placeholder') ||
node.hasAttribute('fallback') ||
node.hasAttribute('overflow'))) {
return true
}
return false
} | javascript | function isInternalNode (node) {
let tagName = (typeof node === 'string') ? node : node.tagName
if (tagName && tagName.toLowerCase().indexOf('mip-i-') === 0) {
return true
}
if (node.tagName && (node.hasAttribute('placeholder') ||
node.hasAttribute('fallback') ||
node.hasAttribute('overflow'))) {
return true
}
return false
} | [
"function",
"isInternalNode",
"(",
"node",
")",
"{",
"let",
"tagName",
"=",
"(",
"typeof",
"node",
"===",
"'string'",
")",
"?",
"node",
":",
"node",
".",
"tagName",
"if",
"(",
"tagName",
"&&",
"tagName",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"'mip-i-'",
")",
"===",
"0",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"node",
".",
"tagName",
"&&",
"(",
"node",
".",
"hasAttribute",
"(",
"'placeholder'",
")",
"||",
"node",
".",
"hasAttribute",
"(",
"'fallback'",
")",
"||",
"node",
".",
"hasAttribute",
"(",
"'overflow'",
")",
")",
")",
"{",
"return",
"true",
"}",
"return",
"false",
"}"
] | Returns "true" for internal MIP nodes or for placeholder elements.
@param {!Node} node
@return {boolean} | [
"Returns",
"true",
"for",
"internal",
"MIP",
"nodes",
"or",
"for",
"placeholder",
"elements",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/base-element.js#L40-L52 |
8,340 | mipengine/mip2 | packages/mip/src/util/gesture/index.js | touchHandler | function touchHandler (event) {
let opt = this._opt
opt.preventDefault && event.preventDefault()
opt.stopPropagation && event.stopPropagation()
// 如果 touchstart 没有被触发(可能被子元素的 touchstart 回调触发了 stopPropagation),
// 那么后续的手势将取消计算
if (event.type !== 'touchstart' && !dataProcessor.startTime) {
return
}
let data = dataProcessor.process(event, opt.preventX, opt.preventY)
this._recognize(data)
this.trigger(event.type, event, data)
} | javascript | function touchHandler (event) {
let opt = this._opt
opt.preventDefault && event.preventDefault()
opt.stopPropagation && event.stopPropagation()
// 如果 touchstart 没有被触发(可能被子元素的 touchstart 回调触发了 stopPropagation),
// 那么后续的手势将取消计算
if (event.type !== 'touchstart' && !dataProcessor.startTime) {
return
}
let data = dataProcessor.process(event, opt.preventX, opt.preventY)
this._recognize(data)
this.trigger(event.type, event, data)
} | [
"function",
"touchHandler",
"(",
"event",
")",
"{",
"let",
"opt",
"=",
"this",
".",
"_opt",
"opt",
".",
"preventDefault",
"&&",
"event",
".",
"preventDefault",
"(",
")",
"opt",
".",
"stopPropagation",
"&&",
"event",
".",
"stopPropagation",
"(",
")",
"// 如果 touchstart 没有被触发(可能被子元素的 touchstart 回调触发了 stopPropagation),",
"// 那么后续的手势将取消计算",
"if",
"(",
"event",
".",
"type",
"!==",
"'touchstart'",
"&&",
"!",
"dataProcessor",
".",
"startTime",
")",
"{",
"return",
"}",
"let",
"data",
"=",
"dataProcessor",
".",
"process",
"(",
"event",
",",
"opt",
".",
"preventX",
",",
"opt",
".",
"preventY",
")",
"this",
".",
"_recognize",
"(",
"data",
")",
"this",
".",
"trigger",
"(",
"event",
".",
"type",
",",
"event",
",",
"data",
")",
"}"
] | Handle touch event.
@inner
@param {Event} event event | [
"Handle",
"touch",
"event",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/gesture/index.js#L153-L167 |
8,341 | mipengine/mip2 | packages/mip/src/util/gesture/index.js | listenersHelp | function listenersHelp (element, events, handler, method) {
let list = events.split(' ')
for (let i = 0, len = list.length; i < len; i++) {
let item = list[i]
if (method === false) {
element.removeEventListener(item, handler)
} else {
element.addEventListener(item, handler, false)
}
}
} | javascript | function listenersHelp (element, events, handler, method) {
let list = events.split(' ')
for (let i = 0, len = list.length; i < len; i++) {
let item = list[i]
if (method === false) {
element.removeEventListener(item, handler)
} else {
element.addEventListener(item, handler, false)
}
}
} | [
"function",
"listenersHelp",
"(",
"element",
",",
"events",
",",
"handler",
",",
"method",
")",
"{",
"let",
"list",
"=",
"events",
".",
"split",
"(",
"' '",
")",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"len",
"=",
"list",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"let",
"item",
"=",
"list",
"[",
"i",
"]",
"if",
"(",
"method",
"===",
"false",
")",
"{",
"element",
".",
"removeEventListener",
"(",
"item",
",",
"handler",
")",
"}",
"else",
"{",
"element",
".",
"addEventListener",
"(",
"item",
",",
"handler",
",",
"false",
")",
"}",
"}",
"}"
] | Add or remove listeners from an element.
@inner
@param {HTMLElement} element element
@param {string} events Events' name that are splitted by space
@param {Function} handler Event handler
@param {?boolean} method Add or remove. | [
"Add",
"or",
"remove",
"listeners",
"from",
"an",
"element",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/gesture/index.js#L178-L188 |
8,342 | mipengine/mip2 | packages/mip/src/components/mip-bind/watcher.js | flushWatcherQueue | function flushWatcherQueue () {
flushing = true
let watcher
let id
queue.sort((a, b) => a.id - b.id)
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production') {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
console.error(
`[MIP warn]:You may have an infinite update loop in watcher with expression "${watcher.exp}"`
)
break
}
}
}
resetState()
} | javascript | function flushWatcherQueue () {
flushing = true
let watcher
let id
queue.sort((a, b) => a.id - b.id)
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production') {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
console.error(
`[MIP warn]:You may have an infinite update loop in watcher with expression "${watcher.exp}"`
)
break
}
}
}
resetState()
} | [
"function",
"flushWatcherQueue",
"(",
")",
"{",
"flushing",
"=",
"true",
"let",
"watcher",
"let",
"id",
"queue",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"id",
"-",
"b",
".",
"id",
")",
"for",
"(",
"index",
"=",
"0",
";",
"index",
"<",
"queue",
".",
"length",
";",
"index",
"++",
")",
"{",
"watcher",
"=",
"queue",
"[",
"index",
"]",
"id",
"=",
"watcher",
".",
"id",
"has",
"[",
"id",
"]",
"=",
"null",
"watcher",
".",
"run",
"(",
")",
"// in dev build, check and stop circular updates.",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"circular",
"[",
"id",
"]",
"=",
"(",
"circular",
"[",
"id",
"]",
"||",
"0",
")",
"+",
"1",
"if",
"(",
"circular",
"[",
"id",
"]",
">",
"MAX_UPDATE_COUNT",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"watcher",
".",
"exp",
"}",
"`",
")",
"break",
"}",
"}",
"}",
"resetState",
"(",
")",
"}"
] | Flush queues and run the watchers. | [
"Flush",
"queues",
"and",
"run",
"the",
"watchers",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/components/mip-bind/watcher.js#L139-L164 |
8,343 | mipengine/mip2 | packages/mip/src/util/dom/event.js | createEvent | function createEvent (type, data) {
let event = document.createEvent(specialEvents[type] || 'Event')
event.initEvent(type, true, true)
data && (event.data = data)
return event
} | javascript | function createEvent (type, data) {
let event = document.createEvent(specialEvents[type] || 'Event')
event.initEvent(type, true, true)
data && (event.data = data)
return event
} | [
"function",
"createEvent",
"(",
"type",
",",
"data",
")",
"{",
"let",
"event",
"=",
"document",
".",
"createEvent",
"(",
"specialEvents",
"[",
"type",
"]",
"||",
"'Event'",
")",
"event",
".",
"initEvent",
"(",
"type",
",",
"true",
",",
"true",
")",
"data",
"&&",
"(",
"event",
".",
"data",
"=",
"data",
")",
"return",
"event",
"}"
] | Create a event object to dispatch
@param {string} type Event name
@param {?Object} data Custom data
@return {Event} | [
"Create",
"a",
"event",
"object",
"to",
"dispatch"
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/event.js#L42-L47 |
8,344 | mipengine/mip2 | packages/mip/src/util/dom/event.js | listenOnce | function listenOnce (element, eventType, listener, optEvtListenerOpts) {
let unlisten = listen(element, eventType, event => {
unlisten()
listener(event)
}, optEvtListenerOpts)
return unlisten
} | javascript | function listenOnce (element, eventType, listener, optEvtListenerOpts) {
let unlisten = listen(element, eventType, event => {
unlisten()
listener(event)
}, optEvtListenerOpts)
return unlisten
} | [
"function",
"listenOnce",
"(",
"element",
",",
"eventType",
",",
"listener",
",",
"optEvtListenerOpts",
")",
"{",
"let",
"unlisten",
"=",
"listen",
"(",
"element",
",",
"eventType",
",",
"event",
"=>",
"{",
"unlisten",
"(",
")",
"listener",
"(",
"event",
")",
"}",
",",
"optEvtListenerOpts",
")",
"return",
"unlisten",
"}"
] | Listens for the specified event on the element and removes the listener
as soon as event has been received.
@param {!EventTarget} element
@param {string} eventType
@param {function(!Event)} listener
@param {Object=} optEvtListenerOpts
@return {!UnlistenDef} | [
"Listens",
"for",
"the",
"specified",
"event",
"on",
"the",
"element",
"and",
"removes",
"the",
"listener",
"as",
"soon",
"as",
"event",
"has",
"been",
"received",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/event.js#L63-L69 |
8,345 | mipengine/mip2 | packages/mip/src/util/dom/event.js | loadPromise | function loadPromise (eleOrWindow) {
if (isLoaded(eleOrWindow)) {
return Promise.resolve(eleOrWindow)
}
let loadingPromise = new Promise((resolve, reject) => {
// Listen once since IE 5/6/7 fire the onload event continuously for
// animated GIFs.
let {tagName} = eleOrWindow
if (tagName === 'AUDIO' || tagName === 'VIDEO') {
listenOnce(eleOrWindow, 'loadstart', resolve)
} else {
listenOnce(eleOrWindow, 'load', resolve)
}
// For elements, unlisten on error (don't for Windows).
if (tagName) {
listenOnce(eleOrWindow, 'error', reject)
}
})
return loadingPromise
} | javascript | function loadPromise (eleOrWindow) {
if (isLoaded(eleOrWindow)) {
return Promise.resolve(eleOrWindow)
}
let loadingPromise = new Promise((resolve, reject) => {
// Listen once since IE 5/6/7 fire the onload event continuously for
// animated GIFs.
let {tagName} = eleOrWindow
if (tagName === 'AUDIO' || tagName === 'VIDEO') {
listenOnce(eleOrWindow, 'loadstart', resolve)
} else {
listenOnce(eleOrWindow, 'load', resolve)
}
// For elements, unlisten on error (don't for Windows).
if (tagName) {
listenOnce(eleOrWindow, 'error', reject)
}
})
return loadingPromise
} | [
"function",
"loadPromise",
"(",
"eleOrWindow",
")",
"{",
"if",
"(",
"isLoaded",
"(",
"eleOrWindow",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"eleOrWindow",
")",
"}",
"let",
"loadingPromise",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"// Listen once since IE 5/6/7 fire the onload event continuously for",
"// animated GIFs.",
"let",
"{",
"tagName",
"}",
"=",
"eleOrWindow",
"if",
"(",
"tagName",
"===",
"'AUDIO'",
"||",
"tagName",
"===",
"'VIDEO'",
")",
"{",
"listenOnce",
"(",
"eleOrWindow",
",",
"'loadstart'",
",",
"resolve",
")",
"}",
"else",
"{",
"listenOnce",
"(",
"eleOrWindow",
",",
"'load'",
",",
"resolve",
")",
"}",
"// For elements, unlisten on error (don't for Windows).",
"if",
"(",
"tagName",
")",
"{",
"listenOnce",
"(",
"eleOrWindow",
",",
"'error'",
",",
"reject",
")",
"}",
"}",
")",
"return",
"loadingPromise",
"}"
] | Returns a promise that will resolve or fail based on the eleOrWindow's 'load'
and 'error' events. Optionally this method takes a timeout, which will reject
the promise if the resource has not loaded by then.
@param {T} eleOrWindow Supports both Elements and as a special case Windows.
@return {!Promise<T>}
@template T | [
"Returns",
"a",
"promise",
"that",
"will",
"resolve",
"or",
"fail",
"based",
"on",
"the",
"eleOrWindow",
"s",
"load",
"and",
"error",
"events",
".",
"Optionally",
"this",
"method",
"takes",
"a",
"timeout",
"which",
"will",
"reject",
"the",
"promise",
"if",
"the",
"resource",
"has",
"not",
"loaded",
"by",
"then",
"."
] | f46dfdd628795d04054667ccd0e89f94e3c73821 | https://github.com/mipengine/mip2/blob/f46dfdd628795d04054667ccd0e89f94e3c73821/packages/mip/src/util/dom/event.js#L90-L111 |
8,346 | cubehouse/themeparks | lib/merlinparks/chessingtonworldofadventures.js | ParseArea | function ParseArea(obj) {
if (!obj) return;
if (obj.areas) {
for (var i in obj.areas) {
AddRideName(obj.areas[i]);
ParseArea(obj.areas[i]);
}
}
if (obj.items) {
for (var j in obj.items) {
AddRideName(obj.items[j]);
ParseArea(obj.items[j]);
}
}
} | javascript | function ParseArea(obj) {
if (!obj) return;
if (obj.areas) {
for (var i in obj.areas) {
AddRideName(obj.areas[i]);
ParseArea(obj.areas[i]);
}
}
if (obj.items) {
for (var j in obj.items) {
AddRideName(obj.items[j]);
ParseArea(obj.items[j]);
}
}
} | [
"function",
"ParseArea",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"return",
";",
"if",
"(",
"obj",
".",
"areas",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"obj",
".",
"areas",
")",
"{",
"AddRideName",
"(",
"obj",
".",
"areas",
"[",
"i",
"]",
")",
";",
"ParseArea",
"(",
"obj",
".",
"areas",
"[",
"i",
"]",
")",
";",
"}",
"}",
"if",
"(",
"obj",
".",
"items",
")",
"{",
"for",
"(",
"var",
"j",
"in",
"obj",
".",
"items",
")",
"{",
"AddRideName",
"(",
"obj",
".",
"items",
"[",
"j",
"]",
")",
";",
"ParseArea",
"(",
"obj",
".",
"items",
"[",
"j",
"]",
")",
";",
"}",
"}",
"}"
] | parse ride names from manually extracted JSON file | [
"parse",
"ride",
"names",
"from",
"manually",
"extracted",
"JSON",
"file"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/lib/merlinparks/chessingtonworldofadventures.js#L14-L31 |
8,347 | cubehouse/themeparks | docs/scripts/sunlight.js | function(context) {
var evaluate = function(rules, createRule) {
var i;
rules = rules || [];
for (i = 0; i < rules.length; i++) {
if (typeof(rules[i]) === "function") {
if (rules[i](context)) {
return defaultHandleToken("named-ident")(context);
}
} else if (createRule && createRule(rules[i])(context.tokens)) {
return defaultHandleToken("named-ident")(context);
}
}
return false;
};
return evaluate(context.language.namedIdentRules.custom)
|| evaluate(context.language.namedIdentRules.follows, function(ruleData) { return createProceduralRule(context.index - 1, -1, ruleData, context.language.caseInsensitive); })
|| evaluate(context.language.namedIdentRules.precedes, function(ruleData) { return createProceduralRule(context.index + 1, 1, ruleData, context.language.caseInsensitive); })
|| evaluate(context.language.namedIdentRules.between, function(ruleData) { return createBetweenRule(context.index, ruleData.opener, ruleData.closer, context.language.caseInsensitive); })
|| defaultHandleToken("ident")(context);
} | javascript | function(context) {
var evaluate = function(rules, createRule) {
var i;
rules = rules || [];
for (i = 0; i < rules.length; i++) {
if (typeof(rules[i]) === "function") {
if (rules[i](context)) {
return defaultHandleToken("named-ident")(context);
}
} else if (createRule && createRule(rules[i])(context.tokens)) {
return defaultHandleToken("named-ident")(context);
}
}
return false;
};
return evaluate(context.language.namedIdentRules.custom)
|| evaluate(context.language.namedIdentRules.follows, function(ruleData) { return createProceduralRule(context.index - 1, -1, ruleData, context.language.caseInsensitive); })
|| evaluate(context.language.namedIdentRules.precedes, function(ruleData) { return createProceduralRule(context.index + 1, 1, ruleData, context.language.caseInsensitive); })
|| evaluate(context.language.namedIdentRules.between, function(ruleData) { return createBetweenRule(context.index, ruleData.opener, ruleData.closer, context.language.caseInsensitive); })
|| defaultHandleToken("ident")(context);
} | [
"function",
"(",
"context",
")",
"{",
"var",
"evaluate",
"=",
"function",
"(",
"rules",
",",
"createRule",
")",
"{",
"var",
"i",
";",
"rules",
"=",
"rules",
"||",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"rules",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"(",
"rules",
"[",
"i",
"]",
")",
"===",
"\"function\"",
")",
"{",
"if",
"(",
"rules",
"[",
"i",
"]",
"(",
"context",
")",
")",
"{",
"return",
"defaultHandleToken",
"(",
"\"named-ident\"",
")",
"(",
"context",
")",
";",
"}",
"}",
"else",
"if",
"(",
"createRule",
"&&",
"createRule",
"(",
"rules",
"[",
"i",
"]",
")",
"(",
"context",
".",
"tokens",
")",
")",
"{",
"return",
"defaultHandleToken",
"(",
"\"named-ident\"",
")",
"(",
"context",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
";",
"return",
"evaluate",
"(",
"context",
".",
"language",
".",
"namedIdentRules",
".",
"custom",
")",
"||",
"evaluate",
"(",
"context",
".",
"language",
".",
"namedIdentRules",
".",
"follows",
",",
"function",
"(",
"ruleData",
")",
"{",
"return",
"createProceduralRule",
"(",
"context",
".",
"index",
"-",
"1",
",",
"-",
"1",
",",
"ruleData",
",",
"context",
".",
"language",
".",
"caseInsensitive",
")",
";",
"}",
")",
"||",
"evaluate",
"(",
"context",
".",
"language",
".",
"namedIdentRules",
".",
"precedes",
",",
"function",
"(",
"ruleData",
")",
"{",
"return",
"createProceduralRule",
"(",
"context",
".",
"index",
"+",
"1",
",",
"1",
",",
"ruleData",
",",
"context",
".",
"language",
".",
"caseInsensitive",
")",
";",
"}",
")",
"||",
"evaluate",
"(",
"context",
".",
"language",
".",
"namedIdentRules",
".",
"between",
",",
"function",
"(",
"ruleData",
")",
"{",
"return",
"createBetweenRule",
"(",
"context",
".",
"index",
",",
"ruleData",
".",
"opener",
",",
"ruleData",
".",
"closer",
",",
"context",
".",
"language",
".",
"caseInsensitive",
")",
";",
"}",
")",
"||",
"defaultHandleToken",
"(",
"\"ident\"",
")",
"(",
"context",
")",
";",
"}"
] | this handles the named ident mayhem | [
"this",
"handles",
"the",
"named",
"ident",
"mayhem"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L65-L87 |
|
8,348 | cubehouse/themeparks | docs/scripts/sunlight.js | last | function last(thing) {
return thing.charAt ? thing.charAt(thing.length - 1) : thing[thing.length - 1];
} | javascript | function last(thing) {
return thing.charAt ? thing.charAt(thing.length - 1) : thing[thing.length - 1];
} | [
"function",
"last",
"(",
"thing",
")",
"{",
"return",
"thing",
".",
"charAt",
"?",
"thing",
".",
"charAt",
"(",
"thing",
".",
"length",
"-",
"1",
")",
":",
"thing",
"[",
"thing",
".",
"length",
"-",
"1",
"]",
";",
"}"
] | gets the last character in a string or the last element in an array | [
"gets",
"the",
"last",
"character",
"in",
"a",
"string",
"or",
"the",
"last",
"element",
"in",
"an",
"array"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L254-L256 |
8,349 | cubehouse/themeparks | docs/scripts/sunlight.js | merge | function merge(defaultObject, objectToMerge) {
var key;
if (!objectToMerge) {
return defaultObject;
}
for (key in objectToMerge) {
defaultObject[key] = objectToMerge[key];
}
return defaultObject;
} | javascript | function merge(defaultObject, objectToMerge) {
var key;
if (!objectToMerge) {
return defaultObject;
}
for (key in objectToMerge) {
defaultObject[key] = objectToMerge[key];
}
return defaultObject;
} | [
"function",
"merge",
"(",
"defaultObject",
",",
"objectToMerge",
")",
"{",
"var",
"key",
";",
"if",
"(",
"!",
"objectToMerge",
")",
"{",
"return",
"defaultObject",
";",
"}",
"for",
"(",
"key",
"in",
"objectToMerge",
")",
"{",
"defaultObject",
"[",
"key",
"]",
"=",
"objectToMerge",
"[",
"key",
"]",
";",
"}",
"return",
"defaultObject",
";",
"}"
] | non-recursively merges one object into the other | [
"non",
"-",
"recursively",
"merges",
"one",
"object",
"into",
"the",
"other"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L279-L290 |
8,350 | cubehouse/themeparks | docs/scripts/sunlight.js | getNextWhile | function getNextWhile(tokens, index, direction, matcher) {
var count = 1,
token;
direction = direction || 1;
while (token = tokens[index + (direction * count++)]) {
if (!matcher(token)) {
return token;
}
}
return undefined;
} | javascript | function getNextWhile(tokens, index, direction, matcher) {
var count = 1,
token;
direction = direction || 1;
while (token = tokens[index + (direction * count++)]) {
if (!matcher(token)) {
return token;
}
}
return undefined;
} | [
"function",
"getNextWhile",
"(",
"tokens",
",",
"index",
",",
"direction",
",",
"matcher",
")",
"{",
"var",
"count",
"=",
"1",
",",
"token",
";",
"direction",
"=",
"direction",
"||",
"1",
";",
"while",
"(",
"token",
"=",
"tokens",
"[",
"index",
"+",
"(",
"direction",
"*",
"count",
"++",
")",
"]",
")",
"{",
"if",
"(",
"!",
"matcher",
"(",
"token",
")",
")",
"{",
"return",
"token",
";",
"}",
"}",
"return",
"undefined",
";",
"}"
] | gets the next token in the specified direction while matcher matches the current token | [
"gets",
"the",
"next",
"token",
"in",
"the",
"specified",
"direction",
"while",
"matcher",
"matches",
"the",
"current",
"token"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L424-L436 |
8,351 | cubehouse/themeparks | docs/scripts/sunlight.js | createHashMap | function createHashMap(wordMap, boundary, caseInsensitive) {
//creates a hash table where the hash is the first character of the word
var newMap = { },
i,
word,
firstChar;
for (i = 0; i < wordMap.length; i++) {
word = caseInsensitive ? wordMap[i].toUpperCase() : wordMap[i];
firstChar = word.charAt(0);
if (!newMap[firstChar]) {
newMap[firstChar] = [];
}
newMap[firstChar].push({ value: word, regex: new RegExp("^" + regexEscape(word) + boundary, caseInsensitive ? "i" : "") });
}
return newMap;
} | javascript | function createHashMap(wordMap, boundary, caseInsensitive) {
//creates a hash table where the hash is the first character of the word
var newMap = { },
i,
word,
firstChar;
for (i = 0; i < wordMap.length; i++) {
word = caseInsensitive ? wordMap[i].toUpperCase() : wordMap[i];
firstChar = word.charAt(0);
if (!newMap[firstChar]) {
newMap[firstChar] = [];
}
newMap[firstChar].push({ value: word, regex: new RegExp("^" + regexEscape(word) + boundary, caseInsensitive ? "i" : "") });
}
return newMap;
} | [
"function",
"createHashMap",
"(",
"wordMap",
",",
"boundary",
",",
"caseInsensitive",
")",
"{",
"//creates a hash table where the hash is the first character of the word",
"var",
"newMap",
"=",
"{",
"}",
",",
"i",
",",
"word",
",",
"firstChar",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"wordMap",
".",
"length",
";",
"i",
"++",
")",
"{",
"word",
"=",
"caseInsensitive",
"?",
"wordMap",
"[",
"i",
"]",
".",
"toUpperCase",
"(",
")",
":",
"wordMap",
"[",
"i",
"]",
";",
"firstChar",
"=",
"word",
".",
"charAt",
"(",
"0",
")",
";",
"if",
"(",
"!",
"newMap",
"[",
"firstChar",
"]",
")",
"{",
"newMap",
"[",
"firstChar",
"]",
"=",
"[",
"]",
";",
"}",
"newMap",
"[",
"firstChar",
"]",
".",
"push",
"(",
"{",
"value",
":",
"word",
",",
"regex",
":",
"new",
"RegExp",
"(",
"\"^\"",
"+",
"regexEscape",
"(",
"word",
")",
"+",
"boundary",
",",
"caseInsensitive",
"?",
"\"i\"",
":",
"\"\"",
")",
"}",
")",
";",
"}",
"return",
"newMap",
";",
"}"
] | this is crucial for performance | [
"this",
"is",
"crucial",
"for",
"performance"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L439-L457 |
8,352 | cubehouse/themeparks | docs/scripts/sunlight.js | switchToEmbeddedLanguageIfNecessary | function switchToEmbeddedLanguageIfNecessary(context) {
var i,
embeddedLanguage;
for (i = 0; i < context.language.embeddedLanguages.length; i++) {
if (!languages[context.language.embeddedLanguages[i].language]) {
//unregistered language
continue;
}
embeddedLanguage = clone(context.language.embeddedLanguages[i]);
if (embeddedLanguage.switchTo(context)) {
embeddedLanguage.oldItems = clone(context.items);
context.embeddedLanguageStack.push(embeddedLanguage);
context.language = languages[embeddedLanguage.language];
context.items = merge(context.items, clone(context.language.contextItems));
break;
}
}
} | javascript | function switchToEmbeddedLanguageIfNecessary(context) {
var i,
embeddedLanguage;
for (i = 0; i < context.language.embeddedLanguages.length; i++) {
if (!languages[context.language.embeddedLanguages[i].language]) {
//unregistered language
continue;
}
embeddedLanguage = clone(context.language.embeddedLanguages[i]);
if (embeddedLanguage.switchTo(context)) {
embeddedLanguage.oldItems = clone(context.items);
context.embeddedLanguageStack.push(embeddedLanguage);
context.language = languages[embeddedLanguage.language];
context.items = merge(context.items, clone(context.language.contextItems));
break;
}
}
} | [
"function",
"switchToEmbeddedLanguageIfNecessary",
"(",
"context",
")",
"{",
"var",
"i",
",",
"embeddedLanguage",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"context",
".",
"language",
".",
"embeddedLanguages",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"languages",
"[",
"context",
".",
"language",
".",
"embeddedLanguages",
"[",
"i",
"]",
".",
"language",
"]",
")",
"{",
"//unregistered language",
"continue",
";",
"}",
"embeddedLanguage",
"=",
"clone",
"(",
"context",
".",
"language",
".",
"embeddedLanguages",
"[",
"i",
"]",
")",
";",
"if",
"(",
"embeddedLanguage",
".",
"switchTo",
"(",
"context",
")",
")",
"{",
"embeddedLanguage",
".",
"oldItems",
"=",
"clone",
"(",
"context",
".",
"items",
")",
";",
"context",
".",
"embeddedLanguageStack",
".",
"push",
"(",
"embeddedLanguage",
")",
";",
"context",
".",
"language",
"=",
"languages",
"[",
"embeddedLanguage",
".",
"language",
"]",
";",
"context",
".",
"items",
"=",
"merge",
"(",
"context",
".",
"items",
",",
"clone",
"(",
"context",
".",
"language",
".",
"contextItems",
")",
")",
";",
"break",
";",
"}",
"}",
"}"
] | called before processing the current | [
"called",
"before",
"processing",
"the",
"current"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L724-L744 |
8,353 | cubehouse/themeparks | docs/scripts/sunlight.js | switchBackFromEmbeddedLanguageIfNecessary | function switchBackFromEmbeddedLanguageIfNecessary(context) {
var current = last(context.embeddedLanguageStack),
lang;
if (current && current.switchBack(context)) {
context.language = languages[current.parentLanguage];
lang = context.embeddedLanguageStack.pop();
//restore old items
context.items = clone(lang.oldItems);
lang.oldItems = {};
}
} | javascript | function switchBackFromEmbeddedLanguageIfNecessary(context) {
var current = last(context.embeddedLanguageStack),
lang;
if (current && current.switchBack(context)) {
context.language = languages[current.parentLanguage];
lang = context.embeddedLanguageStack.pop();
//restore old items
context.items = clone(lang.oldItems);
lang.oldItems = {};
}
} | [
"function",
"switchBackFromEmbeddedLanguageIfNecessary",
"(",
"context",
")",
"{",
"var",
"current",
"=",
"last",
"(",
"context",
".",
"embeddedLanguageStack",
")",
",",
"lang",
";",
"if",
"(",
"current",
"&&",
"current",
".",
"switchBack",
"(",
"context",
")",
")",
"{",
"context",
".",
"language",
"=",
"languages",
"[",
"current",
".",
"parentLanguage",
"]",
";",
"lang",
"=",
"context",
".",
"embeddedLanguageStack",
".",
"pop",
"(",
")",
";",
"//restore old items",
"context",
".",
"items",
"=",
"clone",
"(",
"lang",
".",
"oldItems",
")",
";",
"lang",
".",
"oldItems",
"=",
"{",
"}",
";",
"}",
"}"
] | called after processing the current | [
"called",
"after",
"processing",
"the",
"current"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L747-L759 |
8,354 | cubehouse/themeparks | docs/scripts/sunlight.js | highlightRecursive | function highlightRecursive(node) {
var match,
languageId,
currentNodeCount,
j,
nodes,
k,
partialContext,
container,
codeContainer;
if (this.isAlreadyHighlighted(node) || (match = this.matchSunlightNode(node)) === null) {
return;
}
languageId = match[1];
currentNodeCount = 0;
fireEvent("beforeHighlightNode", this, { node: node });
for (j = 0; j < node.childNodes.length; j++) {
if (node.childNodes[j].nodeType === 3) {
//text nodes
partialContext = highlightText.call(this, node.childNodes[j].nodeValue, languageId, partialContext);
HIGHLIGHTED_NODE_COUNT++;
currentNodeCount = currentNodeCount || HIGHLIGHTED_NODE_COUNT;
nodes = partialContext.getNodes();
node.replaceChild(nodes[0], node.childNodes[j]);
for (k = 1; k < nodes.length; k++) {
node.insertBefore(nodes[k], nodes[k - 1].nextSibling);
}
} else if (node.childNodes[j].nodeType === 1) {
//element nodes
highlightRecursive.call(this, node.childNodes[j]);
}
}
//indicate that this node has been highlighted
node.className += " " + this.options.classPrefix + "highlighted";
//if the node is block level, we put it in a container, otherwise we just leave it alone
if (getComputedStyle(node, "display") === "block") {
container = document.createElement("div");
container.className = this.options.classPrefix + "container";
codeContainer = document.createElement("div");
codeContainer.className = this.options.classPrefix + "code-container";
//apply max height if specified in options
if (this.options.maxHeight !== false) {
codeContainer.style.overflowY = "auto";
codeContainer.style.maxHeight = this.options.maxHeight + (/^\d+$/.test(this.options.maxHeight) ? "px" : "");
}
container.appendChild(codeContainer);
node.parentNode.insertBefore(codeContainer, node);
node.parentNode.removeChild(node);
codeContainer.appendChild(node);
codeContainer.parentNode.insertBefore(container, codeContainer);
codeContainer.parentNode.removeChild(codeContainer);
container.appendChild(codeContainer);
}
fireEvent("afterHighlightNode", this, {
container: container,
codeContainer: codeContainer,
node: node,
count: currentNodeCount
});
} | javascript | function highlightRecursive(node) {
var match,
languageId,
currentNodeCount,
j,
nodes,
k,
partialContext,
container,
codeContainer;
if (this.isAlreadyHighlighted(node) || (match = this.matchSunlightNode(node)) === null) {
return;
}
languageId = match[1];
currentNodeCount = 0;
fireEvent("beforeHighlightNode", this, { node: node });
for (j = 0; j < node.childNodes.length; j++) {
if (node.childNodes[j].nodeType === 3) {
//text nodes
partialContext = highlightText.call(this, node.childNodes[j].nodeValue, languageId, partialContext);
HIGHLIGHTED_NODE_COUNT++;
currentNodeCount = currentNodeCount || HIGHLIGHTED_NODE_COUNT;
nodes = partialContext.getNodes();
node.replaceChild(nodes[0], node.childNodes[j]);
for (k = 1; k < nodes.length; k++) {
node.insertBefore(nodes[k], nodes[k - 1].nextSibling);
}
} else if (node.childNodes[j].nodeType === 1) {
//element nodes
highlightRecursive.call(this, node.childNodes[j]);
}
}
//indicate that this node has been highlighted
node.className += " " + this.options.classPrefix + "highlighted";
//if the node is block level, we put it in a container, otherwise we just leave it alone
if (getComputedStyle(node, "display") === "block") {
container = document.createElement("div");
container.className = this.options.classPrefix + "container";
codeContainer = document.createElement("div");
codeContainer.className = this.options.classPrefix + "code-container";
//apply max height if specified in options
if (this.options.maxHeight !== false) {
codeContainer.style.overflowY = "auto";
codeContainer.style.maxHeight = this.options.maxHeight + (/^\d+$/.test(this.options.maxHeight) ? "px" : "");
}
container.appendChild(codeContainer);
node.parentNode.insertBefore(codeContainer, node);
node.parentNode.removeChild(node);
codeContainer.appendChild(node);
codeContainer.parentNode.insertBefore(container, codeContainer);
codeContainer.parentNode.removeChild(codeContainer);
container.appendChild(codeContainer);
}
fireEvent("afterHighlightNode", this, {
container: container,
codeContainer: codeContainer,
node: node,
count: currentNodeCount
});
} | [
"function",
"highlightRecursive",
"(",
"node",
")",
"{",
"var",
"match",
",",
"languageId",
",",
"currentNodeCount",
",",
"j",
",",
"nodes",
",",
"k",
",",
"partialContext",
",",
"container",
",",
"codeContainer",
";",
"if",
"(",
"this",
".",
"isAlreadyHighlighted",
"(",
"node",
")",
"||",
"(",
"match",
"=",
"this",
".",
"matchSunlightNode",
"(",
"node",
")",
")",
"===",
"null",
")",
"{",
"return",
";",
"}",
"languageId",
"=",
"match",
"[",
"1",
"]",
";",
"currentNodeCount",
"=",
"0",
";",
"fireEvent",
"(",
"\"beforeHighlightNode\"",
",",
"this",
",",
"{",
"node",
":",
"node",
"}",
")",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"node",
".",
"childNodes",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"node",
".",
"childNodes",
"[",
"j",
"]",
".",
"nodeType",
"===",
"3",
")",
"{",
"//text nodes",
"partialContext",
"=",
"highlightText",
".",
"call",
"(",
"this",
",",
"node",
".",
"childNodes",
"[",
"j",
"]",
".",
"nodeValue",
",",
"languageId",
",",
"partialContext",
")",
";",
"HIGHLIGHTED_NODE_COUNT",
"++",
";",
"currentNodeCount",
"=",
"currentNodeCount",
"||",
"HIGHLIGHTED_NODE_COUNT",
";",
"nodes",
"=",
"partialContext",
".",
"getNodes",
"(",
")",
";",
"node",
".",
"replaceChild",
"(",
"nodes",
"[",
"0",
"]",
",",
"node",
".",
"childNodes",
"[",
"j",
"]",
")",
";",
"for",
"(",
"k",
"=",
"1",
";",
"k",
"<",
"nodes",
".",
"length",
";",
"k",
"++",
")",
"{",
"node",
".",
"insertBefore",
"(",
"nodes",
"[",
"k",
"]",
",",
"nodes",
"[",
"k",
"-",
"1",
"]",
".",
"nextSibling",
")",
";",
"}",
"}",
"else",
"if",
"(",
"node",
".",
"childNodes",
"[",
"j",
"]",
".",
"nodeType",
"===",
"1",
")",
"{",
"//element nodes",
"highlightRecursive",
".",
"call",
"(",
"this",
",",
"node",
".",
"childNodes",
"[",
"j",
"]",
")",
";",
"}",
"}",
"//indicate that this node has been highlighted",
"node",
".",
"className",
"+=",
"\" \"",
"+",
"this",
".",
"options",
".",
"classPrefix",
"+",
"\"highlighted\"",
";",
"//if the node is block level, we put it in a container, otherwise we just leave it alone",
"if",
"(",
"getComputedStyle",
"(",
"node",
",",
"\"display\"",
")",
"===",
"\"block\"",
")",
"{",
"container",
"=",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"container",
".",
"className",
"=",
"this",
".",
"options",
".",
"classPrefix",
"+",
"\"container\"",
";",
"codeContainer",
"=",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"codeContainer",
".",
"className",
"=",
"this",
".",
"options",
".",
"classPrefix",
"+",
"\"code-container\"",
";",
"//apply max height if specified in options",
"if",
"(",
"this",
".",
"options",
".",
"maxHeight",
"!==",
"false",
")",
"{",
"codeContainer",
".",
"style",
".",
"overflowY",
"=",
"\"auto\"",
";",
"codeContainer",
".",
"style",
".",
"maxHeight",
"=",
"this",
".",
"options",
".",
"maxHeight",
"+",
"(",
"/",
"^\\d+$",
"/",
".",
"test",
"(",
"this",
".",
"options",
".",
"maxHeight",
")",
"?",
"\"px\"",
":",
"\"\"",
")",
";",
"}",
"container",
".",
"appendChild",
"(",
"codeContainer",
")",
";",
"node",
".",
"parentNode",
".",
"insertBefore",
"(",
"codeContainer",
",",
"node",
")",
";",
"node",
".",
"parentNode",
".",
"removeChild",
"(",
"node",
")",
";",
"codeContainer",
".",
"appendChild",
"(",
"node",
")",
";",
"codeContainer",
".",
"parentNode",
".",
"insertBefore",
"(",
"container",
",",
"codeContainer",
")",
";",
"codeContainer",
".",
"parentNode",
".",
"removeChild",
"(",
"codeContainer",
")",
";",
"container",
".",
"appendChild",
"(",
"codeContainer",
")",
";",
"}",
"fireEvent",
"(",
"\"afterHighlightNode\"",
",",
"this",
",",
"{",
"container",
":",
"container",
",",
"codeContainer",
":",
"codeContainer",
",",
"node",
":",
"node",
",",
"count",
":",
"currentNodeCount",
"}",
")",
";",
"}"
] | recursively highlights a DOM node | [
"recursively",
"highlights",
"a",
"DOM",
"node"
] | 0667da6b5c2e178d66257f0090f6cd5a77a003c6 | https://github.com/cubehouse/themeparks/blob/0667da6b5c2e178d66257f0090f6cd5a77a003c6/docs/scripts/sunlight.js#L994-L1064 |
8,355 | leaflet-extras/leaflet-providers | leaflet-providers.js | function (attr) {
if (attr.indexOf('{attribution.') === -1) {
return attr;
}
return attr.replace(/\{attribution.(\w*)\}/,
function (match, attributionName) {
return attributionReplacer(providers[attributionName].options.attribution);
}
);
} | javascript | function (attr) {
if (attr.indexOf('{attribution.') === -1) {
return attr;
}
return attr.replace(/\{attribution.(\w*)\}/,
function (match, attributionName) {
return attributionReplacer(providers[attributionName].options.attribution);
}
);
} | [
"function",
"(",
"attr",
")",
"{",
"if",
"(",
"attr",
".",
"indexOf",
"(",
"'{attribution.'",
")",
"===",
"-",
"1",
")",
"{",
"return",
"attr",
";",
"}",
"return",
"attr",
".",
"replace",
"(",
"/",
"\\{attribution.(\\w*)\\}",
"/",
",",
"function",
"(",
"match",
",",
"attributionName",
")",
"{",
"return",
"attributionReplacer",
"(",
"providers",
"[",
"attributionName",
"]",
".",
"options",
".",
"attribution",
")",
";",
"}",
")",
";",
"}"
] | replace attribution placeholders with their values from toplevel provider attribution, recursively | [
"replace",
"attribution",
"placeholders",
"with",
"their",
"values",
"from",
"toplevel",
"provider",
"attribution",
"recursively"
] | 2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4 | https://github.com/leaflet-extras/leaflet-providers/blob/2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4/leaflet-providers.js#L55-L64 |
|
8,356 | leaflet-extras/leaflet-providers | preview/vendor/leaflet.draw-src.js | function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
return (p2.y - p.y) * (p1.x - p.x) > (p1.y - p.y) * (p2.x - p.x);
} | javascript | function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
return (p2.y - p.y) * (p1.x - p.x) > (p1.y - p.y) * (p2.x - p.x);
} | [
"function",
"(",
"/*Point*/",
"p",
",",
"/*Point*/",
"p1",
",",
"/*Point*/",
"p2",
")",
"{",
"return",
"(",
"p2",
".",
"y",
"-",
"p",
".",
"y",
")",
"*",
"(",
"p1",
".",
"x",
"-",
"p",
".",
"x",
")",
">",
"(",
"p1",
".",
"y",
"-",
"p",
".",
"y",
")",
"*",
"(",
"p2",
".",
"x",
"-",
"p",
".",
"x",
")",
";",
"}"
] | check to see if points are in counterclockwise order | [
"check",
"to",
"see",
"if",
"points",
"are",
"in",
"counterclockwise",
"order"
] | 2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4 | https://github.com/leaflet-extras/leaflet-providers/blob/2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4/preview/vendor/leaflet.draw-src.js#L1847-L1849 |
|
8,357 | leaflet-extras/leaflet-providers | preview/vendor/leaflet.draw-src.js | function (p, p1, maxIndex, minIndex) {
var points = this._originalPoints,
p2, p3;
minIndex = minIndex || 0;
// Check all previous line segments (beside the immediately previous) for intersections
for (var j = maxIndex; j > minIndex; j--) {
p2 = points[j - 1];
p3 = points[j];
if (L.LineUtil.segmentsIntersect(p, p1, p2, p3)) {
return true;
}
}
return false;
} | javascript | function (p, p1, maxIndex, minIndex) {
var points = this._originalPoints,
p2, p3;
minIndex = minIndex || 0;
// Check all previous line segments (beside the immediately previous) for intersections
for (var j = maxIndex; j > minIndex; j--) {
p2 = points[j - 1];
p3 = points[j];
if (L.LineUtil.segmentsIntersect(p, p1, p2, p3)) {
return true;
}
}
return false;
} | [
"function",
"(",
"p",
",",
"p1",
",",
"maxIndex",
",",
"minIndex",
")",
"{",
"var",
"points",
"=",
"this",
".",
"_originalPoints",
",",
"p2",
",",
"p3",
";",
"minIndex",
"=",
"minIndex",
"||",
"0",
";",
"// Check all previous line segments (beside the immediately previous) for intersections",
"for",
"(",
"var",
"j",
"=",
"maxIndex",
";",
"j",
">",
"minIndex",
";",
"j",
"--",
")",
"{",
"p2",
"=",
"points",
"[",
"j",
"-",
"1",
"]",
";",
"p3",
"=",
"points",
"[",
"j",
"]",
";",
"if",
"(",
"L",
".",
"LineUtil",
".",
"segmentsIntersect",
"(",
"p",
",",
"p1",
",",
"p2",
",",
"p3",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks a line segment intersections with any line segments before its predecessor. Don't need to check the predecessor as will never intersect. | [
"Checks",
"a",
"line",
"segment",
"intersections",
"with",
"any",
"line",
"segments",
"before",
"its",
"predecessor",
".",
"Don",
"t",
"need",
"to",
"check",
"the",
"predecessor",
"as",
"will",
"never",
"intersect",
"."
] | 2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4 | https://github.com/leaflet-extras/leaflet-providers/blob/2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4/preview/vendor/leaflet.draw-src.js#L1918-L1935 |
|
8,358 | leaflet-extras/leaflet-providers | preview/vendor/leaflet.draw-src.js | function (handler) {
return [
{
enabled: handler.deleteLastVertex,
title: L.drawLocal.draw.toolbar.undo.title,
text: L.drawLocal.draw.toolbar.undo.text,
callback: handler.deleteLastVertex,
context: handler
},
{
title: L.drawLocal.draw.toolbar.actions.title,
text: L.drawLocal.draw.toolbar.actions.text,
callback: this.disable,
context: this
}
];
} | javascript | function (handler) {
return [
{
enabled: handler.deleteLastVertex,
title: L.drawLocal.draw.toolbar.undo.title,
text: L.drawLocal.draw.toolbar.undo.text,
callback: handler.deleteLastVertex,
context: handler
},
{
title: L.drawLocal.draw.toolbar.actions.title,
text: L.drawLocal.draw.toolbar.actions.text,
callback: this.disable,
context: this
}
];
} | [
"function",
"(",
"handler",
")",
"{",
"return",
"[",
"{",
"enabled",
":",
"handler",
".",
"deleteLastVertex",
",",
"title",
":",
"L",
".",
"drawLocal",
".",
"draw",
".",
"toolbar",
".",
"undo",
".",
"title",
",",
"text",
":",
"L",
".",
"drawLocal",
".",
"draw",
".",
"toolbar",
".",
"undo",
".",
"text",
",",
"callback",
":",
"handler",
".",
"deleteLastVertex",
",",
"context",
":",
"handler",
"}",
",",
"{",
"title",
":",
"L",
".",
"drawLocal",
".",
"draw",
".",
"toolbar",
".",
"actions",
".",
"title",
",",
"text",
":",
"L",
".",
"drawLocal",
".",
"draw",
".",
"toolbar",
".",
"actions",
".",
"text",
",",
"callback",
":",
"this",
".",
"disable",
",",
"context",
":",
"this",
"}",
"]",
";",
"}"
] | Get the actions part of the toolbar | [
"Get",
"the",
"actions",
"part",
"of",
"the",
"toolbar"
] | 2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4 | https://github.com/leaflet-extras/leaflet-providers/blob/2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4/preview/vendor/leaflet.draw-src.js#L2444-L2460 |
|
8,359 | leaflet-extras/leaflet-providers | preview/preview.js | function (providerName) {
if (providerName === 'ignored') {
return true;
}
// reduce the number of layers previewed for some providers
if (providerName.startsWith('HERE') || providerName.startsWith('OpenWeatherMap') || providerName.startsWith('MapBox')) {
var whitelist = [
// API threshold almost reached, disabling for now.
// 'HERE.normalDay',
'OpenWeatherMap.Clouds',
'OpenWeatherMap.Pressure',
'OpenWeatherMap.Wind'
];
return whitelist.indexOf(providerName) === -1;
}
return false;
} | javascript | function (providerName) {
if (providerName === 'ignored') {
return true;
}
// reduce the number of layers previewed for some providers
if (providerName.startsWith('HERE') || providerName.startsWith('OpenWeatherMap') || providerName.startsWith('MapBox')) {
var whitelist = [
// API threshold almost reached, disabling for now.
// 'HERE.normalDay',
'OpenWeatherMap.Clouds',
'OpenWeatherMap.Pressure',
'OpenWeatherMap.Wind'
];
return whitelist.indexOf(providerName) === -1;
}
return false;
} | [
"function",
"(",
"providerName",
")",
"{",
"if",
"(",
"providerName",
"===",
"'ignored'",
")",
"{",
"return",
"true",
";",
"}",
"// reduce the number of layers previewed for some providers",
"if",
"(",
"providerName",
".",
"startsWith",
"(",
"'HERE'",
")",
"||",
"providerName",
".",
"startsWith",
"(",
"'OpenWeatherMap'",
")",
"||",
"providerName",
".",
"startsWith",
"(",
"'MapBox'",
")",
")",
"{",
"var",
"whitelist",
"=",
"[",
"// API threshold almost reached, disabling for now.",
"// 'HERE.normalDay',",
"'OpenWeatherMap.Clouds'",
",",
"'OpenWeatherMap.Pressure'",
",",
"'OpenWeatherMap.Wind'",
"]",
";",
"return",
"whitelist",
".",
"indexOf",
"(",
"providerName",
")",
"===",
"-",
"1",
";",
"}",
"return",
"false",
";",
"}"
] | Ignore some providers in the preview | [
"Ignore",
"some",
"providers",
"in",
"the",
"preview"
] | 2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4 | https://github.com/leaflet-extras/leaflet-providers/blob/2f76cf3100c5e0eb0a53def3ea3659f55e49d2b4/preview/preview.js#L76-L92 |
|
8,360 | MMF-FE/vue-svgicon | dist/lib/build.js | compile | function compile(content, data) {
return content.replace(/\${(\w+)}/gi, function (match, name) {
return data[name] ? data[name] : '';
});
} | javascript | function compile(content, data) {
return content.replace(/\${(\w+)}/gi, function (match, name) {
return data[name] ? data[name] : '';
});
} | [
"function",
"compile",
"(",
"content",
",",
"data",
")",
"{",
"return",
"content",
".",
"replace",
"(",
"/",
"\\${(\\w+)}",
"/",
"gi",
",",
"function",
"(",
"match",
",",
"name",
")",
"{",
"return",
"data",
"[",
"name",
"]",
"?",
"data",
"[",
"name",
"]",
":",
"''",
";",
"}",
")",
";",
"}"
] | simple template compile | [
"simple",
"template",
"compile"
] | 1c5bc46d2e869acd0f962491fea267c086cbc3ce | https://github.com/MMF-FE/vue-svgicon/blob/1c5bc46d2e869acd0f962491fea267c086cbc3ce/dist/lib/build.js#L84-L88 |
8,361 | MMF-FE/vue-svgicon | dist/lib/build.js | getFilePath | function getFilePath(sourcePath, filename, subDir) {
if (subDir === void 0) { subDir = ''; }
var filePath = filename
.replace(path.resolve(sourcePath), '')
.replace(path.basename(filename), '');
if (subDir) {
filePath = filePath.replace(subDir + path.sep, '');
}
if (/^[\/\\]/.test(filePath)) {
filePath = filePath.substr(1);
}
return filePath.replace(/\\/g, '/');
} | javascript | function getFilePath(sourcePath, filename, subDir) {
if (subDir === void 0) { subDir = ''; }
var filePath = filename
.replace(path.resolve(sourcePath), '')
.replace(path.basename(filename), '');
if (subDir) {
filePath = filePath.replace(subDir + path.sep, '');
}
if (/^[\/\\]/.test(filePath)) {
filePath = filePath.substr(1);
}
return filePath.replace(/\\/g, '/');
} | [
"function",
"getFilePath",
"(",
"sourcePath",
",",
"filename",
",",
"subDir",
")",
"{",
"if",
"(",
"subDir",
"===",
"void",
"0",
")",
"{",
"subDir",
"=",
"''",
";",
"}",
"var",
"filePath",
"=",
"filename",
".",
"replace",
"(",
"path",
".",
"resolve",
"(",
"sourcePath",
")",
",",
"''",
")",
".",
"replace",
"(",
"path",
".",
"basename",
"(",
"filename",
")",
",",
"''",
")",
";",
"if",
"(",
"subDir",
")",
"{",
"filePath",
"=",
"filePath",
".",
"replace",
"(",
"subDir",
"+",
"path",
".",
"sep",
",",
"''",
")",
";",
"}",
"if",
"(",
"/",
"^[\\/\\\\]",
"/",
".",
"test",
"(",
"filePath",
")",
")",
"{",
"filePath",
"=",
"filePath",
".",
"substr",
"(",
"1",
")",
";",
"}",
"return",
"filePath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"}"
] | get file path by filename | [
"get",
"file",
"path",
"by",
"filename"
] | 1c5bc46d2e869acd0f962491fea267c086cbc3ce | https://github.com/MMF-FE/vue-svgicon/blob/1c5bc46d2e869acd0f962491fea267c086cbc3ce/dist/lib/build.js#L90-L102 |
8,362 | MMF-FE/vue-svgicon | dist/lib/build.js | generateIndex | function generateIndex(opts, files, subDir) {
if (subDir === void 0) { subDir = ''; }
var shouldExport = opts.export;
var isES6 = opts.es6;
var content = '';
var dirMap = {};
switch (opts.ext) {
case 'js':
content += '/* eslint-disable */\n';
break;
case 'ts':
content += '/* tslint:disable */\n';
break;
}
files.forEach(function (file) {
var name = path.basename(file).split('.')[0];
var filePath = getFilePath(opts.sourcePath, file, subDir);
var dir = filePath.split('/')[0];
if (dir) {
if (!dirMap[dir]) {
dirMap[dir] = [];
if (shouldExport) {
var dirName = camelcase_1.default(dir, {
pascalCase: true
});
content += isES6
? "export * as " + dirName + " from './" + dir + "'\n"
: "module.exports." + dirName + " = require('./" + dir + "')\n";
}
else {
content += isES6
? "import './" + dir + "'\n"
: "require('./" + dir + "')\n";
}
}
dirMap[dir].push(file);
}
else {
if (shouldExport) {
var fileName = camelcase_1.default(name, {
pascalCase: true
});
content += isES6
? "export " + fileName + " from './" + filePath + name + "'\n"
: "module.exports." + fileName + " = require('./" + filePath + name + "')\n";
}
else {
content += isES6
? "import './" + filePath + name + "'\n"
: "require('./" + filePath + name + "')\n";
}
}
});
fs.writeFileSync(path.join(opts.targetPath, subDir, "index." + opts.ext), content, 'utf-8');
console.log(colors.green("Generated " + (subDir ? subDir + path.sep : '') + "index." + opts.ext));
// generate subDir index.js
for (var dir in dirMap) {
generateIndex(opts, dirMap[dir], path.join(subDir, dir));
}
} | javascript | function generateIndex(opts, files, subDir) {
if (subDir === void 0) { subDir = ''; }
var shouldExport = opts.export;
var isES6 = opts.es6;
var content = '';
var dirMap = {};
switch (opts.ext) {
case 'js':
content += '/* eslint-disable */\n';
break;
case 'ts':
content += '/* tslint:disable */\n';
break;
}
files.forEach(function (file) {
var name = path.basename(file).split('.')[0];
var filePath = getFilePath(opts.sourcePath, file, subDir);
var dir = filePath.split('/')[0];
if (dir) {
if (!dirMap[dir]) {
dirMap[dir] = [];
if (shouldExport) {
var dirName = camelcase_1.default(dir, {
pascalCase: true
});
content += isES6
? "export * as " + dirName + " from './" + dir + "'\n"
: "module.exports." + dirName + " = require('./" + dir + "')\n";
}
else {
content += isES6
? "import './" + dir + "'\n"
: "require('./" + dir + "')\n";
}
}
dirMap[dir].push(file);
}
else {
if (shouldExport) {
var fileName = camelcase_1.default(name, {
pascalCase: true
});
content += isES6
? "export " + fileName + " from './" + filePath + name + "'\n"
: "module.exports." + fileName + " = require('./" + filePath + name + "')\n";
}
else {
content += isES6
? "import './" + filePath + name + "'\n"
: "require('./" + filePath + name + "')\n";
}
}
});
fs.writeFileSync(path.join(opts.targetPath, subDir, "index." + opts.ext), content, 'utf-8');
console.log(colors.green("Generated " + (subDir ? subDir + path.sep : '') + "index." + opts.ext));
// generate subDir index.js
for (var dir in dirMap) {
generateIndex(opts, dirMap[dir], path.join(subDir, dir));
}
} | [
"function",
"generateIndex",
"(",
"opts",
",",
"files",
",",
"subDir",
")",
"{",
"if",
"(",
"subDir",
"===",
"void",
"0",
")",
"{",
"subDir",
"=",
"''",
";",
"}",
"var",
"shouldExport",
"=",
"opts",
".",
"export",
";",
"var",
"isES6",
"=",
"opts",
".",
"es6",
";",
"var",
"content",
"=",
"''",
";",
"var",
"dirMap",
"=",
"{",
"}",
";",
"switch",
"(",
"opts",
".",
"ext",
")",
"{",
"case",
"'js'",
":",
"content",
"+=",
"'/* eslint-disable */\\n'",
";",
"break",
";",
"case",
"'ts'",
":",
"content",
"+=",
"'/* tslint:disable */\\n'",
";",
"break",
";",
"}",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"name",
"=",
"path",
".",
"basename",
"(",
"file",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
";",
"var",
"filePath",
"=",
"getFilePath",
"(",
"opts",
".",
"sourcePath",
",",
"file",
",",
"subDir",
")",
";",
"var",
"dir",
"=",
"filePath",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"dir",
")",
"{",
"if",
"(",
"!",
"dirMap",
"[",
"dir",
"]",
")",
"{",
"dirMap",
"[",
"dir",
"]",
"=",
"[",
"]",
";",
"if",
"(",
"shouldExport",
")",
"{",
"var",
"dirName",
"=",
"camelcase_1",
".",
"default",
"(",
"dir",
",",
"{",
"pascalCase",
":",
"true",
"}",
")",
";",
"content",
"+=",
"isES6",
"?",
"\"export * as \"",
"+",
"dirName",
"+",
"\" from './\"",
"+",
"dir",
"+",
"\"'\\n\"",
":",
"\"module.exports.\"",
"+",
"dirName",
"+",
"\" = require('./\"",
"+",
"dir",
"+",
"\"')\\n\"",
";",
"}",
"else",
"{",
"content",
"+=",
"isES6",
"?",
"\"import './\"",
"+",
"dir",
"+",
"\"'\\n\"",
":",
"\"require('./\"",
"+",
"dir",
"+",
"\"')\\n\"",
";",
"}",
"}",
"dirMap",
"[",
"dir",
"]",
".",
"push",
"(",
"file",
")",
";",
"}",
"else",
"{",
"if",
"(",
"shouldExport",
")",
"{",
"var",
"fileName",
"=",
"camelcase_1",
".",
"default",
"(",
"name",
",",
"{",
"pascalCase",
":",
"true",
"}",
")",
";",
"content",
"+=",
"isES6",
"?",
"\"export \"",
"+",
"fileName",
"+",
"\" from './\"",
"+",
"filePath",
"+",
"name",
"+",
"\"'\\n\"",
":",
"\"module.exports.\"",
"+",
"fileName",
"+",
"\" = require('./\"",
"+",
"filePath",
"+",
"name",
"+",
"\"')\\n\"",
";",
"}",
"else",
"{",
"content",
"+=",
"isES6",
"?",
"\"import './\"",
"+",
"filePath",
"+",
"name",
"+",
"\"'\\n\"",
":",
"\"require('./\"",
"+",
"filePath",
"+",
"name",
"+",
"\"')\\n\"",
";",
"}",
"}",
"}",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"opts",
".",
"targetPath",
",",
"subDir",
",",
"\"index.\"",
"+",
"opts",
".",
"ext",
")",
",",
"content",
",",
"'utf-8'",
")",
";",
"console",
".",
"log",
"(",
"colors",
".",
"green",
"(",
"\"Generated \"",
"+",
"(",
"subDir",
"?",
"subDir",
"+",
"path",
".",
"sep",
":",
"''",
")",
"+",
"\"index.\"",
"+",
"opts",
".",
"ext",
")",
")",
";",
"// generate subDir index.js",
"for",
"(",
"var",
"dir",
"in",
"dirMap",
")",
"{",
"generateIndex",
"(",
"opts",
",",
"dirMap",
"[",
"dir",
"]",
",",
"path",
".",
"join",
"(",
"subDir",
",",
"dir",
")",
")",
";",
"}",
"}"
] | generate index.js, which import all icons | [
"generate",
"index",
".",
"js",
"which",
"import",
"all",
"icons"
] | 1c5bc46d2e869acd0f962491fea267c086cbc3ce | https://github.com/MMF-FE/vue-svgicon/blob/1c5bc46d2e869acd0f962491fea267c086cbc3ce/dist/lib/build.js#L104-L163 |
8,363 | MMF-FE/vue-svgicon | dist/lib/build.js | getSvgoConfig | function getSvgoConfig(svgo) {
if (!svgo) {
return require('../../default/svgo');
}
else if (typeof svgo === 'string') {
return require(path.join(process.cwd(), svgo));
}
else {
return svgo;
}
} | javascript | function getSvgoConfig(svgo) {
if (!svgo) {
return require('../../default/svgo');
}
else if (typeof svgo === 'string') {
return require(path.join(process.cwd(), svgo));
}
else {
return svgo;
}
} | [
"function",
"getSvgoConfig",
"(",
"svgo",
")",
"{",
"if",
"(",
"!",
"svgo",
")",
"{",
"return",
"require",
"(",
"'../../default/svgo'",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"svgo",
"===",
"'string'",
")",
"{",
"return",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"svgo",
")",
")",
";",
"}",
"else",
"{",
"return",
"svgo",
";",
"}",
"}"
] | get svgo config | [
"get",
"svgo",
"config"
] | 1c5bc46d2e869acd0f962491fea267c086cbc3ce | https://github.com/MMF-FE/vue-svgicon/blob/1c5bc46d2e869acd0f962491fea267c086cbc3ce/dist/lib/build.js#L165-L175 |
8,364 | MMF-FE/vue-svgicon | dist/lib/build.js | getViewBox | function getViewBox(svgoResult) {
var viewBoxMatch = svgoResult.data.match(/viewBox="([-\d\.]+\s[-\d\.]+\s[-\d\.]+\s[-\d\.]+)"/);
var viewBox = '0 0 200 200';
if (viewBoxMatch && viewBoxMatch.length > 1) {
viewBox = viewBoxMatch[1];
}
else if (svgoResult.info.height && svgoResult.info.width) {
viewBox = "0 0 " + svgoResult.info.width + " " + svgoResult.info.height;
}
return viewBox;
} | javascript | function getViewBox(svgoResult) {
var viewBoxMatch = svgoResult.data.match(/viewBox="([-\d\.]+\s[-\d\.]+\s[-\d\.]+\s[-\d\.]+)"/);
var viewBox = '0 0 200 200';
if (viewBoxMatch && viewBoxMatch.length > 1) {
viewBox = viewBoxMatch[1];
}
else if (svgoResult.info.height && svgoResult.info.width) {
viewBox = "0 0 " + svgoResult.info.width + " " + svgoResult.info.height;
}
return viewBox;
} | [
"function",
"getViewBox",
"(",
"svgoResult",
")",
"{",
"var",
"viewBoxMatch",
"=",
"svgoResult",
".",
"data",
".",
"match",
"(",
"/",
"viewBox=\"([-\\d\\.]+\\s[-\\d\\.]+\\s[-\\d\\.]+\\s[-\\d\\.]+)\"",
"/",
")",
";",
"var",
"viewBox",
"=",
"'0 0 200 200'",
";",
"if",
"(",
"viewBoxMatch",
"&&",
"viewBoxMatch",
".",
"length",
">",
"1",
")",
"{",
"viewBox",
"=",
"viewBoxMatch",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"svgoResult",
".",
"info",
".",
"height",
"&&",
"svgoResult",
".",
"info",
".",
"width",
")",
"{",
"viewBox",
"=",
"\"0 0 \"",
"+",
"svgoResult",
".",
"info",
".",
"width",
"+",
"\" \"",
"+",
"svgoResult",
".",
"info",
".",
"height",
";",
"}",
"return",
"viewBox",
";",
"}"
] | get svg viewbox | [
"get",
"svg",
"viewbox"
] | 1c5bc46d2e869acd0f962491fea267c086cbc3ce | https://github.com/MMF-FE/vue-svgicon/blob/1c5bc46d2e869acd0f962491fea267c086cbc3ce/dist/lib/build.js#L177-L187 |
8,365 | MMF-FE/vue-svgicon | dist/lib/build.js | addPid | function addPid(content) {
var shapeReg = /<(path|rect|circle|polygon|line|polyline|ellipse)\s/gi;
var id = 0;
content = content.replace(shapeReg, function (match) {
return match + ("pid=\"" + id++ + "\" ");
});
return content;
} | javascript | function addPid(content) {
var shapeReg = /<(path|rect|circle|polygon|line|polyline|ellipse)\s/gi;
var id = 0;
content = content.replace(shapeReg, function (match) {
return match + ("pid=\"" + id++ + "\" ");
});
return content;
} | [
"function",
"addPid",
"(",
"content",
")",
"{",
"var",
"shapeReg",
"=",
"/",
"<(path|rect|circle|polygon|line|polyline|ellipse)\\s",
"/",
"gi",
";",
"var",
"id",
"=",
"0",
";",
"content",
"=",
"content",
".",
"replace",
"(",
"shapeReg",
",",
"function",
"(",
"match",
")",
"{",
"return",
"match",
"+",
"(",
"\"pid=\\\"\"",
"+",
"id",
"++",
"+",
"\"\\\" \"",
")",
";",
"}",
")",
";",
"return",
"content",
";",
"}"
] | add pid attr, for css | [
"add",
"pid",
"attr",
"for",
"css"
] | 1c5bc46d2e869acd0f962491fea267c086cbc3ce | https://github.com/MMF-FE/vue-svgicon/blob/1c5bc46d2e869acd0f962491fea267c086cbc3ce/dist/lib/build.js#L189-L196 |
8,366 | GoogleChrome/accessibility-developer-tools | src/js/AccessibilityUtils.js | getHtmlInfo | function getHtmlInfo(element) {
if (!element)
return null;
var tagName = element.tagName;
if (!tagName)
return null;
tagName = tagName.toUpperCase();
var infos = axs.constants.TAG_TO_IMPLICIT_SEMANTIC_INFO[tagName];
if (!infos || !infos.length)
return null;
var defaultInfo = null; // will contain the info with no specific selector if no others match
for (var i = 0, len = infos.length; i < len; i++) {
var htmlInfo = infos[i];
if (htmlInfo.selector) {
if (axs.browserUtils.matchSelector(element, htmlInfo.selector))
return htmlInfo;
} else {
defaultInfo = htmlInfo;
}
}
return defaultInfo;
} | javascript | function getHtmlInfo(element) {
if (!element)
return null;
var tagName = element.tagName;
if (!tagName)
return null;
tagName = tagName.toUpperCase();
var infos = axs.constants.TAG_TO_IMPLICIT_SEMANTIC_INFO[tagName];
if (!infos || !infos.length)
return null;
var defaultInfo = null; // will contain the info with no specific selector if no others match
for (var i = 0, len = infos.length; i < len; i++) {
var htmlInfo = infos[i];
if (htmlInfo.selector) {
if (axs.browserUtils.matchSelector(element, htmlInfo.selector))
return htmlInfo;
} else {
defaultInfo = htmlInfo;
}
}
return defaultInfo;
} | [
"function",
"getHtmlInfo",
"(",
"element",
")",
"{",
"if",
"(",
"!",
"element",
")",
"return",
"null",
";",
"var",
"tagName",
"=",
"element",
".",
"tagName",
";",
"if",
"(",
"!",
"tagName",
")",
"return",
"null",
";",
"tagName",
"=",
"tagName",
".",
"toUpperCase",
"(",
")",
";",
"var",
"infos",
"=",
"axs",
".",
"constants",
".",
"TAG_TO_IMPLICIT_SEMANTIC_INFO",
"[",
"tagName",
"]",
";",
"if",
"(",
"!",
"infos",
"||",
"!",
"infos",
".",
"length",
")",
"return",
"null",
";",
"var",
"defaultInfo",
"=",
"null",
";",
"// will contain the info with no specific selector if no others match",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"infos",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"htmlInfo",
"=",
"infos",
"[",
"i",
"]",
";",
"if",
"(",
"htmlInfo",
".",
"selector",
")",
"{",
"if",
"(",
"axs",
".",
"browserUtils",
".",
"matchSelector",
"(",
"element",
",",
"htmlInfo",
".",
"selector",
")",
")",
"return",
"htmlInfo",
";",
"}",
"else",
"{",
"defaultInfo",
"=",
"htmlInfo",
";",
"}",
"}",
"return",
"defaultInfo",
";",
"}"
] | Helper for implicit semantic functionality.
Can be made part of the public API if need be.
@param {Element} element
@return {?axs.constants.HtmlInfo} | [
"Helper",
"for",
"implicit",
"semantic",
"functionality",
".",
"Can",
"be",
"made",
"part",
"of",
"the",
"public",
"API",
"if",
"need",
"be",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/js/AccessibilityUtils.js#L667-L688 |
8,367 | GoogleChrome/accessibility-developer-tools | src/audits/RequiredOwnedAriaRoleMissing.js | getRequired | function getRequired(element) {
var elementRole = axs.utils.getRoles(element);
if (!elementRole || !elementRole.applied)
return [];
var appliedRole = elementRole.applied;
if (!appliedRole.valid)
return [];
return appliedRole.details['mustcontain'] || [];
} | javascript | function getRequired(element) {
var elementRole = axs.utils.getRoles(element);
if (!elementRole || !elementRole.applied)
return [];
var appliedRole = elementRole.applied;
if (!appliedRole.valid)
return [];
return appliedRole.details['mustcontain'] || [];
} | [
"function",
"getRequired",
"(",
"element",
")",
"{",
"var",
"elementRole",
"=",
"axs",
".",
"utils",
".",
"getRoles",
"(",
"element",
")",
";",
"if",
"(",
"!",
"elementRole",
"||",
"!",
"elementRole",
".",
"applied",
")",
"return",
"[",
"]",
";",
"var",
"appliedRole",
"=",
"elementRole",
".",
"applied",
";",
"if",
"(",
"!",
"appliedRole",
".",
"valid",
")",
"return",
"[",
"]",
";",
"return",
"appliedRole",
".",
"details",
"[",
"'mustcontain'",
"]",
"||",
"[",
"]",
";",
"}"
] | Get a list of the roles this element must contain, if any, based on its ARIA role.
@param {Element} element A DOM element.
@return {Array.<string>} The roles this element must contain. | [
"Get",
"a",
"list",
"of",
"the",
"roles",
"this",
"element",
"must",
"contain",
"if",
"any",
"based",
"on",
"its",
"ARIA",
"role",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/RequiredOwnedAriaRoleMissing.js#L75-L83 |
8,368 | GoogleChrome/accessibility-developer-tools | src/audits/TableHasAppropriateHeaders.js | tableDoesNotHaveHeaderRow | function tableDoesNotHaveHeaderRow(rows) {
var headerRow = rows[0];
var headerCells = headerRow.children;
for (var i = 0; i < headerCells.length; i++) {
if (headerCells[i].tagName != 'TH') {
return true;
}
}
return false;
} | javascript | function tableDoesNotHaveHeaderRow(rows) {
var headerRow = rows[0];
var headerCells = headerRow.children;
for (var i = 0; i < headerCells.length; i++) {
if (headerCells[i].tagName != 'TH') {
return true;
}
}
return false;
} | [
"function",
"tableDoesNotHaveHeaderRow",
"(",
"rows",
")",
"{",
"var",
"headerRow",
"=",
"rows",
"[",
"0",
"]",
";",
"var",
"headerCells",
"=",
"headerRow",
".",
"children",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"headerCells",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"headerCells",
"[",
"i",
"]",
".",
"tagName",
"!=",
"'TH'",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks for a header row in a table.
@param {NodeList} rows tr elements
@returns {boolean} Table does not have a complete header row | [
"Checks",
"for",
"a",
"header",
"row",
"in",
"a",
"table",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/TableHasAppropriateHeaders.js#L26-L37 |
8,369 | GoogleChrome/accessibility-developer-tools | src/audits/TableHasAppropriateHeaders.js | tableDoesNotHaveHeaderColumn | function tableDoesNotHaveHeaderColumn(rows) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].children[0].tagName != 'TH') {
return true;
}
}
return false;
} | javascript | function tableDoesNotHaveHeaderColumn(rows) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].children[0].tagName != 'TH') {
return true;
}
}
return false;
} | [
"function",
"tableDoesNotHaveHeaderColumn",
"(",
"rows",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rows",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rows",
"[",
"i",
"]",
".",
"children",
"[",
"0",
"]",
".",
"tagName",
"!=",
"'TH'",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks for a header column in a table.
@param {NodeList} rows tr elements
@returns {boolean} Table does not have a complete header column | [
"Checks",
"for",
"a",
"header",
"column",
"in",
"a",
"table",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/TableHasAppropriateHeaders.js#L45-L52 |
8,370 | GoogleChrome/accessibility-developer-tools | src/audits/TableHasAppropriateHeaders.js | tableDoesNotHaveGridLayout | function tableDoesNotHaveGridLayout(rows) {
var headerCells = rows[0].children;
for (var i = 1; i < headerCells.length; i++) {
if (headerCells[i].tagName != 'TH') {
return true;
}
}
for (var i = 1; i < rows.length; i++) {
if (rows[i].children[0].tagName != 'TH') {
return true;
}
}
return false;
} | javascript | function tableDoesNotHaveGridLayout(rows) {
var headerCells = rows[0].children;
for (var i = 1; i < headerCells.length; i++) {
if (headerCells[i].tagName != 'TH') {
return true;
}
}
for (var i = 1; i < rows.length; i++) {
if (rows[i].children[0].tagName != 'TH') {
return true;
}
}
return false;
} | [
"function",
"tableDoesNotHaveGridLayout",
"(",
"rows",
")",
"{",
"var",
"headerCells",
"=",
"rows",
"[",
"0",
"]",
".",
"children",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"headerCells",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"headerCells",
"[",
"i",
"]",
".",
"tagName",
"!=",
"'TH'",
")",
"{",
"return",
"true",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"rows",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rows",
"[",
"i",
"]",
".",
"children",
"[",
"0",
"]",
".",
"tagName",
"!=",
"'TH'",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks whether a table has grid layout with both row and column headers.
@param {NodeList} rows tr elements
@returns {boolean} Table does not have a complete grid layout | [
"Checks",
"whether",
"a",
"table",
"has",
"grid",
"layout",
"with",
"both",
"row",
"and",
"column",
"headers",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/TableHasAppropriateHeaders.js#L60-L75 |
8,371 | GoogleChrome/accessibility-developer-tools | src/audits/TableHasAppropriateHeaders.js | isLayoutTable | function isLayoutTable(element) {
if (element.childElementCount == 0) {
return true;
}
if (element.hasAttribute('role') && element.getAttribute('role') != 'presentation') {
return false;
}
if (element.getAttribute('role') == 'presentation') {
var tableChildren = element.querySelectorAll('*')
// layout tables should only contain TR and TD elements
for (var i = 0; i < tableChildren.length; i++) {
if (tableChildren[i].tagName != 'TR' && tableChildren[i].tagName != 'TD') {
return false;
}
}
return true;
}
return false;
} | javascript | function isLayoutTable(element) {
if (element.childElementCount == 0) {
return true;
}
if (element.hasAttribute('role') && element.getAttribute('role') != 'presentation') {
return false;
}
if (element.getAttribute('role') == 'presentation') {
var tableChildren = element.querySelectorAll('*')
// layout tables should only contain TR and TD elements
for (var i = 0; i < tableChildren.length; i++) {
if (tableChildren[i].tagName != 'TR' && tableChildren[i].tagName != 'TD') {
return false;
}
}
return true;
}
return false;
} | [
"function",
"isLayoutTable",
"(",
"element",
")",
"{",
"if",
"(",
"element",
".",
"childElementCount",
"==",
"0",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"element",
".",
"hasAttribute",
"(",
"'role'",
")",
"&&",
"element",
".",
"getAttribute",
"(",
"'role'",
")",
"!=",
"'presentation'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"element",
".",
"getAttribute",
"(",
"'role'",
")",
"==",
"'presentation'",
")",
"{",
"var",
"tableChildren",
"=",
"element",
".",
"querySelectorAll",
"(",
"'*'",
")",
"// layout tables should only contain TR and TD elements",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tableChildren",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"tableChildren",
"[",
"i",
"]",
".",
"tagName",
"!=",
"'TR'",
"&&",
"tableChildren",
"[",
"i",
"]",
".",
"tagName",
"!=",
"'TD'",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Checks whether a table is a layout table.
@returns {boolean} Table is a layout table | [
"Checks",
"whether",
"a",
"table",
"is",
"a",
"layout",
"table",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/TableHasAppropriateHeaders.js#L82-L105 |
8,372 | GoogleChrome/accessibility-developer-tools | src/js/Properties.js | hasDirectTextDescendantXpath | function hasDirectTextDescendantXpath() {
var selectorResults = ownerDocument.evaluate(axs.properties.TEXT_CONTENT_XPATH,
element,
null,
XPathResult.ANY_TYPE,
null);
for (var resultElement = selectorResults.iterateNext();
resultElement != null;
resultElement = selectorResults.iterateNext()) {
if (resultElement !== element)
continue;
return true;
}
return false;
} | javascript | function hasDirectTextDescendantXpath() {
var selectorResults = ownerDocument.evaluate(axs.properties.TEXT_CONTENT_XPATH,
element,
null,
XPathResult.ANY_TYPE,
null);
for (var resultElement = selectorResults.iterateNext();
resultElement != null;
resultElement = selectorResults.iterateNext()) {
if (resultElement !== element)
continue;
return true;
}
return false;
} | [
"function",
"hasDirectTextDescendantXpath",
"(",
")",
"{",
"var",
"selectorResults",
"=",
"ownerDocument",
".",
"evaluate",
"(",
"axs",
".",
"properties",
".",
"TEXT_CONTENT_XPATH",
",",
"element",
",",
"null",
",",
"XPathResult",
".",
"ANY_TYPE",
",",
"null",
")",
";",
"for",
"(",
"var",
"resultElement",
"=",
"selectorResults",
".",
"iterateNext",
"(",
")",
";",
"resultElement",
"!=",
"null",
";",
"resultElement",
"=",
"selectorResults",
".",
"iterateNext",
"(",
")",
")",
"{",
"if",
"(",
"resultElement",
"!==",
"element",
")",
"continue",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Determines whether element has a text node as a direct descendant.
This method uses XPath on HTML DOM which is not universally supported.
@return {boolean} | [
"Determines",
"whether",
"element",
"has",
"a",
"text",
"node",
"as",
"a",
"direct",
"descendant",
".",
"This",
"method",
"uses",
"XPath",
"on",
"HTML",
"DOM",
"which",
"is",
"not",
"universally",
"supported",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/js/Properties.js#L148-L162 |
8,373 | GoogleChrome/accessibility-developer-tools | src/js/Audit.js | function(auditRuleName, selectors) {
if (!(auditRuleName in this.rules_))
this.rules_[auditRuleName] = {};
if (!('ignore' in this.rules_[auditRuleName]))
this.rules_[auditRuleName].ignore = [];
Array.prototype.push.call(this.rules_[auditRuleName].ignore, selectors);
} | javascript | function(auditRuleName, selectors) {
if (!(auditRuleName in this.rules_))
this.rules_[auditRuleName] = {};
if (!('ignore' in this.rules_[auditRuleName]))
this.rules_[auditRuleName].ignore = [];
Array.prototype.push.call(this.rules_[auditRuleName].ignore, selectors);
} | [
"function",
"(",
"auditRuleName",
",",
"selectors",
")",
"{",
"if",
"(",
"!",
"(",
"auditRuleName",
"in",
"this",
".",
"rules_",
")",
")",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"(",
"'ignore'",
"in",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
")",
")",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
".",
"ignore",
"=",
"[",
"]",
";",
"Array",
".",
"prototype",
".",
"push",
".",
"call",
"(",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
".",
"ignore",
",",
"selectors",
")",
";",
"}"
] | Add the given selectors to the ignore list for the given audit rule.
@param {string} auditRuleName The name of the audit rule
@param {Array.<string>} selectors Query selectors to match nodes to
ignore | [
"Add",
"the",
"given",
"selectors",
"to",
"the",
"ignore",
"list",
"for",
"the",
"given",
"audit",
"rule",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/js/Audit.js#L134-L140 |
|
8,374 | GoogleChrome/accessibility-developer-tools | src/js/Audit.js | function(auditRuleName, severity) {
if (!(auditRuleName in this.rules_))
this.rules_[auditRuleName] = {};
this.rules_[auditRuleName].severity = severity;
} | javascript | function(auditRuleName, severity) {
if (!(auditRuleName in this.rules_))
this.rules_[auditRuleName] = {};
this.rules_[auditRuleName].severity = severity;
} | [
"function",
"(",
"auditRuleName",
",",
"severity",
")",
"{",
"if",
"(",
"!",
"(",
"auditRuleName",
"in",
"this",
".",
"rules_",
")",
")",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
"=",
"{",
"}",
";",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
".",
"severity",
"=",
"severity",
";",
"}"
] | Sets the user-specified severity for the given audit rule. This will
replace the default severity for that audit rule in the audit results.
@param {string} auditRuleName
@param {axs.constants.Severity} severity | [
"Sets",
"the",
"user",
"-",
"specified",
"severity",
"for",
"the",
"given",
"audit",
"rule",
".",
"This",
"will",
"replace",
"the",
"default",
"severity",
"for",
"that",
"audit",
"rule",
"in",
"the",
"audit",
"results",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/js/Audit.js#L163-L167 |
|
8,375 | GoogleChrome/accessibility-developer-tools | src/js/Audit.js | function(auditRuleName, config) {
if (!(auditRuleName in this.rules_))
this.rules_[auditRuleName] = {};
this.rules_[auditRuleName].config = config;
} | javascript | function(auditRuleName, config) {
if (!(auditRuleName in this.rules_))
this.rules_[auditRuleName] = {};
this.rules_[auditRuleName].config = config;
} | [
"function",
"(",
"auditRuleName",
",",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"auditRuleName",
"in",
"this",
".",
"rules_",
")",
")",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
"=",
"{",
"}",
";",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
".",
"config",
"=",
"config",
";",
"}"
] | Sets the user-specified configuration for the given audit rule. This will
vary in structure from rule to rule; see individual rules for
configuration options.
@param {string} auditRuleName
@param {Object} config | [
"Sets",
"the",
"user",
"-",
"specified",
"configuration",
"for",
"the",
"given",
"audit",
"rule",
".",
"This",
"will",
"vary",
"in",
"structure",
"from",
"rule",
"to",
"rule",
";",
"see",
"individual",
"rules",
"for",
"configuration",
"options",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/js/Audit.js#L184-L188 |
|
8,376 | GoogleChrome/accessibility-developer-tools | src/js/Audit.js | function(auditRuleName) {
if (!(auditRuleName in this.rules_))
return null;
if (!('config' in this.rules_[auditRuleName]))
return null;
return this.rules_[auditRuleName].config;
} | javascript | function(auditRuleName) {
if (!(auditRuleName in this.rules_))
return null;
if (!('config' in this.rules_[auditRuleName]))
return null;
return this.rules_[auditRuleName].config;
} | [
"function",
"(",
"auditRuleName",
")",
"{",
"if",
"(",
"!",
"(",
"auditRuleName",
"in",
"this",
".",
"rules_",
")",
")",
"return",
"null",
";",
"if",
"(",
"!",
"(",
"'config'",
"in",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
")",
")",
"return",
"null",
";",
"return",
"this",
".",
"rules_",
"[",
"auditRuleName",
"]",
".",
"config",
";",
"}"
] | Gets the user-specified configuration for the given audit rule.
@param {string} auditRuleName
@return {Object?} The configuration object for the given audit rule. | [
"Gets",
"the",
"user",
"-",
"specified",
"configuration",
"for",
"the",
"given",
"audit",
"rule",
"."
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/js/Audit.js#L195-L201 |
|
8,377 | GoogleChrome/accessibility-developer-tools | src/audits/UncontrolledTabpanel.js | labeledByATab | function labeledByATab(element) {
if (element.hasAttribute('aria-labelledby')) {
var labelingElements = document.querySelectorAll('#' + element.getAttribute('aria-labelledby'));
return labelingElements.length === 1 && labelingElements[0].getAttribute('role') === 'tab';
}
return false;
} | javascript | function labeledByATab(element) {
if (element.hasAttribute('aria-labelledby')) {
var labelingElements = document.querySelectorAll('#' + element.getAttribute('aria-labelledby'));
return labelingElements.length === 1 && labelingElements[0].getAttribute('role') === 'tab';
}
return false;
} | [
"function",
"labeledByATab",
"(",
"element",
")",
"{",
"if",
"(",
"element",
".",
"hasAttribute",
"(",
"'aria-labelledby'",
")",
")",
"{",
"var",
"labelingElements",
"=",
"document",
".",
"querySelectorAll",
"(",
"'#'",
"+",
"element",
".",
"getAttribute",
"(",
"'aria-labelledby'",
")",
")",
";",
"return",
"labelingElements",
".",
"length",
"===",
"1",
"&&",
"labelingElements",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"'role'",
")",
"===",
"'tab'",
";",
"}",
"return",
"false",
";",
"}"
] | Checks if the tabpanel is labeled by a tab
@param {Element} element the tabpanel element
@returns {boolean} the tabpanel has an aria-labelledby with the id of a tab | [
"Checks",
"if",
"the",
"tabpanel",
"is",
"labeled",
"by",
"a",
"tab"
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/UncontrolledTabpanel.js#L26-L32 |
8,378 | GoogleChrome/accessibility-developer-tools | src/audits/UncontrolledTabpanel.js | controlledByATab | function controlledByATab(element) {
var controlledBy = document.querySelectorAll('[role="tab"][aria-controls="' + element.id + '"]')
return element.id && (controlledBy.length === 1);
} | javascript | function controlledByATab(element) {
var controlledBy = document.querySelectorAll('[role="tab"][aria-controls="' + element.id + '"]')
return element.id && (controlledBy.length === 1);
} | [
"function",
"controlledByATab",
"(",
"element",
")",
"{",
"var",
"controlledBy",
"=",
"document",
".",
"querySelectorAll",
"(",
"'[role=\"tab\"][aria-controls=\"'",
"+",
"element",
".",
"id",
"+",
"'\"]'",
")",
"return",
"element",
".",
"id",
"&&",
"(",
"controlledBy",
".",
"length",
"===",
"1",
")",
";",
"}"
] | Checks if the tabpanel is controlled by a tab
@param {Element} element the tabpanel element
@returns {*|boolean} | [
"Checks",
"if",
"the",
"tabpanel",
"is",
"controlled",
"by",
"a",
"tab"
] | 3d7c96bf34b3146f40aeb2720e0927f221ad8725 | https://github.com/GoogleChrome/accessibility-developer-tools/blob/3d7c96bf34b3146f40aeb2720e0927f221ad8725/src/audits/UncontrolledTabpanel.js#L39-L42 |
8,379 | NekR/offline-plugin | lib/misc/utils.js | arrowFnToNormalFn | function arrowFnToNormalFn(string) {
var match = string.match(/^([\s\S]+?)=\>(\s*{)?([\s\S]*?)(}\s*)?$/);
if (!match) {
return string;
}
var args = match[1];
var body = match[3];
var needsReturn = !(match[2] && match[4]);
args = args.replace(/^(\s*\(\s*)([\s\S]*?)(\s*\)\s*)$/, '$2');
if (needsReturn) {
body = 'return ' + body;
}
return 'function(' + args + ') {' + body + '}';
} | javascript | function arrowFnToNormalFn(string) {
var match = string.match(/^([\s\S]+?)=\>(\s*{)?([\s\S]*?)(}\s*)?$/);
if (!match) {
return string;
}
var args = match[1];
var body = match[3];
var needsReturn = !(match[2] && match[4]);
args = args.replace(/^(\s*\(\s*)([\s\S]*?)(\s*\)\s*)$/, '$2');
if (needsReturn) {
body = 'return ' + body;
}
return 'function(' + args + ') {' + body + '}';
} | [
"function",
"arrowFnToNormalFn",
"(",
"string",
")",
"{",
"var",
"match",
"=",
"string",
".",
"match",
"(",
"/",
"^([\\s\\S]+?)=\\>(\\s*{)?([\\s\\S]*?)(}\\s*)?$",
"/",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"string",
";",
"}",
"var",
"args",
"=",
"match",
"[",
"1",
"]",
";",
"var",
"body",
"=",
"match",
"[",
"3",
"]",
";",
"var",
"needsReturn",
"=",
"!",
"(",
"match",
"[",
"2",
"]",
"&&",
"match",
"[",
"4",
"]",
")",
";",
"args",
"=",
"args",
".",
"replace",
"(",
"/",
"^(\\s*\\(\\s*)([\\s\\S]*?)(\\s*\\)\\s*)$",
"/",
",",
"'$2'",
")",
";",
"if",
"(",
"needsReturn",
")",
"{",
"body",
"=",
"'return '",
"+",
"body",
";",
"}",
"return",
"'function('",
"+",
"args",
"+",
"') {'",
"+",
"body",
"+",
"'}'",
";",
"}"
] | Migrate to separate npm-package with full tests | [
"Migrate",
"to",
"separate",
"npm",
"-",
"package",
"with",
"full",
"tests"
] | 71fb6f79da114125e6cb852fa00bb39645349afd | https://github.com/NekR/offline-plugin/blob/71fb6f79da114125e6cb852fa00bb39645349afd/lib/misc/utils.js#L98-L117 |
8,380 | embark-framework/embark | packages/embark/src/lib/utils/debug_util.js | extend | function extend(filename, async) {
if (async._waterfall !== undefined) {
return;
}
async._waterfall = async.waterfall;
async.waterfall = function (_tasks, callback) {
let tasks = _tasks.map(function (t) {
let fn = function () {
console.log("async " + filename + ": " + t.name);
t.apply(t, arguments);
};
return fn;
});
async._waterfall(tasks, callback);
};
} | javascript | function extend(filename, async) {
if (async._waterfall !== undefined) {
return;
}
async._waterfall = async.waterfall;
async.waterfall = function (_tasks, callback) {
let tasks = _tasks.map(function (t) {
let fn = function () {
console.log("async " + filename + ": " + t.name);
t.apply(t, arguments);
};
return fn;
});
async._waterfall(tasks, callback);
};
} | [
"function",
"extend",
"(",
"filename",
",",
"async",
")",
"{",
"if",
"(",
"async",
".",
"_waterfall",
"!==",
"undefined",
")",
"{",
"return",
";",
"}",
"async",
".",
"_waterfall",
"=",
"async",
".",
"waterfall",
";",
"async",
".",
"waterfall",
"=",
"function",
"(",
"_tasks",
",",
"callback",
")",
"{",
"let",
"tasks",
"=",
"_tasks",
".",
"map",
"(",
"function",
"(",
"t",
")",
"{",
"let",
"fn",
"=",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"async \"",
"+",
"filename",
"+",
"\": \"",
"+",
"t",
".",
"name",
")",
";",
"t",
".",
"apply",
"(",
"t",
",",
"arguments",
")",
";",
"}",
";",
"return",
"fn",
";",
"}",
")",
";",
"async",
".",
"_waterfall",
"(",
"tasks",
",",
"callback",
")",
";",
"}",
";",
"}"
] | util to map async method names | [
"util",
"to",
"map",
"async",
"method",
"names"
] | 8b9441967012aefb2349a65623237923c99ec9dc | https://github.com/embark-framework/embark/blob/8b9441967012aefb2349a65623237923c99ec9dc/packages/embark/src/lib/utils/debug_util.js#L3-L18 |
8,381 | googleapis/nodejs-pubsub | samples/subscriptions.js | worker | function worker(message) {
console.log(`Processing "${message.message.data}"...`);
setTimeout(() => {
console.log(`Finished procesing "${message.message.data}".`);
isProcessed = true;
}, 30000);
} | javascript | function worker(message) {
console.log(`Processing "${message.message.data}"...`);
setTimeout(() => {
console.log(`Finished procesing "${message.message.data}".`);
isProcessed = true;
}, 30000);
} | [
"function",
"worker",
"(",
"message",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"message",
".",
"message",
".",
"data",
"}",
"`",
")",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"message",
".",
"message",
".",
"data",
"}",
"`",
")",
";",
"isProcessed",
"=",
"true",
";",
"}",
",",
"30000",
")",
";",
"}"
] | The worker function is meant to be non-blocking. It starts a long- running process, such as writing the message to a table, which may take longer than the default 10-sec acknowledge deadline. | [
"The",
"worker",
"function",
"is",
"meant",
"to",
"be",
"non",
"-",
"blocking",
".",
"It",
"starts",
"a",
"long",
"-",
"running",
"process",
"such",
"as",
"writing",
"the",
"message",
"to",
"a",
"table",
"which",
"may",
"take",
"longer",
"than",
"the",
"default",
"10",
"-",
"sec",
"acknowledge",
"deadline",
"."
] | 22dc668ec16a26b4807ab12afd35356e118e34d1 | https://github.com/googleapis/nodejs-pubsub/blob/22dc668ec16a26b4807ab12afd35356e118e34d1/samples/subscriptions.js#L299-L306 |
8,382 | woocommerce/FlexSlider | bower_components/jquery/src/manipulation.js | setGlobalEval | function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
} | javascript | function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
} | [
"function",
"setGlobalEval",
"(",
"elems",
",",
"refElements",
")",
"{",
"var",
"elem",
",",
"i",
"=",
"0",
";",
"for",
"(",
";",
"(",
"elem",
"=",
"elems",
"[",
"i",
"]",
")",
"!=",
"null",
";",
"i",
"++",
")",
"{",
"jQuery",
".",
"_data",
"(",
"elem",
",",
"\"globalEval\"",
",",
"!",
"refElements",
"||",
"jQuery",
".",
"_data",
"(",
"refElements",
"[",
"i",
"]",
",",
"\"globalEval\"",
")",
")",
";",
"}",
"}"
] | Mark scripts as having already been evaluated | [
"Mark",
"scripts",
"as",
"having",
"already",
"been",
"evaluated"
] | 690832b7f972298e76e2965714657a2beec9e35c | https://github.com/woocommerce/FlexSlider/blob/690832b7f972298e76e2965714657a2beec9e35c/bower_components/jquery/src/manipulation.js#L126-L132 |
8,383 | apiaryio/dredd | lib/childProcess.js | signalKill | function signalKill(childProcess, callback) {
childProcess.emit('signalKill');
if (IS_WINDOWS) {
const taskkill = spawn('taskkill', ['/F', '/T', '/PID', childProcess.pid]);
taskkill.on('exit', (exitStatus) => {
if (exitStatus) {
return callback(
new Error(`Unable to forcefully terminate process ${childProcess.pid}`)
);
}
callback();
});
} else {
childProcess.kill('SIGKILL');
process.nextTick(callback);
}
} | javascript | function signalKill(childProcess, callback) {
childProcess.emit('signalKill');
if (IS_WINDOWS) {
const taskkill = spawn('taskkill', ['/F', '/T', '/PID', childProcess.pid]);
taskkill.on('exit', (exitStatus) => {
if (exitStatus) {
return callback(
new Error(`Unable to forcefully terminate process ${childProcess.pid}`)
);
}
callback();
});
} else {
childProcess.kill('SIGKILL');
process.nextTick(callback);
}
} | [
"function",
"signalKill",
"(",
"childProcess",
",",
"callback",
")",
"{",
"childProcess",
".",
"emit",
"(",
"'signalKill'",
")",
";",
"if",
"(",
"IS_WINDOWS",
")",
"{",
"const",
"taskkill",
"=",
"spawn",
"(",
"'taskkill'",
",",
"[",
"'/F'",
",",
"'/T'",
",",
"'/PID'",
",",
"childProcess",
".",
"pid",
"]",
")",
";",
"taskkill",
".",
"on",
"(",
"'exit'",
",",
"(",
"exitStatus",
")",
"=>",
"{",
"if",
"(",
"exitStatus",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"`",
"${",
"childProcess",
".",
"pid",
"}",
"`",
")",
")",
";",
"}",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"childProcess",
".",
"kill",
"(",
"'SIGKILL'",
")",
";",
"process",
".",
"nextTick",
"(",
"callback",
")",
";",
"}",
"}"
] | Signals the child process to forcefully terminate | [
"Signals",
"the",
"child",
"process",
"to",
"forcefully",
"terminate"
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/childProcess.js#L14-L30 |
8,384 | apiaryio/dredd | lib/childProcess.js | signalTerm | function signalTerm(childProcess, callback) {
childProcess.emit('signalTerm');
if (IS_WINDOWS) {
// On Windows, there is no such way as SIGTERM or SIGINT. The closest
// thing is to interrupt the process with Ctrl+C. Under the hood, that
// generates '\u0003' character on stdin of the process and if
// the process listens on stdin, it's able to catch this as 'SIGINT'.
//
// However, that only works if user does it manually. There is no
// way to do it programmatically, at least not in Node.js (and even
// for C/C++, all the solutions are dirty hacks). Even if you send
// the very same character to stdin of the process, it's not
// recognized (the rl.on('SIGINT') event won't get triggered)
// for some reason.
//
// The only thing Dredd is left with is a convention. So when Dredd
// wants to gracefully signal to the child process it should terminate,
// it sends the '\u0003' to stdin of the child. It's up to the child
// to implement reading from stdin in such way it works both for
// programmatic and manual Ctrl+C.
childProcess.stdin.write(String.fromCharCode(ASCII_CTRL_C));
} else {
childProcess.kill('SIGTERM');
}
process.nextTick(callback);
} | javascript | function signalTerm(childProcess, callback) {
childProcess.emit('signalTerm');
if (IS_WINDOWS) {
// On Windows, there is no such way as SIGTERM or SIGINT. The closest
// thing is to interrupt the process with Ctrl+C. Under the hood, that
// generates '\u0003' character on stdin of the process and if
// the process listens on stdin, it's able to catch this as 'SIGINT'.
//
// However, that only works if user does it manually. There is no
// way to do it programmatically, at least not in Node.js (and even
// for C/C++, all the solutions are dirty hacks). Even if you send
// the very same character to stdin of the process, it's not
// recognized (the rl.on('SIGINT') event won't get triggered)
// for some reason.
//
// The only thing Dredd is left with is a convention. So when Dredd
// wants to gracefully signal to the child process it should terminate,
// it sends the '\u0003' to stdin of the child. It's up to the child
// to implement reading from stdin in such way it works both for
// programmatic and manual Ctrl+C.
childProcess.stdin.write(String.fromCharCode(ASCII_CTRL_C));
} else {
childProcess.kill('SIGTERM');
}
process.nextTick(callback);
} | [
"function",
"signalTerm",
"(",
"childProcess",
",",
"callback",
")",
"{",
"childProcess",
".",
"emit",
"(",
"'signalTerm'",
")",
";",
"if",
"(",
"IS_WINDOWS",
")",
"{",
"// On Windows, there is no such way as SIGTERM or SIGINT. The closest",
"// thing is to interrupt the process with Ctrl+C. Under the hood, that",
"// generates '\\u0003' character on stdin of the process and if",
"// the process listens on stdin, it's able to catch this as 'SIGINT'.",
"//",
"// However, that only works if user does it manually. There is no",
"// way to do it programmatically, at least not in Node.js (and even",
"// for C/C++, all the solutions are dirty hacks). Even if you send",
"// the very same character to stdin of the process, it's not",
"// recognized (the rl.on('SIGINT') event won't get triggered)",
"// for some reason.",
"//",
"// The only thing Dredd is left with is a convention. So when Dredd",
"// wants to gracefully signal to the child process it should terminate,",
"// it sends the '\\u0003' to stdin of the child. It's up to the child",
"// to implement reading from stdin in such way it works both for",
"// programmatic and manual Ctrl+C.",
"childProcess",
".",
"stdin",
".",
"write",
"(",
"String",
".",
"fromCharCode",
"(",
"ASCII_CTRL_C",
")",
")",
";",
"}",
"else",
"{",
"childProcess",
".",
"kill",
"(",
"'SIGTERM'",
")",
";",
"}",
"process",
".",
"nextTick",
"(",
"callback",
")",
";",
"}"
] | Signals the child process to gracefully terminate | [
"Signals",
"the",
"child",
"process",
"to",
"gracefully",
"terminate"
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/childProcess.js#L34-L59 |
8,385 | apiaryio/dredd | lib/childProcess.js | check | function check() {
if (terminated) {
// Successfully terminated
clearTimeout(t);
return callback();
}
if ((Date.now() - start) < timeout) {
// Still not terminated, try again
signalTerm(childProcess, (err) => {
if (err) { return callback(err); }
t = setTimeout(check, retryDelay);
});
} else {
// Still not terminated and the timeout has passed, either
// kill the process (force) or provide an error
clearTimeout(t);
if (force) {
signalKill(childProcess, callback);
} else {
callback(
new Error(`Unable to gracefully terminate process ${childProcess.pid}`)
);
}
}
} | javascript | function check() {
if (terminated) {
// Successfully terminated
clearTimeout(t);
return callback();
}
if ((Date.now() - start) < timeout) {
// Still not terminated, try again
signalTerm(childProcess, (err) => {
if (err) { return callback(err); }
t = setTimeout(check, retryDelay);
});
} else {
// Still not terminated and the timeout has passed, either
// kill the process (force) or provide an error
clearTimeout(t);
if (force) {
signalKill(childProcess, callback);
} else {
callback(
new Error(`Unable to gracefully terminate process ${childProcess.pid}`)
);
}
}
} | [
"function",
"check",
"(",
")",
"{",
"if",
"(",
"terminated",
")",
"{",
"// Successfully terminated",
"clearTimeout",
"(",
"t",
")",
";",
"return",
"callback",
"(",
")",
";",
"}",
"if",
"(",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
")",
"<",
"timeout",
")",
"{",
"// Still not terminated, try again",
"signalTerm",
"(",
"childProcess",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"t",
"=",
"setTimeout",
"(",
"check",
",",
"retryDelay",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// Still not terminated and the timeout has passed, either",
"// kill the process (force) or provide an error",
"clearTimeout",
"(",
"t",
")",
";",
"if",
"(",
"force",
")",
"{",
"signalKill",
"(",
"childProcess",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"new",
"Error",
"(",
"`",
"${",
"childProcess",
".",
"pid",
"}",
"`",
")",
")",
";",
"}",
"}",
"}"
] | A function representing one check, whether the process already ended or not. It is repeatedly called until the timeout has passed. | [
"A",
"function",
"representing",
"one",
"check",
"whether",
"the",
"process",
"already",
"ended",
"or",
"not",
".",
"It",
"is",
"repeatedly",
"called",
"until",
"the",
"timeout",
"has",
"passed",
"."
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/childProcess.js#L98-L122 |
8,386 | apiaryio/dredd | lib/configuration/applyLoggingOptions.js | applyLoggingOptions | function applyLoggingOptions(config) {
if (config.color === false) {
logger.transports.console.colorize = false;
reporterOutputLogger.transports.console.colorize = false;
}
// TODO https://github.com/apiaryio/dredd/issues/1346
if (config.loglevel) {
const loglevel = config.loglevel.toLowerCase();
if (loglevel === 'silent') {
logger.transports.console.silent = true;
} else if (loglevel === 'warning') {
logger.transports.console.level = 'warn';
} else if (loglevel === 'debug') {
logger.transports.console.level = 'debug';
logger.transports.console.timestamp = true;
} else if (['warn', 'error'].includes(loglevel)) {
logger.transports.console.level = loglevel;
} else {
logger.transports.console.level = 'warn';
throw new Error(`The logging level '${loglevel}' is unsupported, `
+ 'supported are: silent, error, warning, debug');
}
} else {
logger.transports.console.level = 'warn';
}
} | javascript | function applyLoggingOptions(config) {
if (config.color === false) {
logger.transports.console.colorize = false;
reporterOutputLogger.transports.console.colorize = false;
}
// TODO https://github.com/apiaryio/dredd/issues/1346
if (config.loglevel) {
const loglevel = config.loglevel.toLowerCase();
if (loglevel === 'silent') {
logger.transports.console.silent = true;
} else if (loglevel === 'warning') {
logger.transports.console.level = 'warn';
} else if (loglevel === 'debug') {
logger.transports.console.level = 'debug';
logger.transports.console.timestamp = true;
} else if (['warn', 'error'].includes(loglevel)) {
logger.transports.console.level = loglevel;
} else {
logger.transports.console.level = 'warn';
throw new Error(`The logging level '${loglevel}' is unsupported, `
+ 'supported are: silent, error, warning, debug');
}
} else {
logger.transports.console.level = 'warn';
}
} | [
"function",
"applyLoggingOptions",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"color",
"===",
"false",
")",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"colorize",
"=",
"false",
";",
"reporterOutputLogger",
".",
"transports",
".",
"console",
".",
"colorize",
"=",
"false",
";",
"}",
"// TODO https://github.com/apiaryio/dredd/issues/1346",
"if",
"(",
"config",
".",
"loglevel",
")",
"{",
"const",
"loglevel",
"=",
"config",
".",
"loglevel",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"loglevel",
"===",
"'silent'",
")",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"silent",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"loglevel",
"===",
"'warning'",
")",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"level",
"=",
"'warn'",
";",
"}",
"else",
"if",
"(",
"loglevel",
"===",
"'debug'",
")",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"level",
"=",
"'debug'",
";",
"logger",
".",
"transports",
".",
"console",
".",
"timestamp",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"[",
"'warn'",
",",
"'error'",
"]",
".",
"includes",
"(",
"loglevel",
")",
")",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"level",
"=",
"loglevel",
";",
"}",
"else",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"level",
"=",
"'warn'",
";",
"throw",
"new",
"Error",
"(",
"`",
"${",
"loglevel",
"}",
"`",
"+",
"'supported are: silent, error, warning, debug'",
")",
";",
"}",
"}",
"else",
"{",
"logger",
".",
"transports",
".",
"console",
".",
"level",
"=",
"'warn'",
";",
"}",
"}"
] | Applies logging options from the given configuration.
Operates on the validated normalized config. | [
"Applies",
"logging",
"options",
"from",
"the",
"given",
"configuration",
".",
"Operates",
"on",
"the",
"validated",
"normalized",
"config",
"."
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/configuration/applyLoggingOptions.js#L8-L34 |
8,387 | apiaryio/dredd | lib/performRequest.js | performRequest | function performRequest(uri, transactionReq, options, callback) {
if (typeof options === 'function') { [options, callback] = [{}, options]; }
const logger = options.logger || defaultLogger;
const request = options.request || defaultRequest;
const httpOptions = Object.assign({}, options.http || {});
httpOptions.proxy = false;
httpOptions.followRedirect = false;
httpOptions.encoding = null;
httpOptions.method = transactionReq.method;
httpOptions.uri = uri;
try {
httpOptions.body = getBodyAsBuffer(transactionReq.body, transactionReq.bodyEncoding);
httpOptions.headers = normalizeContentLengthHeader(transactionReq.headers, httpOptions.body);
const protocol = httpOptions.uri.split(':')[0].toUpperCase();
logger.debug(`Performing ${protocol} request to the server under test: `
+ `${httpOptions.method} ${httpOptions.uri}`);
request(httpOptions, (error, response, responseBody) => {
logger.debug(`Handling ${protocol} response from the server under test`);
if (error) {
callback(error);
} else {
callback(null, createTransactionResponse(response, responseBody));
}
});
} catch (error) {
process.nextTick(() => callback(error));
}
} | javascript | function performRequest(uri, transactionReq, options, callback) {
if (typeof options === 'function') { [options, callback] = [{}, options]; }
const logger = options.logger || defaultLogger;
const request = options.request || defaultRequest;
const httpOptions = Object.assign({}, options.http || {});
httpOptions.proxy = false;
httpOptions.followRedirect = false;
httpOptions.encoding = null;
httpOptions.method = transactionReq.method;
httpOptions.uri = uri;
try {
httpOptions.body = getBodyAsBuffer(transactionReq.body, transactionReq.bodyEncoding);
httpOptions.headers = normalizeContentLengthHeader(transactionReq.headers, httpOptions.body);
const protocol = httpOptions.uri.split(':')[0].toUpperCase();
logger.debug(`Performing ${protocol} request to the server under test: `
+ `${httpOptions.method} ${httpOptions.uri}`);
request(httpOptions, (error, response, responseBody) => {
logger.debug(`Handling ${protocol} response from the server under test`);
if (error) {
callback(error);
} else {
callback(null, createTransactionResponse(response, responseBody));
}
});
} catch (error) {
process.nextTick(() => callback(error));
}
} | [
"function",
"performRequest",
"(",
"uri",
",",
"transactionReq",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"[",
"options",
",",
"callback",
"]",
"=",
"[",
"{",
"}",
",",
"options",
"]",
";",
"}",
"const",
"logger",
"=",
"options",
".",
"logger",
"||",
"defaultLogger",
";",
"const",
"request",
"=",
"options",
".",
"request",
"||",
"defaultRequest",
";",
"const",
"httpOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
".",
"http",
"||",
"{",
"}",
")",
";",
"httpOptions",
".",
"proxy",
"=",
"false",
";",
"httpOptions",
".",
"followRedirect",
"=",
"false",
";",
"httpOptions",
".",
"encoding",
"=",
"null",
";",
"httpOptions",
".",
"method",
"=",
"transactionReq",
".",
"method",
";",
"httpOptions",
".",
"uri",
"=",
"uri",
";",
"try",
"{",
"httpOptions",
".",
"body",
"=",
"getBodyAsBuffer",
"(",
"transactionReq",
".",
"body",
",",
"transactionReq",
".",
"bodyEncoding",
")",
";",
"httpOptions",
".",
"headers",
"=",
"normalizeContentLengthHeader",
"(",
"transactionReq",
".",
"headers",
",",
"httpOptions",
".",
"body",
")",
";",
"const",
"protocol",
"=",
"httpOptions",
".",
"uri",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"`",
"${",
"protocol",
"}",
"`",
"+",
"`",
"${",
"httpOptions",
".",
"method",
"}",
"${",
"httpOptions",
".",
"uri",
"}",
"`",
")",
";",
"request",
"(",
"httpOptions",
",",
"(",
"error",
",",
"response",
",",
"responseBody",
")",
"=>",
"{",
"logger",
".",
"debug",
"(",
"`",
"${",
"protocol",
"}",
"`",
")",
";",
"if",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"createTransactionResponse",
"(",
"response",
",",
"responseBody",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"process",
".",
"nextTick",
"(",
"(",
")",
"=>",
"callback",
"(",
"error",
")",
")",
";",
"}",
"}"
] | Performs the HTTP request as described in the 'transaction.request' object
In future we should introduce a 'real' request object as well so user has
access to the modifications made on the way.
@param {string} uri
@param {Object} transactionReq
@param {Object} [options]
@param {Object} [options.logger] Custom logger
@param {Object} [options.request] Custom 'request' library implementation
@param {Object} [options.http] Custom default 'request' library options
@param {Function} callback | [
"Performs",
"the",
"HTTP",
"request",
"as",
"described",
"in",
"the",
"transaction",
".",
"request",
"object"
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/performRequest.js#L21-L52 |
8,388 | apiaryio/dredd | lib/performRequest.js | getBodyAsBuffer | function getBodyAsBuffer(body, encoding) {
return body instanceof Buffer
? body
: Buffer.from(`${body || ''}`, normalizeBodyEncoding(encoding));
} | javascript | function getBodyAsBuffer(body, encoding) {
return body instanceof Buffer
? body
: Buffer.from(`${body || ''}`, normalizeBodyEncoding(encoding));
} | [
"function",
"getBodyAsBuffer",
"(",
"body",
",",
"encoding",
")",
"{",
"return",
"body",
"instanceof",
"Buffer",
"?",
"body",
":",
"Buffer",
".",
"from",
"(",
"`",
"${",
"body",
"||",
"''",
"}",
"`",
",",
"normalizeBodyEncoding",
"(",
"encoding",
")",
")",
";",
"}"
] | Coerces the HTTP request body to a Buffer
@param {string|Buffer} body
@param {*} encoding | [
"Coerces",
"the",
"HTTP",
"request",
"body",
"to",
"a",
"Buffer"
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/performRequest.js#L61-L65 |
8,389 | apiaryio/dredd | lib/performRequest.js | normalizeContentLengthHeader | function normalizeContentLengthHeader(headers, body, options = {}) {
const logger = options.logger || defaultLogger;
const modifiedHeaders = Object.assign({}, headers);
const calculatedValue = Buffer.byteLength(body);
const name = caseless(modifiedHeaders).has('Content-Length');
if (name) {
const value = parseInt(modifiedHeaders[name], 10);
if (value !== calculatedValue) {
modifiedHeaders[name] = `${calculatedValue}`;
logger.warn(`Specified Content-Length header is ${value}, but the real `
+ `body length is ${calculatedValue}. Using ${calculatedValue} instead.`);
}
} else {
modifiedHeaders['Content-Length'] = `${calculatedValue}`;
}
return modifiedHeaders;
} | javascript | function normalizeContentLengthHeader(headers, body, options = {}) {
const logger = options.logger || defaultLogger;
const modifiedHeaders = Object.assign({}, headers);
const calculatedValue = Buffer.byteLength(body);
const name = caseless(modifiedHeaders).has('Content-Length');
if (name) {
const value = parseInt(modifiedHeaders[name], 10);
if (value !== calculatedValue) {
modifiedHeaders[name] = `${calculatedValue}`;
logger.warn(`Specified Content-Length header is ${value}, but the real `
+ `body length is ${calculatedValue}. Using ${calculatedValue} instead.`);
}
} else {
modifiedHeaders['Content-Length'] = `${calculatedValue}`;
}
return modifiedHeaders;
} | [
"function",
"normalizeContentLengthHeader",
"(",
"headers",
",",
"body",
",",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"logger",
"=",
"options",
".",
"logger",
"||",
"defaultLogger",
";",
"const",
"modifiedHeaders",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"headers",
")",
";",
"const",
"calculatedValue",
"=",
"Buffer",
".",
"byteLength",
"(",
"body",
")",
";",
"const",
"name",
"=",
"caseless",
"(",
"modifiedHeaders",
")",
".",
"has",
"(",
"'Content-Length'",
")",
";",
"if",
"(",
"name",
")",
"{",
"const",
"value",
"=",
"parseInt",
"(",
"modifiedHeaders",
"[",
"name",
"]",
",",
"10",
")",
";",
"if",
"(",
"value",
"!==",
"calculatedValue",
")",
"{",
"modifiedHeaders",
"[",
"name",
"]",
"=",
"`",
"${",
"calculatedValue",
"}",
"`",
";",
"logger",
".",
"warn",
"(",
"`",
"${",
"value",
"}",
"`",
"+",
"`",
"${",
"calculatedValue",
"}",
"${",
"calculatedValue",
"}",
"`",
")",
";",
"}",
"}",
"else",
"{",
"modifiedHeaders",
"[",
"'Content-Length'",
"]",
"=",
"`",
"${",
"calculatedValue",
"}",
"`",
";",
"}",
"return",
"modifiedHeaders",
";",
"}"
] | Detects an existing Content-Length header and overrides the user-provided
header value in case it's out of sync with the real length of the body.
@param {Object} headers HTTP request headers
@param {Buffer} body HTTP request body
@param {Object} [options]
@param {Object} [options.logger] Custom logger | [
"Detects",
"an",
"existing",
"Content",
"-",
"Length",
"header",
"and",
"overrides",
"the",
"user",
"-",
"provided",
"header",
"value",
"in",
"case",
"it",
"s",
"out",
"of",
"sync",
"with",
"the",
"real",
"length",
"of",
"the",
"body",
"."
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/performRequest.js#L99-L116 |
8,390 | apiaryio/dredd | lib/performRequest.js | createTransactionResponse | function createTransactionResponse(response, body) {
const transactionRes = {
statusCode: response.statusCode,
headers: Object.assign({}, response.headers),
};
if (Buffer.byteLength(body || '')) {
transactionRes.bodyEncoding = detectBodyEncoding(body);
transactionRes.body = body.toString(transactionRes.bodyEncoding);
}
return transactionRes;
} | javascript | function createTransactionResponse(response, body) {
const transactionRes = {
statusCode: response.statusCode,
headers: Object.assign({}, response.headers),
};
if (Buffer.byteLength(body || '')) {
transactionRes.bodyEncoding = detectBodyEncoding(body);
transactionRes.body = body.toString(transactionRes.bodyEncoding);
}
return transactionRes;
} | [
"function",
"createTransactionResponse",
"(",
"response",
",",
"body",
")",
"{",
"const",
"transactionRes",
"=",
"{",
"statusCode",
":",
"response",
".",
"statusCode",
",",
"headers",
":",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"response",
".",
"headers",
")",
",",
"}",
";",
"if",
"(",
"Buffer",
".",
"byteLength",
"(",
"body",
"||",
"''",
")",
")",
"{",
"transactionRes",
".",
"bodyEncoding",
"=",
"detectBodyEncoding",
"(",
"body",
")",
";",
"transactionRes",
".",
"body",
"=",
"body",
".",
"toString",
"(",
"transactionRes",
".",
"bodyEncoding",
")",
";",
"}",
"return",
"transactionRes",
";",
"}"
] | Real transaction response object factory. Serializes binary responses
to string using Base64 encoding.
@param {Object} response Node.js HTTP response
@param {Buffer} body HTTP response body as Buffer | [
"Real",
"transaction",
"response",
"object",
"factory",
".",
"Serializes",
"binary",
"responses",
"to",
"string",
"using",
"Base64",
"encoding",
"."
] | 8d2764f71072072b1417732300b50b0b388788c1 | https://github.com/apiaryio/dredd/blob/8d2764f71072072b1417732300b50b0b388788c1/lib/performRequest.js#L126-L136 |
8,391 | LeaVerou/awesomplete | awesomplete.js | function(evt) {
var li = evt.target;
if (li !== this) {
while (li && !/li/i.test(li.nodeName)) {
li = li.parentNode;
}
if (li && evt.button === 0) { // Only select on left click
evt.preventDefault();
me.select(li, evt.target, evt);
}
}
} | javascript | function(evt) {
var li = evt.target;
if (li !== this) {
while (li && !/li/i.test(li.nodeName)) {
li = li.parentNode;
}
if (li && evt.button === 0) { // Only select on left click
evt.preventDefault();
me.select(li, evt.target, evt);
}
}
} | [
"function",
"(",
"evt",
")",
"{",
"var",
"li",
"=",
"evt",
".",
"target",
";",
"if",
"(",
"li",
"!==",
"this",
")",
"{",
"while",
"(",
"li",
"&&",
"!",
"/",
"li",
"/",
"i",
".",
"test",
"(",
"li",
".",
"nodeName",
")",
")",
"{",
"li",
"=",
"li",
".",
"parentNode",
";",
"}",
"if",
"(",
"li",
"&&",
"evt",
".",
"button",
"===",
"0",
")",
"{",
"// Only select on left click",
"evt",
".",
"preventDefault",
"(",
")",
";",
"me",
".",
"select",
"(",
"li",
",",
"evt",
".",
"target",
",",
"evt",
")",
";",
"}",
"}",
"}"
] | The click event is fired even if the corresponding mousedown event has called preventDefault | [
"The",
"click",
"event",
"is",
"fired",
"even",
"if",
"the",
"corresponding",
"mousedown",
"event",
"has",
"called",
"preventDefault"
] | f8bee8dabbb2be47e3fcef9dafabbdaaff9b20aa | https://github.com/LeaVerou/awesomplete/blob/f8bee8dabbb2be47e3fcef9dafabbdaaff9b20aa/awesomplete.js#L106-L120 |
|
8,392 | LeaVerou/awesomplete | awesomplete.js | function (i) {
var lis = this.ul.children;
if (this.selected) {
lis[this.index].setAttribute("aria-selected", "false");
}
this.index = i;
if (i > -1 && lis.length > 0) {
lis[i].setAttribute("aria-selected", "true");
this.status.textContent = lis[i].textContent + ", list item " + (i + 1) + " of " + lis.length;
this.input.setAttribute("aria-activedescendant", this.ul.id + "_item_" + this.index);
// scroll to highlighted element in case parent's height is fixed
this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight;
$.fire(this.input, "awesomplete-highlight", {
text: this.suggestions[this.index]
});
}
} | javascript | function (i) {
var lis = this.ul.children;
if (this.selected) {
lis[this.index].setAttribute("aria-selected", "false");
}
this.index = i;
if (i > -1 && lis.length > 0) {
lis[i].setAttribute("aria-selected", "true");
this.status.textContent = lis[i].textContent + ", list item " + (i + 1) + " of " + lis.length;
this.input.setAttribute("aria-activedescendant", this.ul.id + "_item_" + this.index);
// scroll to highlighted element in case parent's height is fixed
this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight;
$.fire(this.input, "awesomplete-highlight", {
text: this.suggestions[this.index]
});
}
} | [
"function",
"(",
"i",
")",
"{",
"var",
"lis",
"=",
"this",
".",
"ul",
".",
"children",
";",
"if",
"(",
"this",
".",
"selected",
")",
"{",
"lis",
"[",
"this",
".",
"index",
"]",
".",
"setAttribute",
"(",
"\"aria-selected\"",
",",
"\"false\"",
")",
";",
"}",
"this",
".",
"index",
"=",
"i",
";",
"if",
"(",
"i",
">",
"-",
"1",
"&&",
"lis",
".",
"length",
">",
"0",
")",
"{",
"lis",
"[",
"i",
"]",
".",
"setAttribute",
"(",
"\"aria-selected\"",
",",
"\"true\"",
")",
";",
"this",
".",
"status",
".",
"textContent",
"=",
"lis",
"[",
"i",
"]",
".",
"textContent",
"+",
"\", list item \"",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"\" of \"",
"+",
"lis",
".",
"length",
";",
"this",
".",
"input",
".",
"setAttribute",
"(",
"\"aria-activedescendant\"",
",",
"this",
".",
"ul",
".",
"id",
"+",
"\"_item_\"",
"+",
"this",
".",
"index",
")",
";",
"// scroll to highlighted element in case parent's height is fixed",
"this",
".",
"ul",
".",
"scrollTop",
"=",
"lis",
"[",
"i",
"]",
".",
"offsetTop",
"-",
"this",
".",
"ul",
".",
"clientHeight",
"+",
"lis",
"[",
"i",
"]",
".",
"clientHeight",
";",
"$",
".",
"fire",
"(",
"this",
".",
"input",
",",
"\"awesomplete-highlight\"",
",",
"{",
"text",
":",
"this",
".",
"suggestions",
"[",
"this",
".",
"index",
"]",
"}",
")",
";",
"}",
"}"
] | Should not be used, highlights specific item without any checks! | [
"Should",
"not",
"be",
"used",
"highlights",
"specific",
"item",
"without",
"any",
"checks!"
] | f8bee8dabbb2be47e3fcef9dafabbdaaff9b20aa | https://github.com/LeaVerou/awesomplete/blob/f8bee8dabbb2be47e3fcef9dafabbdaaff9b20aa/awesomplete.js#L247-L270 |
|
8,393 | thlorenz/doctoc | lib/transform.js | determineTitle | function determineTitle(title, notitle, lines, info) {
var defaultTitle = '**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*';
if (notitle) return '';
if (title) return title;
return info.hasStart ? lines[info.startIdx + 2] : defaultTitle;
} | javascript | function determineTitle(title, notitle, lines, info) {
var defaultTitle = '**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*';
if (notitle) return '';
if (title) return title;
return info.hasStart ? lines[info.startIdx + 2] : defaultTitle;
} | [
"function",
"determineTitle",
"(",
"title",
",",
"notitle",
",",
"lines",
",",
"info",
")",
"{",
"var",
"defaultTitle",
"=",
"'**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*'",
";",
"if",
"(",
"notitle",
")",
"return",
"''",
";",
"if",
"(",
"title",
")",
"return",
"title",
";",
"return",
"info",
".",
"hasStart",
"?",
"lines",
"[",
"info",
".",
"startIdx",
"+",
"2",
"]",
":",
"defaultTitle",
";",
"}"
] | Use document context as well as command line args to infer the title | [
"Use",
"document",
"context",
"as",
"well",
"as",
"command",
"line",
"args",
"to",
"infer",
"the",
"title"
] | e4c74ae7b1346e3e42972562a440d94b2a561aa3 | https://github.com/thlorenz/doctoc/blob/e4c74ae7b1346e3e42972562a440d94b2a561aa3/lib/transform.js#L101-L107 |
8,394 | webhintio/hint | packages/formatter-html/src/assets/js/scan/scanner-common.js | function (element, closeAll) {
var expanded = typeof closeAll !== 'undefined' ? closeAll : childRulesExpanded(element);
if (expanded) {
element.textContent = 'close all';
element.classList.remove('closed');
element.classList.add('expanded');
} else {
element.textContent = 'expand all';
element.classList.remove('expanded');
element.classList.add('closed');
}
} | javascript | function (element, closeAll) {
var expanded = typeof closeAll !== 'undefined' ? closeAll : childRulesExpanded(element);
if (expanded) {
element.textContent = 'close all';
element.classList.remove('closed');
element.classList.add('expanded');
} else {
element.textContent = 'expand all';
element.classList.remove('expanded');
element.classList.add('closed');
}
} | [
"function",
"(",
"element",
",",
"closeAll",
")",
"{",
"var",
"expanded",
"=",
"typeof",
"closeAll",
"!==",
"'undefined'",
"?",
"closeAll",
":",
"childRulesExpanded",
"(",
"element",
")",
";",
"if",
"(",
"expanded",
")",
"{",
"element",
".",
"textContent",
"=",
"'close all'",
";",
"element",
".",
"classList",
".",
"remove",
"(",
"'closed'",
")",
";",
"element",
".",
"classList",
".",
"add",
"(",
"'expanded'",
")",
";",
"}",
"else",
"{",
"element",
".",
"textContent",
"=",
"'expand all'",
";",
"element",
".",
"classList",
".",
"remove",
"(",
"'expanded'",
")",
";",
"element",
".",
"classList",
".",
"add",
"(",
"'closed'",
")",
";",
"}",
"}"
] | if all rules are closed, toggle button to 'expand all'.
if any rule is open, toggle button to 'close all'. | [
"if",
"all",
"rules",
"are",
"closed",
"toggle",
"button",
"to",
"expand",
"all",
".",
"if",
"any",
"rule",
"is",
"open",
"toggle",
"button",
"to",
"close",
"all",
"."
] | 2e15dbe6997d46f377d095b4178ab5dc36146a61 | https://github.com/webhintio/hint/blob/2e15dbe6997d46f377d095b4178ab5dc36146a61/packages/formatter-html/src/assets/js/scan/scanner-common.js#L56-L68 |
|
8,395 | dollarshaveclub/postmate | build/postmate.es.js | resolveOrigin | function resolveOrigin(url) {
var a = document.createElement('a');
a.href = url;
var protocol = a.protocol.length > 4 ? a.protocol : window.location.protocol;
var host = a.host.length ? a.port === '80' || a.port === '443' ? a.hostname : a.host : window.location.host;
return a.origin || protocol + "//" + host;
} | javascript | function resolveOrigin(url) {
var a = document.createElement('a');
a.href = url;
var protocol = a.protocol.length > 4 ? a.protocol : window.location.protocol;
var host = a.host.length ? a.port === '80' || a.port === '443' ? a.hostname : a.host : window.location.host;
return a.origin || protocol + "//" + host;
} | [
"function",
"resolveOrigin",
"(",
"url",
")",
"{",
"var",
"a",
"=",
"document",
".",
"createElement",
"(",
"'a'",
")",
";",
"a",
".",
"href",
"=",
"url",
";",
"var",
"protocol",
"=",
"a",
".",
"protocol",
".",
"length",
">",
"4",
"?",
"a",
".",
"protocol",
":",
"window",
".",
"location",
".",
"protocol",
";",
"var",
"host",
"=",
"a",
".",
"host",
".",
"length",
"?",
"a",
".",
"port",
"===",
"'80'",
"||",
"a",
".",
"port",
"===",
"'443'",
"?",
"a",
".",
"hostname",
":",
"a",
".",
"host",
":",
"window",
".",
"location",
".",
"host",
";",
"return",
"a",
".",
"origin",
"||",
"protocol",
"+",
"\"//\"",
"+",
"host",
";",
"}"
] | eslint-disable-line no-console
Takes a URL and returns the origin
@param {String} url The full URL being requested
@return {String} The URLs origin | [
"eslint",
"-",
"disable",
"-",
"line",
"no",
"-",
"console",
"Takes",
"a",
"URL",
"and",
"returns",
"the",
"origin"
] | 6e8fc1193f09ef0acbba55b6b89e8e2dae3af057 | https://github.com/dollarshaveclub/postmate/blob/6e8fc1193f09ef0acbba55b6b89e8e2dae3af057/build/postmate.es.js#L50-L56 |
8,396 | dollarshaveclub/postmate | build/postmate.es.js | resolveValue | function resolveValue(model, property) {
var unwrappedContext = typeof model[property] === 'function' ? model[property]() : model[property];
return Postmate.Promise.resolve(unwrappedContext);
} | javascript | function resolveValue(model, property) {
var unwrappedContext = typeof model[property] === 'function' ? model[property]() : model[property];
return Postmate.Promise.resolve(unwrappedContext);
} | [
"function",
"resolveValue",
"(",
"model",
",",
"property",
")",
"{",
"var",
"unwrappedContext",
"=",
"typeof",
"model",
"[",
"property",
"]",
"===",
"'function'",
"?",
"model",
"[",
"property",
"]",
"(",
")",
":",
"model",
"[",
"property",
"]",
";",
"return",
"Postmate",
".",
"Promise",
".",
"resolve",
"(",
"unwrappedContext",
")",
";",
"}"
] | Takes a model, and searches for a value by the property
@param {Object} model The dictionary to search against
@param {String} property A path within a dictionary (i.e. 'window.location.href')
@param {Object} data Additional information from the get request that is
passed to functions in the child model
@return {Promise} | [
"Takes",
"a",
"model",
"and",
"searches",
"for",
"a",
"value",
"by",
"the",
"property"
] | 6e8fc1193f09ef0acbba55b6b89e8e2dae3af057 | https://github.com/dollarshaveclub/postmate/blob/6e8fc1193f09ef0acbba55b6b89e8e2dae3af057/build/postmate.es.js#L89-L92 |
8,397 | dollarshaveclub/postmate | build/postmate.es.js | Postmate | function Postmate(_ref2) {
var _ref2$container = _ref2.container,
container = _ref2$container === void 0 ? typeof container !== 'undefined' ? container : document.body : _ref2$container,
model = _ref2.model,
url = _ref2.url,
_ref2$classListArray = _ref2.classListArray,
classListArray = _ref2$classListArray === void 0 ? [] : _ref2$classListArray;
// eslint-disable-line no-undef
this.parent = window;
this.frame = document.createElement('iframe');
this.frame.classList.add.apply(this.frame.classList, classListArray);
container.appendChild(this.frame);
this.child = this.frame.contentWindow || this.frame.contentDocument.parentWindow;
this.model = model || {};
return this.sendHandshake(url);
} | javascript | function Postmate(_ref2) {
var _ref2$container = _ref2.container,
container = _ref2$container === void 0 ? typeof container !== 'undefined' ? container : document.body : _ref2$container,
model = _ref2.model,
url = _ref2.url,
_ref2$classListArray = _ref2.classListArray,
classListArray = _ref2$classListArray === void 0 ? [] : _ref2$classListArray;
// eslint-disable-line no-undef
this.parent = window;
this.frame = document.createElement('iframe');
this.frame.classList.add.apply(this.frame.classList, classListArray);
container.appendChild(this.frame);
this.child = this.frame.contentWindow || this.frame.contentDocument.parentWindow;
this.model = model || {};
return this.sendHandshake(url);
} | [
"function",
"Postmate",
"(",
"_ref2",
")",
"{",
"var",
"_ref2$container",
"=",
"_ref2",
".",
"container",
",",
"container",
"=",
"_ref2$container",
"===",
"void",
"0",
"?",
"typeof",
"container",
"!==",
"'undefined'",
"?",
"container",
":",
"document",
".",
"body",
":",
"_ref2$container",
",",
"model",
"=",
"_ref2",
".",
"model",
",",
"url",
"=",
"_ref2",
".",
"url",
",",
"_ref2$classListArray",
"=",
"_ref2",
".",
"classListArray",
",",
"classListArray",
"=",
"_ref2$classListArray",
"===",
"void",
"0",
"?",
"[",
"]",
":",
"_ref2$classListArray",
";",
"// eslint-disable-line no-undef",
"this",
".",
"parent",
"=",
"window",
";",
"this",
".",
"frame",
"=",
"document",
".",
"createElement",
"(",
"'iframe'",
")",
";",
"this",
".",
"frame",
".",
"classList",
".",
"add",
".",
"apply",
"(",
"this",
".",
"frame",
".",
"classList",
",",
"classListArray",
")",
";",
"container",
".",
"appendChild",
"(",
"this",
".",
"frame",
")",
";",
"this",
".",
"child",
"=",
"this",
".",
"frame",
".",
"contentWindow",
"||",
"this",
".",
"frame",
".",
"contentDocument",
".",
"parentWindow",
";",
"this",
".",
"model",
"=",
"model",
"||",
"{",
"}",
";",
"return",
"this",
".",
"sendHandshake",
"(",
"url",
")",
";",
"}"
] | eslint-disable-line no-undef Internet Explorer craps itself
Sets options related to the Parent
@param {Object} object The element to inject the frame into, and the url
@return {Promise} | [
"eslint",
"-",
"disable",
"-",
"line",
"no",
"-",
"undef",
"Internet",
"Explorer",
"craps",
"itself",
"Sets",
"options",
"related",
"to",
"the",
"Parent"
] | 6e8fc1193f09ef0acbba55b6b89e8e2dae3af057 | https://github.com/dollarshaveclub/postmate/blob/6e8fc1193f09ef0acbba55b6b89e8e2dae3af057/build/postmate.es.js#L287-L302 |
8,398 | dollarshaveclub/postmate | build/postmate.es.js | Model | function Model(model) {
this.child = window;
this.model = model;
this.parent = this.child.parent;
return this.sendHandshakeReply();
} | javascript | function Model(model) {
this.child = window;
this.model = model;
this.parent = this.child.parent;
return this.sendHandshakeReply();
} | [
"function",
"Model",
"(",
"model",
")",
"{",
"this",
".",
"child",
"=",
"window",
";",
"this",
".",
"model",
"=",
"model",
";",
"this",
".",
"parent",
"=",
"this",
".",
"child",
".",
"parent",
";",
"return",
"this",
".",
"sendHandshakeReply",
"(",
")",
";",
"}"
] | Initializes the child, model, parent, and responds to the Parents handshake
@param {Object} model Hash of values, functions, or promises
@return {Promise} The Promise that resolves when the handshake has been received | [
"Initializes",
"the",
"child",
"model",
"parent",
"and",
"responds",
"to",
"the",
"Parents",
"handshake"
] | 6e8fc1193f09ef0acbba55b6b89e8e2dae3af057 | https://github.com/dollarshaveclub/postmate/blob/6e8fc1193f09ef0acbba55b6b89e8e2dae3af057/build/postmate.es.js#L418-L423 |
8,399 | node-inspector/node-inspector | front-end/profiler/CPUProfileBottomUpDataGrid.js | function(profileDataGridNode)
{
if (!profileDataGridNode)
return;
this.save();
var currentNode = profileDataGridNode;
var focusNode = profileDataGridNode;
while (currentNode.parent && (currentNode instanceof WebInspector.ProfileDataGridNode)) {
currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode);
focusNode = currentNode;
currentNode = currentNode.parent;
if (currentNode instanceof WebInspector.ProfileDataGridNode)
currentNode._keepOnlyChild(focusNode);
}
this.children = [focusNode];
this.totalTime = profileDataGridNode.totalTime;
} | javascript | function(profileDataGridNode)
{
if (!profileDataGridNode)
return;
this.save();
var currentNode = profileDataGridNode;
var focusNode = profileDataGridNode;
while (currentNode.parent && (currentNode instanceof WebInspector.ProfileDataGridNode)) {
currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode);
focusNode = currentNode;
currentNode = currentNode.parent;
if (currentNode instanceof WebInspector.ProfileDataGridNode)
currentNode._keepOnlyChild(focusNode);
}
this.children = [focusNode];
this.totalTime = profileDataGridNode.totalTime;
} | [
"function",
"(",
"profileDataGridNode",
")",
"{",
"if",
"(",
"!",
"profileDataGridNode",
")",
"return",
";",
"this",
".",
"save",
"(",
")",
";",
"var",
"currentNode",
"=",
"profileDataGridNode",
";",
"var",
"focusNode",
"=",
"profileDataGridNode",
";",
"while",
"(",
"currentNode",
".",
"parent",
"&&",
"(",
"currentNode",
"instanceof",
"WebInspector",
".",
"ProfileDataGridNode",
")",
")",
"{",
"currentNode",
".",
"_takePropertiesFromProfileDataGridNode",
"(",
"profileDataGridNode",
")",
";",
"focusNode",
"=",
"currentNode",
";",
"currentNode",
"=",
"currentNode",
".",
"parent",
";",
"if",
"(",
"currentNode",
"instanceof",
"WebInspector",
".",
"ProfileDataGridNode",
")",
"currentNode",
".",
"_keepOnlyChild",
"(",
"focusNode",
")",
";",
"}",
"this",
".",
"children",
"=",
"[",
"focusNode",
"]",
";",
"this",
".",
"totalTime",
"=",
"profileDataGridNode",
".",
"totalTime",
";",
"}"
] | When focusing, we keep the entire callstack up to this ancestor.
@param {!WebInspector.ProfileDataGridNode} profileDataGridNode | [
"When",
"focusing",
"we",
"keep",
"the",
"entire",
"callstack",
"up",
"to",
"this",
"ancestor",
"."
] | 79e01c049286374f86dd560742a614019c02402f | https://github.com/node-inspector/node-inspector/blob/79e01c049286374f86dd560742a614019c02402f/front-end/profiler/CPUProfileBottomUpDataGrid.js#L253-L275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.