id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
3,200
eslint/eslint
lib/rules/no-extra-parens.js
checkClass
function checkClass(node) { if (!node.superClass) { return; } /* * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. * Otherwise, parentheses are needed. */ const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR ? hasExcessParens(node.superClass) : hasDoubleExcessParens(node.superClass); if (hasExtraParens) { report(node.superClass); } }
javascript
function checkClass(node) { if (!node.superClass) { return; } /* * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. * Otherwise, parentheses are needed. */ const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR ? hasExcessParens(node.superClass) : hasDoubleExcessParens(node.superClass); if (hasExtraParens) { report(node.superClass); } }
[ "function", "checkClass", "(", "node", ")", "{", "if", "(", "!", "node", ".", "superClass", ")", "{", "return", ";", "}", "/*\n * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.\n * Otherwise, parentheses are needed.\n */", "const", "hasExtraParens", "=", "precedence", "(", "node", ".", "superClass", ")", ">", "PRECEDENCE_OF_UPDATE_EXPR", "?", "hasExcessParens", "(", "node", ".", "superClass", ")", ":", "hasDoubleExcessParens", "(", "node", ".", "superClass", ")", ";", "if", "(", "hasExtraParens", ")", "{", "report", "(", "node", ".", "superClass", ")", ";", "}", "}" ]
Check the parentheses around the super class of the given class definition. @param {ASTNode} node The node of class declarations to check. @returns {void}
[ "Check", "the", "parentheses", "around", "the", "super", "class", "of", "the", "given", "class", "definition", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L432-L448
3,201
eslint/eslint
lib/rules/no-extra-parens.js
checkSpreadOperator
function checkSpreadOperator(node) { const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR ? hasExcessParens(node.argument) : hasDoubleExcessParens(node.argument); if (hasExtraParens) { report(node.argument); } }
javascript
function checkSpreadOperator(node) { const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR ? hasExcessParens(node.argument) : hasDoubleExcessParens(node.argument); if (hasExtraParens) { report(node.argument); } }
[ "function", "checkSpreadOperator", "(", "node", ")", "{", "const", "hasExtraParens", "=", "precedence", "(", "node", ".", "argument", ")", ">=", "PRECEDENCE_OF_ASSIGNMENT_EXPR", "?", "hasExcessParens", "(", "node", ".", "argument", ")", ":", "hasDoubleExcessParens", "(", "node", ".", "argument", ")", ";", "if", "(", "hasExtraParens", ")", "{", "report", "(", "node", ".", "argument", ")", ";", "}", "}" ]
Check the parentheses around the argument of the given spread operator. @param {ASTNode} node The node of spread elements/properties to check. @returns {void}
[ "Check", "the", "parentheses", "around", "the", "argument", "of", "the", "given", "spread", "operator", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L455-L463
3,202
eslint/eslint
lib/rules/no-extra-parens.js
checkExpressionOrExportStatement
function checkExpressionOrExportStatement(node) { const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null; if ( astUtils.isOpeningParenToken(firstToken) && ( astUtils.isOpeningBraceToken(secondToken) || secondToken.type === "Keyword" && ( secondToken.value === "function" || secondToken.value === "class" || secondToken.value === "let" && tokenAfterClosingParens && ( astUtils.isOpeningBracketToken(tokenAfterClosingParens) || tokenAfterClosingParens.type === "Identifier" ) ) || secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" ) ) { tokensToIgnore.add(secondToken); } if (hasExcessParens(node)) { report(node); } }
javascript
function checkExpressionOrExportStatement(node) { const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null; if ( astUtils.isOpeningParenToken(firstToken) && ( astUtils.isOpeningBraceToken(secondToken) || secondToken.type === "Keyword" && ( secondToken.value === "function" || secondToken.value === "class" || secondToken.value === "let" && tokenAfterClosingParens && ( astUtils.isOpeningBracketToken(tokenAfterClosingParens) || tokenAfterClosingParens.type === "Identifier" ) ) || secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" ) ) { tokensToIgnore.add(secondToken); } if (hasExcessParens(node)) { report(node); } }
[ "function", "checkExpressionOrExportStatement", "(", "node", ")", "{", "const", "firstToken", "=", "isParenthesised", "(", "node", ")", "?", "sourceCode", ".", "getTokenBefore", "(", "node", ")", ":", "sourceCode", ".", "getFirstToken", "(", "node", ")", ";", "const", "secondToken", "=", "sourceCode", ".", "getTokenAfter", "(", "firstToken", ",", "astUtils", ".", "isNotOpeningParenToken", ")", ";", "const", "thirdToken", "=", "secondToken", "?", "sourceCode", ".", "getTokenAfter", "(", "secondToken", ")", ":", "null", ";", "const", "tokenAfterClosingParens", "=", "secondToken", "?", "sourceCode", ".", "getTokenAfter", "(", "secondToken", ",", "astUtils", ".", "isNotClosingParenToken", ")", ":", "null", ";", "if", "(", "astUtils", ".", "isOpeningParenToken", "(", "firstToken", ")", "&&", "(", "astUtils", ".", "isOpeningBraceToken", "(", "secondToken", ")", "||", "secondToken", ".", "type", "===", "\"Keyword\"", "&&", "(", "secondToken", ".", "value", "===", "\"function\"", "||", "secondToken", ".", "value", "===", "\"class\"", "||", "secondToken", ".", "value", "===", "\"let\"", "&&", "tokenAfterClosingParens", "&&", "(", "astUtils", ".", "isOpeningBracketToken", "(", "tokenAfterClosingParens", ")", "||", "tokenAfterClosingParens", ".", "type", "===", "\"Identifier\"", ")", ")", "||", "secondToken", "&&", "secondToken", ".", "type", "===", "\"Identifier\"", "&&", "secondToken", ".", "value", "===", "\"async\"", "&&", "thirdToken", "&&", "thirdToken", ".", "type", "===", "\"Keyword\"", "&&", "thirdToken", ".", "value", "===", "\"function\"", ")", ")", "{", "tokensToIgnore", ".", "add", "(", "secondToken", ")", ";", "}", "if", "(", "hasExcessParens", "(", "node", ")", ")", "{", "report", "(", "node", ")", ";", "}", "}" ]
Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node @returns {void}
[ "Checks", "the", "parentheses", "for", "an", "ExpressionStatement", "or", "ExportDefaultDeclaration" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L470-L499
3,203
eslint/eslint
lib/rules/no-useless-rename.js
checkDestructured
function checkDestructured(node) { if (ignoreDestructuring) { return; } const properties = node.properties; for (let i = 0; i < properties.length; i++) { if (properties[i].shorthand) { continue; } /** * If an ObjectPattern property is computed, we have no idea * if a rename is useless or not. If an ObjectPattern property * lacks a key, it is likely an ExperimentalRestProperty and * so there is no "renaming" occurring here. */ if (properties[i].computed || !properties[i].key) { continue; } if (properties[i].key.type === "Identifier" && properties[i].key.name === properties[i].value.name || properties[i].key.type === "Literal" && properties[i].key.value === properties[i].value.name) { reportError(properties[i], properties[i].key, properties[i].value, "Destructuring assignment"); } } }
javascript
function checkDestructured(node) { if (ignoreDestructuring) { return; } const properties = node.properties; for (let i = 0; i < properties.length; i++) { if (properties[i].shorthand) { continue; } /** * If an ObjectPattern property is computed, we have no idea * if a rename is useless or not. If an ObjectPattern property * lacks a key, it is likely an ExperimentalRestProperty and * so there is no "renaming" occurring here. */ if (properties[i].computed || !properties[i].key) { continue; } if (properties[i].key.type === "Identifier" && properties[i].key.name === properties[i].value.name || properties[i].key.type === "Literal" && properties[i].key.value === properties[i].value.name) { reportError(properties[i], properties[i].key, properties[i].value, "Destructuring assignment"); } } }
[ "function", "checkDestructured", "(", "node", ")", "{", "if", "(", "ignoreDestructuring", ")", "{", "return", ";", "}", "const", "properties", "=", "node", ".", "properties", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "properties", ".", "length", ";", "i", "++", ")", "{", "if", "(", "properties", "[", "i", "]", ".", "shorthand", ")", "{", "continue", ";", "}", "/**\n * If an ObjectPattern property is computed, we have no idea\n * if a rename is useless or not. If an ObjectPattern property\n * lacks a key, it is likely an ExperimentalRestProperty and\n * so there is no \"renaming\" occurring here.\n */", "if", "(", "properties", "[", "i", "]", ".", "computed", "||", "!", "properties", "[", "i", "]", ".", "key", ")", "{", "continue", ";", "}", "if", "(", "properties", "[", "i", "]", ".", "key", ".", "type", "===", "\"Identifier\"", "&&", "properties", "[", "i", "]", ".", "key", ".", "name", "===", "properties", "[", "i", "]", ".", "value", ".", "name", "||", "properties", "[", "i", "]", ".", "key", ".", "type", "===", "\"Literal\"", "&&", "properties", "[", "i", "]", ".", "key", ".", "value", "===", "properties", "[", "i", "]", ".", "value", ".", "name", ")", "{", "reportError", "(", "properties", "[", "i", "]", ",", "properties", "[", "i", "]", ".", "key", ",", "properties", "[", "i", "]", ".", "value", ",", "\"Destructuring assignment\"", ")", ";", "}", "}", "}" ]
Checks whether a destructured assignment is unnecessarily renamed @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "a", "destructured", "assignment", "is", "unnecessarily", "renamed" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-rename.js#L80-L107
3,204
eslint/eslint
lib/rules/no-useless-rename.js
checkImport
function checkImport(node) { if (ignoreImport) { return; } if (node.imported.name === node.local.name && node.imported.range[0] !== node.local.range[0]) { reportError(node, node.imported, node.local, "Import"); } }
javascript
function checkImport(node) { if (ignoreImport) { return; } if (node.imported.name === node.local.name && node.imported.range[0] !== node.local.range[0]) { reportError(node, node.imported, node.local, "Import"); } }
[ "function", "checkImport", "(", "node", ")", "{", "if", "(", "ignoreImport", ")", "{", "return", ";", "}", "if", "(", "node", ".", "imported", ".", "name", "===", "node", ".", "local", ".", "name", "&&", "node", ".", "imported", ".", "range", "[", "0", "]", "!==", "node", ".", "local", ".", "range", "[", "0", "]", ")", "{", "reportError", "(", "node", ",", "node", ".", "imported", ",", "node", ".", "local", ",", "\"Import\"", ")", ";", "}", "}" ]
Checks whether an import is unnecessarily renamed @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "an", "import", "is", "unnecessarily", "renamed" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-rename.js#L114-L123
3,205
eslint/eslint
lib/rules/no-useless-rename.js
checkExport
function checkExport(node) { if (ignoreExport) { return; } if (node.local.name === node.exported.name && node.local.range[0] !== node.exported.range[0]) { reportError(node, node.local, node.exported, "Export"); } }
javascript
function checkExport(node) { if (ignoreExport) { return; } if (node.local.name === node.exported.name && node.local.range[0] !== node.exported.range[0]) { reportError(node, node.local, node.exported, "Export"); } }
[ "function", "checkExport", "(", "node", ")", "{", "if", "(", "ignoreExport", ")", "{", "return", ";", "}", "if", "(", "node", ".", "local", ".", "name", "===", "node", ".", "exported", ".", "name", "&&", "node", ".", "local", ".", "range", "[", "0", "]", "!==", "node", ".", "exported", ".", "range", "[", "0", "]", ")", "{", "reportError", "(", "node", ",", "node", ".", "local", ",", "node", ".", "exported", ",", "\"Export\"", ")", ";", "}", "}" ]
Checks whether an export is unnecessarily renamed @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "an", "export", "is", "unnecessarily", "renamed" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-rename.js#L130-L140
3,206
eslint/eslint
lib/rules/max-params.js
checkFunction
function checkFunction(node) { if (node.params.length > numParams) { context.report({ loc: astUtils.getFunctionHeadLoc(node, sourceCode), node, messageId: "exceed", data: { name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), count: node.params.length, max: numParams } }); } }
javascript
function checkFunction(node) { if (node.params.length > numParams) { context.report({ loc: astUtils.getFunctionHeadLoc(node, sourceCode), node, messageId: "exceed", data: { name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), count: node.params.length, max: numParams } }); } }
[ "function", "checkFunction", "(", "node", ")", "{", "if", "(", "node", ".", "params", ".", "length", ">", "numParams", ")", "{", "context", ".", "report", "(", "{", "loc", ":", "astUtils", ".", "getFunctionHeadLoc", "(", "node", ",", "sourceCode", ")", ",", "node", ",", "messageId", ":", "\"exceed\"", ",", "data", ":", "{", "name", ":", "lodash", ".", "upperFirst", "(", "astUtils", ".", "getFunctionNameWithKind", "(", "node", ")", ")", ",", "count", ":", "node", ".", "params", ".", "length", ",", "max", ":", "numParams", "}", "}", ")", ";", "}", "}" ]
Checks a function to see if it has too many parameters. @param {ASTNode} node The node to check. @returns {void} @private
[ "Checks", "a", "function", "to", "see", "if", "it", "has", "too", "many", "parameters", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-params.js#L81-L94
3,207
eslint/eslint
lib/rules/spaced-comment.js
reportBegin
function reportBegin(node, message, match, refChar) { const type = node.type.toLowerCase(), commentIdentifier = type === "block" ? "/*" : "//"; context.report({ node, fix(fixer) { const start = node.range[0]; let end = start + 2; if (requireSpace) { if (match) { end += match[0].length; } return fixer.insertTextAfterRange([start, end], " "); } end += match[0].length; return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); }, message, data: { refChar } }); }
javascript
function reportBegin(node, message, match, refChar) { const type = node.type.toLowerCase(), commentIdentifier = type === "block" ? "/*" : "//"; context.report({ node, fix(fixer) { const start = node.range[0]; let end = start + 2; if (requireSpace) { if (match) { end += match[0].length; } return fixer.insertTextAfterRange([start, end], " "); } end += match[0].length; return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); }, message, data: { refChar } }); }
[ "function", "reportBegin", "(", "node", ",", "message", ",", "match", ",", "refChar", ")", "{", "const", "type", "=", "node", ".", "type", ".", "toLowerCase", "(", ")", ",", "commentIdentifier", "=", "type", "===", "\"block\"", "?", "\"/*\"", ":", "\"//\"", ";", "context", ".", "report", "(", "{", "node", ",", "fix", "(", "fixer", ")", "{", "const", "start", "=", "node", ".", "range", "[", "0", "]", ";", "let", "end", "=", "start", "+", "2", ";", "if", "(", "requireSpace", ")", "{", "if", "(", "match", ")", "{", "end", "+=", "match", "[", "0", "]", ".", "length", ";", "}", "return", "fixer", ".", "insertTextAfterRange", "(", "[", "start", ",", "end", "]", ",", "\" \"", ")", ";", "}", "end", "+=", "match", "[", "0", "]", ".", "length", ";", "return", "fixer", ".", "replaceTextRange", "(", "[", "start", ",", "end", "]", ",", "commentIdentifier", "+", "(", "match", "[", "1", "]", "?", "match", "[", "1", "]", ":", "\"\"", ")", ")", ";", "}", ",", "message", ",", "data", ":", "{", "refChar", "}", "}", ")", ";", "}" ]
Reports a beginning spacing error with an appropriate message. @param {ASTNode} node - A comment node to check. @param {string} message - An error message to report. @param {Array} match - An array of match results for markers. @param {string} refChar - Character used for reference in the error message. @returns {void}
[ "Reports", "a", "beginning", "spacing", "error", "with", "an", "appropriate", "message", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/spaced-comment.js#L269-L292
3,208
eslint/eslint
lib/rules/spaced-comment.js
reportEnd
function reportEnd(node, message, match) { context.report({ node, fix(fixer) { if (requireSpace) { return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); } const end = node.range[1] - 2, start = end - match[0].length; return fixer.replaceTextRange([start, end], ""); }, message }); }
javascript
function reportEnd(node, message, match) { context.report({ node, fix(fixer) { if (requireSpace) { return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); } const end = node.range[1] - 2, start = end - match[0].length; return fixer.replaceTextRange([start, end], ""); }, message }); }
[ "function", "reportEnd", "(", "node", ",", "message", ",", "match", ")", "{", "context", ".", "report", "(", "{", "node", ",", "fix", "(", "fixer", ")", "{", "if", "(", "requireSpace", ")", "{", "return", "fixer", ".", "insertTextAfterRange", "(", "[", "node", ".", "range", "[", "0", "]", ",", "node", ".", "range", "[", "1", "]", "-", "2", "]", ",", "\" \"", ")", ";", "}", "const", "end", "=", "node", ".", "range", "[", "1", "]", "-", "2", ",", "start", "=", "end", "-", "match", "[", "0", "]", ".", "length", ";", "return", "fixer", ".", "replaceTextRange", "(", "[", "start", ",", "end", "]", ",", "\"\"", ")", ";", "}", ",", "message", "}", ")", ";", "}" ]
Reports an ending spacing error with an appropriate message. @param {ASTNode} node - A comment node to check. @param {string} message - An error message to report. @param {string} match - An array of the matched whitespace characters. @returns {void}
[ "Reports", "an", "ending", "spacing", "error", "with", "an", "appropriate", "message", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/spaced-comment.js#L301-L316
3,209
eslint/eslint
lib/rules/spaced-comment.js
checkCommentForSpace
function checkCommentForSpace(node) { const type = node.type.toLowerCase(), rule = styleRules[type], commentIdentifier = type === "block" ? "/*" : "//"; // Ignores empty comments. if (node.value.length === 0) { return; } const beginMatch = rule.beginRegex.exec(node.value); const endMatch = rule.endRegex.exec(node.value); // Checks. if (requireSpace) { if (!beginMatch) { const hasMarker = rule.markers.exec(node.value); const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; if (rule.hasExceptions) { reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker); } else { reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker); } } if (balanced && type === "block" && !endMatch) { reportEnd(node, "Expected space or tab before '*/' in comment."); } } else { if (beginMatch) { if (!beginMatch[1]) { reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier); } else { reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]); } } if (balanced && type === "block" && endMatch) { reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch); } } }
javascript
function checkCommentForSpace(node) { const type = node.type.toLowerCase(), rule = styleRules[type], commentIdentifier = type === "block" ? "/*" : "//"; // Ignores empty comments. if (node.value.length === 0) { return; } const beginMatch = rule.beginRegex.exec(node.value); const endMatch = rule.endRegex.exec(node.value); // Checks. if (requireSpace) { if (!beginMatch) { const hasMarker = rule.markers.exec(node.value); const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; if (rule.hasExceptions) { reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker); } else { reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker); } } if (balanced && type === "block" && !endMatch) { reportEnd(node, "Expected space or tab before '*/' in comment."); } } else { if (beginMatch) { if (!beginMatch[1]) { reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier); } else { reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]); } } if (balanced && type === "block" && endMatch) { reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch); } } }
[ "function", "checkCommentForSpace", "(", "node", ")", "{", "const", "type", "=", "node", ".", "type", ".", "toLowerCase", "(", ")", ",", "rule", "=", "styleRules", "[", "type", "]", ",", "commentIdentifier", "=", "type", "===", "\"block\"", "?", "\"/*\"", ":", "\"//\"", ";", "// Ignores empty comments.", "if", "(", "node", ".", "value", ".", "length", "===", "0", ")", "{", "return", ";", "}", "const", "beginMatch", "=", "rule", ".", "beginRegex", ".", "exec", "(", "node", ".", "value", ")", ";", "const", "endMatch", "=", "rule", ".", "endRegex", ".", "exec", "(", "node", ".", "value", ")", ";", "// Checks.", "if", "(", "requireSpace", ")", "{", "if", "(", "!", "beginMatch", ")", "{", "const", "hasMarker", "=", "rule", ".", "markers", ".", "exec", "(", "node", ".", "value", ")", ";", "const", "marker", "=", "hasMarker", "?", "commentIdentifier", "+", "hasMarker", "[", "0", "]", ":", "commentIdentifier", ";", "if", "(", "rule", ".", "hasExceptions", ")", "{", "reportBegin", "(", "node", ",", "\"Expected exception block, space or tab after '{{refChar}}' in comment.\"", ",", "hasMarker", ",", "marker", ")", ";", "}", "else", "{", "reportBegin", "(", "node", ",", "\"Expected space or tab after '{{refChar}}' in comment.\"", ",", "hasMarker", ",", "marker", ")", ";", "}", "}", "if", "(", "balanced", "&&", "type", "===", "\"block\"", "&&", "!", "endMatch", ")", "{", "reportEnd", "(", "node", ",", "\"Expected space or tab before '*/' in comment.\"", ")", ";", "}", "}", "else", "{", "if", "(", "beginMatch", ")", "{", "if", "(", "!", "beginMatch", "[", "1", "]", ")", "{", "reportBegin", "(", "node", ",", "\"Unexpected space or tab after '{{refChar}}' in comment.\"", ",", "beginMatch", ",", "commentIdentifier", ")", ";", "}", "else", "{", "reportBegin", "(", "node", ",", "\"Unexpected space or tab after marker ({{refChar}}) in comment.\"", ",", "beginMatch", ",", "beginMatch", "[", "1", "]", ")", ";", "}", "}", "if", "(", "balanced", "&&", "type", "===", "\"block\"", "&&", "endMatch", ")", "{", "reportEnd", "(", "node", ",", "\"Unexpected space or tab before '*/' in comment.\"", ",", "endMatch", ")", ";", "}", "}", "}" ]
Reports a given comment if it's invalid. @param {ASTNode} node - a comment node to check. @returns {void}
[ "Reports", "a", "given", "comment", "if", "it", "s", "invalid", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/spaced-comment.js#L323-L365
3,210
eslint/eslint
tools/eslint-fuzzer.js
isolateBadConfig
function isolateBadConfig(text, config, problemType) { for (const ruleId of Object.keys(config.rules)) { const reducedConfig = Object.assign({}, config, { rules: { [ruleId]: config.rules[ruleId] } }); let fixResult; try { fixResult = linter.verifyAndFix(text, reducedConfig, {}); } catch (err) { return reducedConfig; } if (fixResult.messages.length === 1 && fixResult.messages[0].fatal && problemType === "autofix") { return reducedConfig; } } return config; }
javascript
function isolateBadConfig(text, config, problemType) { for (const ruleId of Object.keys(config.rules)) { const reducedConfig = Object.assign({}, config, { rules: { [ruleId]: config.rules[ruleId] } }); let fixResult; try { fixResult = linter.verifyAndFix(text, reducedConfig, {}); } catch (err) { return reducedConfig; } if (fixResult.messages.length === 1 && fixResult.messages[0].fatal && problemType === "autofix") { return reducedConfig; } } return config; }
[ "function", "isolateBadConfig", "(", "text", ",", "config", ",", "problemType", ")", "{", "for", "(", "const", "ruleId", "of", "Object", ".", "keys", "(", "config", ".", "rules", ")", ")", "{", "const", "reducedConfig", "=", "Object", ".", "assign", "(", "{", "}", ",", "config", ",", "{", "rules", ":", "{", "[", "ruleId", "]", ":", "config", ".", "rules", "[", "ruleId", "]", "}", "}", ")", ";", "let", "fixResult", ";", "try", "{", "fixResult", "=", "linter", ".", "verifyAndFix", "(", "text", ",", "reducedConfig", ",", "{", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "reducedConfig", ";", "}", "if", "(", "fixResult", ".", "messages", ".", "length", "===", "1", "&&", "fixResult", ".", "messages", "[", "0", "]", ".", "fatal", "&&", "problemType", "===", "\"autofix\"", ")", "{", "return", "reducedConfig", ";", "}", "}", "return", "config", ";", "}" ]
Tries to isolate the smallest config that reproduces a problem @param {string} text The source text to lint @param {Object} config A config object that causes a crash or autofix error @param {("crash"|"autofix")} problemType The type of problem that occurred @returns {Object} A config object with only one rule enabled that produces the same crash or autofix error, if possible. Otherwise, the same as `config`
[ "Tries", "to", "isolate", "the", "smallest", "config", "that", "reproduces", "a", "problem" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/eslint-fuzzer.js#L59-L75
3,211
eslint/eslint
tools/eslint-fuzzer.js
isolateBadAutofixPass
function isolateBadAutofixPass(originalText, config) { let lastGoodText = originalText; let currentText = originalText; do { let messages; try { messages = linter.verify(currentText, config); } catch (err) { return lastGoodText; } if (messages.length === 1 && messages[0].fatal) { return lastGoodText; } lastGoodText = currentText; currentText = SourceCodeFixer.applyFixes(currentText, messages).output; } while (lastGoodText !== currentText); return lastGoodText; }
javascript
function isolateBadAutofixPass(originalText, config) { let lastGoodText = originalText; let currentText = originalText; do { let messages; try { messages = linter.verify(currentText, config); } catch (err) { return lastGoodText; } if (messages.length === 1 && messages[0].fatal) { return lastGoodText; } lastGoodText = currentText; currentText = SourceCodeFixer.applyFixes(currentText, messages).output; } while (lastGoodText !== currentText); return lastGoodText; }
[ "function", "isolateBadAutofixPass", "(", "originalText", ",", "config", ")", "{", "let", "lastGoodText", "=", "originalText", ";", "let", "currentText", "=", "originalText", ";", "do", "{", "let", "messages", ";", "try", "{", "messages", "=", "linter", ".", "verify", "(", "currentText", ",", "config", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "lastGoodText", ";", "}", "if", "(", "messages", ".", "length", "===", "1", "&&", "messages", "[", "0", "]", ".", "fatal", ")", "{", "return", "lastGoodText", ";", "}", "lastGoodText", "=", "currentText", ";", "currentText", "=", "SourceCodeFixer", ".", "applyFixes", "(", "currentText", ",", "messages", ")", ".", "output", ";", "}", "while", "(", "lastGoodText", "!==", "currentText", ")", ";", "return", "lastGoodText", ";", "}" ]
Runs multipass autofix one pass at a time to find the last good source text before a fatal error occurs @param {string} originalText Syntactically valid source code that results in a syntax error or crash when autofixing with `config` @param {Object} config The config to lint with @returns {string} A possibly-modified version of originalText that results in the same syntax error or crash after only one pass
[ "Runs", "multipass", "autofix", "one", "pass", "at", "a", "time", "to", "find", "the", "last", "good", "source", "text", "before", "a", "fatal", "error", "occurs" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/eslint-fuzzer.js#L83-L105
3,212
eslint/eslint
lib/util/path-utils.js
getRelativePath
function getRelativePath(filepath, baseDir) { const absolutePath = path.isAbsolute(filepath) ? filepath : path.resolve(filepath); if (baseDir) { if (!path.isAbsolute(baseDir)) { throw new Error(`baseDir should be an absolute path: ${baseDir}`); } return path.relative(baseDir, absolutePath); } return absolutePath.replace(/^\//u, ""); }
javascript
function getRelativePath(filepath, baseDir) { const absolutePath = path.isAbsolute(filepath) ? filepath : path.resolve(filepath); if (baseDir) { if (!path.isAbsolute(baseDir)) { throw new Error(`baseDir should be an absolute path: ${baseDir}`); } return path.relative(baseDir, absolutePath); } return absolutePath.replace(/^\//u, ""); }
[ "function", "getRelativePath", "(", "filepath", ",", "baseDir", ")", "{", "const", "absolutePath", "=", "path", ".", "isAbsolute", "(", "filepath", ")", "?", "filepath", ":", "path", ".", "resolve", "(", "filepath", ")", ";", "if", "(", "baseDir", ")", "{", "if", "(", "!", "path", ".", "isAbsolute", "(", "baseDir", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "baseDir", "}", "`", ")", ";", "}", "return", "path", ".", "relative", "(", "baseDir", ",", "absolutePath", ")", ";", "}", "return", "absolutePath", ".", "replace", "(", "/", "^\\/", "/", "u", ",", "\"\"", ")", ";", "}" ]
Converts an absolute filepath to a relative path from a given base path For example, if the filepath is `/my/awesome/project/foo.bar`, and the base directory is `/my/awesome/project/`, then this function should return `foo.bar`. path.relative() does something similar, but it requires a baseDir (`from` argument). This function makes it optional and just removes a leading slash if the baseDir is not given. It does not take into account symlinks (for now). @param {string} filepath Path to convert to relative path. If already relative, it will be assumed to be relative to process.cwd(), converted to absolute, and then processed. @param {string} [baseDir] Absolute base directory to resolve the filepath from. If not provided, all this function will do is remove a leading slash. @returns {string} Relative filepath
[ "Converts", "an", "absolute", "filepath", "to", "a", "relative", "path", "from", "a", "given", "base", "path" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/path-utils.js#L50-L63
3,213
eslint/eslint
tools/update-readme.js
formatSponsors
function formatSponsors(sponsors) { const nonEmptySponsors = Object.keys(sponsors).filter(tier => sponsors[tier].length > 0); /* eslint-disable indent*/ return stripIndents`<!--sponsorsstart--> ${ nonEmptySponsors.map(tier => `<h3>${tier[0].toUpperCase()}${tier.slice(1)} Sponsors</h3> <p>${ sponsors[tier].map(sponsor => `<a href="${sponsor.url}"><img src="${sponsor.image}" alt="${sponsor.name}" height="${heights[tier]}"></a>`).join(" ") }</p>`).join("") } <!--sponsorsend-->`; /* eslint-enable indent*/ }
javascript
function formatSponsors(sponsors) { const nonEmptySponsors = Object.keys(sponsors).filter(tier => sponsors[tier].length > 0); /* eslint-disable indent*/ return stripIndents`<!--sponsorsstart--> ${ nonEmptySponsors.map(tier => `<h3>${tier[0].toUpperCase()}${tier.slice(1)} Sponsors</h3> <p>${ sponsors[tier].map(sponsor => `<a href="${sponsor.url}"><img src="${sponsor.image}" alt="${sponsor.name}" height="${heights[tier]}"></a>`).join(" ") }</p>`).join("") } <!--sponsorsend-->`; /* eslint-enable indent*/ }
[ "function", "formatSponsors", "(", "sponsors", ")", "{", "const", "nonEmptySponsors", "=", "Object", ".", "keys", "(", "sponsors", ")", ".", "filter", "(", "tier", "=>", "sponsors", "[", "tier", "]", ".", "length", ">", "0", ")", ";", "/* eslint-disable indent*/", "return", "stripIndents", "`", "${", "nonEmptySponsors", ".", "map", "(", "tier", "=>", "`", "${", "tier", "[", "0", "]", ".", "toUpperCase", "(", ")", "}", "${", "tier", ".", "slice", "(", "1", ")", "}", "${", "sponsors", "[", "tier", "]", ".", "map", "(", "sponsor", "=>", "`", "${", "sponsor", ".", "url", "}", "${", "sponsor", ".", "image", "}", "${", "sponsor", ".", "name", "}", "${", "heights", "[", "tier", "]", "}", "`", ")", ".", "join", "(", "\" \"", ")", "}", "`", ")", ".", "join", "(", "\"\"", ")", "}", "`", ";", "/* eslint-enable indent*/", "}" ]
Formats an array of sponsors into HTML for the readme. @param {Array} sponsors The array of sponsors. @returns {string} The HTML for the readme.
[ "Formats", "an", "array", "of", "sponsors", "into", "HTML", "for", "the", "readme", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/update-readme.js#L69-L82
3,214
eslint/eslint
lib/rules/max-len.js
computeLineLength
function computeLineLength(line, tabWidth) { let extraCharacterCount = 0; line.replace(/\t/gu, (match, offset) => { const totalOffset = offset + extraCharacterCount, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, spaceCount = tabWidth - previousTabStopOffset; extraCharacterCount += spaceCount - 1; // -1 for the replaced tab }); return Array.from(line).length + extraCharacterCount; }
javascript
function computeLineLength(line, tabWidth) { let extraCharacterCount = 0; line.replace(/\t/gu, (match, offset) => { const totalOffset = offset + extraCharacterCount, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, spaceCount = tabWidth - previousTabStopOffset; extraCharacterCount += spaceCount - 1; // -1 for the replaced tab }); return Array.from(line).length + extraCharacterCount; }
[ "function", "computeLineLength", "(", "line", ",", "tabWidth", ")", "{", "let", "extraCharacterCount", "=", "0", ";", "line", ".", "replace", "(", "/", "\\t", "/", "gu", ",", "(", "match", ",", "offset", ")", "=>", "{", "const", "totalOffset", "=", "offset", "+", "extraCharacterCount", ",", "previousTabStopOffset", "=", "tabWidth", "?", "totalOffset", "%", "tabWidth", ":", "0", ",", "spaceCount", "=", "tabWidth", "-", "previousTabStopOffset", ";", "extraCharacterCount", "+=", "spaceCount", "-", "1", ";", "// -1 for the replaced tab", "}", ")", ";", "return", "Array", ".", "from", "(", "line", ")", ".", "length", "+", "extraCharacterCount", ";", "}" ]
Computes the length of a line that may contain tabs. The width of each tab will be the number of spaces to the next tab stop. @param {string} line The line. @param {int} tabWidth The width of each tab stop in spaces. @returns {int} The computed line length. @private
[ "Computes", "the", "length", "of", "a", "line", "that", "may", "contain", "tabs", ".", "The", "width", "of", "each", "tab", "will", "be", "the", "number", "of", "spaces", "to", "the", "next", "tab", "stop", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L110-L121
3,215
eslint/eslint
lib/rules/max-len.js
stripTrailingComment
function stripTrailingComment(line, comment) { // loc.column is zero-indexed return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); }
javascript
function stripTrailingComment(line, comment) { // loc.column is zero-indexed return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); }
[ "function", "stripTrailingComment", "(", "line", ",", "comment", ")", "{", "// loc.column is zero-indexed", "return", "line", ".", "slice", "(", "0", ",", "comment", ".", "loc", ".", "start", ".", "column", ")", ".", "replace", "(", "/", "\\s+$", "/", "u", ",", "\"\"", ")", ";", "}" ]
Gets the line after the comment and any remaining trailing whitespace is stripped. @param {string} line The source line with a trailing comment @param {ASTNode} comment The comment to remove @returns {string} Line without comment and trailing whitepace
[ "Gets", "the", "line", "after", "the", "comment", "and", "any", "remaining", "trailing", "whitespace", "is", "stripped", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L193-L197
3,216
eslint/eslint
lib/rules/max-len.js
groupByLineNumber
function groupByLineNumber(acc, node) { for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) { ensureArrayAndPush(acc, i, node); } return acc; }
javascript
function groupByLineNumber(acc, node) { for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) { ensureArrayAndPush(acc, i, node); } return acc; }
[ "function", "groupByLineNumber", "(", "acc", ",", "node", ")", "{", "for", "(", "let", "i", "=", "node", ".", "loc", ".", "start", ".", "line", ";", "i", "<=", "node", ".", "loc", ".", "end", ".", "line", ";", "++", "i", ")", "{", "ensureArrayAndPush", "(", "acc", ",", "i", ",", "node", ")", ";", "}", "return", "acc", ";", "}" ]
A reducer to group an AST node by line number, both start and end. @param {Object} acc the accumulator @param {ASTNode} node the AST node in question @returns {Object} the modified accumulator @private
[ "A", "reducer", "to", "group", "an", "AST", "node", "by", "line", "number", "both", "start", "and", "end", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L253-L258
3,217
eslint/eslint
lib/rules/max-len.js
checkProgramForMaxLength
function checkProgramForMaxLength(node) { // split (honors line-ending) const lines = sourceCode.lines, // list of comments to ignore comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : []; // we iterate over comments in parallel with the lines let commentsIndex = 0; const strings = getAllStrings(); const stringsByLine = strings.reduce(groupByLineNumber, {}); const templateLiterals = getAllTemplateLiterals(); const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); const regExpLiterals = getAllRegExpLiterals(); const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); lines.forEach((line, i) => { // i is zero-indexed, line numbers are one-indexed const lineNumber = i + 1; /* * if we're checking comment length; we need to know whether this * line is a comment */ let lineIsComment = false; let textToMeasure; /* * We can short-circuit the comment checks if we're already out of * comments to check. */ if (commentsIndex < comments.length) { let comment = null; // iterate over comments until we find one past the current line do { comment = comments[++commentsIndex]; } while (comment && comment.loc.start.line <= lineNumber); // and step back by one comment = comments[--commentsIndex]; if (isFullLineComment(line, lineNumber, comment)) { lineIsComment = true; textToMeasure = line; } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { textToMeasure = stripTrailingComment(line, comment); } else { textToMeasure = line; } } else { textToMeasure = line; } if (ignorePattern && ignorePattern.test(textToMeasure) || ignoreUrls && URL_REGEXP.test(textToMeasure) || ignoreStrings && stringsByLine[lineNumber] || ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] ) { // ignore this line return; } const lineLength = computeLineLength(textToMeasure, tabWidth); const commentLengthApplies = lineIsComment && maxCommentLength; if (lineIsComment && ignoreComments) { return; } if (commentLengthApplies) { if (lineLength > maxCommentLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "maxComment", data: { lineNumber: i + 1, maxCommentLength } }); } } else if (lineLength > maxLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "max", data: { lineNumber: i + 1, maxLength } }); } }); }
javascript
function checkProgramForMaxLength(node) { // split (honors line-ending) const lines = sourceCode.lines, // list of comments to ignore comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : []; // we iterate over comments in parallel with the lines let commentsIndex = 0; const strings = getAllStrings(); const stringsByLine = strings.reduce(groupByLineNumber, {}); const templateLiterals = getAllTemplateLiterals(); const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); const regExpLiterals = getAllRegExpLiterals(); const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); lines.forEach((line, i) => { // i is zero-indexed, line numbers are one-indexed const lineNumber = i + 1; /* * if we're checking comment length; we need to know whether this * line is a comment */ let lineIsComment = false; let textToMeasure; /* * We can short-circuit the comment checks if we're already out of * comments to check. */ if (commentsIndex < comments.length) { let comment = null; // iterate over comments until we find one past the current line do { comment = comments[++commentsIndex]; } while (comment && comment.loc.start.line <= lineNumber); // and step back by one comment = comments[--commentsIndex]; if (isFullLineComment(line, lineNumber, comment)) { lineIsComment = true; textToMeasure = line; } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { textToMeasure = stripTrailingComment(line, comment); } else { textToMeasure = line; } } else { textToMeasure = line; } if (ignorePattern && ignorePattern.test(textToMeasure) || ignoreUrls && URL_REGEXP.test(textToMeasure) || ignoreStrings && stringsByLine[lineNumber] || ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] ) { // ignore this line return; } const lineLength = computeLineLength(textToMeasure, tabWidth); const commentLengthApplies = lineIsComment && maxCommentLength; if (lineIsComment && ignoreComments) { return; } if (commentLengthApplies) { if (lineLength > maxCommentLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "maxComment", data: { lineNumber: i + 1, maxCommentLength } }); } } else if (lineLength > maxLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "max", data: { lineNumber: i + 1, maxLength } }); } }); }
[ "function", "checkProgramForMaxLength", "(", "node", ")", "{", "// split (honors line-ending)", "const", "lines", "=", "sourceCode", ".", "lines", ",", "// list of comments to ignore", "comments", "=", "ignoreComments", "||", "maxCommentLength", "||", "ignoreTrailingComments", "?", "sourceCode", ".", "getAllComments", "(", ")", ":", "[", "]", ";", "// we iterate over comments in parallel with the lines", "let", "commentsIndex", "=", "0", ";", "const", "strings", "=", "getAllStrings", "(", ")", ";", "const", "stringsByLine", "=", "strings", ".", "reduce", "(", "groupByLineNumber", ",", "{", "}", ")", ";", "const", "templateLiterals", "=", "getAllTemplateLiterals", "(", ")", ";", "const", "templateLiteralsByLine", "=", "templateLiterals", ".", "reduce", "(", "groupByLineNumber", ",", "{", "}", ")", ";", "const", "regExpLiterals", "=", "getAllRegExpLiterals", "(", ")", ";", "const", "regExpLiteralsByLine", "=", "regExpLiterals", ".", "reduce", "(", "groupByLineNumber", ",", "{", "}", ")", ";", "lines", ".", "forEach", "(", "(", "line", ",", "i", ")", "=>", "{", "// i is zero-indexed, line numbers are one-indexed", "const", "lineNumber", "=", "i", "+", "1", ";", "/*\n * if we're checking comment length; we need to know whether this\n * line is a comment\n */", "let", "lineIsComment", "=", "false", ";", "let", "textToMeasure", ";", "/*\n * We can short-circuit the comment checks if we're already out of\n * comments to check.\n */", "if", "(", "commentsIndex", "<", "comments", ".", "length", ")", "{", "let", "comment", "=", "null", ";", "// iterate over comments until we find one past the current line", "do", "{", "comment", "=", "comments", "[", "++", "commentsIndex", "]", ";", "}", "while", "(", "comment", "&&", "comment", ".", "loc", ".", "start", ".", "line", "<=", "lineNumber", ")", ";", "// and step back by one", "comment", "=", "comments", "[", "--", "commentsIndex", "]", ";", "if", "(", "isFullLineComment", "(", "line", ",", "lineNumber", ",", "comment", ")", ")", "{", "lineIsComment", "=", "true", ";", "textToMeasure", "=", "line", ";", "}", "else", "if", "(", "ignoreTrailingComments", "&&", "isTrailingComment", "(", "line", ",", "lineNumber", ",", "comment", ")", ")", "{", "textToMeasure", "=", "stripTrailingComment", "(", "line", ",", "comment", ")", ";", "}", "else", "{", "textToMeasure", "=", "line", ";", "}", "}", "else", "{", "textToMeasure", "=", "line", ";", "}", "if", "(", "ignorePattern", "&&", "ignorePattern", ".", "test", "(", "textToMeasure", ")", "||", "ignoreUrls", "&&", "URL_REGEXP", ".", "test", "(", "textToMeasure", ")", "||", "ignoreStrings", "&&", "stringsByLine", "[", "lineNumber", "]", "||", "ignoreTemplateLiterals", "&&", "templateLiteralsByLine", "[", "lineNumber", "]", "||", "ignoreRegExpLiterals", "&&", "regExpLiteralsByLine", "[", "lineNumber", "]", ")", "{", "// ignore this line", "return", ";", "}", "const", "lineLength", "=", "computeLineLength", "(", "textToMeasure", ",", "tabWidth", ")", ";", "const", "commentLengthApplies", "=", "lineIsComment", "&&", "maxCommentLength", ";", "if", "(", "lineIsComment", "&&", "ignoreComments", ")", "{", "return", ";", "}", "if", "(", "commentLengthApplies", ")", "{", "if", "(", "lineLength", ">", "maxCommentLength", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "{", "line", ":", "lineNumber", ",", "column", ":", "0", "}", ",", "messageId", ":", "\"maxComment\"", ",", "data", ":", "{", "lineNumber", ":", "i", "+", "1", ",", "maxCommentLength", "}", "}", ")", ";", "}", "}", "else", "if", "(", "lineLength", ">", "maxLength", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "{", "line", ":", "lineNumber", ",", "column", ":", "0", "}", ",", "messageId", ":", "\"max\"", ",", "data", ":", "{", "lineNumber", ":", "i", "+", "1", ",", "maxLength", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Check the program for max length @param {ASTNode} node Node to examine @returns {void} @private
[ "Check", "the", "program", "for", "max", "length" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L266-L366
3,218
eslint/eslint
lib/rules/no-eval.js
isConstant
function isConstant(node, name) { switch (node.type) { case "Literal": return node.value === name; case "TemplateLiteral": return ( node.expressions.length === 0 && node.quasis[0].value.cooked === name ); default: return false; } }
javascript
function isConstant(node, name) { switch (node.type) { case "Literal": return node.value === name; case "TemplateLiteral": return ( node.expressions.length === 0 && node.quasis[0].value.cooked === name ); default: return false; } }
[ "function", "isConstant", "(", "node", ",", "name", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "\"Literal\"", ":", "return", "node", ".", "value", "===", "name", ";", "case", "\"TemplateLiteral\"", ":", "return", "(", "node", ".", "expressions", ".", "length", "===", "0", "&&", "node", ".", "quasis", "[", "0", "]", ".", "value", ".", "cooked", "===", "name", ")", ";", "default", ":", "return", "false", ";", "}", "}" ]
Checks a given node is a Literal node of the specified string value. @param {ASTNode} node - A node to check. @param {string} name - A name to check. @returns {boolean} `true` if the node is a Literal node of the name.
[ "Checks", "a", "given", "node", "is", "a", "Literal", "node", "of", "the", "specified", "string", "value", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-eval.js#L41-L55
3,219
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
3,220
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", ";", "// To detect code like `window.window.eval`.", "while", "(", "isMember", "(", "node", ",", "name", ")", ")", "{", "node", "=", "node", ".", "parent", ";", "}", "// Reports.", "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
3,221
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
3,222
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
3,223
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
3,224
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", ")", ";", "}", ")", ";", "// 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", "]", ")", ";", "}" ]
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
3,225
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
3,226
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
3,227
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
3,228
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", ")", "{", "// 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", ")", ";", "}" ]
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
3,229
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", "(", "// Don't include youtube's uid values, they change\ton reload", "!", "id", ".", "match", "(", "/", "player_uid_", "/", ")", "&&", "// Don't include IDs that occur more then once on the page", "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
3,230
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
3,231
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
3,232
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", ")", "{", "/*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", ";", "/**\n\t * Try to find a unique selector by filtering out all the clashing\n\t * nodes by adding ancestor selectors iteratively.\n\t * This loop is much faster than recursing and using querySelectorAll\n\t */", "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'", ";", "}" ]
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
3,233
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", ":", "[", "]", ";", "// 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", ";", "}", "}" ]
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
3,234
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
3,235
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
3,236
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", ")", "{", "// 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", ";", "}" ]
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
3,237
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
3,238
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
3,239
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", "(", "// 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", ";", "}" ]
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
3,240
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
3,241
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", ")", "{", "// 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", ";", "}" ]
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
3,242
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", ")", "{", "// 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", ";", "}" ]
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
3,243
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
3,244
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
3,245
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
3,246
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", "''", ";", "}", "// 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'", ";", "}" ]
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
3,247
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
3,248
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
3,249
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
3,250
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
3,251
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
3,252
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", "}", "\\`", "`", ";", "}", "/**\n\t\t\t\t\t * if element is not a string it will be an object with structure:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnodeName: string,\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\ttype: {string|string[]}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t*/", "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", ";", "}" ]
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
3,253
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", "(", "// 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", ")", ";", "}" ]
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
3,254
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", "}", ";", "}", "/**\n\t * When `aria-labelledby` directly references a `hidden` element\n\t * the element needs to be included in the accessible name.\n\t *\n\t * When a descendent of the `aria-labelledby` reference is `hidden`\n\t * the element should not be included in the accessible name.\n\t *\n\t * This is done by setting `includeHidden` for the `aria-labelledby` reference.\n\t */", "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
3,255
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
3,256
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
3,257
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", "(", "// 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", "}", ";", "}", "}" ]
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
3,258
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
3,259
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
3,260
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
3,261
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
3,262
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", ")", ";", "}", "// 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", ";", "}", ")", ";", "}" ]
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
3,263
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", ";", "// 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", "}", "}" ]
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
3,264
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
3,265
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", "(", "// 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", ";", "}" ]
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
3,266
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
3,267
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
3,268
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
3,269
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
3,270
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'", "+", "error", ".", "stack", ".", "replace", "(", "error", ".", "message", ",", "''", ")", ";", "}", "return", "new", "ErrConstructor", "(", "msg", ")", ";", "}" ]
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
3,271
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", ")", "{", "/*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", ";", "}" ]
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
3,272
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
3,273
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
3,274
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", "(", ")", ";", "/**\n\t * `sheet.cssRules` throws an error on `cross-origin` stylesheets\n\t */", "const", "cssRules", "=", "sheet", ".", "cssRules", ";", "const", "rules", "=", "Array", ".", "from", "(", "cssRules", ")", ";", "if", "(", "!", "rules", ")", "{", "return", "q", ";", "}", "/**\n\t * reference -> https://developer.mozilla.org/en-US/docs/Web/API/CSSRule#Type_constants\n\t */", "const", "cssImportRules", "=", "rules", ".", "filter", "(", "r", "=>", "r", ".", "type", "===", "3", ")", ";", "// type === 3 -> CSSRule.IMPORT_RULE", "/**\n\t * when no `@import` rules in given sheet\n\t * -> resolve the current `sheet` & exit\n\t */", "if", "(", "!", "cssImportRules", ".", "length", ")", "{", "q", ".", "defer", "(", "resolve", "=>", "resolve", "(", "{", "isExternal", ":", "false", ",", "priority", ",", "root", ":", "options", ".", "rootNode", ",", "shadowId", ":", "options", ".", "shadowId", ",", "sheet", "}", ")", ")", ";", "// exit", "return", "q", ";", "}", "/**\n\t * iterate `@import` rules and fetch styles\n\t */", "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", ";", "}" ]
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
3,275
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
3,276
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", ")", "// 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", ";", "}", ",", "[", "]", ")", ")", ";", "}" ]
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
3,277
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
3,278
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", ")", "{", "// 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", ";", "}", ")", ";", "}" ]
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
3,279
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
3,280
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", ")", ",", "}", ",", "}", ",", "{", "// 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", ")", "}", "`", ")", ";", "}", ",", "}", ")", ";", "console", ".", "log", "(", "'\\n\\n'", ")", ";", "console", ".", "log", "(", "res", ".", "data", ")", ";", "return", "res", ".", "data", ";", "}" ]
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
3,281
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", "(", ")", "{", "// the first query will return data with an etag", "const", "res", "=", "await", "getPlaylistData", "(", "null", ")", ";", "const", "etag", "=", "res", ".", "data", ".", "etag", ";", "console", ".", "log", "(", "`", "${", "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", ")", ";", "}" ]
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
3,282
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
3,283
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", "(", ")", "{", "// 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", ";", "}" ]
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
3,284
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", "(", ")", "{", "// 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", ")", ";", "}" ]
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
3,285
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
3,286
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", ")", ";", "// 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", "(", ")", ";", "}" ]
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
3,287
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
3,288
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
3,289
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", ")", "{", "// 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", ";", "}" ]
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
3,290
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", ":", "{", "}", "// 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", "}" ]
data remove data field
[ "data", "remove", "data", "field" ]
ad2051b65e2243cfd953d8b24a8bf95bfa8559e5
https://github.com/cytoscape/cytoscape.js/blob/ad2051b65e2243cfd953d8b24a8bf95bfa8559e5/dist/cytoscape.esm.js#L6107-L6174
3,291
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", ";", "// we've consumed one expr, so we can return now", "}", "}", "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
3,292
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
3,293
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", ")", ";", "// 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", "}" ]
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
3,294
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
3,295
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
3,296
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
3,297
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", "{", "// replace", "var", "_index", "=", "map", ".", "get", "(", "id", ")", ".", "index", ";", "this", "[", "_index", "]", "=", "toAddEle", ";", "map", ".", "set", "(", "id", ",", "{", "ele", ":", "toAddEle", ",", "index", ":", "_index", "}", ")", ";", "}", "}", "return", "this", ";", "// chaining", "}" ]
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
3,298
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", ";", "// no need to remove", "}", "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
3,299
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", ";", "// chaining", "}" ]
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