repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
eslint/eslint
|
lib/rules/no-eval.js
|
report
|
function report(node) {
const parent = node.parent;
const locationNode = node.type === "MemberExpression"
? node.property
: node;
const reportNode = parent.type === "CallExpression" && parent.callee === node
? parent
: node;
context.report({
node: reportNode,
loc: locationNode.loc.start,
messageId: "unexpected"
});
}
|
javascript
|
function report(node) {
const parent = node.parent;
const locationNode = node.type === "MemberExpression"
? node.property
: node;
const reportNode = parent.type === "CallExpression" && parent.callee === node
? parent
: node;
context.report({
node: reportNode,
loc: locationNode.loc.start,
messageId: "unexpected"
});
}
|
[
"function",
"report",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"const",
"locationNode",
"=",
"node",
".",
"type",
"===",
"\"MemberExpression\"",
"?",
"node",
".",
"property",
":",
"node",
";",
"const",
"reportNode",
"=",
"parent",
".",
"type",
"===",
"\"CallExpression\"",
"&&",
"parent",
".",
"callee",
"===",
"node",
"?",
"parent",
":",
"node",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"reportNode",
",",
"loc",
":",
"locationNode",
".",
"loc",
".",
"start",
",",
"messageId",
":",
"\"unexpected\"",
"}",
")",
";",
"}"
] |
Reports a given node.
`node` is `Identifier` or `MemberExpression`.
The parent of `node` might be `CallExpression`.
The location of the report is always `eval` `Identifier` (or possibly
`Literal`). The type of the report is `CallExpression` if the parent is
`CallExpression`. Otherwise, it's the given node type.
@param {ASTNode} node - A node to report.
@returns {void}
|
[
"Reports",
"a",
"given",
"node",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-eval.js#L155-L170
|
train
|
eslint/eslint
|
lib/rules/no-eval.js
|
reportAccessingEvalViaGlobalObject
|
function reportAccessingEvalViaGlobalObject(globalScope) {
for (let i = 0; i < candidatesOfGlobalObject.length; ++i) {
const name = candidatesOfGlobalObject[i];
const variable = astUtils.getVariableByName(globalScope, name);
if (!variable) {
continue;
}
const references = variable.references;
for (let j = 0; j < references.length; ++j) {
const identifier = references[j].identifier;
let node = identifier.parent;
// To detect code like `window.window.eval`.
while (isMember(node, name)) {
node = node.parent;
}
// Reports.
if (isMember(node, "eval")) {
report(node);
}
}
}
}
|
javascript
|
function reportAccessingEvalViaGlobalObject(globalScope) {
for (let i = 0; i < candidatesOfGlobalObject.length; ++i) {
const name = candidatesOfGlobalObject[i];
const variable = astUtils.getVariableByName(globalScope, name);
if (!variable) {
continue;
}
const references = variable.references;
for (let j = 0; j < references.length; ++j) {
const identifier = references[j].identifier;
let node = identifier.parent;
// To detect code like `window.window.eval`.
while (isMember(node, name)) {
node = node.parent;
}
// Reports.
if (isMember(node, "eval")) {
report(node);
}
}
}
}
|
[
"function",
"reportAccessingEvalViaGlobalObject",
"(",
"globalScope",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"candidatesOfGlobalObject",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"name",
"=",
"candidatesOfGlobalObject",
"[",
"i",
"]",
";",
"const",
"variable",
"=",
"astUtils",
".",
"getVariableByName",
"(",
"globalScope",
",",
"name",
")",
";",
"if",
"(",
"!",
"variable",
")",
"{",
"continue",
";",
"}",
"const",
"references",
"=",
"variable",
".",
"references",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"references",
".",
"length",
";",
"++",
"j",
")",
"{",
"const",
"identifier",
"=",
"references",
"[",
"j",
"]",
".",
"identifier",
";",
"let",
"node",
"=",
"identifier",
".",
"parent",
";",
"while",
"(",
"isMember",
"(",
"node",
",",
"name",
")",
")",
"{",
"node",
"=",
"node",
".",
"parent",
";",
"}",
"if",
"(",
"isMember",
"(",
"node",
",",
"\"eval\"",
")",
")",
"{",
"report",
"(",
"node",
")",
";",
"}",
"}",
"}",
"}"
] |
Reports accesses of `eval` via the global object.
@param {eslint-scope.Scope} globalScope - The global scope.
@returns {void}
|
[
"Reports",
"accesses",
"of",
"eval",
"via",
"the",
"global",
"object",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-eval.js#L178-L204
|
train
|
eslint/eslint
|
lib/util/naming.js
|
getShorthandName
|
function getShorthandName(fullname, prefix) {
if (fullname[0] === "@") {
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
if (matchResult) {
return matchResult[1];
}
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
if (matchResult) {
return `${matchResult[1]}/${matchResult[2]}`;
}
} else if (fullname.startsWith(`${prefix}-`)) {
return fullname.slice(prefix.length + 1);
}
return fullname;
}
|
javascript
|
function getShorthandName(fullname, prefix) {
if (fullname[0] === "@") {
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
if (matchResult) {
return matchResult[1];
}
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
if (matchResult) {
return `${matchResult[1]}/${matchResult[2]}`;
}
} else if (fullname.startsWith(`${prefix}-`)) {
return fullname.slice(prefix.length + 1);
}
return fullname;
}
|
[
"function",
"getShorthandName",
"(",
"fullname",
",",
"prefix",
")",
"{",
"if",
"(",
"fullname",
"[",
"0",
"]",
"===",
"\"@\"",
")",
"{",
"let",
"matchResult",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
"}",
"`",
",",
"\"u\"",
")",
".",
"exec",
"(",
"fullname",
")",
";",
"if",
"(",
"matchResult",
")",
"{",
"return",
"matchResult",
"[",
"1",
"]",
";",
"}",
"matchResult",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
"}",
"`",
",",
"\"u\"",
")",
".",
"exec",
"(",
"fullname",
")",
";",
"if",
"(",
"matchResult",
")",
"{",
"return",
"`",
"${",
"matchResult",
"[",
"1",
"]",
"}",
"${",
"matchResult",
"[",
"2",
"]",
"}",
"`",
";",
"}",
"}",
"else",
"if",
"(",
"fullname",
".",
"startsWith",
"(",
"`",
"${",
"prefix",
"}",
"`",
")",
")",
"{",
"return",
"fullname",
".",
"slice",
"(",
"prefix",
".",
"length",
"+",
"1",
")",
";",
"}",
"return",
"fullname",
";",
"}"
] |
Removes the prefix from a fullname.
@param {string} fullname The term which may have the prefix.
@param {string} prefix The prefix to remove.
@returns {string} The term without prefix.
|
[
"Removes",
"the",
"prefix",
"from",
"a",
"fullname",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/naming.js#L69-L86
|
train
|
dequelabs/axe-core
|
lib/checks/label/label-content-name-mismatch.js
|
isStringContained
|
function isStringContained(compare, compareWith) {
const curatedCompareWith = curateString(compareWith);
const curatedCompare = curateString(compare);
if (!curatedCompareWith || !curatedCompare) {
return false;
}
return curatedCompareWith.includes(curatedCompare);
}
|
javascript
|
function isStringContained(compare, compareWith) {
const curatedCompareWith = curateString(compareWith);
const curatedCompare = curateString(compare);
if (!curatedCompareWith || !curatedCompare) {
return false;
}
return curatedCompareWith.includes(curatedCompare);
}
|
[
"function",
"isStringContained",
"(",
"compare",
",",
"compareWith",
")",
"{",
"const",
"curatedCompareWith",
"=",
"curateString",
"(",
"compareWith",
")",
";",
"const",
"curatedCompare",
"=",
"curateString",
"(",
"compare",
")",
";",
"if",
"(",
"!",
"curatedCompareWith",
"||",
"!",
"curatedCompare",
")",
"{",
"return",
"false",
";",
"}",
"return",
"curatedCompareWith",
".",
"includes",
"(",
"curatedCompare",
")",
";",
"}"
] |
Check if a given text exists in another
@param {String} compare given text to check
@param {String} compareWith text against which to be compared
@returns {Boolean}
|
[
"Check",
"if",
"a",
"given",
"text",
"exists",
"in",
"another"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/checks/label/label-content-name-mismatch.js#L27-L34
|
train
|
dequelabs/axe-core
|
lib/checks/label/label-content-name-mismatch.js
|
curateString
|
function curateString(str) {
const noUnicodeStr = text.removeUnicode(str, {
emoji: true,
nonBmp: true,
punctuations: true
});
return text.sanitize(noUnicodeStr);
}
|
javascript
|
function curateString(str) {
const noUnicodeStr = text.removeUnicode(str, {
emoji: true,
nonBmp: true,
punctuations: true
});
return text.sanitize(noUnicodeStr);
}
|
[
"function",
"curateString",
"(",
"str",
")",
"{",
"const",
"noUnicodeStr",
"=",
"text",
".",
"removeUnicode",
"(",
"str",
",",
"{",
"emoji",
":",
"true",
",",
"nonBmp",
":",
"true",
",",
"punctuations",
":",
"true",
"}",
")",
";",
"return",
"text",
".",
"sanitize",
"(",
"noUnicodeStr",
")",
";",
"}"
] |
Curate given text, by removing emoji's, punctuations, unicode and trim whitespace.
@param {String} str given text to curate
@returns {String}
|
[
"Curate",
"given",
"text",
"by",
"removing",
"emoji",
"s",
"punctuations",
"unicode",
"and",
"trim",
"whitespace",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/checks/label/label-content-name-mismatch.js#L42-L49
|
train
|
dequelabs/axe-core
|
lib/commons/text/native-text-alternative.js
|
findTextMethods
|
function findTextMethods(virtualNode) {
const { nativeElementType, nativeTextMethods } = text;
const nativeType = nativeElementType.find(({ matches }) => {
return axe.commons.matches(virtualNode, matches);
});
// Use concat because namingMethods can be a string or an array of strings
const methods = nativeType ? [].concat(nativeType.namingMethods) : [];
return methods.map(methodName => nativeTextMethods[methodName]);
}
|
javascript
|
function findTextMethods(virtualNode) {
const { nativeElementType, nativeTextMethods } = text;
const nativeType = nativeElementType.find(({ matches }) => {
return axe.commons.matches(virtualNode, matches);
});
// Use concat because namingMethods can be a string or an array of strings
const methods = nativeType ? [].concat(nativeType.namingMethods) : [];
return methods.map(methodName => nativeTextMethods[methodName]);
}
|
[
"function",
"findTextMethods",
"(",
"virtualNode",
")",
"{",
"const",
"{",
"nativeElementType",
",",
"nativeTextMethods",
"}",
"=",
"text",
";",
"const",
"nativeType",
"=",
"nativeElementType",
".",
"find",
"(",
"(",
"{",
"matches",
"}",
")",
"=>",
"{",
"return",
"axe",
".",
"commons",
".",
"matches",
"(",
"virtualNode",
",",
"matches",
")",
";",
"}",
")",
";",
"const",
"methods",
"=",
"nativeType",
"?",
"[",
"]",
".",
"concat",
"(",
"nativeType",
".",
"namingMethods",
")",
":",
"[",
"]",
";",
"return",
"methods",
".",
"map",
"(",
"methodName",
"=>",
"nativeTextMethods",
"[",
"methodName",
"]",
")",
";",
"}"
] |
Get accessible text functions for a specific native HTML element
@private
@param {VirtualNode} element
@return {Function[]} Array of native accessible name computation methods
|
[
"Get",
"accessible",
"text",
"functions",
"for",
"a",
"specific",
"native",
"HTML",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/native-text-alternative.js#L40-L50
|
train
|
dequelabs/axe-core
|
lib/rules/aria-hidden-focus-matches.js
|
shouldMatchElement
|
function shouldMatchElement(el) {
if (!el) {
return true;
}
if (el.getAttribute('aria-hidden') === 'true') {
return false;
}
return shouldMatchElement(getComposedParent(el));
}
|
javascript
|
function shouldMatchElement(el) {
if (!el) {
return true;
}
if (el.getAttribute('aria-hidden') === 'true') {
return false;
}
return shouldMatchElement(getComposedParent(el));
}
|
[
"function",
"shouldMatchElement",
"(",
"el",
")",
"{",
"if",
"(",
"!",
"el",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"el",
".",
"getAttribute",
"(",
"'aria-hidden'",
")",
"===",
"'true'",
")",
"{",
"return",
"false",
";",
"}",
"return",
"shouldMatchElement",
"(",
"getComposedParent",
"(",
"el",
")",
")",
";",
"}"
] |
Only match the outer-most `aria-hidden=true` element
@param {HTMLElement} el the HTMLElement to verify
@return {Boolean}
|
[
"Only",
"match",
"the",
"outer",
"-",
"most",
"aria",
"-",
"hidden",
"=",
"true",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/rules/aria-hidden-focus-matches.js#L8-L16
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
getAttributeNameValue
|
function getAttributeNameValue(node, at) {
const name = at.name;
let atnv;
if (name.indexOf('href') !== -1 || name.indexOf('src') !== -1) {
let friendly = axe.utils.getFriendlyUriEnd(node.getAttribute(name));
if (friendly) {
let value = encodeURI(friendly);
if (value) {
atnv = escapeSelector(at.name) + '$="' + escapeSelector(value) + '"';
} else {
return;
}
} else {
atnv =
escapeSelector(at.name) +
'="' +
escapeSelector(node.getAttribute(name)) +
'"';
}
} else {
atnv = escapeSelector(name) + '="' + escapeSelector(at.value) + '"';
}
return atnv;
}
|
javascript
|
function getAttributeNameValue(node, at) {
const name = at.name;
let atnv;
if (name.indexOf('href') !== -1 || name.indexOf('src') !== -1) {
let friendly = axe.utils.getFriendlyUriEnd(node.getAttribute(name));
if (friendly) {
let value = encodeURI(friendly);
if (value) {
atnv = escapeSelector(at.name) + '$="' + escapeSelector(value) + '"';
} else {
return;
}
} else {
atnv =
escapeSelector(at.name) +
'="' +
escapeSelector(node.getAttribute(name)) +
'"';
}
} else {
atnv = escapeSelector(name) + '="' + escapeSelector(at.value) + '"';
}
return atnv;
}
|
[
"function",
"getAttributeNameValue",
"(",
"node",
",",
"at",
")",
"{",
"const",
"name",
"=",
"at",
".",
"name",
";",
"let",
"atnv",
";",
"if",
"(",
"name",
".",
"indexOf",
"(",
"'href'",
")",
"!==",
"-",
"1",
"||",
"name",
".",
"indexOf",
"(",
"'src'",
")",
"!==",
"-",
"1",
")",
"{",
"let",
"friendly",
"=",
"axe",
".",
"utils",
".",
"getFriendlyUriEnd",
"(",
"node",
".",
"getAttribute",
"(",
"name",
")",
")",
";",
"if",
"(",
"friendly",
")",
"{",
"let",
"value",
"=",
"encodeURI",
"(",
"friendly",
")",
";",
"if",
"(",
"value",
")",
"{",
"atnv",
"=",
"escapeSelector",
"(",
"at",
".",
"name",
")",
"+",
"'$=\"'",
"+",
"escapeSelector",
"(",
"value",
")",
"+",
"'\"'",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"else",
"{",
"atnv",
"=",
"escapeSelector",
"(",
"at",
".",
"name",
")",
"+",
"'=\"'",
"+",
"escapeSelector",
"(",
"node",
".",
"getAttribute",
"(",
"name",
")",
")",
"+",
"'\"'",
";",
"}",
"}",
"else",
"{",
"atnv",
"=",
"escapeSelector",
"(",
"name",
")",
"+",
"'=\"'",
"+",
"escapeSelector",
"(",
"at",
".",
"value",
")",
"+",
"'\"'",
";",
"}",
"return",
"atnv",
";",
"}"
] |
get the attribute name and value as a string
@param {Element} node The element that has the attribute
@param {Attribute} at The attribute
@return {String}
|
[
"get",
"the",
"attribute",
"name",
"and",
"value",
"as",
"a",
"string"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L30-L54
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
filterAttributes
|
function filterAttributes(at) {
return (
!ignoredAttributes.includes(at.name) &&
at.name.indexOf(':') === -1 &&
(!at.value || at.value.length < MAXATTRIBUTELENGTH)
);
}
|
javascript
|
function filterAttributes(at) {
return (
!ignoredAttributes.includes(at.name) &&
at.name.indexOf(':') === -1 &&
(!at.value || at.value.length < MAXATTRIBUTELENGTH)
);
}
|
[
"function",
"filterAttributes",
"(",
"at",
")",
"{",
"return",
"(",
"!",
"ignoredAttributes",
".",
"includes",
"(",
"at",
".",
"name",
")",
"&&",
"at",
".",
"name",
".",
"indexOf",
"(",
"':'",
")",
"===",
"-",
"1",
"&&",
"(",
"!",
"at",
".",
"value",
"||",
"at",
".",
"value",
".",
"length",
"<",
"MAXATTRIBUTELENGTH",
")",
")",
";",
"}"
] |
Filter the attributes
@param {Attribute} The potential attribute
@return {Boolean} Whether to include or exclude
|
[
"Filter",
"the",
"attributes"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L65-L71
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
uncommonClasses
|
function uncommonClasses(node, selectorData) {
// eslint no-loop-func:false
let retVal = [];
let classData = selectorData.classes;
let tagData = selectorData.tags;
if (node.classList) {
Array.from(node.classList).forEach(cl => {
let ind = escapeSelector(cl);
if (classData[ind] < tagData[node.nodeName]) {
retVal.push({
name: ind,
count: classData[ind],
species: 'class'
});
}
});
}
return retVal.sort(countSort);
}
|
javascript
|
function uncommonClasses(node, selectorData) {
// eslint no-loop-func:false
let retVal = [];
let classData = selectorData.classes;
let tagData = selectorData.tags;
if (node.classList) {
Array.from(node.classList).forEach(cl => {
let ind = escapeSelector(cl);
if (classData[ind] < tagData[node.nodeName]) {
retVal.push({
name: ind,
count: classData[ind],
species: 'class'
});
}
});
}
return retVal.sort(countSort);
}
|
[
"function",
"uncommonClasses",
"(",
"node",
",",
"selectorData",
")",
"{",
"let",
"retVal",
"=",
"[",
"]",
";",
"let",
"classData",
"=",
"selectorData",
".",
"classes",
";",
"let",
"tagData",
"=",
"selectorData",
".",
"tags",
";",
"if",
"(",
"node",
".",
"classList",
")",
"{",
"Array",
".",
"from",
"(",
"node",
".",
"classList",
")",
".",
"forEach",
"(",
"cl",
"=>",
"{",
"let",
"ind",
"=",
"escapeSelector",
"(",
"cl",
")",
";",
"if",
"(",
"classData",
"[",
"ind",
"]",
"<",
"tagData",
"[",
"node",
".",
"nodeName",
"]",
")",
"{",
"retVal",
".",
"push",
"(",
"{",
"name",
":",
"ind",
",",
"count",
":",
"classData",
"[",
"ind",
"]",
",",
"species",
":",
"'class'",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"retVal",
".",
"sort",
"(",
"countSort",
")",
";",
"}"
] |
Given a node and the statistics on class frequency on the page,
return all its uncommon class data sorted in order of decreasing uniqueness
@param {Element} node The node
@param {Object} classData The map of classes to counts
@return {Array} The sorted array of uncommon class data
|
[
"Given",
"a",
"node",
"and",
"the",
"statistics",
"on",
"class",
"frequency",
"on",
"the",
"page",
"return",
"all",
"its",
"uncommon",
"class",
"data",
"sorted",
"in",
"order",
"of",
"decreasing",
"uniqueness"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L156-L175
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
getElmId
|
function getElmId(elm) {
if (!elm.getAttribute('id')) {
return;
}
let doc = (elm.getRootNode && elm.getRootNode()) || document;
const id = '#' + escapeSelector(elm.getAttribute('id') || '');
if (
// Don't include youtube's uid values, they change on reload
!id.match(/player_uid_/) &&
// Don't include IDs that occur more then once on the page
doc.querySelectorAll(id).length === 1
) {
return id;
}
}
|
javascript
|
function getElmId(elm) {
if (!elm.getAttribute('id')) {
return;
}
let doc = (elm.getRootNode && elm.getRootNode()) || document;
const id = '#' + escapeSelector(elm.getAttribute('id') || '');
if (
// Don't include youtube's uid values, they change on reload
!id.match(/player_uid_/) &&
// Don't include IDs that occur more then once on the page
doc.querySelectorAll(id).length === 1
) {
return id;
}
}
|
[
"function",
"getElmId",
"(",
"elm",
")",
"{",
"if",
"(",
"!",
"elm",
".",
"getAttribute",
"(",
"'id'",
")",
")",
"{",
"return",
";",
"}",
"let",
"doc",
"=",
"(",
"elm",
".",
"getRootNode",
"&&",
"elm",
".",
"getRootNode",
"(",
")",
")",
"||",
"document",
";",
"const",
"id",
"=",
"'#'",
"+",
"escapeSelector",
"(",
"elm",
".",
"getAttribute",
"(",
"'id'",
")",
"||",
"''",
")",
";",
"if",
"(",
"!",
"id",
".",
"match",
"(",
"/",
"player_uid_",
"/",
")",
"&&",
"doc",
".",
"querySelectorAll",
"(",
"id",
")",
".",
"length",
"===",
"1",
")",
"{",
"return",
"id",
";",
"}",
"}"
] |
Get ID selector
|
[
"Get",
"ID",
"selector"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L201-L215
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
getBaseSelector
|
function getBaseSelector(elm) {
if (typeof isXHTML === 'undefined') {
isXHTML = axe.utils.isXHTML(document);
}
return escapeSelector(isXHTML ? elm.localName : elm.nodeName.toLowerCase());
}
|
javascript
|
function getBaseSelector(elm) {
if (typeof isXHTML === 'undefined') {
isXHTML = axe.utils.isXHTML(document);
}
return escapeSelector(isXHTML ? elm.localName : elm.nodeName.toLowerCase());
}
|
[
"function",
"getBaseSelector",
"(",
"elm",
")",
"{",
"if",
"(",
"typeof",
"isXHTML",
"===",
"'undefined'",
")",
"{",
"isXHTML",
"=",
"axe",
".",
"utils",
".",
"isXHTML",
"(",
"document",
")",
";",
"}",
"return",
"escapeSelector",
"(",
"isXHTML",
"?",
"elm",
".",
"localName",
":",
"elm",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
")",
";",
"}"
] |
Return the base CSS selector for a given element
@param {HTMLElement} elm The element to get the selector for
@return {String|Array<String>} Base CSS selector for the node
|
[
"Return",
"the",
"base",
"CSS",
"selector",
"for",
"a",
"given",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L222-L227
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
uncommonAttributes
|
function uncommonAttributes(node, selectorData) {
let retVal = [];
let attData = selectorData.attributes;
let tagData = selectorData.tags;
if (node.hasAttributes()) {
Array.from(axe.utils.getNodeAttributes(node))
.filter(filterAttributes)
.forEach(at => {
const atnv = getAttributeNameValue(node, at);
if (atnv && attData[atnv] < tagData[node.nodeName]) {
retVal.push({
name: atnv,
count: attData[atnv],
species: 'attribute'
});
}
});
}
return retVal.sort(countSort);
}
|
javascript
|
function uncommonAttributes(node, selectorData) {
let retVal = [];
let attData = selectorData.attributes;
let tagData = selectorData.tags;
if (node.hasAttributes()) {
Array.from(axe.utils.getNodeAttributes(node))
.filter(filterAttributes)
.forEach(at => {
const atnv = getAttributeNameValue(node, at);
if (atnv && attData[atnv] < tagData[node.nodeName]) {
retVal.push({
name: atnv,
count: attData[atnv],
species: 'attribute'
});
}
});
}
return retVal.sort(countSort);
}
|
[
"function",
"uncommonAttributes",
"(",
"node",
",",
"selectorData",
")",
"{",
"let",
"retVal",
"=",
"[",
"]",
";",
"let",
"attData",
"=",
"selectorData",
".",
"attributes",
";",
"let",
"tagData",
"=",
"selectorData",
".",
"tags",
";",
"if",
"(",
"node",
".",
"hasAttributes",
"(",
")",
")",
"{",
"Array",
".",
"from",
"(",
"axe",
".",
"utils",
".",
"getNodeAttributes",
"(",
"node",
")",
")",
".",
"filter",
"(",
"filterAttributes",
")",
".",
"forEach",
"(",
"at",
"=>",
"{",
"const",
"atnv",
"=",
"getAttributeNameValue",
"(",
"node",
",",
"at",
")",
";",
"if",
"(",
"atnv",
"&&",
"attData",
"[",
"atnv",
"]",
"<",
"tagData",
"[",
"node",
".",
"nodeName",
"]",
")",
"{",
"retVal",
".",
"push",
"(",
"{",
"name",
":",
"atnv",
",",
"count",
":",
"attData",
"[",
"atnv",
"]",
",",
"species",
":",
"'attribute'",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"retVal",
".",
"sort",
"(",
"countSort",
")",
";",
"}"
] |
Given a node and the statistics on attribute frequency on the page,
return all its uncommon attribute data sorted in order of decreasing uniqueness
@param {Element} node The node
@param {Object} attData The map of attributes to counts
@return {Array} The sorted array of uncommon attribute data
|
[
"Given",
"a",
"node",
"and",
"the",
"statistics",
"on",
"attribute",
"frequency",
"on",
"the",
"page",
"return",
"all",
"its",
"uncommon",
"attribute",
"data",
"sorted",
"in",
"order",
"of",
"decreasing",
"uniqueness"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L236-L257
|
train
|
dequelabs/axe-core
|
lib/core/utils/get-selector.js
|
generateSelector
|
function generateSelector(elm, options, doc) {
/*eslint no-loop-func:0*/
if (!axe._selectorData) {
throw new Error('Expect axe._selectorData to be set up');
}
const { toRoot = false } = options;
let selector;
let similar;
/**
* Try to find a unique selector by filtering out all the clashing
* nodes by adding ancestor selectors iteratively.
* This loop is much faster than recursing and using querySelectorAll
*/
do {
let features = getElmId(elm);
if (!features) {
features = getThreeLeastCommonFeatures(elm, axe._selectorData);
features += getNthChildString(elm, features);
}
if (selector) {
selector = features + ' > ' + selector;
} else {
selector = features;
}
if (!similar) {
similar = Array.from(doc.querySelectorAll(selector));
} else {
similar = similar.filter(item => {
return axe.utils.matchesSelector(item, selector);
});
}
elm = elm.parentElement;
} while ((similar.length > 1 || toRoot) && elm && elm.nodeType !== 11);
if (similar.length === 1) {
return selector;
} else if (selector.indexOf(' > ') !== -1) {
// For the odd case that document doesn't have a unique selector
return ':root' + selector.substring(selector.indexOf(' > '));
}
return ':root';
}
|
javascript
|
function generateSelector(elm, options, doc) {
/*eslint no-loop-func:0*/
if (!axe._selectorData) {
throw new Error('Expect axe._selectorData to be set up');
}
const { toRoot = false } = options;
let selector;
let similar;
/**
* Try to find a unique selector by filtering out all the clashing
* nodes by adding ancestor selectors iteratively.
* This loop is much faster than recursing and using querySelectorAll
*/
do {
let features = getElmId(elm);
if (!features) {
features = getThreeLeastCommonFeatures(elm, axe._selectorData);
features += getNthChildString(elm, features);
}
if (selector) {
selector = features + ' > ' + selector;
} else {
selector = features;
}
if (!similar) {
similar = Array.from(doc.querySelectorAll(selector));
} else {
similar = similar.filter(item => {
return axe.utils.matchesSelector(item, selector);
});
}
elm = elm.parentElement;
} while ((similar.length > 1 || toRoot) && elm && elm.nodeType !== 11);
if (similar.length === 1) {
return selector;
} else if (selector.indexOf(' > ') !== -1) {
// For the odd case that document doesn't have a unique selector
return ':root' + selector.substring(selector.indexOf(' > '));
}
return ':root';
}
|
[
"function",
"generateSelector",
"(",
"elm",
",",
"options",
",",
"doc",
")",
"{",
"if",
"(",
"!",
"axe",
".",
"_selectorData",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expect axe._selectorData to be set up'",
")",
";",
"}",
"const",
"{",
"toRoot",
"=",
"false",
"}",
"=",
"options",
";",
"let",
"selector",
";",
"let",
"similar",
";",
"do",
"{",
"let",
"features",
"=",
"getElmId",
"(",
"elm",
")",
";",
"if",
"(",
"!",
"features",
")",
"{",
"features",
"=",
"getThreeLeastCommonFeatures",
"(",
"elm",
",",
"axe",
".",
"_selectorData",
")",
";",
"features",
"+=",
"getNthChildString",
"(",
"elm",
",",
"features",
")",
";",
"}",
"if",
"(",
"selector",
")",
"{",
"selector",
"=",
"features",
"+",
"' > '",
"+",
"selector",
";",
"}",
"else",
"{",
"selector",
"=",
"features",
";",
"}",
"if",
"(",
"!",
"similar",
")",
"{",
"similar",
"=",
"Array",
".",
"from",
"(",
"doc",
".",
"querySelectorAll",
"(",
"selector",
")",
")",
";",
"}",
"else",
"{",
"similar",
"=",
"similar",
".",
"filter",
"(",
"item",
"=>",
"{",
"return",
"axe",
".",
"utils",
".",
"matchesSelector",
"(",
"item",
",",
"selector",
")",
";",
"}",
")",
";",
"}",
"elm",
"=",
"elm",
".",
"parentElement",
";",
"}",
"while",
"(",
"(",
"similar",
".",
"length",
">",
"1",
"||",
"toRoot",
")",
"&&",
"elm",
"&&",
"elm",
".",
"nodeType",
"!==",
"11",
")",
";",
"if",
"(",
"similar",
".",
"length",
"===",
"1",
")",
"{",
"return",
"selector",
";",
"}",
"else",
"if",
"(",
"selector",
".",
"indexOf",
"(",
"' > '",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"':root'",
"+",
"selector",
".",
"substring",
"(",
"selector",
".",
"indexOf",
"(",
"' > '",
")",
")",
";",
"}",
"return",
"':root'",
";",
"}"
] |
generates a single selector for an element
@param {Element} elm The element for which to generate a selector
@param {Object} options Options for how to generate the selector
@param {RootNode} doc The root node of the document or document fragment
@returns {String} The selector
|
[
"generates",
"a",
"single",
"selector",
"for",
"an",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/get-selector.js#L336-L378
|
train
|
dequelabs/axe-core
|
lib/core/utils/rule-should-run.js
|
matchTags
|
function matchTags(rule, runOnly) {
'use strict';
var include, exclude, matching;
var defaultExclude =
axe._audit && axe._audit.tagExclude ? axe._audit.tagExclude : [];
// normalize include/exclude
if (runOnly.hasOwnProperty('include') || runOnly.hasOwnProperty('exclude')) {
// Wrap include and exclude if it's not already an array
include = runOnly.include || [];
include = Array.isArray(include) ? include : [include];
exclude = runOnly.exclude || [];
exclude = Array.isArray(exclude) ? exclude : [exclude];
// add defaults, unless mentioned in include
exclude = exclude.concat(
defaultExclude.filter(function(tag) {
return include.indexOf(tag) === -1;
})
);
// Otherwise, only use the include value, ignore exclude
} else {
include = Array.isArray(runOnly) ? runOnly : [runOnly];
// exclude the defaults not included
exclude = defaultExclude.filter(function(tag) {
return include.indexOf(tag) === -1;
});
}
matching = include.some(function(tag) {
return rule.tags.indexOf(tag) !== -1;
});
if (matching || (include.length === 0 && rule.enabled !== false)) {
return exclude.every(function(tag) {
return rule.tags.indexOf(tag) === -1;
});
} else {
return false;
}
}
|
javascript
|
function matchTags(rule, runOnly) {
'use strict';
var include, exclude, matching;
var defaultExclude =
axe._audit && axe._audit.tagExclude ? axe._audit.tagExclude : [];
// normalize include/exclude
if (runOnly.hasOwnProperty('include') || runOnly.hasOwnProperty('exclude')) {
// Wrap include and exclude if it's not already an array
include = runOnly.include || [];
include = Array.isArray(include) ? include : [include];
exclude = runOnly.exclude || [];
exclude = Array.isArray(exclude) ? exclude : [exclude];
// add defaults, unless mentioned in include
exclude = exclude.concat(
defaultExclude.filter(function(tag) {
return include.indexOf(tag) === -1;
})
);
// Otherwise, only use the include value, ignore exclude
} else {
include = Array.isArray(runOnly) ? runOnly : [runOnly];
// exclude the defaults not included
exclude = defaultExclude.filter(function(tag) {
return include.indexOf(tag) === -1;
});
}
matching = include.some(function(tag) {
return rule.tags.indexOf(tag) !== -1;
});
if (matching || (include.length === 0 && rule.enabled !== false)) {
return exclude.every(function(tag) {
return rule.tags.indexOf(tag) === -1;
});
} else {
return false;
}
}
|
[
"function",
"matchTags",
"(",
"rule",
",",
"runOnly",
")",
"{",
"'use strict'",
";",
"var",
"include",
",",
"exclude",
",",
"matching",
";",
"var",
"defaultExclude",
"=",
"axe",
".",
"_audit",
"&&",
"axe",
".",
"_audit",
".",
"tagExclude",
"?",
"axe",
".",
"_audit",
".",
"tagExclude",
":",
"[",
"]",
";",
"if",
"(",
"runOnly",
".",
"hasOwnProperty",
"(",
"'include'",
")",
"||",
"runOnly",
".",
"hasOwnProperty",
"(",
"'exclude'",
")",
")",
"{",
"include",
"=",
"runOnly",
".",
"include",
"||",
"[",
"]",
";",
"include",
"=",
"Array",
".",
"isArray",
"(",
"include",
")",
"?",
"include",
":",
"[",
"include",
"]",
";",
"exclude",
"=",
"runOnly",
".",
"exclude",
"||",
"[",
"]",
";",
"exclude",
"=",
"Array",
".",
"isArray",
"(",
"exclude",
")",
"?",
"exclude",
":",
"[",
"exclude",
"]",
";",
"exclude",
"=",
"exclude",
".",
"concat",
"(",
"defaultExclude",
".",
"filter",
"(",
"function",
"(",
"tag",
")",
"{",
"return",
"include",
".",
"indexOf",
"(",
"tag",
")",
"===",
"-",
"1",
";",
"}",
")",
")",
";",
"}",
"else",
"{",
"include",
"=",
"Array",
".",
"isArray",
"(",
"runOnly",
")",
"?",
"runOnly",
":",
"[",
"runOnly",
"]",
";",
"exclude",
"=",
"defaultExclude",
".",
"filter",
"(",
"function",
"(",
"tag",
")",
"{",
"return",
"include",
".",
"indexOf",
"(",
"tag",
")",
"===",
"-",
"1",
";",
"}",
")",
";",
"}",
"matching",
"=",
"include",
".",
"some",
"(",
"function",
"(",
"tag",
")",
"{",
"return",
"rule",
".",
"tags",
".",
"indexOf",
"(",
"tag",
")",
"!==",
"-",
"1",
";",
"}",
")",
";",
"if",
"(",
"matching",
"||",
"(",
"include",
".",
"length",
"===",
"0",
"&&",
"rule",
".",
"enabled",
"!==",
"false",
")",
")",
"{",
"return",
"exclude",
".",
"every",
"(",
"function",
"(",
"tag",
")",
"{",
"return",
"rule",
".",
"tags",
".",
"indexOf",
"(",
"tag",
")",
"===",
"-",
"1",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Check if a rule matches the value of runOnly type=tag
@private
@param {object} rule
@param {object} runOnly Value of runOnly with type=tags
@return {bool}
|
[
"Check",
"if",
"a",
"rule",
"matches",
"the",
"value",
"of",
"runOnly",
"type",
"=",
"tag"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/rule-should-run.js#L8-L48
|
train
|
dequelabs/axe-core
|
lib/core/utils/select.js
|
getDeepest
|
function getDeepest(collection) {
'use strict';
return collection.sort(function(a, b) {
if (axe.utils.contains(a, b)) {
return 1;
}
return -1;
})[0];
}
|
javascript
|
function getDeepest(collection) {
'use strict';
return collection.sort(function(a, b) {
if (axe.utils.contains(a, b)) {
return 1;
}
return -1;
})[0];
}
|
[
"function",
"getDeepest",
"(",
"collection",
")",
"{",
"'use strict'",
";",
"return",
"collection",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"axe",
".",
"utils",
".",
"contains",
"(",
"a",
",",
"b",
")",
")",
"{",
"return",
"1",
";",
"}",
"return",
"-",
"1",
";",
"}",
")",
"[",
"0",
"]",
";",
"}"
] |
Get the deepest node in a given collection
@private
@param {Array} collection Array of nodes to test
@return {Node} The deepest node
|
[
"Get",
"the",
"deepest",
"node",
"in",
"a",
"given",
"collection"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/select.js#L7-L16
|
train
|
dequelabs/axe-core
|
lib/core/utils/select.js
|
isNodeInContext
|
function isNodeInContext(node, context) {
'use strict';
var include =
context.include &&
getDeepest(
context.include.filter(function(candidate) {
return axe.utils.contains(candidate, node);
})
);
var exclude =
context.exclude &&
getDeepest(
context.exclude.filter(function(candidate) {
return axe.utils.contains(candidate, node);
})
);
if (
(!exclude && include) ||
(exclude && axe.utils.contains(exclude, include))
) {
return true;
}
return false;
}
|
javascript
|
function isNodeInContext(node, context) {
'use strict';
var include =
context.include &&
getDeepest(
context.include.filter(function(candidate) {
return axe.utils.contains(candidate, node);
})
);
var exclude =
context.exclude &&
getDeepest(
context.exclude.filter(function(candidate) {
return axe.utils.contains(candidate, node);
})
);
if (
(!exclude && include) ||
(exclude && axe.utils.contains(exclude, include))
) {
return true;
}
return false;
}
|
[
"function",
"isNodeInContext",
"(",
"node",
",",
"context",
")",
"{",
"'use strict'",
";",
"var",
"include",
"=",
"context",
".",
"include",
"&&",
"getDeepest",
"(",
"context",
".",
"include",
".",
"filter",
"(",
"function",
"(",
"candidate",
")",
"{",
"return",
"axe",
".",
"utils",
".",
"contains",
"(",
"candidate",
",",
"node",
")",
";",
"}",
")",
")",
";",
"var",
"exclude",
"=",
"context",
".",
"exclude",
"&&",
"getDeepest",
"(",
"context",
".",
"exclude",
".",
"filter",
"(",
"function",
"(",
"candidate",
")",
"{",
"return",
"axe",
".",
"utils",
".",
"contains",
"(",
"candidate",
",",
"node",
")",
";",
"}",
")",
")",
";",
"if",
"(",
"(",
"!",
"exclude",
"&&",
"include",
")",
"||",
"(",
"exclude",
"&&",
"axe",
".",
"utils",
".",
"contains",
"(",
"exclude",
",",
"include",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Determines if a node is included or excluded in a given context
@private
@param {Node} node The node to test
@param {Object} context "Resolved" context object, @see resolveContext
@return {Boolean} [description]
|
[
"Determines",
"if",
"a",
"node",
"is",
"included",
"or",
"excluded",
"in",
"a",
"given",
"context"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/select.js#L25-L49
|
train
|
dequelabs/axe-core
|
lib/core/utils/select.js
|
pushNode
|
function pushNode(result, nodes) {
'use strict';
var temp;
if (result.length === 0) {
return nodes;
}
if (result.length < nodes.length) {
// switch so the comparison is shortest
temp = result;
result = nodes;
nodes = temp;
}
for (var i = 0, l = nodes.length; i < l; i++) {
if (!result.includes(nodes[i])) {
result.push(nodes[i]);
}
}
return result;
}
|
javascript
|
function pushNode(result, nodes) {
'use strict';
var temp;
if (result.length === 0) {
return nodes;
}
if (result.length < nodes.length) {
// switch so the comparison is shortest
temp = result;
result = nodes;
nodes = temp;
}
for (var i = 0, l = nodes.length; i < l; i++) {
if (!result.includes(nodes[i])) {
result.push(nodes[i]);
}
}
return result;
}
|
[
"function",
"pushNode",
"(",
"result",
",",
"nodes",
")",
"{",
"'use strict'",
";",
"var",
"temp",
";",
"if",
"(",
"result",
".",
"length",
"===",
"0",
")",
"{",
"return",
"nodes",
";",
"}",
"if",
"(",
"result",
".",
"length",
"<",
"nodes",
".",
"length",
")",
"{",
"temp",
"=",
"result",
";",
"result",
"=",
"nodes",
";",
"nodes",
"=",
"temp",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"result",
".",
"includes",
"(",
"nodes",
"[",
"i",
"]",
")",
")",
"{",
"result",
".",
"push",
"(",
"nodes",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Pushes unique nodes that are in context to an array
@private
@param {Array} result The array to push to
@param {Array} nodes The list of nodes to push
@param {Object} context The "resolved" context object, @see resolveContext
|
[
"Pushes",
"unique",
"nodes",
"that",
"are",
"in",
"context",
"to",
"an",
"array"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/select.js#L58-L78
|
train
|
dequelabs/axe-core
|
lib/core/utils/select.js
|
reduceIncludes
|
function reduceIncludes(includes) {
return includes.reduce((res, el) => {
if (
!res.length ||
!res[res.length - 1].actualNode.contains(el.actualNode)
) {
res.push(el);
}
return res;
}, []);
}
|
javascript
|
function reduceIncludes(includes) {
return includes.reduce((res, el) => {
if (
!res.length ||
!res[res.length - 1].actualNode.contains(el.actualNode)
) {
res.push(el);
}
return res;
}, []);
}
|
[
"function",
"reduceIncludes",
"(",
"includes",
")",
"{",
"return",
"includes",
".",
"reduce",
"(",
"(",
"res",
",",
"el",
")",
"=>",
"{",
"if",
"(",
"!",
"res",
".",
"length",
"||",
"!",
"res",
"[",
"res",
".",
"length",
"-",
"1",
"]",
".",
"actualNode",
".",
"contains",
"(",
"el",
".",
"actualNode",
")",
")",
"{",
"res",
".",
"push",
"(",
"el",
")",
";",
"}",
"return",
"res",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
reduces the includes list to only the outermost includes
@param {Array} the array of include nodes
@return {Array} the modified array of nodes
|
[
"reduces",
"the",
"includes",
"list",
"to",
"only",
"the",
"outermost",
"includes"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/select.js#L85-L95
|
train
|
dequelabs/axe-core
|
lib/commons/text/label-text.js
|
getExplicitLabels
|
function getExplicitLabels({ actualNode }) {
if (!actualNode.id) {
return [];
}
return dom.findElmsInContext({
elm: 'label',
attr: 'for',
value: actualNode.id,
context: actualNode
});
}
|
javascript
|
function getExplicitLabels({ actualNode }) {
if (!actualNode.id) {
return [];
}
return dom.findElmsInContext({
elm: 'label',
attr: 'for',
value: actualNode.id,
context: actualNode
});
}
|
[
"function",
"getExplicitLabels",
"(",
"{",
"actualNode",
"}",
")",
"{",
"if",
"(",
"!",
"actualNode",
".",
"id",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"dom",
".",
"findElmsInContext",
"(",
"{",
"elm",
":",
"'label'",
",",
"attr",
":",
"'for'",
",",
"value",
":",
"actualNode",
".",
"id",
",",
"context",
":",
"actualNode",
"}",
")",
";",
"}"
] |
Find a non-ARIA label for an element
@private
@param {VirtualNode} element The VirtualNode instance whose label we are seeking
@return {HTMLElement} The label element, or null if none is found
|
[
"Find",
"a",
"non",
"-",
"ARIA",
"label",
"for",
"an",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/label-text.js#L48-L58
|
train
|
dequelabs/axe-core
|
lib/commons/color/get-background-color.js
|
sortPageBackground
|
function sortPageBackground(elmStack) {
let bodyIndex = elmStack.indexOf(document.body);
let bgNodes = elmStack;
if (
// Check that the body background is the page's background
bodyIndex > 1 && // only if there are negative z-index elements
!color.elementHasImage(document.documentElement) &&
color.getOwnBackgroundColor(
window.getComputedStyle(document.documentElement)
).alpha === 0
) {
// Remove body and html from it's current place
bgNodes.splice(bodyIndex, 1);
bgNodes.splice(elmStack.indexOf(document.documentElement), 1);
// Put the body background as the lowest element
bgNodes.push(document.body);
}
return bgNodes;
}
|
javascript
|
function sortPageBackground(elmStack) {
let bodyIndex = elmStack.indexOf(document.body);
let bgNodes = elmStack;
if (
// Check that the body background is the page's background
bodyIndex > 1 && // only if there are negative z-index elements
!color.elementHasImage(document.documentElement) &&
color.getOwnBackgroundColor(
window.getComputedStyle(document.documentElement)
).alpha === 0
) {
// Remove body and html from it's current place
bgNodes.splice(bodyIndex, 1);
bgNodes.splice(elmStack.indexOf(document.documentElement), 1);
// Put the body background as the lowest element
bgNodes.push(document.body);
}
return bgNodes;
}
|
[
"function",
"sortPageBackground",
"(",
"elmStack",
")",
"{",
"let",
"bodyIndex",
"=",
"elmStack",
".",
"indexOf",
"(",
"document",
".",
"body",
")",
";",
"let",
"bgNodes",
"=",
"elmStack",
";",
"if",
"(",
"bodyIndex",
">",
"1",
"&&",
"!",
"color",
".",
"elementHasImage",
"(",
"document",
".",
"documentElement",
")",
"&&",
"color",
".",
"getOwnBackgroundColor",
"(",
"window",
".",
"getComputedStyle",
"(",
"document",
".",
"documentElement",
")",
")",
".",
"alpha",
"===",
"0",
")",
"{",
"bgNodes",
".",
"splice",
"(",
"bodyIndex",
",",
"1",
")",
";",
"bgNodes",
".",
"splice",
"(",
"elmStack",
".",
"indexOf",
"(",
"document",
".",
"documentElement",
")",
",",
"1",
")",
";",
"bgNodes",
".",
"push",
"(",
"document",
".",
"body",
")",
";",
"}",
"return",
"bgNodes",
";",
"}"
] |
Look at document and body elements for relevant background information
@method sortPageBackground
@private
@param {Array} elmStack
@returns {Array}
|
[
"Look",
"at",
"document",
"and",
"body",
"elements",
"for",
"relevant",
"background",
"information"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/color/get-background-color.js#L207-L227
|
train
|
dequelabs/axe-core
|
lib/commons/color/get-background-color.js
|
elmPartiallyObscured
|
function elmPartiallyObscured(elm, bgElm, bgColor) {
var obscured =
elm !== bgElm && !dom.visuallyContains(elm, bgElm) && bgColor.alpha !== 0;
if (obscured) {
axe.commons.color.incompleteData.set('bgColor', 'elmPartiallyObscured');
}
return obscured;
}
|
javascript
|
function elmPartiallyObscured(elm, bgElm, bgColor) {
var obscured =
elm !== bgElm && !dom.visuallyContains(elm, bgElm) && bgColor.alpha !== 0;
if (obscured) {
axe.commons.color.incompleteData.set('bgColor', 'elmPartiallyObscured');
}
return obscured;
}
|
[
"function",
"elmPartiallyObscured",
"(",
"elm",
",",
"bgElm",
",",
"bgColor",
")",
"{",
"var",
"obscured",
"=",
"elm",
"!==",
"bgElm",
"&&",
"!",
"dom",
".",
"visuallyContains",
"(",
"elm",
",",
"bgElm",
")",
"&&",
"bgColor",
".",
"alpha",
"!==",
"0",
";",
"if",
"(",
"obscured",
")",
"{",
"axe",
".",
"commons",
".",
"color",
".",
"incompleteData",
".",
"set",
"(",
"'bgColor'",
",",
"'elmPartiallyObscured'",
")",
";",
"}",
"return",
"obscured",
";",
"}"
] |
Determine if element is partially overlapped, triggering a Can't Tell result
@private
@param {Element} elm
@param {Element} bgElm
@param {Object} bgColor
@return {Boolean}
|
[
"Determine",
"if",
"element",
"is",
"partially",
"overlapped",
"triggering",
"a",
"Can",
"t",
"Tell",
"result"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/color/get-background-color.js#L294-L301
|
train
|
dequelabs/axe-core
|
lib/commons/color/get-background-color.js
|
calculateObscuringAlpha
|
function calculateObscuringAlpha(elmIndex, elmStack, originalElm) {
var totalAlpha = 0;
if (elmIndex > 0) {
// there are elements above our element, check if they contribute to the background
for (var i = elmIndex - 1; i >= 0; i--) {
let bgElm = elmStack[i];
let bgElmStyle = window.getComputedStyle(bgElm);
let bgColor = color.getOwnBackgroundColor(bgElmStyle);
if (bgColor.alpha && contentOverlapping(originalElm, bgElm)) {
totalAlpha += bgColor.alpha;
} else {
// remove elements not contributing to the background
elmStack.splice(i, 1);
}
}
}
return totalAlpha;
}
|
javascript
|
function calculateObscuringAlpha(elmIndex, elmStack, originalElm) {
var totalAlpha = 0;
if (elmIndex > 0) {
// there are elements above our element, check if they contribute to the background
for (var i = elmIndex - 1; i >= 0; i--) {
let bgElm = elmStack[i];
let bgElmStyle = window.getComputedStyle(bgElm);
let bgColor = color.getOwnBackgroundColor(bgElmStyle);
if (bgColor.alpha && contentOverlapping(originalElm, bgElm)) {
totalAlpha += bgColor.alpha;
} else {
// remove elements not contributing to the background
elmStack.splice(i, 1);
}
}
}
return totalAlpha;
}
|
[
"function",
"calculateObscuringAlpha",
"(",
"elmIndex",
",",
"elmStack",
",",
"originalElm",
")",
"{",
"var",
"totalAlpha",
"=",
"0",
";",
"if",
"(",
"elmIndex",
">",
"0",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"elmIndex",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"let",
"bgElm",
"=",
"elmStack",
"[",
"i",
"]",
";",
"let",
"bgElmStyle",
"=",
"window",
".",
"getComputedStyle",
"(",
"bgElm",
")",
";",
"let",
"bgColor",
"=",
"color",
".",
"getOwnBackgroundColor",
"(",
"bgElmStyle",
")",
";",
"if",
"(",
"bgColor",
".",
"alpha",
"&&",
"contentOverlapping",
"(",
"originalElm",
",",
"bgElm",
")",
")",
"{",
"totalAlpha",
"+=",
"bgColor",
".",
"alpha",
";",
"}",
"else",
"{",
"elmStack",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}",
"}",
"return",
"totalAlpha",
";",
"}"
] |
Calculate alpha transparency of a background element obscuring the current node
@private
@param {Number} elmIndex
@param {Array} elmStack
@param {Element} originalElm
@return {Number|undefined}
|
[
"Calculate",
"alpha",
"transparency",
"of",
"a",
"background",
"element",
"obscuring",
"the",
"current",
"node"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/color/get-background-color.js#L311-L329
|
train
|
dequelabs/axe-core
|
lib/commons/color/get-background-color.js
|
contentOverlapping
|
function contentOverlapping(targetElement, bgNode) {
// get content box of target element
// check to see if the current bgNode is overlapping
var targetRect = targetElement.getClientRects()[0];
var obscuringElements = dom.shadowElementsFromPoint(
targetRect.left,
targetRect.top
);
if (obscuringElements) {
for (var i = 0; i < obscuringElements.length; i++) {
if (
obscuringElements[i] !== targetElement &&
obscuringElements[i] === bgNode
) {
return true;
}
}
}
return false;
}
|
javascript
|
function contentOverlapping(targetElement, bgNode) {
// get content box of target element
// check to see if the current bgNode is overlapping
var targetRect = targetElement.getClientRects()[0];
var obscuringElements = dom.shadowElementsFromPoint(
targetRect.left,
targetRect.top
);
if (obscuringElements) {
for (var i = 0; i < obscuringElements.length; i++) {
if (
obscuringElements[i] !== targetElement &&
obscuringElements[i] === bgNode
) {
return true;
}
}
}
return false;
}
|
[
"function",
"contentOverlapping",
"(",
"targetElement",
",",
"bgNode",
")",
"{",
"var",
"targetRect",
"=",
"targetElement",
".",
"getClientRects",
"(",
")",
"[",
"0",
"]",
";",
"var",
"obscuringElements",
"=",
"dom",
".",
"shadowElementsFromPoint",
"(",
"targetRect",
".",
"left",
",",
"targetRect",
".",
"top",
")",
";",
"if",
"(",
"obscuringElements",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obscuringElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"obscuringElements",
"[",
"i",
"]",
"!==",
"targetElement",
"&&",
"obscuringElements",
"[",
"i",
"]",
"===",
"bgNode",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] |
Determines overlap of node's content with a bgNode. Used for inline elements
@private
@param {Element} targetElement
@param {Element} bgNode
@return {Boolean}
|
[
"Determines",
"overlap",
"of",
"node",
"s",
"content",
"with",
"a",
"bgNode",
".",
"Used",
"for",
"inline",
"elements"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/color/get-background-color.js#L338-L357
|
train
|
dequelabs/axe-core
|
lib/commons/color/incomplete-data.js
|
function(key, reason) {
if (typeof key !== 'string') {
throw new Error('Incomplete data: key must be a string');
}
if (reason) {
data[key] = reason;
}
return data[key];
}
|
javascript
|
function(key, reason) {
if (typeof key !== 'string') {
throw new Error('Incomplete data: key must be a string');
}
if (reason) {
data[key] = reason;
}
return data[key];
}
|
[
"function",
"(",
"key",
",",
"reason",
")",
"{",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Incomplete data: key must be a string'",
")",
";",
"}",
"if",
"(",
"reason",
")",
"{",
"data",
"[",
"key",
"]",
"=",
"reason",
";",
"}",
"return",
"data",
"[",
"key",
"]",
";",
"}"
] |
Store incomplete data by key with a string value
@method set
@memberof axe.commons.color.incompleteData
@instance
@param {String} key Identifier for missing data point (fgColor, bgColor, etc.)
@param {String} reason Missing data reason to match message template
|
[
"Store",
"incomplete",
"data",
"by",
"key",
"with",
"a",
"string",
"value"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/color/incomplete-data.js#L20-L28
|
train
|
|
dequelabs/axe-core
|
lib/commons/text/form-control-value.js
|
nativeSelectValue
|
function nativeSelectValue(node) {
node = node.actualNode || node;
if (node.nodeName.toUpperCase() !== 'SELECT') {
return '';
}
return (
Array.from(node.options)
.filter(option => option.selected)
.map(option => option.text)
.join(' ') || ''
);
}
|
javascript
|
function nativeSelectValue(node) {
node = node.actualNode || node;
if (node.nodeName.toUpperCase() !== 'SELECT') {
return '';
}
return (
Array.from(node.options)
.filter(option => option.selected)
.map(option => option.text)
.join(' ') || ''
);
}
|
[
"function",
"nativeSelectValue",
"(",
"node",
")",
"{",
"node",
"=",
"node",
".",
"actualNode",
"||",
"node",
";",
"if",
"(",
"node",
".",
"nodeName",
".",
"toUpperCase",
"(",
")",
"!==",
"'SELECT'",
")",
"{",
"return",
"''",
";",
"}",
"return",
"(",
"Array",
".",
"from",
"(",
"node",
".",
"options",
")",
".",
"filter",
"(",
"option",
"=>",
"option",
".",
"selected",
")",
".",
"map",
"(",
"option",
"=>",
"option",
".",
"text",
")",
".",
"join",
"(",
"' '",
")",
"||",
"''",
")",
";",
"}"
] |
Calculate value of a select element
@param {VirtualNode} element The VirtualNode instance whose value we want
@return {string} The calculated value
|
[
"Calculate",
"value",
"of",
"a",
"select",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/form-control-value.js#L94-L105
|
train
|
dequelabs/axe-core
|
lib/commons/text/form-control-value.js
|
ariaTextboxValue
|
function ariaTextboxValue(virtualNode) {
const { actualNode } = virtualNode;
const role = aria.getRole(actualNode);
if (role !== 'textbox') {
return '';
}
if (!dom.isHiddenWithCSS(actualNode)) {
return text.visibleVirtual(virtualNode, true);
} else {
return actualNode.textContent;
}
}
|
javascript
|
function ariaTextboxValue(virtualNode) {
const { actualNode } = virtualNode;
const role = aria.getRole(actualNode);
if (role !== 'textbox') {
return '';
}
if (!dom.isHiddenWithCSS(actualNode)) {
return text.visibleVirtual(virtualNode, true);
} else {
return actualNode.textContent;
}
}
|
[
"function",
"ariaTextboxValue",
"(",
"virtualNode",
")",
"{",
"const",
"{",
"actualNode",
"}",
"=",
"virtualNode",
";",
"const",
"role",
"=",
"aria",
".",
"getRole",
"(",
"actualNode",
")",
";",
"if",
"(",
"role",
"!==",
"'textbox'",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"!",
"dom",
".",
"isHiddenWithCSS",
"(",
"actualNode",
")",
")",
"{",
"return",
"text",
".",
"visibleVirtual",
"(",
"virtualNode",
",",
"true",
")",
";",
"}",
"else",
"{",
"return",
"actualNode",
".",
"textContent",
";",
"}",
"}"
] |
Calculate value of a an element with role=textbox
@param {VirtualNode} element The VirtualNode instance whose value we want
@return {string} The calculated value
|
[
"Calculate",
"value",
"of",
"a",
"an",
"element",
"with",
"role",
"=",
"textbox"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/form-control-value.js#L113-L124
|
train
|
dequelabs/axe-core
|
lib/commons/text/form-control-value.js
|
ariaRangeValue
|
function ariaRangeValue(node) {
node = node.actualNode || node;
const role = aria.getRole(node);
if (!rangeRoles.includes(role) || !node.hasAttribute('aria-valuenow')) {
return '';
}
// Validate the number, if not, return 0.
// Chrome 70 typecasts this, Firefox 62 does not
const valueNow = +node.getAttribute('aria-valuenow');
return !isNaN(valueNow) ? String(valueNow) : '0';
}
|
javascript
|
function ariaRangeValue(node) {
node = node.actualNode || node;
const role = aria.getRole(node);
if (!rangeRoles.includes(role) || !node.hasAttribute('aria-valuenow')) {
return '';
}
// Validate the number, if not, return 0.
// Chrome 70 typecasts this, Firefox 62 does not
const valueNow = +node.getAttribute('aria-valuenow');
return !isNaN(valueNow) ? String(valueNow) : '0';
}
|
[
"function",
"ariaRangeValue",
"(",
"node",
")",
"{",
"node",
"=",
"node",
".",
"actualNode",
"||",
"node",
";",
"const",
"role",
"=",
"aria",
".",
"getRole",
"(",
"node",
")",
";",
"if",
"(",
"!",
"rangeRoles",
".",
"includes",
"(",
"role",
")",
"||",
"!",
"node",
".",
"hasAttribute",
"(",
"'aria-valuenow'",
")",
")",
"{",
"return",
"''",
";",
"}",
"const",
"valueNow",
"=",
"+",
"node",
".",
"getAttribute",
"(",
"'aria-valuenow'",
")",
";",
"return",
"!",
"isNaN",
"(",
"valueNow",
")",
"?",
"String",
"(",
"valueNow",
")",
":",
"'0'",
";",
"}"
] |
Calculate value of an element with range-type role
@param {VirtualNode|Node} element The VirtualNode instance whose value we want
@return {string} The calculated value
|
[
"Calculate",
"value",
"of",
"an",
"element",
"with",
"range",
"-",
"type",
"role"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/form-control-value.js#L194-L204
|
train
|
dequelabs/axe-core
|
lib/core/utils/queue.js
|
function(e) {
err = e;
setTimeout(function() {
if (err !== undefined && err !== null) {
axe.log('Uncaught error (of queue)', err);
}
}, 1);
}
|
javascript
|
function(e) {
err = e;
setTimeout(function() {
if (err !== undefined && err !== null) {
axe.log('Uncaught error (of queue)', err);
}
}, 1);
}
|
[
"function",
"(",
"e",
")",
"{",
"err",
"=",
"e",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"err",
"!==",
"undefined",
"&&",
"err",
"!==",
"null",
")",
"{",
"axe",
".",
"log",
"(",
"'Uncaught error (of queue)'",
",",
"err",
")",
";",
"}",
"}",
",",
"1",
")",
";",
"}"
] |
By default, wait until the next tick, if no catch was set, throw to console.
|
[
"By",
"default",
"wait",
"until",
"the",
"next",
"tick",
"if",
"no",
"catch",
"was",
"set",
"throw",
"to",
"console",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/queue.js#L24-L31
|
train
|
|
dequelabs/axe-core
|
lib/core/utils/queue.js
|
function(fn) {
if (typeof fn === 'object' && fn.then && fn.catch) {
var defer = fn;
fn = function(resolve, reject) {
defer.then(resolve).catch(reject);
};
}
funcGuard(fn);
if (err !== undefined) {
return;
} else if (complete) {
throw new Error('Queue already completed');
}
tasks.push(fn);
++remaining;
pop();
return q;
}
|
javascript
|
function(fn) {
if (typeof fn === 'object' && fn.then && fn.catch) {
var defer = fn;
fn = function(resolve, reject) {
defer.then(resolve).catch(reject);
};
}
funcGuard(fn);
if (err !== undefined) {
return;
} else if (complete) {
throw new Error('Queue already completed');
}
tasks.push(fn);
++remaining;
pop();
return q;
}
|
[
"function",
"(",
"fn",
")",
"{",
"if",
"(",
"typeof",
"fn",
"===",
"'object'",
"&&",
"fn",
".",
"then",
"&&",
"fn",
".",
"catch",
")",
"{",
"var",
"defer",
"=",
"fn",
";",
"fn",
"=",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"defer",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
";",
"}",
"funcGuard",
"(",
"fn",
")",
";",
"if",
"(",
"err",
"!==",
"undefined",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"complete",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Queue already completed'",
")",
";",
"}",
"tasks",
".",
"push",
"(",
"fn",
")",
";",
"++",
"remaining",
";",
"pop",
"(",
")",
";",
"return",
"q",
";",
"}"
] |
Defer a function that may or may not run asynchronously.
First parameter should be the function to execute with subsequent
parameters being passed as arguments to that function
|
[
"Defer",
"a",
"function",
"that",
"may",
"or",
"may",
"not",
"run",
"asynchronously",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/queue.js#L75-L93
|
train
|
|
dequelabs/axe-core
|
lib/core/utils/queue.js
|
function(fn) {
funcGuard(fn);
if (completeQueue !== noop) {
throw new Error('queue `then` already set');
}
if (!err) {
completeQueue = fn;
if (!remaining) {
complete = true;
completeQueue(tasks);
}
}
return q;
}
|
javascript
|
function(fn) {
funcGuard(fn);
if (completeQueue !== noop) {
throw new Error('queue `then` already set');
}
if (!err) {
completeQueue = fn;
if (!remaining) {
complete = true;
completeQueue(tasks);
}
}
return q;
}
|
[
"function",
"(",
"fn",
")",
"{",
"funcGuard",
"(",
"fn",
")",
";",
"if",
"(",
"completeQueue",
"!==",
"noop",
")",
"{",
"throw",
"new",
"Error",
"(",
"'queue `then` already set'",
")",
";",
"}",
"if",
"(",
"!",
"err",
")",
"{",
"completeQueue",
"=",
"fn",
";",
"if",
"(",
"!",
"remaining",
")",
"{",
"complete",
"=",
"true",
";",
"completeQueue",
"(",
"tasks",
")",
";",
"}",
"}",
"return",
"q",
";",
"}"
] |
The callback to execute once all "deferred" functions have completed. Will only be invoked once.
@param {Function} f The callback, receives an array of the return/callbacked
values of each of the "deferred" functions
|
[
"The",
"callback",
"to",
"execute",
"once",
"all",
"deferred",
"functions",
"have",
"completed",
".",
"Will",
"only",
"be",
"invoked",
"once",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/queue.js#L100-L113
|
train
|
|
dequelabs/axe-core
|
build/tasks/aria-supported.js
|
getAriaQueryAttributes
|
function getAriaQueryAttributes() {
const ariaKeys = Array.from(props).map(([key]) => key);
const roleAriaKeys = Array.from(roles).reduce((out, [name, rule]) => {
return [...out, ...Object.keys(rule.props)];
}, []);
return new Set(axe.utils.uniqueArray(roleAriaKeys, ariaKeys));
}
|
javascript
|
function getAriaQueryAttributes() {
const ariaKeys = Array.from(props).map(([key]) => key);
const roleAriaKeys = Array.from(roles).reduce((out, [name, rule]) => {
return [...out, ...Object.keys(rule.props)];
}, []);
return new Set(axe.utils.uniqueArray(roleAriaKeys, ariaKeys));
}
|
[
"function",
"getAriaQueryAttributes",
"(",
")",
"{",
"const",
"ariaKeys",
"=",
"Array",
".",
"from",
"(",
"props",
")",
".",
"map",
"(",
"(",
"[",
"key",
"]",
")",
"=>",
"key",
")",
";",
"const",
"roleAriaKeys",
"=",
"Array",
".",
"from",
"(",
"roles",
")",
".",
"reduce",
"(",
"(",
"out",
",",
"[",
"name",
",",
"rule",
"]",
")",
"=>",
"{",
"return",
"[",
"...",
"out",
",",
"...",
"Object",
".",
"keys",
"(",
"rule",
".",
"props",
")",
"]",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"new",
"Set",
"(",
"axe",
".",
"utils",
".",
"uniqueArray",
"(",
"roleAriaKeys",
",",
"ariaKeys",
")",
")",
";",
"}"
] |
Get list of aria attributes, from `aria-query`
@returns {Set|Object} collection of aria attributes from `aria-query` module
|
[
"Get",
"list",
"of",
"aria",
"attributes",
"from",
"aria",
"-",
"query"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/build/tasks/aria-supported.js#L80-L86
|
train
|
dequelabs/axe-core
|
build/tasks/aria-supported.js
|
getDiff
|
function getDiff(base, subject, type) {
const diff = [];
const notes = [];
const sortedBase = Array.from(base.entries()).sort();
sortedBase.forEach(([key] = item) => {
switch (type) {
case 'supported':
if (
subject.hasOwnProperty(key) &&
subject[key].unsupported === false
) {
diff.push([`${key}`, 'Yes']);
}
break;
case 'unsupported':
if (
(subject[key] && subject[key].unsupported === true) ||
!subject.hasOwnProperty(key)
) {
diff.push([`${key}`, 'No']);
} else if (
subject[key] &&
subject[key].unsupported &&
subject[key].unsupported.exceptions
) {
diff.push([`${key}`, `Mixed[^${notes.length + 1}]`]);
notes.push(
getSupportedElementsAsFootnote(
subject[key].unsupported.exceptions
)
);
}
break;
case 'all':
default:
diff.push([
`${key}`,
subject.hasOwnProperty(key) &&
subject[key].unsupported === false
? 'Yes'
: 'No'
]);
break;
}
});
return {
diff,
notes
};
}
|
javascript
|
function getDiff(base, subject, type) {
const diff = [];
const notes = [];
const sortedBase = Array.from(base.entries()).sort();
sortedBase.forEach(([key] = item) => {
switch (type) {
case 'supported':
if (
subject.hasOwnProperty(key) &&
subject[key].unsupported === false
) {
diff.push([`${key}`, 'Yes']);
}
break;
case 'unsupported':
if (
(subject[key] && subject[key].unsupported === true) ||
!subject.hasOwnProperty(key)
) {
diff.push([`${key}`, 'No']);
} else if (
subject[key] &&
subject[key].unsupported &&
subject[key].unsupported.exceptions
) {
diff.push([`${key}`, `Mixed[^${notes.length + 1}]`]);
notes.push(
getSupportedElementsAsFootnote(
subject[key].unsupported.exceptions
)
);
}
break;
case 'all':
default:
diff.push([
`${key}`,
subject.hasOwnProperty(key) &&
subject[key].unsupported === false
? 'Yes'
: 'No'
]);
break;
}
});
return {
diff,
notes
};
}
|
[
"function",
"getDiff",
"(",
"base",
",",
"subject",
",",
"type",
")",
"{",
"const",
"diff",
"=",
"[",
"]",
";",
"const",
"notes",
"=",
"[",
"]",
";",
"const",
"sortedBase",
"=",
"Array",
".",
"from",
"(",
"base",
".",
"entries",
"(",
")",
")",
".",
"sort",
"(",
")",
";",
"sortedBase",
".",
"forEach",
"(",
"(",
"[",
"key",
"]",
"=",
"item",
")",
"=>",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"'supported'",
":",
"if",
"(",
"subject",
".",
"hasOwnProperty",
"(",
"key",
")",
"&&",
"subject",
"[",
"key",
"]",
".",
"unsupported",
"===",
"false",
")",
"{",
"diff",
".",
"push",
"(",
"[",
"`",
"${",
"key",
"}",
"`",
",",
"'Yes'",
"]",
")",
";",
"}",
"break",
";",
"case",
"'unsupported'",
":",
"if",
"(",
"(",
"subject",
"[",
"key",
"]",
"&&",
"subject",
"[",
"key",
"]",
".",
"unsupported",
"===",
"true",
")",
"||",
"!",
"subject",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"diff",
".",
"push",
"(",
"[",
"`",
"${",
"key",
"}",
"`",
",",
"'No'",
"]",
")",
";",
"}",
"else",
"if",
"(",
"subject",
"[",
"key",
"]",
"&&",
"subject",
"[",
"key",
"]",
".",
"unsupported",
"&&",
"subject",
"[",
"key",
"]",
".",
"unsupported",
".",
"exceptions",
")",
"{",
"diff",
".",
"push",
"(",
"[",
"`",
"${",
"key",
"}",
"`",
",",
"`",
"${",
"notes",
".",
"length",
"+",
"1",
"}",
"`",
"]",
")",
";",
"notes",
".",
"push",
"(",
"getSupportedElementsAsFootnote",
"(",
"subject",
"[",
"key",
"]",
".",
"unsupported",
".",
"exceptions",
")",
")",
";",
"}",
"break",
";",
"case",
"'all'",
":",
"default",
":",
"diff",
".",
"push",
"(",
"[",
"`",
"${",
"key",
"}",
"`",
",",
"subject",
".",
"hasOwnProperty",
"(",
"key",
")",
"&&",
"subject",
"[",
"key",
"]",
".",
"unsupported",
"===",
"false",
"?",
"'Yes'",
":",
"'No'",
"]",
")",
";",
"break",
";",
"}",
"}",
")",
";",
"return",
"{",
"diff",
",",
"notes",
"}",
";",
"}"
] |
Given a `base` Map and `subject` Map object,
The function converts the `base` Map entries to an array which is sorted then enumerated to compare each entry against the `subject` Map
The function constructs a `string` to represent a `markdown table`, as well as returns notes to append to footnote
@param {Map} base Base Map Object
@param {Map} subject Subject Map Object
@param {String} type type to compare
@returns {Array<Object>[]}
@example Example Output: [ [ 'alert', 'No' ], [ 'figure', 'Yes' ] ]
|
[
"Given",
"a",
"base",
"Map",
"and",
"subject",
"Map",
"object",
"The",
"function",
"converts",
"the",
"base",
"Map",
"entries",
"to",
"an",
"array",
"which",
"is",
"sorted",
"then",
"enumerated",
"to",
"compare",
"each",
"entry",
"against",
"the",
"subject",
"Map",
"The",
"function",
"constructs",
"a",
"string",
"to",
"represent",
"a",
"markdown",
"table",
"as",
"well",
"as",
"returns",
"notes",
"to",
"append",
"to",
"footnote"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/build/tasks/aria-supported.js#L98-L150
|
train
|
dequelabs/axe-core
|
build/tasks/aria-supported.js
|
getSupportedElementsAsFootnote
|
function getSupportedElementsAsFootnote(elements) {
const notes = [];
const supportedElements = elements.map(element => {
if (typeof element === 'string') {
return `\`<${element}>\``;
}
/**
* if element is not a string it will be an object with structure:
{
nodeName: string,
properties: {
type: {string|string[]}
}
}
*/
return Object.keys(element.properties).map(prop => {
const value = element.properties[prop];
// the 'type' property can be a string or an array
if (typeof value === 'string') {
return `\`<${element.nodeName} ${prop}="${value}">\``;
}
// output format for an array of types:
// <input type="button" | "checkbox">
const values = value.map(v => `"${v}"`).join(' | ');
return `\`<${element.nodeName} ${prop}=${values}>\``;
});
});
notes.push('Supported on elements: ' + supportedElements.join(', '));
return notes;
}
|
javascript
|
function getSupportedElementsAsFootnote(elements) {
const notes = [];
const supportedElements = elements.map(element => {
if (typeof element === 'string') {
return `\`<${element}>\``;
}
/**
* if element is not a string it will be an object with structure:
{
nodeName: string,
properties: {
type: {string|string[]}
}
}
*/
return Object.keys(element.properties).map(prop => {
const value = element.properties[prop];
// the 'type' property can be a string or an array
if (typeof value === 'string') {
return `\`<${element.nodeName} ${prop}="${value}">\``;
}
// output format for an array of types:
// <input type="button" | "checkbox">
const values = value.map(v => `"${v}"`).join(' | ');
return `\`<${element.nodeName} ${prop}=${values}>\``;
});
});
notes.push('Supported on elements: ' + supportedElements.join(', '));
return notes;
}
|
[
"function",
"getSupportedElementsAsFootnote",
"(",
"elements",
")",
"{",
"const",
"notes",
"=",
"[",
"]",
";",
"const",
"supportedElements",
"=",
"elements",
".",
"map",
"(",
"element",
"=>",
"{",
"if",
"(",
"typeof",
"element",
"===",
"'string'",
")",
"{",
"return",
"`",
"\\`",
"${",
"element",
"}",
"\\`",
"`",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"element",
".",
"properties",
")",
".",
"map",
"(",
"prop",
"=>",
"{",
"const",
"value",
"=",
"element",
".",
"properties",
"[",
"prop",
"]",
";",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"return",
"`",
"\\`",
"${",
"element",
".",
"nodeName",
"}",
"${",
"prop",
"}",
"${",
"value",
"}",
"\\`",
"`",
";",
"}",
"const",
"values",
"=",
"value",
".",
"map",
"(",
"v",
"=>",
"`",
"${",
"v",
"}",
"`",
")",
".",
"join",
"(",
"' | '",
")",
";",
"return",
"`",
"\\`",
"${",
"element",
".",
"nodeName",
"}",
"${",
"prop",
"}",
"${",
"values",
"}",
"\\`",
"`",
";",
"}",
")",
";",
"}",
")",
";",
"notes",
".",
"push",
"(",
"'Supported on elements: '",
"+",
"supportedElements",
".",
"join",
"(",
"', '",
")",
")",
";",
"return",
"notes",
";",
"}"
] |
Parse a list of unsupported exception elements and add a footnote
detailing which HTML elements are supported.
@param {Array<String|Object>} elements List of supported elements
@returns {Array<String|Object>} notes
|
[
"Parse",
"a",
"list",
"of",
"unsupported",
"exception",
"elements",
"and",
"add",
"a",
"footnote",
"detailing",
"which",
"HTML",
"elements",
"are",
"supported",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/build/tasks/aria-supported.js#L159-L194
|
train
|
dequelabs/axe-core
|
lib/commons/text/accessible-text-virtual.js
|
shouldIgnoreHidden
|
function shouldIgnoreHidden({ actualNode }, context) {
if (
// If the parent isn't ignored, the text node should not be either
actualNode.nodeType !== 1 ||
// If the target of aria-labelledby is hidden, ignore all descendents
context.includeHidden
) {
return false;
}
return !dom.isVisible(actualNode, true);
}
|
javascript
|
function shouldIgnoreHidden({ actualNode }, context) {
if (
// If the parent isn't ignored, the text node should not be either
actualNode.nodeType !== 1 ||
// If the target of aria-labelledby is hidden, ignore all descendents
context.includeHidden
) {
return false;
}
return !dom.isVisible(actualNode, true);
}
|
[
"function",
"shouldIgnoreHidden",
"(",
"{",
"actualNode",
"}",
",",
"context",
")",
"{",
"if",
"(",
"actualNode",
".",
"nodeType",
"!==",
"1",
"||",
"context",
".",
"includeHidden",
")",
"{",
"return",
"false",
";",
"}",
"return",
"!",
"dom",
".",
"isVisible",
"(",
"actualNode",
",",
"true",
")",
";",
"}"
] |
Check if the
@param {VirtualNode} element
@param {Object} context
@property {VirtualNode[]} processed
@return {Boolean}
|
[
"Check",
"if",
"the"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/accessible-text-virtual.js#L88-L99
|
train
|
dequelabs/axe-core
|
lib/commons/text/accessible-text-virtual.js
|
prepareContext
|
function prepareContext(virtualNode, context) {
const { actualNode } = virtualNode;
if (!context.startNode) {
context = { startNode: virtualNode, ...context };
}
/**
* When `aria-labelledby` directly references a `hidden` element
* the element needs to be included in the accessible name.
*
* When a descendent of the `aria-labelledby` reference is `hidden`
* the element should not be included in the accessible name.
*
* This is done by setting `includeHidden` for the `aria-labelledby` reference.
*/
if (
actualNode.nodeType === 1 &&
context.inLabelledByContext &&
context.includeHidden === undefined
) {
context = {
includeHidden: !dom.isVisible(actualNode, true),
...context
};
}
return context;
}
|
javascript
|
function prepareContext(virtualNode, context) {
const { actualNode } = virtualNode;
if (!context.startNode) {
context = { startNode: virtualNode, ...context };
}
/**
* When `aria-labelledby` directly references a `hidden` element
* the element needs to be included in the accessible name.
*
* When a descendent of the `aria-labelledby` reference is `hidden`
* the element should not be included in the accessible name.
*
* This is done by setting `includeHidden` for the `aria-labelledby` reference.
*/
if (
actualNode.nodeType === 1 &&
context.inLabelledByContext &&
context.includeHidden === undefined
) {
context = {
includeHidden: !dom.isVisible(actualNode, true),
...context
};
}
return context;
}
|
[
"function",
"prepareContext",
"(",
"virtualNode",
",",
"context",
")",
"{",
"const",
"{",
"actualNode",
"}",
"=",
"virtualNode",
";",
"if",
"(",
"!",
"context",
".",
"startNode",
")",
"{",
"context",
"=",
"{",
"startNode",
":",
"virtualNode",
",",
"...",
"context",
"}",
";",
"}",
"if",
"(",
"actualNode",
".",
"nodeType",
"===",
"1",
"&&",
"context",
".",
"inLabelledByContext",
"&&",
"context",
".",
"includeHidden",
"===",
"undefined",
")",
"{",
"context",
"=",
"{",
"includeHidden",
":",
"!",
"dom",
".",
"isVisible",
"(",
"actualNode",
",",
"true",
")",
",",
"...",
"context",
"}",
";",
"}",
"return",
"context",
";",
"}"
] |
Apply defaults to the context
@param {VirtualNode} element
@param {Object} context
@return {Object} context object with defaults applied
|
[
"Apply",
"defaults",
"to",
"the",
"context"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/commons/text/accessible-text-virtual.js#L107-L132
|
train
|
dequelabs/axe-core
|
lib/core/base/rule.js
|
findAfterChecks
|
function findAfterChecks(rule) {
'use strict';
return axe.utils
.getAllChecks(rule)
.map(function(c) {
var check = rule._audit.checks[c.id || c];
return check && typeof check.after === 'function' ? check : null;
})
.filter(Boolean);
}
|
javascript
|
function findAfterChecks(rule) {
'use strict';
return axe.utils
.getAllChecks(rule)
.map(function(c) {
var check = rule._audit.checks[c.id || c];
return check && typeof check.after === 'function' ? check : null;
})
.filter(Boolean);
}
|
[
"function",
"findAfterChecks",
"(",
"rule",
")",
"{",
"'use strict'",
";",
"return",
"axe",
".",
"utils",
".",
"getAllChecks",
"(",
"rule",
")",
".",
"map",
"(",
"function",
"(",
"c",
")",
"{",
"var",
"check",
"=",
"rule",
".",
"_audit",
".",
"checks",
"[",
"c",
".",
"id",
"||",
"c",
"]",
";",
"return",
"check",
"&&",
"typeof",
"check",
".",
"after",
"===",
"'function'",
"?",
"check",
":",
"null",
";",
"}",
")",
".",
"filter",
"(",
"Boolean",
")",
";",
"}"
] |
Iterates the rule's Checks looking for ones that have an after function
@private
@param {Rule} rule The rule to check for after checks
@return {Array} Checks that have an after function
|
[
"Iterates",
"the",
"rule",
"s",
"Checks",
"looking",
"for",
"ones",
"that",
"have",
"an",
"after",
"function"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/base/rule.js#L297-L307
|
train
|
dequelabs/axe-core
|
lib/core/base/rule.js
|
findCheckResults
|
function findCheckResults(nodes, checkID) {
'use strict';
var checkResults = [];
nodes.forEach(function(nodeResult) {
var checks = axe.utils.getAllChecks(nodeResult);
checks.forEach(function(checkResult) {
if (checkResult.id === checkID) {
checkResults.push(checkResult);
}
});
});
return checkResults;
}
|
javascript
|
function findCheckResults(nodes, checkID) {
'use strict';
var checkResults = [];
nodes.forEach(function(nodeResult) {
var checks = axe.utils.getAllChecks(nodeResult);
checks.forEach(function(checkResult) {
if (checkResult.id === checkID) {
checkResults.push(checkResult);
}
});
});
return checkResults;
}
|
[
"function",
"findCheckResults",
"(",
"nodes",
",",
"checkID",
")",
"{",
"'use strict'",
";",
"var",
"checkResults",
"=",
"[",
"]",
";",
"nodes",
".",
"forEach",
"(",
"function",
"(",
"nodeResult",
")",
"{",
"var",
"checks",
"=",
"axe",
".",
"utils",
".",
"getAllChecks",
"(",
"nodeResult",
")",
";",
"checks",
".",
"forEach",
"(",
"function",
"(",
"checkResult",
")",
"{",
"if",
"(",
"checkResult",
".",
"id",
"===",
"checkID",
")",
"{",
"checkResults",
".",
"push",
"(",
"checkResult",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"checkResults",
";",
"}"
] |
Finds and collates all results for a given Check on a specific Rule
@private
@param {Array} nodes RuleResult#nodes; array of 'detail' objects
@param {String} checkID The ID of the Check to find
@return {Array} Matching CheckResults
|
[
"Finds",
"and",
"collates",
"all",
"results",
"for",
"a",
"given",
"Check",
"on",
"a",
"specific",
"Rule"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/base/rule.js#L316-L329
|
train
|
dequelabs/axe-core
|
lib/core/utils/scroll-state.js
|
getScroll
|
function getScroll(elm) {
const style = window.getComputedStyle(elm);
const visibleOverflowY = style.getPropertyValue('overflow-y') === 'visible';
const visibleOverflowX = style.getPropertyValue('overflow-x') === 'visible';
if (
// See if the element hides overflowing content
(!visibleOverflowY && elm.scrollHeight > elm.clientHeight) ||
(!visibleOverflowX && elm.scrollWidth > elm.clientWidth)
) {
return { elm, top: elm.scrollTop, left: elm.scrollLeft };
}
}
|
javascript
|
function getScroll(elm) {
const style = window.getComputedStyle(elm);
const visibleOverflowY = style.getPropertyValue('overflow-y') === 'visible';
const visibleOverflowX = style.getPropertyValue('overflow-x') === 'visible';
if (
// See if the element hides overflowing content
(!visibleOverflowY && elm.scrollHeight > elm.clientHeight) ||
(!visibleOverflowX && elm.scrollWidth > elm.clientWidth)
) {
return { elm, top: elm.scrollTop, left: elm.scrollLeft };
}
}
|
[
"function",
"getScroll",
"(",
"elm",
")",
"{",
"const",
"style",
"=",
"window",
".",
"getComputedStyle",
"(",
"elm",
")",
";",
"const",
"visibleOverflowY",
"=",
"style",
".",
"getPropertyValue",
"(",
"'overflow-y'",
")",
"===",
"'visible'",
";",
"const",
"visibleOverflowX",
"=",
"style",
".",
"getPropertyValue",
"(",
"'overflow-x'",
")",
"===",
"'visible'",
";",
"if",
"(",
"(",
"!",
"visibleOverflowY",
"&&",
"elm",
".",
"scrollHeight",
">",
"elm",
".",
"clientHeight",
")",
"||",
"(",
"!",
"visibleOverflowX",
"&&",
"elm",
".",
"scrollWidth",
">",
"elm",
".",
"clientWidth",
")",
")",
"{",
"return",
"{",
"elm",
",",
"top",
":",
"elm",
".",
"scrollTop",
",",
"left",
":",
"elm",
".",
"scrollLeft",
"}",
";",
"}",
"}"
] |
Return the scroll position of scrollable elements
|
[
"Return",
"the",
"scroll",
"position",
"of",
"scrollable",
"elements"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/scroll-state.js#L4-L16
|
train
|
dequelabs/axe-core
|
lib/core/utils/scroll-state.js
|
setScroll
|
function setScroll(elm, top, left) {
if (elm === window) {
return elm.scroll(left, top);
} else {
elm.scrollTop = top;
elm.scrollLeft = left;
}
}
|
javascript
|
function setScroll(elm, top, left) {
if (elm === window) {
return elm.scroll(left, top);
} else {
elm.scrollTop = top;
elm.scrollLeft = left;
}
}
|
[
"function",
"setScroll",
"(",
"elm",
",",
"top",
",",
"left",
")",
"{",
"if",
"(",
"elm",
"===",
"window",
")",
"{",
"return",
"elm",
".",
"scroll",
"(",
"left",
",",
"top",
")",
";",
"}",
"else",
"{",
"elm",
".",
"scrollTop",
"=",
"top",
";",
"elm",
".",
"scrollLeft",
"=",
"left",
";",
"}",
"}"
] |
set the scroll position of an element
|
[
"set",
"the",
"scroll",
"position",
"of",
"an",
"element"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/scroll-state.js#L21-L28
|
train
|
dequelabs/axe-core
|
lib/core/utils/scroll-state.js
|
getElmScrollRecursive
|
function getElmScrollRecursive(root) {
return Array.from(root.children).reduce((scrolls, elm) => {
const scroll = getScroll(elm);
if (scroll) {
scrolls.push(scroll);
}
return scrolls.concat(getElmScrollRecursive(elm));
}, []);
}
|
javascript
|
function getElmScrollRecursive(root) {
return Array.from(root.children).reduce((scrolls, elm) => {
const scroll = getScroll(elm);
if (scroll) {
scrolls.push(scroll);
}
return scrolls.concat(getElmScrollRecursive(elm));
}, []);
}
|
[
"function",
"getElmScrollRecursive",
"(",
"root",
")",
"{",
"return",
"Array",
".",
"from",
"(",
"root",
".",
"children",
")",
".",
"reduce",
"(",
"(",
"scrolls",
",",
"elm",
")",
"=>",
"{",
"const",
"scroll",
"=",
"getScroll",
"(",
"elm",
")",
";",
"if",
"(",
"scroll",
")",
"{",
"scrolls",
".",
"push",
"(",
"scroll",
")",
";",
"}",
"return",
"scrolls",
".",
"concat",
"(",
"getElmScrollRecursive",
"(",
"elm",
")",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
Create an array scroll positions from descending elements
|
[
"Create",
"an",
"array",
"scroll",
"positions",
"from",
"descending",
"elements"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/scroll-state.js#L33-L41
|
train
|
dequelabs/axe-core
|
lib/core/utils/merge-results.js
|
pushFrame
|
function pushFrame(resultSet, options, frameElement, frameSelector) {
'use strict';
var frameXpath = axe.utils.getXpath(frameElement);
var frameSpec = {
element: frameElement,
selector: frameSelector,
xpath: frameXpath
};
resultSet.forEach(function(res) {
res.node = axe.utils.DqElement.fromFrame(res.node, options, frameSpec);
var checks = axe.utils.getAllChecks(res);
if (checks.length) {
checks.forEach(function(check) {
check.relatedNodes = check.relatedNodes.map(node =>
axe.utils.DqElement.fromFrame(node, options, frameSpec)
);
});
}
});
}
|
javascript
|
function pushFrame(resultSet, options, frameElement, frameSelector) {
'use strict';
var frameXpath = axe.utils.getXpath(frameElement);
var frameSpec = {
element: frameElement,
selector: frameSelector,
xpath: frameXpath
};
resultSet.forEach(function(res) {
res.node = axe.utils.DqElement.fromFrame(res.node, options, frameSpec);
var checks = axe.utils.getAllChecks(res);
if (checks.length) {
checks.forEach(function(check) {
check.relatedNodes = check.relatedNodes.map(node =>
axe.utils.DqElement.fromFrame(node, options, frameSpec)
);
});
}
});
}
|
[
"function",
"pushFrame",
"(",
"resultSet",
",",
"options",
",",
"frameElement",
",",
"frameSelector",
")",
"{",
"'use strict'",
";",
"var",
"frameXpath",
"=",
"axe",
".",
"utils",
".",
"getXpath",
"(",
"frameElement",
")",
";",
"var",
"frameSpec",
"=",
"{",
"element",
":",
"frameElement",
",",
"selector",
":",
"frameSelector",
",",
"xpath",
":",
"frameXpath",
"}",
";",
"resultSet",
".",
"forEach",
"(",
"function",
"(",
"res",
")",
"{",
"res",
".",
"node",
"=",
"axe",
".",
"utils",
".",
"DqElement",
".",
"fromFrame",
"(",
"res",
".",
"node",
",",
"options",
",",
"frameSpec",
")",
";",
"var",
"checks",
"=",
"axe",
".",
"utils",
".",
"getAllChecks",
"(",
"res",
")",
";",
"if",
"(",
"checks",
".",
"length",
")",
"{",
"checks",
".",
"forEach",
"(",
"function",
"(",
"check",
")",
"{",
"check",
".",
"relatedNodes",
"=",
"check",
".",
"relatedNodes",
".",
"map",
"(",
"node",
"=>",
"axe",
".",
"utils",
".",
"DqElement",
".",
"fromFrame",
"(",
"node",
",",
"options",
",",
"frameSpec",
")",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Adds the owning frame's CSS selector onto each instance of DqElement
@private
@param {Array} resultSet `nodes` array on a `RuleResult`
@param {HTMLElement} frameElement The frame element
@param {String} frameSelector Unique CSS selector for the frame
|
[
"Adds",
"the",
"owning",
"frame",
"s",
"CSS",
"selector",
"onto",
"each",
"instance",
"of",
"DqElement"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/merge-results.js#L8-L29
|
train
|
dequelabs/axe-core
|
lib/core/utils/merge-results.js
|
spliceNodes
|
function spliceNodes(target, to) {
'use strict';
var firstFromFrame = to[0].node,
sorterResult,
t;
for (var i = 0, l = target.length; i < l; i++) {
t = target[i].node;
sorterResult = axe.utils.nodeSorter(
{ actualNode: t.element },
{ actualNode: firstFromFrame.element }
);
if (
sorterResult > 0 ||
(sorterResult === 0 && firstFromFrame.selector.length < t.selector.length)
) {
target.splice.apply(target, [i, 0].concat(to));
return;
}
}
target.push.apply(target, to);
}
|
javascript
|
function spliceNodes(target, to) {
'use strict';
var firstFromFrame = to[0].node,
sorterResult,
t;
for (var i = 0, l = target.length; i < l; i++) {
t = target[i].node;
sorterResult = axe.utils.nodeSorter(
{ actualNode: t.element },
{ actualNode: firstFromFrame.element }
);
if (
sorterResult > 0 ||
(sorterResult === 0 && firstFromFrame.selector.length < t.selector.length)
) {
target.splice.apply(target, [i, 0].concat(to));
return;
}
}
target.push.apply(target, to);
}
|
[
"function",
"spliceNodes",
"(",
"target",
",",
"to",
")",
"{",
"'use strict'",
";",
"var",
"firstFromFrame",
"=",
"to",
"[",
"0",
"]",
".",
"node",
",",
"sorterResult",
",",
"t",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"target",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"t",
"=",
"target",
"[",
"i",
"]",
".",
"node",
";",
"sorterResult",
"=",
"axe",
".",
"utils",
".",
"nodeSorter",
"(",
"{",
"actualNode",
":",
"t",
".",
"element",
"}",
",",
"{",
"actualNode",
":",
"firstFromFrame",
".",
"element",
"}",
")",
";",
"if",
"(",
"sorterResult",
">",
"0",
"||",
"(",
"sorterResult",
"===",
"0",
"&&",
"firstFromFrame",
".",
"selector",
".",
"length",
"<",
"t",
".",
"selector",
".",
"length",
")",
")",
"{",
"target",
".",
"splice",
".",
"apply",
"(",
"target",
",",
"[",
"i",
",",
"0",
"]",
".",
"concat",
"(",
"to",
")",
")",
";",
"return",
";",
"}",
"}",
"target",
".",
"push",
".",
"apply",
"(",
"target",
",",
"to",
")",
";",
"}"
] |
Adds `to` to `from` and then re-sorts by DOM order
@private
@param {Array} target `nodes` array on a `RuleResult`
@param {Array} to `nodes` array on a `RuleResult`
@return {Array} The merged and sorted result
|
[
"Adds",
"to",
"to",
"from",
"and",
"then",
"re",
"-",
"sorts",
"by",
"DOM",
"order"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/merge-results.js#L38-L60
|
train
|
dequelabs/axe-core
|
lib/checks/navigation/region.js
|
isRegion
|
function isRegion(virtualNode) {
const node = virtualNode.actualNode;
const explicitRole = axe.commons.aria.getRole(node, { noImplicit: true });
const ariaLive = (node.getAttribute('aria-live') || '').toLowerCase().trim();
if (explicitRole) {
return explicitRole === 'dialog' || landmarkRoles.includes(explicitRole);
}
// Ignore content inside of aria-live
if (['assertive', 'polite'].includes(ariaLive)) {
return true;
}
// Check if the node matches any of the CSS selectors of implicit landmarks
return implicitLandmarks.some(implicitSelector => {
let matches = axe.utils.matchesSelector(node, implicitSelector);
if (node.nodeName.toUpperCase() === 'FORM') {
let titleAttr = node.getAttribute('title');
let title =
titleAttr && titleAttr.trim() !== ''
? axe.commons.text.sanitize(titleAttr)
: null;
return matches && (!!aria.labelVirtual(virtualNode) || !!title);
}
return matches;
});
}
|
javascript
|
function isRegion(virtualNode) {
const node = virtualNode.actualNode;
const explicitRole = axe.commons.aria.getRole(node, { noImplicit: true });
const ariaLive = (node.getAttribute('aria-live') || '').toLowerCase().trim();
if (explicitRole) {
return explicitRole === 'dialog' || landmarkRoles.includes(explicitRole);
}
// Ignore content inside of aria-live
if (['assertive', 'polite'].includes(ariaLive)) {
return true;
}
// Check if the node matches any of the CSS selectors of implicit landmarks
return implicitLandmarks.some(implicitSelector => {
let matches = axe.utils.matchesSelector(node, implicitSelector);
if (node.nodeName.toUpperCase() === 'FORM') {
let titleAttr = node.getAttribute('title');
let title =
titleAttr && titleAttr.trim() !== ''
? axe.commons.text.sanitize(titleAttr)
: null;
return matches && (!!aria.labelVirtual(virtualNode) || !!title);
}
return matches;
});
}
|
[
"function",
"isRegion",
"(",
"virtualNode",
")",
"{",
"const",
"node",
"=",
"virtualNode",
".",
"actualNode",
";",
"const",
"explicitRole",
"=",
"axe",
".",
"commons",
".",
"aria",
".",
"getRole",
"(",
"node",
",",
"{",
"noImplicit",
":",
"true",
"}",
")",
";",
"const",
"ariaLive",
"=",
"(",
"node",
".",
"getAttribute",
"(",
"'aria-live'",
")",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"explicitRole",
")",
"{",
"return",
"explicitRole",
"===",
"'dialog'",
"||",
"landmarkRoles",
".",
"includes",
"(",
"explicitRole",
")",
";",
"}",
"if",
"(",
"[",
"'assertive'",
",",
"'polite'",
"]",
".",
"includes",
"(",
"ariaLive",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"implicitLandmarks",
".",
"some",
"(",
"implicitSelector",
"=>",
"{",
"let",
"matches",
"=",
"axe",
".",
"utils",
".",
"matchesSelector",
"(",
"node",
",",
"implicitSelector",
")",
";",
"if",
"(",
"node",
".",
"nodeName",
".",
"toUpperCase",
"(",
")",
"===",
"'FORM'",
")",
"{",
"let",
"titleAttr",
"=",
"node",
".",
"getAttribute",
"(",
"'title'",
")",
";",
"let",
"title",
"=",
"titleAttr",
"&&",
"titleAttr",
".",
"trim",
"(",
")",
"!==",
"''",
"?",
"axe",
".",
"commons",
".",
"text",
".",
"sanitize",
"(",
"titleAttr",
")",
":",
"null",
";",
"return",
"matches",
"&&",
"(",
"!",
"!",
"aria",
".",
"labelVirtual",
"(",
"virtualNode",
")",
"||",
"!",
"!",
"title",
")",
";",
"}",
"return",
"matches",
";",
"}",
")",
";",
"}"
] |
Check if the current element is a landmark
|
[
"Check",
"if",
"the",
"current",
"element",
"is",
"a",
"landmark"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/checks/navigation/region.js#L10-L36
|
train
|
dequelabs/axe-core
|
lib/checks/navigation/region.js
|
findRegionlessElms
|
function findRegionlessElms(virtualNode) {
const node = virtualNode.actualNode;
// End recursion if the element is a landmark, skiplink, or hidden content
if (
isRegion(virtualNode) ||
(dom.isSkipLink(virtualNode.actualNode) &&
dom.getElementByReference(virtualNode.actualNode, 'href')) ||
!dom.isVisible(node, true)
) {
return [];
// Return the node is a content element
} else if (dom.hasContent(node, /* noRecursion: */ true)) {
return [node];
// Recursively look at all child elements
} else {
return virtualNode.children
.filter(({ actualNode }) => actualNode.nodeType === 1)
.map(findRegionlessElms)
.reduce((a, b) => a.concat(b), []); // flatten the results
}
}
|
javascript
|
function findRegionlessElms(virtualNode) {
const node = virtualNode.actualNode;
// End recursion if the element is a landmark, skiplink, or hidden content
if (
isRegion(virtualNode) ||
(dom.isSkipLink(virtualNode.actualNode) &&
dom.getElementByReference(virtualNode.actualNode, 'href')) ||
!dom.isVisible(node, true)
) {
return [];
// Return the node is a content element
} else if (dom.hasContent(node, /* noRecursion: */ true)) {
return [node];
// Recursively look at all child elements
} else {
return virtualNode.children
.filter(({ actualNode }) => actualNode.nodeType === 1)
.map(findRegionlessElms)
.reduce((a, b) => a.concat(b), []); // flatten the results
}
}
|
[
"function",
"findRegionlessElms",
"(",
"virtualNode",
")",
"{",
"const",
"node",
"=",
"virtualNode",
".",
"actualNode",
";",
"if",
"(",
"isRegion",
"(",
"virtualNode",
")",
"||",
"(",
"dom",
".",
"isSkipLink",
"(",
"virtualNode",
".",
"actualNode",
")",
"&&",
"dom",
".",
"getElementByReference",
"(",
"virtualNode",
".",
"actualNode",
",",
"'href'",
")",
")",
"||",
"!",
"dom",
".",
"isVisible",
"(",
"node",
",",
"true",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"dom",
".",
"hasContent",
"(",
"node",
",",
"true",
")",
")",
"{",
"return",
"[",
"node",
"]",
";",
"}",
"else",
"{",
"return",
"virtualNode",
".",
"children",
".",
"filter",
"(",
"(",
"{",
"actualNode",
"}",
")",
"=>",
"actualNode",
".",
"nodeType",
"===",
"1",
")",
".",
"map",
"(",
"findRegionlessElms",
")",
".",
"reduce",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"concat",
"(",
"b",
")",
",",
"[",
"]",
")",
";",
"}",
"}"
] |
Find all visible elements not wrapped inside a landmark or skiplink
|
[
"Find",
"all",
"visible",
"elements",
"not",
"wrapped",
"inside",
"a",
"landmark",
"or",
"skiplink"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/checks/navigation/region.js#L41-L63
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
_getSource
|
function _getSource() {
var application = 'axeAPI',
version = '',
src;
if (typeof axe !== 'undefined' && axe._audit && axe._audit.application) {
application = axe._audit.application;
}
if (typeof axe !== 'undefined') {
version = axe.version;
}
src = application + '.' + version;
return src;
}
|
javascript
|
function _getSource() {
var application = 'axeAPI',
version = '',
src;
if (typeof axe !== 'undefined' && axe._audit && axe._audit.application) {
application = axe._audit.application;
}
if (typeof axe !== 'undefined') {
version = axe.version;
}
src = application + '.' + version;
return src;
}
|
[
"function",
"_getSource",
"(",
")",
"{",
"var",
"application",
"=",
"'axeAPI'",
",",
"version",
"=",
"''",
",",
"src",
";",
"if",
"(",
"typeof",
"axe",
"!==",
"'undefined'",
"&&",
"axe",
".",
"_audit",
"&&",
"axe",
".",
"_audit",
".",
"application",
")",
"{",
"application",
"=",
"axe",
".",
"_audit",
".",
"application",
";",
"}",
"if",
"(",
"typeof",
"axe",
"!==",
"'undefined'",
")",
"{",
"version",
"=",
"axe",
".",
"version",
";",
"}",
"src",
"=",
"application",
"+",
"'.'",
"+",
"version",
";",
"return",
"src",
";",
"}"
] |
get the unique string to be used to identify our instance of axe
@private
|
[
"get",
"the",
"unique",
"string",
"to",
"be",
"used",
"to",
"identify",
"our",
"instance",
"of",
"axe"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L19-L31
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
verify
|
function verify(postedMessage) {
if (
// Check incoming message is valid
typeof postedMessage === 'object' &&
typeof postedMessage.uuid === 'string' &&
postedMessage._respondable === true
) {
var messageSource = _getSource();
return (
// Check the version matches
postedMessage._source === messageSource ||
// Allow free communication with axe test
postedMessage._source === 'axeAPI.x.y.z' ||
messageSource === 'axeAPI.x.y.z'
);
}
return false;
}
|
javascript
|
function verify(postedMessage) {
if (
// Check incoming message is valid
typeof postedMessage === 'object' &&
typeof postedMessage.uuid === 'string' &&
postedMessage._respondable === true
) {
var messageSource = _getSource();
return (
// Check the version matches
postedMessage._source === messageSource ||
// Allow free communication with axe test
postedMessage._source === 'axeAPI.x.y.z' ||
messageSource === 'axeAPI.x.y.z'
);
}
return false;
}
|
[
"function",
"verify",
"(",
"postedMessage",
")",
"{",
"if",
"(",
"typeof",
"postedMessage",
"===",
"'object'",
"&&",
"typeof",
"postedMessage",
".",
"uuid",
"===",
"'string'",
"&&",
"postedMessage",
".",
"_respondable",
"===",
"true",
")",
"{",
"var",
"messageSource",
"=",
"_getSource",
"(",
")",
";",
"return",
"(",
"postedMessage",
".",
"_source",
"===",
"messageSource",
"||",
"postedMessage",
".",
"_source",
"===",
"'axeAPI.x.y.z'",
"||",
"messageSource",
"===",
"'axeAPI.x.y.z'",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Verify the received message is from the "respondable" module
@private
@param {Object} postedMessage The message received via postMessage
@return {Boolean} `true` if the message is verified from respondable
|
[
"Verify",
"the",
"received",
"message",
"is",
"from",
"the",
"respondable",
"module"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L38-L55
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
post
|
function post(win, topic, message, uuid, keepalive, callback) {
var error;
if (message instanceof Error) {
error = {
name: message.name,
message: message.message,
stack: message.stack
};
message = undefined;
}
var data = {
uuid: uuid,
topic: topic,
message: message,
error: error,
_respondable: true,
_source: _getSource(),
_keepalive: keepalive
};
if (typeof callback === 'function') {
messages[uuid] = callback;
}
win.postMessage(JSON.stringify(data), '*');
}
|
javascript
|
function post(win, topic, message, uuid, keepalive, callback) {
var error;
if (message instanceof Error) {
error = {
name: message.name,
message: message.message,
stack: message.stack
};
message = undefined;
}
var data = {
uuid: uuid,
topic: topic,
message: message,
error: error,
_respondable: true,
_source: _getSource(),
_keepalive: keepalive
};
if (typeof callback === 'function') {
messages[uuid] = callback;
}
win.postMessage(JSON.stringify(data), '*');
}
|
[
"function",
"post",
"(",
"win",
",",
"topic",
",",
"message",
",",
"uuid",
",",
"keepalive",
",",
"callback",
")",
"{",
"var",
"error",
";",
"if",
"(",
"message",
"instanceof",
"Error",
")",
"{",
"error",
"=",
"{",
"name",
":",
"message",
".",
"name",
",",
"message",
":",
"message",
".",
"message",
",",
"stack",
":",
"message",
".",
"stack",
"}",
";",
"message",
"=",
"undefined",
";",
"}",
"var",
"data",
"=",
"{",
"uuid",
":",
"uuid",
",",
"topic",
":",
"topic",
",",
"message",
":",
"message",
",",
"error",
":",
"error",
",",
"_respondable",
":",
"true",
",",
"_source",
":",
"_getSource",
"(",
")",
",",
"_keepalive",
":",
"keepalive",
"}",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"messages",
"[",
"uuid",
"]",
"=",
"callback",
";",
"}",
"win",
".",
"postMessage",
"(",
"JSON",
".",
"stringify",
"(",
"data",
")",
",",
"'*'",
")",
";",
"}"
] |
Posts the message to correct frame.
This abstraction necessary because IE9 & 10 do not support posting Objects; only strings
@private
@param {Window} win The `window` to post the message to
@param {String} topic The topic of the message
@param {Object} message The message content
@param {String} uuid The UUID, or pseudo-unique ID of the message
@param {Boolean} keepalive Whether to allow multiple responses - default is false
@param {Function} callback The function to invoke when/if the message is responded to
|
[
"Posts",
"the",
"message",
"to",
"correct",
"frame",
".",
"This",
"abstraction",
"necessary",
"because",
"IE9",
"&",
"10",
"do",
"not",
"support",
"posting",
"Objects",
";",
"only",
"strings"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L68-L94
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
respondable
|
function respondable(win, topic, message, keepalive, callback) {
var id = uuid.v1();
post(win, topic, message, id, keepalive, callback);
}
|
javascript
|
function respondable(win, topic, message, keepalive, callback) {
var id = uuid.v1();
post(win, topic, message, id, keepalive, callback);
}
|
[
"function",
"respondable",
"(",
"win",
",",
"topic",
",",
"message",
",",
"keepalive",
",",
"callback",
")",
"{",
"var",
"id",
"=",
"uuid",
".",
"v1",
"(",
")",
";",
"post",
"(",
"win",
",",
"topic",
",",
"message",
",",
"id",
",",
"keepalive",
",",
"callback",
")",
";",
"}"
] |
Post a message to a window who may or may not respond to it.
@param {Window} win The window to post the message to
@param {String} topic The topic of the message
@param {Object} message The message content
@param {Boolean} keepalive Whether to allow multiple responses - default is false
@param {Function} callback The function to invoke when/if the message is responded to
|
[
"Post",
"a",
"message",
"to",
"a",
"window",
"who",
"may",
"or",
"may",
"not",
"respond",
"to",
"it",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L104-L107
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
createResponder
|
function createResponder(source, topic, uuid) {
return function(message, keepalive, callback) {
post(source, topic, message, uuid, keepalive, callback);
};
}
|
javascript
|
function createResponder(source, topic, uuid) {
return function(message, keepalive, callback) {
post(source, topic, message, uuid, keepalive, callback);
};
}
|
[
"function",
"createResponder",
"(",
"source",
",",
"topic",
",",
"uuid",
")",
"{",
"return",
"function",
"(",
"message",
",",
"keepalive",
",",
"callback",
")",
"{",
"post",
"(",
"source",
",",
"topic",
",",
"message",
",",
"uuid",
",",
"keepalive",
",",
"callback",
")",
";",
"}",
";",
"}"
] |
Helper closure to create a function that may be used to respond to a message
@private
@param {Window} source The window from which the message originated
@param {String} topic The topic of the message
@param {String} uuid The "unique" ID of the original message
@return {Function} A function that may be invoked to respond to the message
|
[
"Helper",
"closure",
"to",
"create",
"a",
"function",
"that",
"may",
"be",
"used",
"to",
"respond",
"to",
"a",
"message"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L138-L142
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
publish
|
function publish(source, data, keepalive) {
var topic = data.topic;
var subscriber = subscribers[topic];
if (subscriber) {
var responder = createResponder(source, null, data.uuid);
subscriber(data.message, keepalive, responder);
}
}
|
javascript
|
function publish(source, data, keepalive) {
var topic = data.topic;
var subscriber = subscribers[topic];
if (subscriber) {
var responder = createResponder(source, null, data.uuid);
subscriber(data.message, keepalive, responder);
}
}
|
[
"function",
"publish",
"(",
"source",
",",
"data",
",",
"keepalive",
")",
"{",
"var",
"topic",
"=",
"data",
".",
"topic",
";",
"var",
"subscriber",
"=",
"subscribers",
"[",
"topic",
"]",
";",
"if",
"(",
"subscriber",
")",
"{",
"var",
"responder",
"=",
"createResponder",
"(",
"source",
",",
"null",
",",
"data",
".",
"uuid",
")",
";",
"subscriber",
"(",
"data",
".",
"message",
",",
"keepalive",
",",
"responder",
")",
";",
"}",
"}"
] |
Publishes the "respondable" message to the appropriate subscriber
@private
@param {Window} source The window from which the message originated
@param {Object} data The data sent with the message
@param {Boolean} keepalive Whether to allow multiple responses - default is false
|
[
"Publishes",
"the",
"respondable",
"message",
"to",
"the",
"appropriate",
"subscriber"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L151-L159
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
buildErrorObject
|
function buildErrorObject(error) {
var msg = error.message || 'Unknown error occurred';
var errorName = errorTypes.includes(error.name) ? error.name : 'Error';
var ErrConstructor = window[errorName] || Error;
if (error.stack) {
msg += '\n' + error.stack.replace(error.message, '');
}
return new ErrConstructor(msg);
}
|
javascript
|
function buildErrorObject(error) {
var msg = error.message || 'Unknown error occurred';
var errorName = errorTypes.includes(error.name) ? error.name : 'Error';
var ErrConstructor = window[errorName] || Error;
if (error.stack) {
msg += '\n' + error.stack.replace(error.message, '');
}
return new ErrConstructor(msg);
}
|
[
"function",
"buildErrorObject",
"(",
"error",
")",
"{",
"var",
"msg",
"=",
"error",
".",
"message",
"||",
"'Unknown error occurred'",
";",
"var",
"errorName",
"=",
"errorTypes",
".",
"includes",
"(",
"error",
".",
"name",
")",
"?",
"error",
".",
"name",
":",
"'Error'",
";",
"var",
"ErrConstructor",
"=",
"window",
"[",
"errorName",
"]",
"||",
"Error",
";",
"if",
"(",
"error",
".",
"stack",
")",
"{",
"msg",
"+=",
"'\\n'",
"+",
"\\n",
";",
"}",
"error",
".",
"stack",
".",
"replace",
"(",
"error",
".",
"message",
",",
"''",
")",
"}"
] |
Convert a javascript Error into something that can be stringified
@param {Error} error Any type of error
@return {Object} Processable object
|
[
"Convert",
"a",
"javascript",
"Error",
"into",
"something",
"that",
"can",
"be",
"stringified"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L166-L175
|
train
|
dequelabs/axe-core
|
lib/core/utils/respondable.js
|
parseMessage
|
function parseMessage(dataString) {
/*eslint no-empty: 0*/
var data;
if (typeof dataString !== 'string') {
return;
}
try {
data = JSON.parse(dataString);
} catch (ex) {}
if (!verify(data)) {
return;
}
if (typeof data.error === 'object') {
data.error = buildErrorObject(data.error);
} else {
data.error = undefined;
}
return data;
}
|
javascript
|
function parseMessage(dataString) {
/*eslint no-empty: 0*/
var data;
if (typeof dataString !== 'string') {
return;
}
try {
data = JSON.parse(dataString);
} catch (ex) {}
if (!verify(data)) {
return;
}
if (typeof data.error === 'object') {
data.error = buildErrorObject(data.error);
} else {
data.error = undefined;
}
return data;
}
|
[
"function",
"parseMessage",
"(",
"dataString",
")",
"{",
"var",
"data",
";",
"if",
"(",
"typeof",
"dataString",
"!==",
"'string'",
")",
"{",
"return",
";",
"}",
"try",
"{",
"data",
"=",
"JSON",
".",
"parse",
"(",
"dataString",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"}",
"if",
"(",
"!",
"verify",
"(",
"data",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"typeof",
"data",
".",
"error",
"===",
"'object'",
")",
"{",
"data",
".",
"error",
"=",
"buildErrorObject",
"(",
"data",
".",
"error",
")",
";",
"}",
"else",
"{",
"data",
".",
"error",
"=",
"undefined",
";",
"}",
"return",
"data",
";",
"}"
] |
Parse the received message for processing
@param {string} dataString Message received
@return {object} Object to be used for pub/sub
|
[
"Parse",
"the",
"received",
"message",
"for",
"processing"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/respondable.js#L182-L203
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
getAllRootNodesInTree
|
function getAllRootNodesInTree(tree) {
let ids = [];
const rootNodes = axe.utils
.querySelectorAllFilter(tree, '*', node => {
if (ids.includes(node.shadowId)) {
return false;
}
ids.push(node.shadowId);
return true;
})
.map(node => {
return {
shadowId: node.shadowId,
rootNode: axe.utils.getRootNode(node.actualNode)
};
});
return axe.utils.uniqueArray(rootNodes, []);
}
|
javascript
|
function getAllRootNodesInTree(tree) {
let ids = [];
const rootNodes = axe.utils
.querySelectorAllFilter(tree, '*', node => {
if (ids.includes(node.shadowId)) {
return false;
}
ids.push(node.shadowId);
return true;
})
.map(node => {
return {
shadowId: node.shadowId,
rootNode: axe.utils.getRootNode(node.actualNode)
};
});
return axe.utils.uniqueArray(rootNodes, []);
}
|
[
"function",
"getAllRootNodesInTree",
"(",
"tree",
")",
"{",
"let",
"ids",
"=",
"[",
"]",
";",
"const",
"rootNodes",
"=",
"axe",
".",
"utils",
".",
"querySelectorAllFilter",
"(",
"tree",
",",
"'*'",
",",
"node",
"=>",
"{",
"if",
"(",
"ids",
".",
"includes",
"(",
"node",
".",
"shadowId",
")",
")",
"{",
"return",
"false",
";",
"}",
"ids",
".",
"push",
"(",
"node",
".",
"shadowId",
")",
";",
"return",
"true",
";",
"}",
")",
".",
"map",
"(",
"node",
"=>",
"{",
"return",
"{",
"shadowId",
":",
"node",
".",
"shadowId",
",",
"rootNode",
":",
"axe",
".",
"utils",
".",
"getRootNode",
"(",
"node",
".",
"actualNode",
")",
"}",
";",
"}",
")",
";",
"return",
"axe",
".",
"utils",
".",
"uniqueArray",
"(",
"rootNodes",
",",
"[",
"]",
")",
";",
"}"
] |
Returns am array of source nodes containing `document` and `documentFragment` in a given `tree`.
@param {Object} treeRoot tree
@returns {Array<Object>} array of objects, which each object containing a root and an optional `shadowId`
|
[
"Returns",
"am",
"array",
"of",
"source",
"nodes",
"containing",
"document",
"and",
"documentFragment",
"in",
"a",
"given",
"tree",
"."
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L56-L75
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
getCssomForAllRootNodes
|
function getCssomForAllRootNodes(rootNodes, convertDataToStylesheet, timeout) {
const q = axe.utils.queue();
rootNodes.forEach(({ rootNode, shadowId }, index) =>
q.defer((resolve, reject) =>
loadCssom({
rootNode,
shadowId,
timeout,
convertDataToStylesheet,
rootIndex: index + 1
})
.then(resolve)
.catch(reject)
)
);
return q;
}
|
javascript
|
function getCssomForAllRootNodes(rootNodes, convertDataToStylesheet, timeout) {
const q = axe.utils.queue();
rootNodes.forEach(({ rootNode, shadowId }, index) =>
q.defer((resolve, reject) =>
loadCssom({
rootNode,
shadowId,
timeout,
convertDataToStylesheet,
rootIndex: index + 1
})
.then(resolve)
.catch(reject)
)
);
return q;
}
|
[
"function",
"getCssomForAllRootNodes",
"(",
"rootNodes",
",",
"convertDataToStylesheet",
",",
"timeout",
")",
"{",
"const",
"q",
"=",
"axe",
".",
"utils",
".",
"queue",
"(",
")",
";",
"rootNodes",
".",
"forEach",
"(",
"(",
"{",
"rootNode",
",",
"shadowId",
"}",
",",
"index",
")",
"=>",
"q",
".",
"defer",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"loadCssom",
"(",
"{",
"rootNode",
",",
"shadowId",
",",
"timeout",
",",
"convertDataToStylesheet",
",",
"rootIndex",
":",
"index",
"+",
"1",
"}",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
")",
")",
";",
"return",
"q",
";",
"}"
] |
Deferred function for CSSOM queue processing on all root nodes
@param {Array<Object>} rootNodes array of root nodes, where node is an enhanced `document` or `documentFragment` object returned from `getAllRootNodesInTree`
@param {Function} convertDataToStylesheet fn to convert given data to Stylesheet object
@returns {Object} `axe.utils.queue`
|
[
"Deferred",
"function",
"for",
"CSSOM",
"queue",
"processing",
"on",
"all",
"root",
"nodes"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L123-L141
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
parseNonCrossOriginStylesheet
|
function parseNonCrossOriginStylesheet(sheet, options, priority) {
const q = axe.utils.queue();
/**
* `sheet.cssRules` throws an error on `cross-origin` stylesheets
*/
const cssRules = sheet.cssRules;
const rules = Array.from(cssRules);
if (!rules) {
return q;
}
/**
* reference -> https://developer.mozilla.org/en-US/docs/Web/API/CSSRule#Type_constants
*/
const cssImportRules = rules.filter(r => r.type === 3); // type === 3 -> CSSRule.IMPORT_RULE
/**
* when no `@import` rules in given sheet
* -> resolve the current `sheet` & exit
*/
if (!cssImportRules.length) {
q.defer(resolve =>
resolve({
isExternal: false,
priority,
root: options.rootNode,
shadowId: options.shadowId,
sheet
})
);
// exit
return q;
}
/**
* iterate `@import` rules and fetch styles
*/
cssImportRules.forEach((importRule, cssRuleIndex) =>
q.defer((resolve, reject) => {
const importUrl = importRule.href;
const newPriority = [...priority, cssRuleIndex];
const axiosOptions = {
method: 'get',
url: importUrl,
timeout: options.timeout
};
axe.imports
.axios(axiosOptions)
.then(({ data }) =>
resolve(
options.convertDataToStylesheet({
data,
isExternal: true,
priority: newPriority,
root: options.rootNode,
shadowId: options.shadowId
})
)
)
.catch(reject);
})
);
const nonImportCSSRules = rules.filter(r => r.type !== 3);
// no further rules to process in this sheet
if (!nonImportCSSRules.length) {
return q;
}
// convert all `nonImportCSSRules` style rules into `text` and defer into queue
q.defer(resolve =>
resolve(
options.convertDataToStylesheet({
data: nonImportCSSRules.map(rule => rule.cssText).join(),
isExternal: false,
priority,
root: options.rootNode,
shadowId: options.shadowId
})
)
);
return q;
}
|
javascript
|
function parseNonCrossOriginStylesheet(sheet, options, priority) {
const q = axe.utils.queue();
/**
* `sheet.cssRules` throws an error on `cross-origin` stylesheets
*/
const cssRules = sheet.cssRules;
const rules = Array.from(cssRules);
if (!rules) {
return q;
}
/**
* reference -> https://developer.mozilla.org/en-US/docs/Web/API/CSSRule#Type_constants
*/
const cssImportRules = rules.filter(r => r.type === 3); // type === 3 -> CSSRule.IMPORT_RULE
/**
* when no `@import` rules in given sheet
* -> resolve the current `sheet` & exit
*/
if (!cssImportRules.length) {
q.defer(resolve =>
resolve({
isExternal: false,
priority,
root: options.rootNode,
shadowId: options.shadowId,
sheet
})
);
// exit
return q;
}
/**
* iterate `@import` rules and fetch styles
*/
cssImportRules.forEach((importRule, cssRuleIndex) =>
q.defer((resolve, reject) => {
const importUrl = importRule.href;
const newPriority = [...priority, cssRuleIndex];
const axiosOptions = {
method: 'get',
url: importUrl,
timeout: options.timeout
};
axe.imports
.axios(axiosOptions)
.then(({ data }) =>
resolve(
options.convertDataToStylesheet({
data,
isExternal: true,
priority: newPriority,
root: options.rootNode,
shadowId: options.shadowId
})
)
)
.catch(reject);
})
);
const nonImportCSSRules = rules.filter(r => r.type !== 3);
// no further rules to process in this sheet
if (!nonImportCSSRules.length) {
return q;
}
// convert all `nonImportCSSRules` style rules into `text` and defer into queue
q.defer(resolve =>
resolve(
options.convertDataToStylesheet({
data: nonImportCSSRules.map(rule => rule.cssText).join(),
isExternal: false,
priority,
root: options.rootNode,
shadowId: options.shadowId
})
)
);
return q;
}
|
[
"function",
"parseNonCrossOriginStylesheet",
"(",
"sheet",
",",
"options",
",",
"priority",
")",
"{",
"const",
"q",
"=",
"axe",
".",
"utils",
".",
"queue",
"(",
")",
";",
"const",
"cssRules",
"=",
"sheet",
".",
"cssRules",
";",
"const",
"rules",
"=",
"Array",
".",
"from",
"(",
"cssRules",
")",
";",
"if",
"(",
"!",
"rules",
")",
"{",
"return",
"q",
";",
"}",
"const",
"cssImportRules",
"=",
"rules",
".",
"filter",
"(",
"r",
"=>",
"r",
".",
"type",
"===",
"3",
")",
";",
"if",
"(",
"!",
"cssImportRules",
".",
"length",
")",
"{",
"q",
".",
"defer",
"(",
"resolve",
"=>",
"resolve",
"(",
"{",
"isExternal",
":",
"false",
",",
"priority",
",",
"root",
":",
"options",
".",
"rootNode",
",",
"shadowId",
":",
"options",
".",
"shadowId",
",",
"sheet",
"}",
")",
")",
";",
"return",
"q",
";",
"}",
"cssImportRules",
".",
"forEach",
"(",
"(",
"importRule",
",",
"cssRuleIndex",
")",
"=>",
"q",
".",
"defer",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"importUrl",
"=",
"importRule",
".",
"href",
";",
"const",
"newPriority",
"=",
"[",
"...",
"priority",
",",
"cssRuleIndex",
"]",
";",
"const",
"axiosOptions",
"=",
"{",
"method",
":",
"'get'",
",",
"url",
":",
"importUrl",
",",
"timeout",
":",
"options",
".",
"timeout",
"}",
";",
"axe",
".",
"imports",
".",
"axios",
"(",
"axiosOptions",
")",
".",
"then",
"(",
"(",
"{",
"data",
"}",
")",
"=>",
"resolve",
"(",
"options",
".",
"convertDataToStylesheet",
"(",
"{",
"data",
",",
"isExternal",
":",
"true",
",",
"priority",
":",
"newPriority",
",",
"root",
":",
"options",
".",
"rootNode",
",",
"shadowId",
":",
"options",
".",
"shadowId",
"}",
")",
")",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
")",
";",
"const",
"nonImportCSSRules",
"=",
"rules",
".",
"filter",
"(",
"r",
"=>",
"r",
".",
"type",
"!==",
"3",
")",
";",
"if",
"(",
"!",
"nonImportCSSRules",
".",
"length",
")",
"{",
"return",
"q",
";",
"}",
"q",
".",
"defer",
"(",
"resolve",
"=>",
"resolve",
"(",
"options",
".",
"convertDataToStylesheet",
"(",
"{",
"data",
":",
"nonImportCSSRules",
".",
"map",
"(",
"rule",
"=>",
"rule",
".",
"cssText",
")",
".",
"join",
"(",
")",
",",
"isExternal",
":",
"false",
",",
"priority",
",",
"root",
":",
"options",
".",
"rootNode",
",",
"shadowId",
":",
"options",
".",
"shadowId",
"}",
")",
")",
")",
";",
"return",
"q",
";",
"}"
] |
Parse non cross-origin stylesheets
@param {Object} sheet CSSStylesheet object
@param {Object} options `loadCssom` options
@param {Array<Number>} priority sheet priority
|
[
"Parse",
"non",
"cross",
"-",
"origin",
"stylesheets"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L213-L300
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
parseCrossOriginStylesheet
|
function parseCrossOriginStylesheet(url, options, priority) {
const q = axe.utils.queue();
if (!url) {
return q;
}
const axiosOptions = {
method: 'get',
url,
timeout: options.timeout
};
q.defer((resolve, reject) => {
axe.imports
.axios(axiosOptions)
.then(({ data }) =>
resolve(
options.convertDataToStylesheet({
data,
isExternal: true,
priority,
root: options.rootNode,
shadowId: options.shadowId
})
)
)
.catch(reject);
});
return q;
}
|
javascript
|
function parseCrossOriginStylesheet(url, options, priority) {
const q = axe.utils.queue();
if (!url) {
return q;
}
const axiosOptions = {
method: 'get',
url,
timeout: options.timeout
};
q.defer((resolve, reject) => {
axe.imports
.axios(axiosOptions)
.then(({ data }) =>
resolve(
options.convertDataToStylesheet({
data,
isExternal: true,
priority,
root: options.rootNode,
shadowId: options.shadowId
})
)
)
.catch(reject);
});
return q;
}
|
[
"function",
"parseCrossOriginStylesheet",
"(",
"url",
",",
"options",
",",
"priority",
")",
"{",
"const",
"q",
"=",
"axe",
".",
"utils",
".",
"queue",
"(",
")",
";",
"if",
"(",
"!",
"url",
")",
"{",
"return",
"q",
";",
"}",
"const",
"axiosOptions",
"=",
"{",
"method",
":",
"'get'",
",",
"url",
",",
"timeout",
":",
"options",
".",
"timeout",
"}",
";",
"q",
".",
"defer",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"axe",
".",
"imports",
".",
"axios",
"(",
"axiosOptions",
")",
".",
"then",
"(",
"(",
"{",
"data",
"}",
")",
"=>",
"resolve",
"(",
"options",
".",
"convertDataToStylesheet",
"(",
"{",
"data",
",",
"isExternal",
":",
"true",
",",
"priority",
",",
"root",
":",
"options",
".",
"rootNode",
",",
"shadowId",
":",
"options",
".",
"shadowId",
"}",
")",
")",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"return",
"q",
";",
"}"
] |
Parse cross-origin stylesheets
@param {String} url url from which to fetch stylesheet
@param {Object} options `loadCssom` options
@param {Array<Number>} priority sheet priority
|
[
"Parse",
"cross",
"-",
"origin",
"stylesheets"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L309-L340
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
getStylesheetsFromDocumentFragment
|
function getStylesheetsFromDocumentFragment(options) {
const { rootNode, convertDataToStylesheet } = options;
return (
Array.from(rootNode.children)
.filter(filerStyleAndLinkAttributesInDocumentFragment)
// Reducer to convert `<style></style>` and `<link>` references to `CSSStyleSheet` object
.reduce((out, node) => {
const nodeName = node.nodeName.toUpperCase();
const data = nodeName === 'STYLE' ? node.textContent : node;
const isLink = nodeName === 'LINK';
const stylesheet = convertDataToStylesheet({
data,
isLink,
root: rootNode
});
out.push(stylesheet.sheet);
return out;
}, [])
);
}
|
javascript
|
function getStylesheetsFromDocumentFragment(options) {
const { rootNode, convertDataToStylesheet } = options;
return (
Array.from(rootNode.children)
.filter(filerStyleAndLinkAttributesInDocumentFragment)
// Reducer to convert `<style></style>` and `<link>` references to `CSSStyleSheet` object
.reduce((out, node) => {
const nodeName = node.nodeName.toUpperCase();
const data = nodeName === 'STYLE' ? node.textContent : node;
const isLink = nodeName === 'LINK';
const stylesheet = convertDataToStylesheet({
data,
isLink,
root: rootNode
});
out.push(stylesheet.sheet);
return out;
}, [])
);
}
|
[
"function",
"getStylesheetsFromDocumentFragment",
"(",
"options",
")",
"{",
"const",
"{",
"rootNode",
",",
"convertDataToStylesheet",
"}",
"=",
"options",
";",
"return",
"(",
"Array",
".",
"from",
"(",
"rootNode",
".",
"children",
")",
".",
"filter",
"(",
"filerStyleAndLinkAttributesInDocumentFragment",
")",
".",
"reduce",
"(",
"(",
"out",
",",
"node",
")",
"=>",
"{",
"const",
"nodeName",
"=",
"node",
".",
"nodeName",
".",
"toUpperCase",
"(",
")",
";",
"const",
"data",
"=",
"nodeName",
"===",
"'STYLE'",
"?",
"node",
".",
"textContent",
":",
"node",
";",
"const",
"isLink",
"=",
"nodeName",
"===",
"'LINK'",
";",
"const",
"stylesheet",
"=",
"convertDataToStylesheet",
"(",
"{",
"data",
",",
"isLink",
",",
"root",
":",
"rootNode",
"}",
")",
";",
"out",
".",
"push",
"(",
"stylesheet",
".",
"sheet",
")",
";",
"return",
"out",
";",
"}",
",",
"[",
"]",
")",
")",
";",
"}"
] |
Get stylesheets from `documentFragment`
@param {Object} options configuration options of `loadCssom`
@returns {Array<Object>}
|
[
"Get",
"stylesheets",
"from",
"documentFragment"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L368-L387
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
getStylesheetsFromDocument
|
function getStylesheetsFromDocument(rootNode) {
return Array.from(rootNode.styleSheets).filter(sheet =>
filterMediaIsPrint(sheet.media.mediaText)
);
}
|
javascript
|
function getStylesheetsFromDocument(rootNode) {
return Array.from(rootNode.styleSheets).filter(sheet =>
filterMediaIsPrint(sheet.media.mediaText)
);
}
|
[
"function",
"getStylesheetsFromDocument",
"(",
"rootNode",
")",
"{",
"return",
"Array",
".",
"from",
"(",
"rootNode",
".",
"styleSheets",
")",
".",
"filter",
"(",
"sheet",
"=>",
"filterMediaIsPrint",
"(",
"sheet",
".",
"media",
".",
"mediaText",
")",
")",
";",
"}"
] |
Get stylesheets from `document`
-> filter out stylesheet that are `media=print`
@param {Object} rootNode `document`
@returns {Array<Object>}
|
[
"Get",
"stylesheets",
"from",
"document",
"-",
">",
"filter",
"out",
"stylesheet",
"that",
"are",
"media",
"=",
"print"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L396-L400
|
train
|
dequelabs/axe-core
|
lib/core/utils/preload-cssom.js
|
filterStylesheetsWithSameHref
|
function filterStylesheetsWithSameHref(sheets) {
let hrefs = [];
return sheets.filter(sheet => {
if (!sheet.href) {
// include sheets without `href`
return true;
}
// if `href` is present, ensure they are not duplicates
if (hrefs.includes(sheet.href)) {
return false;
}
hrefs.push(sheet.href);
return true;
});
}
|
javascript
|
function filterStylesheetsWithSameHref(sheets) {
let hrefs = [];
return sheets.filter(sheet => {
if (!sheet.href) {
// include sheets without `href`
return true;
}
// if `href` is present, ensure they are not duplicates
if (hrefs.includes(sheet.href)) {
return false;
}
hrefs.push(sheet.href);
return true;
});
}
|
[
"function",
"filterStylesheetsWithSameHref",
"(",
"sheets",
")",
"{",
"let",
"hrefs",
"=",
"[",
"]",
";",
"return",
"sheets",
".",
"filter",
"(",
"sheet",
"=>",
"{",
"if",
"(",
"!",
"sheet",
".",
"href",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"hrefs",
".",
"includes",
"(",
"sheet",
".",
"href",
")",
")",
"{",
"return",
"false",
";",
"}",
"hrefs",
".",
"push",
"(",
"sheet",
".",
"href",
")",
";",
"return",
"true",
";",
"}",
")",
";",
"}"
] |
Exclude any duplicate `stylesheets`, that share the same `href`
@param {Array<Object>} sheets stylesheets
@returns {Array<Object>}
|
[
"Exclude",
"any",
"duplicate",
"stylesheets",
"that",
"share",
"the",
"same",
"href"
] |
727323c07980e2291575f545444d389fb942906f
|
https://github.com/dequelabs/axe-core/blob/727323c07980e2291575f545444d389fb942906f/lib/core/utils/preload-cssom.js#L441-L455
|
train
|
googleapis/google-api-nodejs-client
|
samples/youtube/search.js
|
runSample
|
async function runSample() {
const res = await youtube.search.list({
part: 'id,snippet',
q: 'Node.js on Google Cloud',
});
console.log(res.data);
}
|
javascript
|
async function runSample() {
const res = await youtube.search.list({
part: 'id,snippet',
q: 'Node.js on Google Cloud',
});
console.log(res.data);
}
|
[
"async",
"function",
"runSample",
"(",
")",
"{",
"const",
"res",
"=",
"await",
"youtube",
".",
"search",
".",
"list",
"(",
"{",
"part",
":",
"'id,snippet'",
",",
"q",
":",
"'Node.js on Google Cloud'",
",",
"}",
")",
";",
"console",
".",
"log",
"(",
"res",
".",
"data",
")",
";",
"}"
] |
a very simple example of searching for youtube videos
|
[
"a",
"very",
"simple",
"example",
"of",
"searching",
"for",
"youtube",
"videos"
] |
e6e632a29d0b246d058e3067de3a5c3827e2b54e
|
https://github.com/googleapis/google-api-nodejs-client/blob/e6e632a29d0b246d058e3067de3a5c3827e2b54e/samples/youtube/search.js#L26-L32
|
train
|
googleapis/google-api-nodejs-client
|
samples/youtube/upload.js
|
runSample
|
async function runSample(fileName) {
const fileSize = fs.statSync(fileName).size;
const res = await youtube.videos.insert(
{
part: 'id,snippet,status',
notifySubscribers: false,
requestBody: {
snippet: {
title: 'Node.js YouTube Upload Test',
description: 'Testing YouTube upload via Google APIs Node.js Client',
},
status: {
privacyStatus: 'private',
},
},
media: {
body: fs.createReadStream(fileName),
},
},
{
// Use the `onUploadProgress` event from Axios to track the
// number of bytes uploaded to this point.
onUploadProgress: evt => {
const progress = (evt.bytesRead / fileSize) * 100;
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
process.stdout.write(`${Math.round(progress)}% complete`);
},
}
);
console.log('\n\n');
console.log(res.data);
return res.data;
}
|
javascript
|
async function runSample(fileName) {
const fileSize = fs.statSync(fileName).size;
const res = await youtube.videos.insert(
{
part: 'id,snippet,status',
notifySubscribers: false,
requestBody: {
snippet: {
title: 'Node.js YouTube Upload Test',
description: 'Testing YouTube upload via Google APIs Node.js Client',
},
status: {
privacyStatus: 'private',
},
},
media: {
body: fs.createReadStream(fileName),
},
},
{
// Use the `onUploadProgress` event from Axios to track the
// number of bytes uploaded to this point.
onUploadProgress: evt => {
const progress = (evt.bytesRead / fileSize) * 100;
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
process.stdout.write(`${Math.round(progress)}% complete`);
},
}
);
console.log('\n\n');
console.log(res.data);
return res.data;
}
|
[
"async",
"function",
"runSample",
"(",
"fileName",
")",
"{",
"const",
"fileSize",
"=",
"fs",
".",
"statSync",
"(",
"fileName",
")",
".",
"size",
";",
"const",
"res",
"=",
"await",
"youtube",
".",
"videos",
".",
"insert",
"(",
"{",
"part",
":",
"'id,snippet,status'",
",",
"notifySubscribers",
":",
"false",
",",
"requestBody",
":",
"{",
"snippet",
":",
"{",
"title",
":",
"'Node.js YouTube Upload Test'",
",",
"description",
":",
"'Testing YouTube upload via Google APIs Node.js Client'",
",",
"}",
",",
"status",
":",
"{",
"privacyStatus",
":",
"'private'",
",",
"}",
",",
"}",
",",
"media",
":",
"{",
"body",
":",
"fs",
".",
"createReadStream",
"(",
"fileName",
")",
",",
"}",
",",
"}",
",",
"{",
"onUploadProgress",
":",
"evt",
"=>",
"{",
"const",
"progress",
"=",
"(",
"evt",
".",
"bytesRead",
"/",
"fileSize",
")",
"*",
"100",
";",
"readline",
".",
"clearLine",
"(",
"process",
".",
"stdout",
",",
"0",
")",
";",
"readline",
".",
"cursorTo",
"(",
"process",
".",
"stdout",
",",
"0",
",",
"null",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"`",
"${",
"Math",
".",
"round",
"(",
"progress",
")",
"}",
"`",
")",
";",
"}",
",",
"}",
")",
";",
"console",
".",
"log",
"(",
"'\\n\\n'",
")",
";",
"\\n",
"\\n",
"}"
] |
very basic example of uploading a video to youtube
|
[
"very",
"basic",
"example",
"of",
"uploading",
"a",
"video",
"to",
"youtube"
] |
e6e632a29d0b246d058e3067de3a5c3827e2b54e
|
https://github.com/googleapis/google-api-nodejs-client/blob/e6e632a29d0b246d058e3067de3a5c3827e2b54e/samples/youtube/upload.js#L33-L66
|
train
|
googleapis/google-api-nodejs-client
|
samples/youtube/playlist.js
|
runSample
|
async function runSample() {
// the first query will return data with an etag
const res = await getPlaylistData(null);
const etag = res.data.etag;
console.log(`etag: ${etag}`);
// the second query will (likely) return no data, and an HTTP 304
// since the If-None-Match header was set with a matching eTag
const res2 = await getPlaylistData(etag);
console.log(res2.status);
}
|
javascript
|
async function runSample() {
// the first query will return data with an etag
const res = await getPlaylistData(null);
const etag = res.data.etag;
console.log(`etag: ${etag}`);
// the second query will (likely) return no data, and an HTTP 304
// since the If-None-Match header was set with a matching eTag
const res2 = await getPlaylistData(etag);
console.log(res2.status);
}
|
[
"async",
"function",
"runSample",
"(",
")",
"{",
"const",
"res",
"=",
"await",
"getPlaylistData",
"(",
"null",
")",
";",
"const",
"etag",
"=",
"res",
".",
"data",
".",
"etag",
";",
"console",
".",
"log",
"(",
"`",
"${",
"etag",
"}",
"`",
")",
";",
"const",
"res2",
"=",
"await",
"getPlaylistData",
"(",
"etag",
")",
";",
"console",
".",
"log",
"(",
"res2",
".",
"status",
")",
";",
"}"
] |
a very simple example of getting data from a playlist
|
[
"a",
"very",
"simple",
"example",
"of",
"getting",
"data",
"from",
"a",
"playlist"
] |
e6e632a29d0b246d058e3067de3a5c3827e2b54e
|
https://github.com/googleapis/google-api-nodejs-client/blob/e6e632a29d0b246d058e3067de3a5c3827e2b54e/samples/youtube/playlist.js#L26-L36
|
train
|
googleapis/google-api-nodejs-client
|
samples/mirror/mirror.js
|
runSample
|
async function runSample() {
const res = await mirror.locations.list({});
console.log(res.data);
}
|
javascript
|
async function runSample() {
const res = await mirror.locations.list({});
console.log(res.data);
}
|
[
"async",
"function",
"runSample",
"(",
")",
"{",
"const",
"res",
"=",
"await",
"mirror",
".",
"locations",
".",
"list",
"(",
"{",
"}",
")",
";",
"console",
".",
"log",
"(",
"res",
".",
"data",
")",
";",
"}"
] |
a very simple example of listing locations from the mirror API
|
[
"a",
"very",
"simple",
"example",
"of",
"listing",
"locations",
"from",
"the",
"mirror",
"API"
] |
e6e632a29d0b246d058e3067de3a5c3827e2b54e
|
https://github.com/googleapis/google-api-nodejs-client/blob/e6e632a29d0b246d058e3067de3a5c3827e2b54e/samples/mirror/mirror.js#L26-L29
|
train
|
googleapis/google-api-nodejs-client
|
samples/jwt.js
|
runSample
|
async function runSample() {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const client = await google.auth.getClient({
keyFile: path.join(__dirname, 'jwt.keys.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly',
});
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v2',
auth: client,
});
// Make an authorized request to list Drive files.
const res = await drive.files.list();
console.log(res.data);
return res.data;
}
|
javascript
|
async function runSample() {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const client = await google.auth.getClient({
keyFile: path.join(__dirname, 'jwt.keys.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly',
});
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v2',
auth: client,
});
// Make an authorized request to list Drive files.
const res = await drive.files.list();
console.log(res.data);
return res.data;
}
|
[
"async",
"function",
"runSample",
"(",
")",
"{",
"const",
"client",
"=",
"await",
"google",
".",
"auth",
".",
"getClient",
"(",
"{",
"keyFile",
":",
"path",
".",
"join",
"(",
"__dirname",
",",
"'jwt.keys.json'",
")",
",",
"scopes",
":",
"'https://www.googleapis.com/auth/drive.readonly'",
",",
"}",
")",
";",
"const",
"drive",
"=",
"google",
".",
"drive",
"(",
"{",
"version",
":",
"'v2'",
",",
"auth",
":",
"client",
",",
"}",
")",
";",
"const",
"res",
"=",
"await",
"drive",
".",
"files",
".",
"list",
"(",
")",
";",
"console",
".",
"log",
"(",
"res",
".",
"data",
")",
";",
"return",
"res",
".",
"data",
";",
"}"
] |
The JWT authorization is ideal for performing server-to-server
communication without asking for user consent.
Suggested reading for Admin SDK users using service accounts:
https://developers.google.com/admin-sdk/directory/v1/guides/delegation
See the defaultauth.js sample for an alternate way of fetching compute credentials.
|
[
"The",
"JWT",
"authorization",
"is",
"ideal",
"for",
"performing",
"server",
"-",
"to",
"-",
"server",
"communication",
"without",
"asking",
"for",
"user",
"consent",
"."
] |
e6e632a29d0b246d058e3067de3a5c3827e2b54e
|
https://github.com/googleapis/google-api-nodejs-client/blob/e6e632a29d0b246d058e3067de3a5c3827e2b54e/samples/jwt.js#L28-L46
|
train
|
googleapis/google-api-nodejs-client
|
samples/defaultauth.js
|
main
|
async function main() {
// The `getClient` method will choose a service based authentication model
const auth = await google.auth.getClient({
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: ['https://www.googleapis.com/auth/compute'],
});
// Obtain the current project Id
const project = await google.auth.getProjectId();
// Get the list of available compute zones for your project
const res = await compute.zones.list({project, auth});
console.log(res.data);
}
|
javascript
|
async function main() {
// The `getClient` method will choose a service based authentication model
const auth = await google.auth.getClient({
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: ['https://www.googleapis.com/auth/compute'],
});
// Obtain the current project Id
const project = await google.auth.getProjectId();
// Get the list of available compute zones for your project
const res = await compute.zones.list({project, auth});
console.log(res.data);
}
|
[
"async",
"function",
"main",
"(",
")",
"{",
"const",
"auth",
"=",
"await",
"google",
".",
"auth",
".",
"getClient",
"(",
"{",
"scopes",
":",
"[",
"'https://www.googleapis.com/auth/compute'",
"]",
",",
"}",
")",
";",
"const",
"project",
"=",
"await",
"google",
".",
"auth",
".",
"getProjectId",
"(",
")",
";",
"const",
"res",
"=",
"await",
"compute",
".",
"zones",
".",
"list",
"(",
"{",
"project",
",",
"auth",
"}",
")",
";",
"console",
".",
"log",
"(",
"res",
".",
"data",
")",
";",
"}"
] |
The google.auth.getClient method creates the appropriate type of credential client for you,
depending upon whether the client is running in Google App Engine, Google Compute Engine, a
Managed VM, or on a local developer machine. This allows you to write one set of auth code that
will work in all cases. It most situations, it is advisable to use the getClient method rather
than creating your own JWT or Compute client directly.
Note: In order to run on a local developer machine, it is necessary to download a private key
file to your machine, and to set a local environment variable pointing to the location of the
file. Create a service account using the Google Developers Console using the section APIs & Auth.
Select "Generate new JSON key" and download the resulting file. Once this is done, set the
GOOGLE_APPLICATION_CREDENTIALS environment variable to point to the location of the .json file.
See also:
https://developers.google.com/accounts/docs/application-default-credentials
Get the appropriate type of credential client, depending upon the runtime environment.
|
[
"The",
"google",
".",
"auth",
".",
"getClient",
"method",
"creates",
"the",
"appropriate",
"type",
"of",
"credential",
"client",
"for",
"you",
"depending",
"upon",
"whether",
"the",
"client",
"is",
"running",
"in",
"Google",
"App",
"Engine",
"Google",
"Compute",
"Engine",
"a",
"Managed",
"VM",
"or",
"on",
"a",
"local",
"developer",
"machine",
".",
"This",
"allows",
"you",
"to",
"write",
"one",
"set",
"of",
"auth",
"code",
"that",
"will",
"work",
"in",
"all",
"cases",
".",
"It",
"most",
"situations",
"it",
"is",
"advisable",
"to",
"use",
"the",
"getClient",
"method",
"rather",
"than",
"creating",
"your",
"own",
"JWT",
"or",
"Compute",
"client",
"directly",
"."
] |
e6e632a29d0b246d058e3067de3a5c3827e2b54e
|
https://github.com/googleapis/google-api-nodejs-client/blob/e6e632a29d0b246d058e3067de3a5c3827e2b54e/samples/defaultauth.js#L37-L50
|
train
|
cytoscape/cytoscape.js
|
documentation/demos/tokyo-railways/tokyo-railways.js
|
function(tag, attrs, children){
var el = document.createElement(tag);
if(attrs != null && typeof attrs === typeof {}){
Object.keys(attrs).forEach(function(key){
var val = attrs[key];
el.setAttribute(key, val);
});
} else if(typeof attrs === typeof []){
children = attrs;
}
if(children != null && typeof children === typeof []){
children.forEach(function(child){
el.appendChild(child);
});
} else if(children != null && typeof children === typeof ''){
el.appendChild(document.createTextNode(children));
}
return el;
}
|
javascript
|
function(tag, attrs, children){
var el = document.createElement(tag);
if(attrs != null && typeof attrs === typeof {}){
Object.keys(attrs).forEach(function(key){
var val = attrs[key];
el.setAttribute(key, val);
});
} else if(typeof attrs === typeof []){
children = attrs;
}
if(children != null && typeof children === typeof []){
children.forEach(function(child){
el.appendChild(child);
});
} else if(children != null && typeof children === typeof ''){
el.appendChild(document.createTextNode(children));
}
return el;
}
|
[
"function",
"(",
"tag",
",",
"attrs",
",",
"children",
")",
"{",
"var",
"el",
"=",
"document",
".",
"createElement",
"(",
"tag",
")",
";",
"if",
"(",
"attrs",
"!=",
"null",
"&&",
"typeof",
"attrs",
"===",
"typeof",
"{",
"}",
")",
"{",
"Object",
".",
"keys",
"(",
"attrs",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"val",
"=",
"attrs",
"[",
"key",
"]",
";",
"el",
".",
"setAttribute",
"(",
"key",
",",
"val",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"attrs",
"===",
"typeof",
"[",
"]",
")",
"{",
"children",
"=",
"attrs",
";",
"}",
"if",
"(",
"children",
"!=",
"null",
"&&",
"typeof",
"children",
"===",
"typeof",
"[",
"]",
")",
"{",
"children",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"el",
".",
"appendChild",
"(",
"child",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"children",
"!=",
"null",
"&&",
"typeof",
"children",
"===",
"typeof",
"''",
")",
"{",
"el",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"children",
")",
")",
";",
"}",
"return",
"el",
";",
"}"
] |
hyperscript-like function
|
[
"hyperscript",
"-",
"like",
"function"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/documentation/demos/tokyo-railways/tokyo-railways.js#L20-L42
|
train
|
|
cytoscape/cytoscape.js
|
src/extension.js
|
function( options ){
this.options = options;
registrant.call( this, options );
// make sure layout has _private for use w/ std apis like .on()
if( !is.plainObject( this._private ) ){
this._private = {};
}
this._private.cy = options.cy;
this._private.listeners = [];
this.createEmitter();
}
|
javascript
|
function( options ){
this.options = options;
registrant.call( this, options );
// make sure layout has _private for use w/ std apis like .on()
if( !is.plainObject( this._private ) ){
this._private = {};
}
this._private.cy = options.cy;
this._private.listeners = [];
this.createEmitter();
}
|
[
"function",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"options",
";",
"registrant",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"if",
"(",
"!",
"is",
".",
"plainObject",
"(",
"this",
".",
"_private",
")",
")",
"{",
"this",
".",
"_private",
"=",
"{",
"}",
";",
"}",
"this",
".",
"_private",
".",
"cy",
"=",
"options",
".",
"cy",
";",
"this",
".",
"_private",
".",
"listeners",
"=",
"[",
"]",
";",
"this",
".",
"createEmitter",
"(",
")",
";",
"}"
] |
fill in missing layout functions in the prototype
|
[
"fill",
"in",
"missing",
"layout",
"functions",
"in",
"the",
"prototype"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/src/extension.js#L40-L54
|
train
|
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
memoize
|
function memoize(fn, keyFn) {
if (!keyFn) {
keyFn = function keyFn() {
if (arguments.length === 1) {
return arguments[0];
} else if (arguments.length === 0) {
return 'undefined';
}
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
return args.join('$');
};
}
var memoizedFn = function memoizedFn() {
var self = this;
var args = arguments;
var ret;
var k = keyFn.apply(self, args);
var cache = memoizedFn.cache;
if (!(ret = cache[k])) {
ret = cache[k] = fn.apply(self, args);
}
return ret;
};
memoizedFn.cache = {};
return memoizedFn;
}
|
javascript
|
function memoize(fn, keyFn) {
if (!keyFn) {
keyFn = function keyFn() {
if (arguments.length === 1) {
return arguments[0];
} else if (arguments.length === 0) {
return 'undefined';
}
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
return args.join('$');
};
}
var memoizedFn = function memoizedFn() {
var self = this;
var args = arguments;
var ret;
var k = keyFn.apply(self, args);
var cache = memoizedFn.cache;
if (!(ret = cache[k])) {
ret = cache[k] = fn.apply(self, args);
}
return ret;
};
memoizedFn.cache = {};
return memoizedFn;
}
|
[
"function",
"memoize",
"(",
"fn",
",",
"keyFn",
")",
"{",
"if",
"(",
"!",
"keyFn",
")",
"{",
"keyFn",
"=",
"function",
"keyFn",
"(",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arguments",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
")",
"{",
"return",
"'undefined'",
";",
"}",
"var",
"args",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"args",
".",
"push",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"return",
"args",
".",
"join",
"(",
"'$'",
")",
";",
"}",
";",
"}",
"var",
"memoizedFn",
"=",
"function",
"memoizedFn",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"args",
"=",
"arguments",
";",
"var",
"ret",
";",
"var",
"k",
"=",
"keyFn",
".",
"apply",
"(",
"self",
",",
"args",
")",
";",
"var",
"cache",
"=",
"memoizedFn",
".",
"cache",
";",
"if",
"(",
"!",
"(",
"ret",
"=",
"cache",
"[",
"k",
"]",
")",
")",
"{",
"ret",
"=",
"cache",
"[",
"k",
"]",
"=",
"fn",
".",
"apply",
"(",
"self",
",",
"args",
")",
";",
"}",
"return",
"ret",
";",
"}",
";",
"memoizedFn",
".",
"cache",
"=",
"{",
"}",
";",
"return",
"memoizedFn",
";",
"}"
] |
probably a better way to detect this...
|
[
"probably",
"a",
"better",
"way",
"to",
"detect",
"this",
"..."
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L205-L240
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
getMap
|
function getMap(options) {
var obj = options.map;
var keys = options.keys;
var l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (plainObject(key)) {
throw Error('Tried to get map with object key');
}
obj = obj[key];
if (obj == null) {
return obj;
}
}
return obj;
}
|
javascript
|
function getMap(options) {
var obj = options.map;
var keys = options.keys;
var l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (plainObject(key)) {
throw Error('Tried to get map with object key');
}
obj = obj[key];
if (obj == null) {
return obj;
}
}
return obj;
}
|
[
"function",
"getMap",
"(",
"options",
")",
"{",
"var",
"obj",
"=",
"options",
".",
"map",
";",
"var",
"keys",
"=",
"options",
".",
"keys",
";",
"var",
"l",
"=",
"keys",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"plainObject",
"(",
"key",
")",
")",
"{",
"throw",
"Error",
"(",
"'Tried to get map with object key'",
")",
";",
"}",
"obj",
"=",
"obj",
"[",
"key",
"]",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
"obj",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] |
gets the value in a map even if it's not built in places
|
[
"gets",
"the",
"value",
"in",
"a",
"map",
"even",
"if",
"it",
"s",
"not",
"built",
"in",
"places"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L642-L662
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
contractUntil
|
function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {
while (size > sizeLimit) {
// Choose an edge randomly
var edgeIndex = Math.floor(Math.random() * remainingEdges.length); // Collapse graph based on edge
remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);
size--;
}
return remainingEdges;
}
|
javascript
|
function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {
while (size > sizeLimit) {
// Choose an edge randomly
var edgeIndex = Math.floor(Math.random() * remainingEdges.length); // Collapse graph based on edge
remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);
size--;
}
return remainingEdges;
}
|
[
"function",
"contractUntil",
"(",
"metaNodeMap",
",",
"remainingEdges",
",",
"size",
",",
"sizeLimit",
")",
"{",
"while",
"(",
"size",
">",
"sizeLimit",
")",
"{",
"var",
"edgeIndex",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"remainingEdges",
".",
"length",
")",
";",
"remainingEdges",
"=",
"collapse",
"(",
"edgeIndex",
",",
"metaNodeMap",
",",
"remainingEdges",
")",
";",
"size",
"--",
";",
"}",
"return",
"remainingEdges",
";",
"}"
] |
Contracts a graph until we reach a certain number of meta nodes
|
[
"Contracts",
"a",
"graph",
"until",
"we",
"reach",
"a",
"certain",
"number",
"of",
"meta",
"nodes"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L2087-L2097
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
removeData
|
function removeData(params) {
var defaults$$1 = {
field: 'data',
event: 'data',
triggerFnName: 'trigger',
triggerEvent: false,
immutableKeys: {} // key => true if immutable
};
params = extend({}, defaults$$1, params);
return function removeDataImpl(names) {
var p = params;
var self = this;
var selfIsArrayLike = self.length !== undefined;
var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
// .removeData('foo bar')
if (string(names)) {
// then get the list of keys, and delete them
var keys = names.split(/\s+/);
var l = keys.length;
for (var i = 0; i < l; i++) {
// delete each non-empty key
var key = keys[i];
if (emptyString(key)) {
continue;
}
var valid = !p.immutableKeys[key]; // not valid if immutable
if (valid) {
for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {
all[i_a]._private[p.field][key] = undefined;
}
}
}
if (p.triggerEvent) {
self[p.triggerFnName](p.event);
} // .removeData()
} else if (names === undefined) {
// then delete all keys
for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {
var _privateFields = all[_i_a]._private[p.field];
var _keys = Object.keys(_privateFields);
for (var _i2 = 0; _i2 < _keys.length; _i2++) {
var _key = _keys[_i2];
var validKeyToDelete = !p.immutableKeys[_key];
if (validKeyToDelete) {
_privateFields[_key] = undefined;
}
}
}
if (p.triggerEvent) {
self[p.triggerFnName](p.event);
}
}
return self; // maintain chaining
}; // function
}
|
javascript
|
function removeData(params) {
var defaults$$1 = {
field: 'data',
event: 'data',
triggerFnName: 'trigger',
triggerEvent: false,
immutableKeys: {} // key => true if immutable
};
params = extend({}, defaults$$1, params);
return function removeDataImpl(names) {
var p = params;
var self = this;
var selfIsArrayLike = self.length !== undefined;
var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
// .removeData('foo bar')
if (string(names)) {
// then get the list of keys, and delete them
var keys = names.split(/\s+/);
var l = keys.length;
for (var i = 0; i < l; i++) {
// delete each non-empty key
var key = keys[i];
if (emptyString(key)) {
continue;
}
var valid = !p.immutableKeys[key]; // not valid if immutable
if (valid) {
for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {
all[i_a]._private[p.field][key] = undefined;
}
}
}
if (p.triggerEvent) {
self[p.triggerFnName](p.event);
} // .removeData()
} else if (names === undefined) {
// then delete all keys
for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {
var _privateFields = all[_i_a]._private[p.field];
var _keys = Object.keys(_privateFields);
for (var _i2 = 0; _i2 < _keys.length; _i2++) {
var _key = _keys[_i2];
var validKeyToDelete = !p.immutableKeys[_key];
if (validKeyToDelete) {
_privateFields[_key] = undefined;
}
}
}
if (p.triggerEvent) {
self[p.triggerFnName](p.event);
}
}
return self; // maintain chaining
}; // function
}
|
[
"function",
"removeData",
"(",
"params",
")",
"{",
"var",
"defaults$$1",
"=",
"{",
"field",
":",
"'data'",
",",
"event",
":",
"'data'",
",",
"triggerFnName",
":",
"'trigger'",
",",
"triggerEvent",
":",
"false",
",",
"immutableKeys",
":",
"{",
"}",
"}",
";",
"params",
"=",
"extend",
"(",
"{",
"}",
",",
"defaults$$1",
",",
"params",
")",
";",
"return",
"function",
"removeDataImpl",
"(",
"names",
")",
"{",
"var",
"p",
"=",
"params",
";",
"var",
"self",
"=",
"this",
";",
"var",
"selfIsArrayLike",
"=",
"self",
".",
"length",
"!==",
"undefined",
";",
"var",
"all",
"=",
"selfIsArrayLike",
"?",
"self",
":",
"[",
"self",
"]",
";",
"if",
"(",
"string",
"(",
"names",
")",
")",
"{",
"var",
"keys",
"=",
"names",
".",
"split",
"(",
"/",
"\\s+",
"/",
")",
";",
"var",
"l",
"=",
"keys",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"emptyString",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"var",
"valid",
"=",
"!",
"p",
".",
"immutableKeys",
"[",
"key",
"]",
";",
"if",
"(",
"valid",
")",
"{",
"for",
"(",
"var",
"i_a",
"=",
"0",
",",
"l_a",
"=",
"all",
".",
"length",
";",
"i_a",
"<",
"l_a",
";",
"i_a",
"++",
")",
"{",
"all",
"[",
"i_a",
"]",
".",
"_private",
"[",
"p",
".",
"field",
"]",
"[",
"key",
"]",
"=",
"undefined",
";",
"}",
"}",
"}",
"if",
"(",
"p",
".",
"triggerEvent",
")",
"{",
"self",
"[",
"p",
".",
"triggerFnName",
"]",
"(",
"p",
".",
"event",
")",
";",
"}",
"}",
"else",
"if",
"(",
"names",
"===",
"undefined",
")",
"{",
"for",
"(",
"var",
"_i_a",
"=",
"0",
",",
"_l_a",
"=",
"all",
".",
"length",
";",
"_i_a",
"<",
"_l_a",
";",
"_i_a",
"++",
")",
"{",
"var",
"_privateFields",
"=",
"all",
"[",
"_i_a",
"]",
".",
"_private",
"[",
"p",
".",
"field",
"]",
";",
"var",
"_keys",
"=",
"Object",
".",
"keys",
"(",
"_privateFields",
")",
";",
"for",
"(",
"var",
"_i2",
"=",
"0",
";",
"_i2",
"<",
"_keys",
".",
"length",
";",
"_i2",
"++",
")",
"{",
"var",
"_key",
"=",
"_keys",
"[",
"_i2",
"]",
";",
"var",
"validKeyToDelete",
"=",
"!",
"p",
".",
"immutableKeys",
"[",
"_key",
"]",
";",
"if",
"(",
"validKeyToDelete",
")",
"{",
"_privateFields",
"[",
"_key",
"]",
"=",
"undefined",
";",
"}",
"}",
"}",
"if",
"(",
"p",
".",
"triggerEvent",
")",
"{",
"self",
"[",
"p",
".",
"triggerFnName",
"]",
"(",
"p",
".",
"event",
")",
";",
"}",
"}",
"return",
"self",
";",
"}",
";",
"}"
] |
data remove data field
|
[
"data",
"remove",
"data",
"field"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L6107-L6174
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
consumeExpr
|
function consumeExpr(remaining) {
var expr;
var match;
var name;
for (var j = 0; j < exprs.length; j++) {
var e = exprs[j];
var n = e.name;
var m = remaining.match(e.regexObj);
if (m != null) {
match = m;
expr = e;
name = n;
var consumed = m[0];
remaining = remaining.substring(consumed.length);
break; // we've consumed one expr, so we can return now
}
}
return {
expr: expr,
match: match,
name: name,
remaining: remaining
};
}
|
javascript
|
function consumeExpr(remaining) {
var expr;
var match;
var name;
for (var j = 0; j < exprs.length; j++) {
var e = exprs[j];
var n = e.name;
var m = remaining.match(e.regexObj);
if (m != null) {
match = m;
expr = e;
name = n;
var consumed = m[0];
remaining = remaining.substring(consumed.length);
break; // we've consumed one expr, so we can return now
}
}
return {
expr: expr,
match: match,
name: name,
remaining: remaining
};
}
|
[
"function",
"consumeExpr",
"(",
"remaining",
")",
"{",
"var",
"expr",
";",
"var",
"match",
";",
"var",
"name",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"exprs",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"e",
"=",
"exprs",
"[",
"j",
"]",
";",
"var",
"n",
"=",
"e",
".",
"name",
";",
"var",
"m",
"=",
"remaining",
".",
"match",
"(",
"e",
".",
"regexObj",
")",
";",
"if",
"(",
"m",
"!=",
"null",
")",
"{",
"match",
"=",
"m",
";",
"expr",
"=",
"e",
";",
"name",
"=",
"n",
";",
"var",
"consumed",
"=",
"m",
"[",
"0",
"]",
";",
"remaining",
"=",
"remaining",
".",
"substring",
"(",
"consumed",
".",
"length",
")",
";",
"break",
";",
"}",
"}",
"return",
"{",
"expr",
":",
"expr",
",",
"match",
":",
"match",
",",
"name",
":",
"name",
",",
"remaining",
":",
"remaining",
"}",
";",
"}"
] |
Of all the expressions, find the first match in the remaining text.
@param {string} remaining The remaining text to parse
@returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`
|
[
"Of",
"all",
"the",
"expressions",
"find",
"the",
"first",
"match",
"in",
"the",
"remaining",
"text",
"."
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L7101-L7127
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
consumeWhitespace
|
function consumeWhitespace(remaining) {
var match = remaining.match(/^\s+/);
if (match) {
var consumed = match[0];
remaining = remaining.substring(consumed.length);
}
return remaining;
}
|
javascript
|
function consumeWhitespace(remaining) {
var match = remaining.match(/^\s+/);
if (match) {
var consumed = match[0];
remaining = remaining.substring(consumed.length);
}
return remaining;
}
|
[
"function",
"consumeWhitespace",
"(",
"remaining",
")",
"{",
"var",
"match",
"=",
"remaining",
".",
"match",
"(",
"/",
"^\\s+",
"/",
")",
";",
"if",
"(",
"match",
")",
"{",
"var",
"consumed",
"=",
"match",
"[",
"0",
"]",
";",
"remaining",
"=",
"remaining",
".",
"substring",
"(",
"consumed",
".",
"length",
")",
";",
"}",
"return",
"remaining",
";",
"}"
] |
Consume all the leading whitespace
@param {string} remaining The text to consume
@returns The text with the leading whitespace removed
|
[
"Consume",
"all",
"the",
"leading",
"whitespace"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L7135-L7144
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
parse
|
function parse(selector) {
var self = this;
var remaining = self.inputText = selector;
var currentQuery = self[0] = newQuery();
self.length = 1;
remaining = consumeWhitespace(remaining); // get rid of leading whitespace
for (;;) {
var exprInfo = consumeExpr(remaining);
if (exprInfo.expr == null) {
warn('The selector `' + selector + '`is invalid');
return false;
} else {
var args = exprInfo.match.slice(1); // let the token populate the selector object in currentQuery
var ret = exprInfo.expr.populate(self, currentQuery, args);
if (ret === false) {
return false; // exit if population failed
} else if (ret != null) {
currentQuery = ret; // change the current query to be filled if the expr specifies
}
}
remaining = exprInfo.remaining; // we're done when there's nothing left to parse
if (remaining.match(/^\s*$/)) {
break;
}
}
var lastQ = self[self.length - 1];
if (self.currentSubject != null) {
lastQ.subject = self.currentSubject;
}
lastQ.edgeCount = self.edgeCount;
lastQ.compoundCount = self.compoundCount;
for (var i = 0; i < self.length; i++) {
var q = self[i]; // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations
if (q.compoundCount > 0 && q.edgeCount > 0) {
warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');
return false;
}
if (q.edgeCount > 1) {
warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');
return false;
} else if (q.edgeCount === 1) {
warn('The selector `' + selector + '` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.');
}
}
return true; // success
}
|
javascript
|
function parse(selector) {
var self = this;
var remaining = self.inputText = selector;
var currentQuery = self[0] = newQuery();
self.length = 1;
remaining = consumeWhitespace(remaining); // get rid of leading whitespace
for (;;) {
var exprInfo = consumeExpr(remaining);
if (exprInfo.expr == null) {
warn('The selector `' + selector + '`is invalid');
return false;
} else {
var args = exprInfo.match.slice(1); // let the token populate the selector object in currentQuery
var ret = exprInfo.expr.populate(self, currentQuery, args);
if (ret === false) {
return false; // exit if population failed
} else if (ret != null) {
currentQuery = ret; // change the current query to be filled if the expr specifies
}
}
remaining = exprInfo.remaining; // we're done when there's nothing left to parse
if (remaining.match(/^\s*$/)) {
break;
}
}
var lastQ = self[self.length - 1];
if (self.currentSubject != null) {
lastQ.subject = self.currentSubject;
}
lastQ.edgeCount = self.edgeCount;
lastQ.compoundCount = self.compoundCount;
for (var i = 0; i < self.length; i++) {
var q = self[i]; // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations
if (q.compoundCount > 0 && q.edgeCount > 0) {
warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');
return false;
}
if (q.edgeCount > 1) {
warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');
return false;
} else if (q.edgeCount === 1) {
warn('The selector `' + selector + '` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.');
}
}
return true; // success
}
|
[
"function",
"parse",
"(",
"selector",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"remaining",
"=",
"self",
".",
"inputText",
"=",
"selector",
";",
"var",
"currentQuery",
"=",
"self",
"[",
"0",
"]",
"=",
"newQuery",
"(",
")",
";",
"self",
".",
"length",
"=",
"1",
";",
"remaining",
"=",
"consumeWhitespace",
"(",
"remaining",
")",
";",
"for",
"(",
";",
";",
")",
"{",
"var",
"exprInfo",
"=",
"consumeExpr",
"(",
"remaining",
")",
";",
"if",
"(",
"exprInfo",
".",
"expr",
"==",
"null",
")",
"{",
"warn",
"(",
"'The selector `'",
"+",
"selector",
"+",
"'`is invalid'",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"var",
"args",
"=",
"exprInfo",
".",
"match",
".",
"slice",
"(",
"1",
")",
";",
"var",
"ret",
"=",
"exprInfo",
".",
"expr",
".",
"populate",
"(",
"self",
",",
"currentQuery",
",",
"args",
")",
";",
"if",
"(",
"ret",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"ret",
"!=",
"null",
")",
"{",
"currentQuery",
"=",
"ret",
";",
"}",
"}",
"remaining",
"=",
"exprInfo",
".",
"remaining",
";",
"if",
"(",
"remaining",
".",
"match",
"(",
"/",
"^\\s*$",
"/",
")",
")",
"{",
"break",
";",
"}",
"}",
"var",
"lastQ",
"=",
"self",
"[",
"self",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"self",
".",
"currentSubject",
"!=",
"null",
")",
"{",
"lastQ",
".",
"subject",
"=",
"self",
".",
"currentSubject",
";",
"}",
"lastQ",
".",
"edgeCount",
"=",
"self",
".",
"edgeCount",
";",
"lastQ",
".",
"compoundCount",
"=",
"self",
".",
"compoundCount",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"self",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"q",
"=",
"self",
"[",
"i",
"]",
";",
"if",
"(",
"q",
".",
"compoundCount",
">",
"0",
"&&",
"q",
".",
"edgeCount",
">",
"0",
")",
"{",
"warn",
"(",
"'The selector `'",
"+",
"selector",
"+",
"'` is invalid because it uses both a compound selector and an edge selector'",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"q",
".",
"edgeCount",
">",
"1",
")",
"{",
"warn",
"(",
"'The selector `'",
"+",
"selector",
"+",
"'` is invalid because it uses multiple edge selectors'",
")",
";",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"q",
".",
"edgeCount",
"===",
"1",
")",
"{",
"warn",
"(",
"'The selector `'",
"+",
"selector",
"+",
"'` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.'",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Parse the string and store the parsed representation in the Selector.
@param {string} selector The selector string
@returns `true` if the selector was successfully parsed, `false` otherwise
|
[
"Parse",
"the",
"string",
"and",
"store",
"the",
"parsed",
"representation",
"in",
"the",
"Selector",
"."
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L7152-L7210
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
matches
|
function matches(query, ele) {
return query.checks.every(function (chk) {
return match[chk.type](chk, ele);
});
}
|
javascript
|
function matches(query, ele) {
return query.checks.every(function (chk) {
return match[chk.type](chk, ele);
});
}
|
[
"function",
"matches",
"(",
"query",
",",
"ele",
")",
"{",
"return",
"query",
".",
"checks",
".",
"every",
"(",
"function",
"(",
"chk",
")",
"{",
"return",
"match",
"[",
"chk",
".",
"type",
"]",
"(",
"chk",
",",
"ele",
")",
";",
"}",
")",
";",
"}"
] |
Returns whether the query matches for the element
@param query The `{ type, value, ... }` query object
@param ele The element to compare against
|
[
"Returns",
"whether",
"the",
"query",
"matches",
"for",
"the",
"element"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L7460-L7464
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
matches$$1
|
function matches$$1(ele) {
var self = this;
for (var j = 0; j < self.length; j++) {
var query = self[j];
if (matches(query, ele)) {
return true;
}
}
return false;
}
|
javascript
|
function matches$$1(ele) {
var self = this;
for (var j = 0; j < self.length; j++) {
var query = self[j];
if (matches(query, ele)) {
return true;
}
}
return false;
}
|
[
"function",
"matches$$1",
"(",
"ele",
")",
"{",
"var",
"self",
"=",
"this",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"self",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"query",
"=",
"self",
"[",
"j",
"]",
";",
"if",
"(",
"matches",
"(",
"query",
",",
"ele",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
filter does selector match a single element?
|
[
"filter",
"does",
"selector",
"match",
"a",
"single",
"element?"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L7612-L7624
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
byGroup
|
function byGroup() {
var nodes = this.spawn();
var edges = this.spawn();
for (var i = 0; i < this.length; i++) {
var ele = this[i];
if (ele.isNode()) {
nodes.merge(ele);
} else {
edges.merge(ele);
}
}
return {
nodes: nodes,
edges: edges
};
}
|
javascript
|
function byGroup() {
var nodes = this.spawn();
var edges = this.spawn();
for (var i = 0; i < this.length; i++) {
var ele = this[i];
if (ele.isNode()) {
nodes.merge(ele);
} else {
edges.merge(ele);
}
}
return {
nodes: nodes,
edges: edges
};
}
|
[
"function",
"byGroup",
"(",
")",
"{",
"var",
"nodes",
"=",
"this",
".",
"spawn",
"(",
")",
";",
"var",
"edges",
"=",
"this",
".",
"spawn",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"ele",
"=",
"this",
"[",
"i",
"]",
";",
"if",
"(",
"ele",
".",
"isNode",
"(",
")",
")",
"{",
"nodes",
".",
"merge",
"(",
"ele",
")",
";",
"}",
"else",
"{",
"edges",
".",
"merge",
"(",
"ele",
")",
";",
"}",
"}",
"return",
"{",
"nodes",
":",
"nodes",
",",
"edges",
":",
"edges",
"}",
";",
"}"
] |
internal helper to get nodes and edges as separate collections with single iteration over elements
|
[
"internal",
"helper",
"to",
"get",
"nodes",
"and",
"edges",
"as",
"separate",
"collections",
"with",
"single",
"iteration",
"over",
"elements"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L10039-L10057
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
merge
|
function merge(toAdd) {
var _p = this._private;
var cy = _p.cy;
if (!toAdd) {
return this;
}
if (toAdd && string(toAdd)) {
var selector = toAdd;
toAdd = cy.mutableElements().filter(selector);
}
var map = _p.map;
for (var i = 0; i < toAdd.length; i++) {
var toAddEle = toAdd[i];
var id = toAddEle._private.data.id;
var add = !map.has(id);
if (add) {
var index = this.length++;
this[index] = toAddEle;
map.set(id, {
ele: toAddEle,
index: index
});
} else {
// replace
var _index = map.get(id).index;
this[_index] = toAddEle;
map.set(id, {
ele: toAddEle,
index: _index
});
}
}
return this; // chaining
}
|
javascript
|
function merge(toAdd) {
var _p = this._private;
var cy = _p.cy;
if (!toAdd) {
return this;
}
if (toAdd && string(toAdd)) {
var selector = toAdd;
toAdd = cy.mutableElements().filter(selector);
}
var map = _p.map;
for (var i = 0; i < toAdd.length; i++) {
var toAddEle = toAdd[i];
var id = toAddEle._private.data.id;
var add = !map.has(id);
if (add) {
var index = this.length++;
this[index] = toAddEle;
map.set(id, {
ele: toAddEle,
index: index
});
} else {
// replace
var _index = map.get(id).index;
this[_index] = toAddEle;
map.set(id, {
ele: toAddEle,
index: _index
});
}
}
return this; // chaining
}
|
[
"function",
"merge",
"(",
"toAdd",
")",
"{",
"var",
"_p",
"=",
"this",
".",
"_private",
";",
"var",
"cy",
"=",
"_p",
".",
"cy",
";",
"if",
"(",
"!",
"toAdd",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"toAdd",
"&&",
"string",
"(",
"toAdd",
")",
")",
"{",
"var",
"selector",
"=",
"toAdd",
";",
"toAdd",
"=",
"cy",
".",
"mutableElements",
"(",
")",
".",
"filter",
"(",
"selector",
")",
";",
"}",
"var",
"map",
"=",
"_p",
".",
"map",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"toAdd",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"toAddEle",
"=",
"toAdd",
"[",
"i",
"]",
";",
"var",
"id",
"=",
"toAddEle",
".",
"_private",
".",
"data",
".",
"id",
";",
"var",
"add",
"=",
"!",
"map",
".",
"has",
"(",
"id",
")",
";",
"if",
"(",
"add",
")",
"{",
"var",
"index",
"=",
"this",
".",
"length",
"++",
";",
"this",
"[",
"index",
"]",
"=",
"toAddEle",
";",
"map",
".",
"set",
"(",
"id",
",",
"{",
"ele",
":",
"toAddEle",
",",
"index",
":",
"index",
"}",
")",
";",
"}",
"else",
"{",
"var",
"_index",
"=",
"map",
".",
"get",
"(",
"id",
")",
".",
"index",
";",
"this",
"[",
"_index",
"]",
"=",
"toAddEle",
";",
"map",
".",
"set",
"(",
"id",
",",
"{",
"ele",
":",
"toAddEle",
",",
"index",
":",
"_index",
"}",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
in place merge on calling collection
|
[
"in",
"place",
"merge",
"on",
"calling",
"collection"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L10233-L10272
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
unmergeOne
|
function unmergeOne(ele) {
ele = ele[0];
var _p = this._private;
var id = ele._private.data.id;
var map = _p.map;
var entry = map.get(id);
if (!entry) {
return this; // no need to remove
}
var i = entry.index;
this.unmergeAt(i);
return this;
}
|
javascript
|
function unmergeOne(ele) {
ele = ele[0];
var _p = this._private;
var id = ele._private.data.id;
var map = _p.map;
var entry = map.get(id);
if (!entry) {
return this; // no need to remove
}
var i = entry.index;
this.unmergeAt(i);
return this;
}
|
[
"function",
"unmergeOne",
"(",
"ele",
")",
"{",
"ele",
"=",
"ele",
"[",
"0",
"]",
";",
"var",
"_p",
"=",
"this",
".",
"_private",
";",
"var",
"id",
"=",
"ele",
".",
"_private",
".",
"data",
".",
"id",
";",
"var",
"map",
"=",
"_p",
".",
"map",
";",
"var",
"entry",
"=",
"map",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"!",
"entry",
")",
"{",
"return",
"this",
";",
"}",
"var",
"i",
"=",
"entry",
".",
"index",
";",
"this",
".",
"unmergeAt",
"(",
"i",
")",
";",
"return",
"this",
";",
"}"
] |
remove single ele in place in calling collection
|
[
"remove",
"single",
"ele",
"in",
"place",
"in",
"calling",
"collection"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L10300-L10314
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
unmerge
|
function unmerge(toRemove) {
var cy = this._private.cy;
if (!toRemove) {
return this;
}
if (toRemove && string(toRemove)) {
var selector = toRemove;
toRemove = cy.mutableElements().filter(selector);
}
for (var i = 0; i < toRemove.length; i++) {
this.unmergeOne(toRemove[i]);
}
return this; // chaining
}
|
javascript
|
function unmerge(toRemove) {
var cy = this._private.cy;
if (!toRemove) {
return this;
}
if (toRemove && string(toRemove)) {
var selector = toRemove;
toRemove = cy.mutableElements().filter(selector);
}
for (var i = 0; i < toRemove.length; i++) {
this.unmergeOne(toRemove[i]);
}
return this; // chaining
}
|
[
"function",
"unmerge",
"(",
"toRemove",
")",
"{",
"var",
"cy",
"=",
"this",
".",
"_private",
".",
"cy",
";",
"if",
"(",
"!",
"toRemove",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"toRemove",
"&&",
"string",
"(",
"toRemove",
")",
")",
"{",
"var",
"selector",
"=",
"toRemove",
";",
"toRemove",
"=",
"cy",
".",
"mutableElements",
"(",
")",
".",
"filter",
"(",
"selector",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"toRemove",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"unmergeOne",
"(",
"toRemove",
"[",
"i",
"]",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
remove eles in place on calling collection
|
[
"remove",
"eles",
"in",
"place",
"on",
"calling",
"collection"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L10316-L10333
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
addConnectedEdges
|
function addConnectedEdges(node) {
var edges = node._private.edges;
for (var i = 0; i < edges.length; i++) {
add(edges[i]);
}
}
|
javascript
|
function addConnectedEdges(node) {
var edges = node._private.edges;
for (var i = 0; i < edges.length; i++) {
add(edges[i]);
}
}
|
[
"function",
"addConnectedEdges",
"(",
"node",
")",
"{",
"var",
"edges",
"=",
"node",
".",
"_private",
".",
"edges",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"edges",
".",
"length",
";",
"i",
"++",
")",
"{",
"add",
"(",
"edges",
"[",
"i",
"]",
")",
";",
"}",
"}"
] |
add connected edges
|
[
"add",
"connected",
"edges"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L12352-L12358
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
addChildren
|
function addChildren(node) {
var children = node._private.children;
for (var i = 0; i < children.length; i++) {
add(children[i]);
}
}
|
javascript
|
function addChildren(node) {
var children = node._private.children;
for (var i = 0; i < children.length; i++) {
add(children[i]);
}
}
|
[
"function",
"addChildren",
"(",
"node",
")",
"{",
"var",
"children",
"=",
"node",
".",
"_private",
".",
"children",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"length",
";",
"i",
"++",
")",
"{",
"add",
"(",
"children",
"[",
"i",
"]",
")",
";",
"}",
"}"
] |
add descendant nodes
|
[
"add",
"descendant",
"nodes"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L12361-L12367
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
spring
|
function spring(tension, friction, duration) {
if (duration === 0) {
// can't get a spring w/ duration 0
return easings.linear; // duration 0 => jump to end so impl doesn't matter
}
var spring = generateSpringRK4(tension, friction, duration);
return function (start, end, percent) {
return start + (end - start) * spring(percent);
};
}
|
javascript
|
function spring(tension, friction, duration) {
if (duration === 0) {
// can't get a spring w/ duration 0
return easings.linear; // duration 0 => jump to end so impl doesn't matter
}
var spring = generateSpringRK4(tension, friction, duration);
return function (start, end, percent) {
return start + (end - start) * spring(percent);
};
}
|
[
"function",
"spring",
"(",
"tension",
",",
"friction",
",",
"duration",
")",
"{",
"if",
"(",
"duration",
"===",
"0",
")",
"{",
"return",
"easings",
".",
"linear",
";",
"}",
"var",
"spring",
"=",
"generateSpringRK4",
"(",
"tension",
",",
"friction",
",",
"duration",
")",
";",
"return",
"function",
"(",
"start",
",",
"end",
",",
"percent",
")",
"{",
"return",
"start",
"+",
"(",
"end",
"-",
"start",
")",
"*",
"spring",
"(",
"percent",
")",
";",
"}",
";",
"}"
] |
user param easings...
|
[
"user",
"param",
"easings",
"..."
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L12947-L12957
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
batchData
|
function batchData(map) {
var cy = this;
return this.batch(function () {
var ids = Object.keys(map);
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var data = map[id];
var ele = cy.getElementById(id);
ele.data(data);
}
});
}
|
javascript
|
function batchData(map) {
var cy = this;
return this.batch(function () {
var ids = Object.keys(map);
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var data = map[id];
var ele = cy.getElementById(id);
ele.data(data);
}
});
}
|
[
"function",
"batchData",
"(",
"map",
")",
"{",
"var",
"cy",
"=",
"this",
";",
"return",
"this",
".",
"batch",
"(",
"function",
"(",
")",
"{",
"var",
"ids",
"=",
"Object",
".",
"keys",
"(",
"map",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ids",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"id",
"=",
"ids",
"[",
"i",
"]",
";",
"var",
"data",
"=",
"map",
"[",
"id",
"]",
";",
"var",
"ele",
"=",
"cy",
".",
"getElementById",
"(",
"id",
")",
";",
"ele",
".",
"data",
"(",
"data",
")",
";",
"}",
"}",
")",
";",
"}"
] |
for backwards compatibility
|
[
"for",
"backwards",
"compatibility"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L13604-L13616
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
sortFn
|
function sortFn(a, b) {
var apct = getWeightedPercent(a);
var bpct = getWeightedPercent(b);
var diff = apct - bpct;
if (diff === 0) {
return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons
} else {
return diff;
}
}
|
javascript
|
function sortFn(a, b) {
var apct = getWeightedPercent(a);
var bpct = getWeightedPercent(b);
var diff = apct - bpct;
if (diff === 0) {
return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons
} else {
return diff;
}
}
|
[
"function",
"sortFn",
"(",
"a",
",",
"b",
")",
"{",
"var",
"apct",
"=",
"getWeightedPercent",
"(",
"a",
")",
";",
"var",
"bpct",
"=",
"getWeightedPercent",
"(",
"b",
")",
";",
"var",
"diff",
"=",
"apct",
"-",
"bpct",
";",
"if",
"(",
"diff",
"===",
"0",
")",
"{",
"return",
"ascending",
"(",
"a",
".",
"id",
"(",
")",
",",
"b",
".",
"id",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"diff",
";",
"}",
"}"
] |
rearrange the indices in each depth level based on connectivity
|
[
"rearrange",
"the",
"indices",
"in",
"each",
"depth",
"level",
"based",
"on",
"connectivity"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L18322-L18332
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
addNodesToDrag
|
function addNodesToDrag(nodes, opts) {
opts = opts || {};
var hasCompoundNodes = nodes.cy().hasCompoundNodes();
if (opts.inDragLayer) {
nodes.forEach(setInDragLayer);
nodes.neighborhood().stdFilter(function (ele) {
return !hasCompoundNodes || ele.isEdge();
}).forEach(setInDragLayer);
}
if (opts.addToList) {
nodes.forEach(function (ele) {
addToDragList(ele, opts);
});
}
addDescendantsToDrag(nodes, opts); // always add to drag
// also add nodes and edges related to the topmost ancestor
updateAncestorsInDragLayer(nodes, {
inDragLayer: opts.inDragLayer
});
r.updateCachedGrabbedEles();
}
|
javascript
|
function addNodesToDrag(nodes, opts) {
opts = opts || {};
var hasCompoundNodes = nodes.cy().hasCompoundNodes();
if (opts.inDragLayer) {
nodes.forEach(setInDragLayer);
nodes.neighborhood().stdFilter(function (ele) {
return !hasCompoundNodes || ele.isEdge();
}).forEach(setInDragLayer);
}
if (opts.addToList) {
nodes.forEach(function (ele) {
addToDragList(ele, opts);
});
}
addDescendantsToDrag(nodes, opts); // always add to drag
// also add nodes and edges related to the topmost ancestor
updateAncestorsInDragLayer(nodes, {
inDragLayer: opts.inDragLayer
});
r.updateCachedGrabbedEles();
}
|
[
"function",
"addNodesToDrag",
"(",
"nodes",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"hasCompoundNodes",
"=",
"nodes",
".",
"cy",
"(",
")",
".",
"hasCompoundNodes",
"(",
")",
";",
"if",
"(",
"opts",
".",
"inDragLayer",
")",
"{",
"nodes",
".",
"forEach",
"(",
"setInDragLayer",
")",
";",
"nodes",
".",
"neighborhood",
"(",
")",
".",
"stdFilter",
"(",
"function",
"(",
"ele",
")",
"{",
"return",
"!",
"hasCompoundNodes",
"||",
"ele",
".",
"isEdge",
"(",
")",
";",
"}",
")",
".",
"forEach",
"(",
"setInDragLayer",
")",
";",
"}",
"if",
"(",
"opts",
".",
"addToList",
")",
"{",
"nodes",
".",
"forEach",
"(",
"function",
"(",
"ele",
")",
"{",
"addToDragList",
"(",
"ele",
",",
"opts",
")",
";",
"}",
")",
";",
"}",
"addDescendantsToDrag",
"(",
"nodes",
",",
"opts",
")",
";",
"updateAncestorsInDragLayer",
"(",
"nodes",
",",
"{",
"inDragLayer",
":",
"opts",
".",
"inDragLayer",
"}",
")",
";",
"r",
".",
"updateCachedGrabbedEles",
"(",
")",
";",
"}"
] |
adds the given nodes and its neighbourhood to the drag layer
|
[
"adds",
"the",
"given",
"nodes",
"and",
"its",
"neighbourhood",
"to",
"the",
"drag",
"layer"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L23307-L23331
|
train
|
cytoscape/cytoscape.js
|
dist/cytoscape.esm.js
|
setupShapeColor
|
function setupShapeColor() {
var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
r.eleFillStyle(context, node, bgOpy);
}
|
javascript
|
function setupShapeColor() {
var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
r.eleFillStyle(context, node, bgOpy);
}
|
[
"function",
"setupShapeColor",
"(",
")",
"{",
"var",
"bgOpy",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"bgOpacity",
";",
"r",
".",
"eleFillStyle",
"(",
"context",
",",
"node",
",",
"bgOpy",
")",
";",
"}"
] |
so borders are square with the node shape
|
[
"so",
"borders",
"are",
"square",
"with",
"the",
"node",
"shape"
] |
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
|
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L28500-L28503
|
train
|
fex-team/webuploader
|
build/tasks/build.js
|
convert
|
function convert( name, _path, contents ) {
var rDefine = /(define\s*\(\s*('|").*?\2\s*,\s*\[)([\s\S]*?)\]/ig,
rDeps = /('|")(.*?)\1/g,
root = _path.substr( 0, _path.length - name.length - 3 ),
dir = path.dirname( _path ),
m, m2, deps, dep, _path2;
contents = contents.replace( rDefine, function( m, m1, m2, m3 ) {
return m1 + m3.replace( rDeps, function( m, m1, m2 ) {
m2 = path.join( dir, m2 );
m2 = path.relative( root, m2 );
m2 = m2.replace(/\\/g, '/');
return m1 + m2 + m1;
}) + ']';
});
return contents;
}
|
javascript
|
function convert( name, _path, contents ) {
var rDefine = /(define\s*\(\s*('|").*?\2\s*,\s*\[)([\s\S]*?)\]/ig,
rDeps = /('|")(.*?)\1/g,
root = _path.substr( 0, _path.length - name.length - 3 ),
dir = path.dirname( _path ),
m, m2, deps, dep, _path2;
contents = contents.replace( rDefine, function( m, m1, m2, m3 ) {
return m1 + m3.replace( rDeps, function( m, m1, m2 ) {
m2 = path.join( dir, m2 );
m2 = path.relative( root, m2 );
m2 = m2.replace(/\\/g, '/');
return m1 + m2 + m1;
}) + ']';
});
return contents;
}
|
[
"function",
"convert",
"(",
"name",
",",
"_path",
",",
"contents",
")",
"{",
"var",
"rDefine",
"=",
"/",
"(define\\s*\\(\\s*('|\").*?\\2\\s*,\\s*\\[)([\\s\\S]*?)\\]",
"/",
"ig",
",",
"rDeps",
"=",
"/",
"('|\")(.*?)\\1",
"/",
"g",
",",
"root",
"=",
"_path",
".",
"substr",
"(",
"0",
",",
"_path",
".",
"length",
"-",
"name",
".",
"length",
"-",
"3",
")",
",",
"dir",
"=",
"path",
".",
"dirname",
"(",
"_path",
")",
",",
"m",
",",
"m2",
",",
"deps",
",",
"dep",
",",
"_path2",
";",
"contents",
"=",
"contents",
".",
"replace",
"(",
"rDefine",
",",
"function",
"(",
"m",
",",
"m1",
",",
"m2",
",",
"m3",
")",
"{",
"return",
"m1",
"+",
"m3",
".",
"replace",
"(",
"rDeps",
",",
"function",
"(",
"m",
",",
"m1",
",",
"m2",
")",
"{",
"m2",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"m2",
")",
";",
"m2",
"=",
"path",
".",
"relative",
"(",
"root",
",",
"m2",
")",
";",
"m2",
"=",
"m2",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"return",
"m1",
"+",
"m2",
"+",
"m1",
";",
"}",
")",
"+",
"']'",
";",
"}",
")",
";",
"return",
"contents",
";",
"}"
] |
convert relative path to absolute path.
|
[
"convert",
"relative",
"path",
"to",
"absolute",
"path",
"."
] |
7094e4476c5af3b06993d91dde2d223200b9feb7
|
https://github.com/fex-team/webuploader/blob/7094e4476c5af3b06993d91dde2d223200b9feb7/build/tasks/build.js#L12-L30
|
train
|
fex-team/webuploader
|
src/runtime/html5/image.js
|
detectSubsampling
|
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
|
javascript
|
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
|
[
"function",
"detectSubsampling",
"(",
"img",
")",
"{",
"var",
"iw",
"=",
"img",
".",
"naturalWidth",
",",
"ih",
"=",
"img",
".",
"naturalHeight",
",",
"canvas",
",",
"ctx",
";",
"if",
"(",
"iw",
"*",
"ih",
">",
"1024",
"*",
"1024",
")",
"{",
"canvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"canvas",
".",
"width",
"=",
"canvas",
".",
"height",
"=",
"1",
";",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
";",
"ctx",
".",
"drawImage",
"(",
"img",
",",
"-",
"iw",
"+",
"1",
",",
"0",
")",
";",
"return",
"ctx",
".",
"getImageData",
"(",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
".",
"data",
"[",
"3",
"]",
"===",
"0",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Detect subsampling in loaded image.
In iOS, larger images than 2M pixels may be
subsampled in rendering.
|
[
"Detect",
"subsampling",
"in",
"loaded",
"image",
".",
"In",
"iOS",
"larger",
"images",
"than",
"2M",
"pixels",
"may",
"be",
"subsampled",
"in",
"rendering",
"."
] |
7094e4476c5af3b06993d91dde2d223200b9feb7
|
https://github.com/fex-team/webuploader/blob/7094e4476c5af3b06993d91dde2d223200b9feb7/src/runtime/html5/image.js#L366-L386
|
train
|
swimlane/ngx-datatable
|
release/utils/sort.js
|
nextSortDir
|
function nextSortDir(sortType, current) {
if (sortType === types_1.SortType.single) {
if (current === types_1.SortDirection.asc) {
return types_1.SortDirection.desc;
}
else {
return types_1.SortDirection.asc;
}
}
else {
if (!current) {
return types_1.SortDirection.asc;
}
else if (current === types_1.SortDirection.asc) {
return types_1.SortDirection.desc;
}
else if (current === types_1.SortDirection.desc) {
return undefined;
}
// avoid TS7030: Not all code paths return a value.
return undefined;
}
}
|
javascript
|
function nextSortDir(sortType, current) {
if (sortType === types_1.SortType.single) {
if (current === types_1.SortDirection.asc) {
return types_1.SortDirection.desc;
}
else {
return types_1.SortDirection.asc;
}
}
else {
if (!current) {
return types_1.SortDirection.asc;
}
else if (current === types_1.SortDirection.asc) {
return types_1.SortDirection.desc;
}
else if (current === types_1.SortDirection.desc) {
return undefined;
}
// avoid TS7030: Not all code paths return a value.
return undefined;
}
}
|
[
"function",
"nextSortDir",
"(",
"sortType",
",",
"current",
")",
"{",
"if",
"(",
"sortType",
"===",
"types_1",
".",
"SortType",
".",
"single",
")",
"{",
"if",
"(",
"current",
"===",
"types_1",
".",
"SortDirection",
".",
"asc",
")",
"{",
"return",
"types_1",
".",
"SortDirection",
".",
"desc",
";",
"}",
"else",
"{",
"return",
"types_1",
".",
"SortDirection",
".",
"asc",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"current",
")",
"{",
"return",
"types_1",
".",
"SortDirection",
".",
"asc",
";",
"}",
"else",
"if",
"(",
"current",
"===",
"types_1",
".",
"SortDirection",
".",
"asc",
")",
"{",
"return",
"types_1",
".",
"SortDirection",
".",
"desc",
";",
"}",
"else",
"if",
"(",
"current",
"===",
"types_1",
".",
"SortDirection",
".",
"desc",
")",
"{",
"return",
"undefined",
";",
"}",
"return",
"undefined",
";",
"}",
"}"
] |
Gets the next sort direction
|
[
"Gets",
"the",
"next",
"sort",
"direction"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/sort.js#L8-L30
|
train
|
swimlane/ngx-datatable
|
release/utils/sort.js
|
sortRows
|
function sortRows(rows, columns, dirs) {
if (!rows)
return [];
if (!dirs || !dirs.length || !columns)
return rows.slice();
/**
* record the row ordering of results from prior sort operations (if applicable)
* this is necessary to guarantee stable sorting behavior
*/
var rowToIndexMap = new Map();
rows.forEach(function (row, index) { return rowToIndexMap.set(row, index); });
var temp = rows.slice();
var cols = columns.reduce(function (obj, col) {
if (col.comparator && typeof col.comparator === 'function') {
obj[col.prop] = col.comparator;
}
return obj;
}, {});
// cache valueGetter and compareFn so that they
// do not need to be looked-up in the sort function body
var cachedDirs = dirs.map(function (dir) {
var prop = dir.prop;
return {
prop: prop,
dir: dir.dir,
valueGetter: column_prop_getters_1.getterForProp(prop),
compareFn: cols[prop] || orderByComparator
};
});
return temp.sort(function (rowA, rowB) {
for (var _i = 0, cachedDirs_1 = cachedDirs; _i < cachedDirs_1.length; _i++) {
var cachedDir = cachedDirs_1[_i];
// Get property and valuegetters for column to be sorted
var prop = cachedDir.prop, valueGetter = cachedDir.valueGetter;
// Get A and B cell values from rows based on properties of the columns
var propA = valueGetter(rowA, prop);
var propB = valueGetter(rowB, prop);
// Compare function gets five parameters:
// Two cell values to be compared as propA and propB
// Two rows corresponding to the cells as rowA and rowB
// Direction of the sort for this column as SortDirection
// Compare can be a standard JS comparison function (a,b) => -1|0|1
// as additional parameters are silently ignored. The whole row and sort
// direction enable more complex sort logic.
var comparison = cachedDir.dir !== types_1.SortDirection.desc ?
cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir) :
-cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir);
// Don't return 0 yet in case of needing to sort by next property
if (comparison !== 0)
return comparison;
}
if (!(rowToIndexMap.has(rowA) && rowToIndexMap.has(rowB)))
return 0;
/**
* all else being equal, preserve original order of the rows (stable sort)
*/
return rowToIndexMap.get(rowA) < rowToIndexMap.get(rowB) ? -1 : 1;
});
}
|
javascript
|
function sortRows(rows, columns, dirs) {
if (!rows)
return [];
if (!dirs || !dirs.length || !columns)
return rows.slice();
/**
* record the row ordering of results from prior sort operations (if applicable)
* this is necessary to guarantee stable sorting behavior
*/
var rowToIndexMap = new Map();
rows.forEach(function (row, index) { return rowToIndexMap.set(row, index); });
var temp = rows.slice();
var cols = columns.reduce(function (obj, col) {
if (col.comparator && typeof col.comparator === 'function') {
obj[col.prop] = col.comparator;
}
return obj;
}, {});
// cache valueGetter and compareFn so that they
// do not need to be looked-up in the sort function body
var cachedDirs = dirs.map(function (dir) {
var prop = dir.prop;
return {
prop: prop,
dir: dir.dir,
valueGetter: column_prop_getters_1.getterForProp(prop),
compareFn: cols[prop] || orderByComparator
};
});
return temp.sort(function (rowA, rowB) {
for (var _i = 0, cachedDirs_1 = cachedDirs; _i < cachedDirs_1.length; _i++) {
var cachedDir = cachedDirs_1[_i];
// Get property and valuegetters for column to be sorted
var prop = cachedDir.prop, valueGetter = cachedDir.valueGetter;
// Get A and B cell values from rows based on properties of the columns
var propA = valueGetter(rowA, prop);
var propB = valueGetter(rowB, prop);
// Compare function gets five parameters:
// Two cell values to be compared as propA and propB
// Two rows corresponding to the cells as rowA and rowB
// Direction of the sort for this column as SortDirection
// Compare can be a standard JS comparison function (a,b) => -1|0|1
// as additional parameters are silently ignored. The whole row and sort
// direction enable more complex sort logic.
var comparison = cachedDir.dir !== types_1.SortDirection.desc ?
cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir) :
-cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir);
// Don't return 0 yet in case of needing to sort by next property
if (comparison !== 0)
return comparison;
}
if (!(rowToIndexMap.has(rowA) && rowToIndexMap.has(rowB)))
return 0;
/**
* all else being equal, preserve original order of the rows (stable sort)
*/
return rowToIndexMap.get(rowA) < rowToIndexMap.get(rowB) ? -1 : 1;
});
}
|
[
"function",
"sortRows",
"(",
"rows",
",",
"columns",
",",
"dirs",
")",
"{",
"if",
"(",
"!",
"rows",
")",
"return",
"[",
"]",
";",
"if",
"(",
"!",
"dirs",
"||",
"!",
"dirs",
".",
"length",
"||",
"!",
"columns",
")",
"return",
"rows",
".",
"slice",
"(",
")",
";",
"var",
"rowToIndexMap",
"=",
"new",
"Map",
"(",
")",
";",
"rows",
".",
"forEach",
"(",
"function",
"(",
"row",
",",
"index",
")",
"{",
"return",
"rowToIndexMap",
".",
"set",
"(",
"row",
",",
"index",
")",
";",
"}",
")",
";",
"var",
"temp",
"=",
"rows",
".",
"slice",
"(",
")",
";",
"var",
"cols",
"=",
"columns",
".",
"reduce",
"(",
"function",
"(",
"obj",
",",
"col",
")",
"{",
"if",
"(",
"col",
".",
"comparator",
"&&",
"typeof",
"col",
".",
"comparator",
"===",
"'function'",
")",
"{",
"obj",
"[",
"col",
".",
"prop",
"]",
"=",
"col",
".",
"comparator",
";",
"}",
"return",
"obj",
";",
"}",
",",
"{",
"}",
")",
";",
"var",
"cachedDirs",
"=",
"dirs",
".",
"map",
"(",
"function",
"(",
"dir",
")",
"{",
"var",
"prop",
"=",
"dir",
".",
"prop",
";",
"return",
"{",
"prop",
":",
"prop",
",",
"dir",
":",
"dir",
".",
"dir",
",",
"valueGetter",
":",
"column_prop_getters_1",
".",
"getterForProp",
"(",
"prop",
")",
",",
"compareFn",
":",
"cols",
"[",
"prop",
"]",
"||",
"orderByComparator",
"}",
";",
"}",
")",
";",
"return",
"temp",
".",
"sort",
"(",
"function",
"(",
"rowA",
",",
"rowB",
")",
"{",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"cachedDirs_1",
"=",
"cachedDirs",
";",
"_i",
"<",
"cachedDirs_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"cachedDir",
"=",
"cachedDirs_1",
"[",
"_i",
"]",
";",
"var",
"prop",
"=",
"cachedDir",
".",
"prop",
",",
"valueGetter",
"=",
"cachedDir",
".",
"valueGetter",
";",
"var",
"propA",
"=",
"valueGetter",
"(",
"rowA",
",",
"prop",
")",
";",
"var",
"propB",
"=",
"valueGetter",
"(",
"rowB",
",",
"prop",
")",
";",
"var",
"comparison",
"=",
"cachedDir",
".",
"dir",
"!==",
"types_1",
".",
"SortDirection",
".",
"desc",
"?",
"cachedDir",
".",
"compareFn",
"(",
"propA",
",",
"propB",
",",
"rowA",
",",
"rowB",
",",
"cachedDir",
".",
"dir",
")",
":",
"-",
"cachedDir",
".",
"compareFn",
"(",
"propA",
",",
"propB",
",",
"rowA",
",",
"rowB",
",",
"cachedDir",
".",
"dir",
")",
";",
"if",
"(",
"comparison",
"!==",
"0",
")",
"return",
"comparison",
";",
"}",
"if",
"(",
"!",
"(",
"rowToIndexMap",
".",
"has",
"(",
"rowA",
")",
"&&",
"rowToIndexMap",
".",
"has",
"(",
"rowB",
")",
")",
")",
"return",
"0",
";",
"return",
"rowToIndexMap",
".",
"get",
"(",
"rowA",
")",
"<",
"rowToIndexMap",
".",
"get",
"(",
"rowB",
")",
"?",
"-",
"1",
":",
"1",
";",
"}",
")",
";",
"}"
] |
creates a shallow copy of the `rows` input and returns the sorted copy. this function
does not sort the `rows` argument in place
|
[
"creates",
"a",
"shallow",
"copy",
"of",
"the",
"rows",
"input",
"and",
"returns",
"the",
"sorted",
"copy",
".",
"this",
"function",
"does",
"not",
"sort",
"the",
"rows",
"argument",
"in",
"place"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/sort.js#L72-L130
|
train
|
swimlane/ngx-datatable
|
release/utils/column.js
|
columnsByPin
|
function columnsByPin(cols) {
var ret = {
left: [],
center: [],
right: []
};
if (cols) {
for (var _i = 0, cols_1 = cols; _i < cols_1.length; _i++) {
var col = cols_1[_i];
if (col.frozenLeft) {
ret.left.push(col);
}
else if (col.frozenRight) {
ret.right.push(col);
}
else {
ret.center.push(col);
}
}
}
return ret;
}
|
javascript
|
function columnsByPin(cols) {
var ret = {
left: [],
center: [],
right: []
};
if (cols) {
for (var _i = 0, cols_1 = cols; _i < cols_1.length; _i++) {
var col = cols_1[_i];
if (col.frozenLeft) {
ret.left.push(col);
}
else if (col.frozenRight) {
ret.right.push(col);
}
else {
ret.center.push(col);
}
}
}
return ret;
}
|
[
"function",
"columnsByPin",
"(",
"cols",
")",
"{",
"var",
"ret",
"=",
"{",
"left",
":",
"[",
"]",
",",
"center",
":",
"[",
"]",
",",
"right",
":",
"[",
"]",
"}",
";",
"if",
"(",
"cols",
")",
"{",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"cols_1",
"=",
"cols",
";",
"_i",
"<",
"cols_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"col",
"=",
"cols_1",
"[",
"_i",
"]",
";",
"if",
"(",
"col",
".",
"frozenLeft",
")",
"{",
"ret",
".",
"left",
".",
"push",
"(",
"col",
")",
";",
"}",
"else",
"if",
"(",
"col",
".",
"frozenRight",
")",
"{",
"ret",
".",
"right",
".",
"push",
"(",
"col",
")",
";",
"}",
"else",
"{",
"ret",
".",
"center",
".",
"push",
"(",
"col",
")",
";",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
] |
Returns the columns by pin.
|
[
"Returns",
"the",
"columns",
"by",
"pin",
"."
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/column.js#L6-L27
|
train
|
swimlane/ngx-datatable
|
release/utils/column.js
|
columnGroupWidths
|
function columnGroupWidths(groups, all) {
return {
left: columnTotalWidth(groups.left),
center: columnTotalWidth(groups.center),
right: columnTotalWidth(groups.right),
total: Math.floor(columnTotalWidth(all))
};
}
|
javascript
|
function columnGroupWidths(groups, all) {
return {
left: columnTotalWidth(groups.left),
center: columnTotalWidth(groups.center),
right: columnTotalWidth(groups.right),
total: Math.floor(columnTotalWidth(all))
};
}
|
[
"function",
"columnGroupWidths",
"(",
"groups",
",",
"all",
")",
"{",
"return",
"{",
"left",
":",
"columnTotalWidth",
"(",
"groups",
".",
"left",
")",
",",
"center",
":",
"columnTotalWidth",
"(",
"groups",
".",
"center",
")",
",",
"right",
":",
"columnTotalWidth",
"(",
"groups",
".",
"right",
")",
",",
"total",
":",
"Math",
".",
"floor",
"(",
"columnTotalWidth",
"(",
"all",
")",
")",
"}",
";",
"}"
] |
Returns the widths of all group sets of a column
|
[
"Returns",
"the",
"widths",
"of",
"all",
"group",
"sets",
"of",
"a",
"column"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/column.js#L32-L39
|
train
|
swimlane/ngx-datatable
|
release/utils/math.js
|
getTotalFlexGrow
|
function getTotalFlexGrow(columns) {
var totalFlexGrow = 0;
for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
var c = columns_1[_i];
totalFlexGrow += c.flexGrow || 0;
}
return totalFlexGrow;
}
|
javascript
|
function getTotalFlexGrow(columns) {
var totalFlexGrow = 0;
for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
var c = columns_1[_i];
totalFlexGrow += c.flexGrow || 0;
}
return totalFlexGrow;
}
|
[
"function",
"getTotalFlexGrow",
"(",
"columns",
")",
"{",
"var",
"totalFlexGrow",
"=",
"0",
";",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"columns_1",
"=",
"columns",
";",
"_i",
"<",
"columns_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"c",
"=",
"columns_1",
"[",
"_i",
"]",
";",
"totalFlexGrow",
"+=",
"c",
".",
"flexGrow",
"||",
"0",
";",
"}",
"return",
"totalFlexGrow",
";",
"}"
] |
Calculates the Total Flex Grow
|
[
"Calculates",
"the",
"Total",
"Flex",
"Grow"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/math.js#L7-L14
|
train
|
swimlane/ngx-datatable
|
release/utils/math.js
|
scaleColumns
|
function scaleColumns(colsByGroup, maxWidth, totalFlexGrow) {
// calculate total width and flexgrow points for coulumns that can be resized
for (var attr in colsByGroup) {
for (var _i = 0, _a = colsByGroup[attr]; _i < _a.length; _i++) {
var column = _a[_i];
if (!column.canAutoResize) {
maxWidth -= column.width;
totalFlexGrow -= column.flexGrow ? column.flexGrow : 0;
}
else {
column.width = 0;
}
}
}
var hasMinWidth = {};
var remainingWidth = maxWidth;
// resize columns until no width is left to be distributed
do {
var widthPerFlexPoint = remainingWidth / totalFlexGrow;
remainingWidth = 0;
for (var attr in colsByGroup) {
for (var _b = 0, _c = colsByGroup[attr]; _b < _c.length; _b++) {
var column = _c[_b];
// if the column can be resize and it hasn't reached its minimum width yet
if (column.canAutoResize && !hasMinWidth[column.prop]) {
var newWidth = column.width + column.flexGrow * widthPerFlexPoint;
if (column.minWidth !== undefined && newWidth < column.minWidth) {
remainingWidth += newWidth - column.minWidth;
column.width = column.minWidth;
hasMinWidth[column.prop] = true;
}
else {
column.width = newWidth;
}
}
}
}
} while (remainingWidth !== 0);
}
|
javascript
|
function scaleColumns(colsByGroup, maxWidth, totalFlexGrow) {
// calculate total width and flexgrow points for coulumns that can be resized
for (var attr in colsByGroup) {
for (var _i = 0, _a = colsByGroup[attr]; _i < _a.length; _i++) {
var column = _a[_i];
if (!column.canAutoResize) {
maxWidth -= column.width;
totalFlexGrow -= column.flexGrow ? column.flexGrow : 0;
}
else {
column.width = 0;
}
}
}
var hasMinWidth = {};
var remainingWidth = maxWidth;
// resize columns until no width is left to be distributed
do {
var widthPerFlexPoint = remainingWidth / totalFlexGrow;
remainingWidth = 0;
for (var attr in colsByGroup) {
for (var _b = 0, _c = colsByGroup[attr]; _b < _c.length; _b++) {
var column = _c[_b];
// if the column can be resize and it hasn't reached its minimum width yet
if (column.canAutoResize && !hasMinWidth[column.prop]) {
var newWidth = column.width + column.flexGrow * widthPerFlexPoint;
if (column.minWidth !== undefined && newWidth < column.minWidth) {
remainingWidth += newWidth - column.minWidth;
column.width = column.minWidth;
hasMinWidth[column.prop] = true;
}
else {
column.width = newWidth;
}
}
}
}
} while (remainingWidth !== 0);
}
|
[
"function",
"scaleColumns",
"(",
"colsByGroup",
",",
"maxWidth",
",",
"totalFlexGrow",
")",
"{",
"for",
"(",
"var",
"attr",
"in",
"colsByGroup",
")",
"{",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"_a",
"=",
"colsByGroup",
"[",
"attr",
"]",
";",
"_i",
"<",
"_a",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"column",
"=",
"_a",
"[",
"_i",
"]",
";",
"if",
"(",
"!",
"column",
".",
"canAutoResize",
")",
"{",
"maxWidth",
"-=",
"column",
".",
"width",
";",
"totalFlexGrow",
"-=",
"column",
".",
"flexGrow",
"?",
"column",
".",
"flexGrow",
":",
"0",
";",
"}",
"else",
"{",
"column",
".",
"width",
"=",
"0",
";",
"}",
"}",
"}",
"var",
"hasMinWidth",
"=",
"{",
"}",
";",
"var",
"remainingWidth",
"=",
"maxWidth",
";",
"do",
"{",
"var",
"widthPerFlexPoint",
"=",
"remainingWidth",
"/",
"totalFlexGrow",
";",
"remainingWidth",
"=",
"0",
";",
"for",
"(",
"var",
"attr",
"in",
"colsByGroup",
")",
"{",
"for",
"(",
"var",
"_b",
"=",
"0",
",",
"_c",
"=",
"colsByGroup",
"[",
"attr",
"]",
";",
"_b",
"<",
"_c",
".",
"length",
";",
"_b",
"++",
")",
"{",
"var",
"column",
"=",
"_c",
"[",
"_b",
"]",
";",
"if",
"(",
"column",
".",
"canAutoResize",
"&&",
"!",
"hasMinWidth",
"[",
"column",
".",
"prop",
"]",
")",
"{",
"var",
"newWidth",
"=",
"column",
".",
"width",
"+",
"column",
".",
"flexGrow",
"*",
"widthPerFlexPoint",
";",
"if",
"(",
"column",
".",
"minWidth",
"!==",
"undefined",
"&&",
"newWidth",
"<",
"column",
".",
"minWidth",
")",
"{",
"remainingWidth",
"+=",
"newWidth",
"-",
"column",
".",
"minWidth",
";",
"column",
".",
"width",
"=",
"column",
".",
"minWidth",
";",
"hasMinWidth",
"[",
"column",
".",
"prop",
"]",
"=",
"true",
";",
"}",
"else",
"{",
"column",
".",
"width",
"=",
"newWidth",
";",
"}",
"}",
"}",
"}",
"}",
"while",
"(",
"remainingWidth",
"!==",
"0",
")",
";",
"}"
] |
Resizes columns based on the flexGrow property, while respecting manually set widths
|
[
"Resizes",
"columns",
"based",
"on",
"the",
"flexGrow",
"property",
"while",
"respecting",
"manually",
"set",
"widths"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/math.js#L32-L70
|
train
|
swimlane/ngx-datatable
|
release/utils/math.js
|
forceFillColumnWidths
|
function forceFillColumnWidths(allColumns, expectedWidth, startIdx, allowBleed, defaultColWidth) {
if (defaultColWidth === void 0) { defaultColWidth = 300; }
var columnsToResize = allColumns
.slice(startIdx + 1, allColumns.length)
.filter(function (c) {
return c.canAutoResize !== false;
});
for (var _i = 0, columnsToResize_1 = columnsToResize; _i < columnsToResize_1.length; _i++) {
var column = columnsToResize_1[_i];
if (!column.$$oldWidth) {
column.$$oldWidth = column.width;
}
}
var additionWidthPerColumn = 0;
var exceedsWindow = false;
var contentWidth = getContentWidth(allColumns, defaultColWidth);
var remainingWidth = expectedWidth - contentWidth;
var columnsProcessed = [];
// This loop takes care of the
do {
additionWidthPerColumn = remainingWidth / columnsToResize.length;
exceedsWindow = contentWidth >= expectedWidth;
for (var _a = 0, columnsToResize_2 = columnsToResize; _a < columnsToResize_2.length; _a++) {
var column = columnsToResize_2[_a];
if (exceedsWindow && allowBleed) {
column.width = column.$$oldWidth || column.width || defaultColWidth;
}
else {
var newSize = (column.width || defaultColWidth) + additionWidthPerColumn;
if (column.minWidth && newSize < column.minWidth) {
column.width = column.minWidth;
columnsProcessed.push(column);
}
else if (column.maxWidth && newSize > column.maxWidth) {
column.width = column.maxWidth;
columnsProcessed.push(column);
}
else {
column.width = newSize;
}
}
column.width = Math.max(0, column.width);
}
contentWidth = getContentWidth(allColumns);
remainingWidth = expectedWidth - contentWidth;
removeProcessedColumns(columnsToResize, columnsProcessed);
} while (remainingWidth > 0 && columnsToResize.length !== 0);
}
|
javascript
|
function forceFillColumnWidths(allColumns, expectedWidth, startIdx, allowBleed, defaultColWidth) {
if (defaultColWidth === void 0) { defaultColWidth = 300; }
var columnsToResize = allColumns
.slice(startIdx + 1, allColumns.length)
.filter(function (c) {
return c.canAutoResize !== false;
});
for (var _i = 0, columnsToResize_1 = columnsToResize; _i < columnsToResize_1.length; _i++) {
var column = columnsToResize_1[_i];
if (!column.$$oldWidth) {
column.$$oldWidth = column.width;
}
}
var additionWidthPerColumn = 0;
var exceedsWindow = false;
var contentWidth = getContentWidth(allColumns, defaultColWidth);
var remainingWidth = expectedWidth - contentWidth;
var columnsProcessed = [];
// This loop takes care of the
do {
additionWidthPerColumn = remainingWidth / columnsToResize.length;
exceedsWindow = contentWidth >= expectedWidth;
for (var _a = 0, columnsToResize_2 = columnsToResize; _a < columnsToResize_2.length; _a++) {
var column = columnsToResize_2[_a];
if (exceedsWindow && allowBleed) {
column.width = column.$$oldWidth || column.width || defaultColWidth;
}
else {
var newSize = (column.width || defaultColWidth) + additionWidthPerColumn;
if (column.minWidth && newSize < column.minWidth) {
column.width = column.minWidth;
columnsProcessed.push(column);
}
else if (column.maxWidth && newSize > column.maxWidth) {
column.width = column.maxWidth;
columnsProcessed.push(column);
}
else {
column.width = newSize;
}
}
column.width = Math.max(0, column.width);
}
contentWidth = getContentWidth(allColumns);
remainingWidth = expectedWidth - contentWidth;
removeProcessedColumns(columnsToResize, columnsProcessed);
} while (remainingWidth > 0 && columnsToResize.length !== 0);
}
|
[
"function",
"forceFillColumnWidths",
"(",
"allColumns",
",",
"expectedWidth",
",",
"startIdx",
",",
"allowBleed",
",",
"defaultColWidth",
")",
"{",
"if",
"(",
"defaultColWidth",
"===",
"void",
"0",
")",
"{",
"defaultColWidth",
"=",
"300",
";",
"}",
"var",
"columnsToResize",
"=",
"allColumns",
".",
"slice",
"(",
"startIdx",
"+",
"1",
",",
"allColumns",
".",
"length",
")",
".",
"filter",
"(",
"function",
"(",
"c",
")",
"{",
"return",
"c",
".",
"canAutoResize",
"!==",
"false",
";",
"}",
")",
";",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"columnsToResize_1",
"=",
"columnsToResize",
";",
"_i",
"<",
"columnsToResize_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"column",
"=",
"columnsToResize_1",
"[",
"_i",
"]",
";",
"if",
"(",
"!",
"column",
".",
"$$oldWidth",
")",
"{",
"column",
".",
"$$oldWidth",
"=",
"column",
".",
"width",
";",
"}",
"}",
"var",
"additionWidthPerColumn",
"=",
"0",
";",
"var",
"exceedsWindow",
"=",
"false",
";",
"var",
"contentWidth",
"=",
"getContentWidth",
"(",
"allColumns",
",",
"defaultColWidth",
")",
";",
"var",
"remainingWidth",
"=",
"expectedWidth",
"-",
"contentWidth",
";",
"var",
"columnsProcessed",
"=",
"[",
"]",
";",
"do",
"{",
"additionWidthPerColumn",
"=",
"remainingWidth",
"/",
"columnsToResize",
".",
"length",
";",
"exceedsWindow",
"=",
"contentWidth",
">=",
"expectedWidth",
";",
"for",
"(",
"var",
"_a",
"=",
"0",
",",
"columnsToResize_2",
"=",
"columnsToResize",
";",
"_a",
"<",
"columnsToResize_2",
".",
"length",
";",
"_a",
"++",
")",
"{",
"var",
"column",
"=",
"columnsToResize_2",
"[",
"_a",
"]",
";",
"if",
"(",
"exceedsWindow",
"&&",
"allowBleed",
")",
"{",
"column",
".",
"width",
"=",
"column",
".",
"$$oldWidth",
"||",
"column",
".",
"width",
"||",
"defaultColWidth",
";",
"}",
"else",
"{",
"var",
"newSize",
"=",
"(",
"column",
".",
"width",
"||",
"defaultColWidth",
")",
"+",
"additionWidthPerColumn",
";",
"if",
"(",
"column",
".",
"minWidth",
"&&",
"newSize",
"<",
"column",
".",
"minWidth",
")",
"{",
"column",
".",
"width",
"=",
"column",
".",
"minWidth",
";",
"columnsProcessed",
".",
"push",
"(",
"column",
")",
";",
"}",
"else",
"if",
"(",
"column",
".",
"maxWidth",
"&&",
"newSize",
">",
"column",
".",
"maxWidth",
")",
"{",
"column",
".",
"width",
"=",
"column",
".",
"maxWidth",
";",
"columnsProcessed",
".",
"push",
"(",
"column",
")",
";",
"}",
"else",
"{",
"column",
".",
"width",
"=",
"newSize",
";",
"}",
"}",
"column",
".",
"width",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"column",
".",
"width",
")",
";",
"}",
"contentWidth",
"=",
"getContentWidth",
"(",
"allColumns",
")",
";",
"remainingWidth",
"=",
"expectedWidth",
"-",
"contentWidth",
";",
"removeProcessedColumns",
"(",
"columnsToResize",
",",
"columnsProcessed",
")",
";",
"}",
"while",
"(",
"remainingWidth",
">",
"0",
"&&",
"columnsToResize",
".",
"length",
"!==",
"0",
")",
";",
"}"
] |
Forces the width of the columns to
distribute equally but overflowing when necessary
Rules:
- If combined withs are less than the total width of the grid,
proportion the widths given the min / max / normal widths to fill the width.
- If the combined widths, exceed the total width of the grid,
use the standard widths.
- If a column is resized, it should always use that width
- The proportional widths should never fall below min size if specified.
- If the grid starts off small but then becomes greater than the size ( + / - )
the width should use the original width; not the newly proportioned widths.
|
[
"Forces",
"the",
"width",
"of",
"the",
"columns",
"to",
"distribute",
"equally",
"but",
"overflowing",
"when",
"necessary"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/math.js#L90-L137
|
train
|
swimlane/ngx-datatable
|
release/utils/math.js
|
removeProcessedColumns
|
function removeProcessedColumns(columnsToResize, columnsProcessed) {
for (var _i = 0, columnsProcessed_1 = columnsProcessed; _i < columnsProcessed_1.length; _i++) {
var column = columnsProcessed_1[_i];
var index = columnsToResize.indexOf(column);
columnsToResize.splice(index, 1);
}
}
|
javascript
|
function removeProcessedColumns(columnsToResize, columnsProcessed) {
for (var _i = 0, columnsProcessed_1 = columnsProcessed; _i < columnsProcessed_1.length; _i++) {
var column = columnsProcessed_1[_i];
var index = columnsToResize.indexOf(column);
columnsToResize.splice(index, 1);
}
}
|
[
"function",
"removeProcessedColumns",
"(",
"columnsToResize",
",",
"columnsProcessed",
")",
"{",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"columnsProcessed_1",
"=",
"columnsProcessed",
";",
"_i",
"<",
"columnsProcessed_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"column",
"=",
"columnsProcessed_1",
"[",
"_i",
"]",
";",
"var",
"index",
"=",
"columnsToResize",
".",
"indexOf",
"(",
"column",
")",
";",
"columnsToResize",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"}"
] |
Remove the processed columns from the current active columns.
|
[
"Remove",
"the",
"processed",
"columns",
"from",
"the",
"current",
"active",
"columns",
"."
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/math.js#L142-L148
|
train
|
swimlane/ngx-datatable
|
release/utils/math.js
|
getContentWidth
|
function getContentWidth(allColumns, defaultColWidth) {
if (defaultColWidth === void 0) { defaultColWidth = 300; }
var contentWidth = 0;
for (var _i = 0, allColumns_1 = allColumns; _i < allColumns_1.length; _i++) {
var column = allColumns_1[_i];
contentWidth += (column.width || defaultColWidth);
}
return contentWidth;
}
|
javascript
|
function getContentWidth(allColumns, defaultColWidth) {
if (defaultColWidth === void 0) { defaultColWidth = 300; }
var contentWidth = 0;
for (var _i = 0, allColumns_1 = allColumns; _i < allColumns_1.length; _i++) {
var column = allColumns_1[_i];
contentWidth += (column.width || defaultColWidth);
}
return contentWidth;
}
|
[
"function",
"getContentWidth",
"(",
"allColumns",
",",
"defaultColWidth",
")",
"{",
"if",
"(",
"defaultColWidth",
"===",
"void",
"0",
")",
"{",
"defaultColWidth",
"=",
"300",
";",
"}",
"var",
"contentWidth",
"=",
"0",
";",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"allColumns_1",
"=",
"allColumns",
";",
"_i",
"<",
"allColumns_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"column",
"=",
"allColumns_1",
"[",
"_i",
"]",
";",
"contentWidth",
"+=",
"(",
"column",
".",
"width",
"||",
"defaultColWidth",
")",
";",
"}",
"return",
"contentWidth",
";",
"}"
] |
Gets the width of the columns
|
[
"Gets",
"the",
"width",
"of",
"the",
"columns"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/math.js#L152-L160
|
train
|
swimlane/ngx-datatable
|
release/utils/tree.js
|
groupRowsByParents
|
function groupRowsByParents(rows, from, to) {
if (from && to) {
var nodeById = {};
var l = rows.length;
var node = null;
nodeById[0] = new TreeNode(); // that's the root node
var uniqIDs = rows.reduce(function (arr, item) {
var toValue = to(item);
if (arr.indexOf(toValue) === -1) {
arr.push(toValue);
}
return arr;
}, []);
for (var i = 0; i < l; i++) { // make TreeNode objects for each item
nodeById[to(rows[i])] = new TreeNode(rows[i]);
}
for (var i = 0; i < l; i++) { // link all TreeNode objects
node = nodeById[to(rows[i])];
var parent_1 = 0;
var fromValue = from(node.row);
if (!!fromValue && (uniqIDs.indexOf(fromValue) > -1)) {
parent_1 = fromValue;
}
node.parent = nodeById[parent_1];
node.row['level'] = node.parent.row['level'] + 1;
node.parent.children.push(node);
}
var resolvedRows_1 = [];
nodeById[0].flatten(function () {
resolvedRows_1 = resolvedRows_1.concat([this.row]);
}, true);
return resolvedRows_1;
}
else {
return rows;
}
}
|
javascript
|
function groupRowsByParents(rows, from, to) {
if (from && to) {
var nodeById = {};
var l = rows.length;
var node = null;
nodeById[0] = new TreeNode(); // that's the root node
var uniqIDs = rows.reduce(function (arr, item) {
var toValue = to(item);
if (arr.indexOf(toValue) === -1) {
arr.push(toValue);
}
return arr;
}, []);
for (var i = 0; i < l; i++) { // make TreeNode objects for each item
nodeById[to(rows[i])] = new TreeNode(rows[i]);
}
for (var i = 0; i < l; i++) { // link all TreeNode objects
node = nodeById[to(rows[i])];
var parent_1 = 0;
var fromValue = from(node.row);
if (!!fromValue && (uniqIDs.indexOf(fromValue) > -1)) {
parent_1 = fromValue;
}
node.parent = nodeById[parent_1];
node.row['level'] = node.parent.row['level'] + 1;
node.parent.children.push(node);
}
var resolvedRows_1 = [];
nodeById[0].flatten(function () {
resolvedRows_1 = resolvedRows_1.concat([this.row]);
}, true);
return resolvedRows_1;
}
else {
return rows;
}
}
|
[
"function",
"groupRowsByParents",
"(",
"rows",
",",
"from",
",",
"to",
")",
"{",
"if",
"(",
"from",
"&&",
"to",
")",
"{",
"var",
"nodeById",
"=",
"{",
"}",
";",
"var",
"l",
"=",
"rows",
".",
"length",
";",
"var",
"node",
"=",
"null",
";",
"nodeById",
"[",
"0",
"]",
"=",
"new",
"TreeNode",
"(",
")",
";",
"var",
"uniqIDs",
"=",
"rows",
".",
"reduce",
"(",
"function",
"(",
"arr",
",",
"item",
")",
"{",
"var",
"toValue",
"=",
"to",
"(",
"item",
")",
";",
"if",
"(",
"arr",
".",
"indexOf",
"(",
"toValue",
")",
"===",
"-",
"1",
")",
"{",
"arr",
".",
"push",
"(",
"toValue",
")",
";",
"}",
"return",
"arr",
";",
"}",
",",
"[",
"]",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"nodeById",
"[",
"to",
"(",
"rows",
"[",
"i",
"]",
")",
"]",
"=",
"new",
"TreeNode",
"(",
"rows",
"[",
"i",
"]",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"node",
"=",
"nodeById",
"[",
"to",
"(",
"rows",
"[",
"i",
"]",
")",
"]",
";",
"var",
"parent_1",
"=",
"0",
";",
"var",
"fromValue",
"=",
"from",
"(",
"node",
".",
"row",
")",
";",
"if",
"(",
"!",
"!",
"fromValue",
"&&",
"(",
"uniqIDs",
".",
"indexOf",
"(",
"fromValue",
")",
">",
"-",
"1",
")",
")",
"{",
"parent_1",
"=",
"fromValue",
";",
"}",
"node",
".",
"parent",
"=",
"nodeById",
"[",
"parent_1",
"]",
";",
"node",
".",
"row",
"[",
"'level'",
"]",
"=",
"node",
".",
"parent",
".",
"row",
"[",
"'level'",
"]",
"+",
"1",
";",
"node",
".",
"parent",
".",
"children",
".",
"push",
"(",
"node",
")",
";",
"}",
"var",
"resolvedRows_1",
"=",
"[",
"]",
";",
"nodeById",
"[",
"0",
"]",
".",
"flatten",
"(",
"function",
"(",
")",
"{",
"resolvedRows_1",
"=",
"resolvedRows_1",
".",
"concat",
"(",
"[",
"this",
".",
"row",
"]",
")",
";",
"}",
",",
"true",
")",
";",
"return",
"resolvedRows_1",
";",
"}",
"else",
"{",
"return",
"rows",
";",
"}",
"}"
] |
This functions rearrange items by their parents
Also sets the level value to each of the items
Note: Expecting each item has a property called parentId
Note: This algorithm will fail if a list has two or more items with same ID
NOTE: This algorithm will fail if there is a deadlock of relationship
For example,
Input
id -> parent
1 -> 0
2 -> 0
3 -> 1
4 -> 1
5 -> 2
7 -> 8
6 -> 3
Output
id -> level
1 -> 0
--3 -> 1
----6 -> 2
--4 -> 1
2 -> 0
--5 -> 1
7 -> 8
@param rows
|
[
"This",
"functions",
"rearrange",
"items",
"by",
"their",
"parents",
"Also",
"sets",
"the",
"level",
"value",
"to",
"each",
"of",
"the",
"items"
] |
d7df15a070282a169524dba51d9572008b74804c
|
https://github.com/swimlane/ngx-datatable/blob/d7df15a070282a169524dba51d9572008b74804c/release/utils/tree.js#L44-L80
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.