Best JavaScript code snippet using playwright-internal
RelationshipSetter.js
Source:RelationshipSetter.js
1(function() {2 Firecrow.RelationshipSetter = function()3 {4 this._currentBranchingConstruct = null;5 };6 Firecrow.RelationshipSetter.prototype =7 {8 traverseHtmlElement: function(htmlElement, parent)9 {10 this.establishParentChildRelationshipAndSetChildId(htmlElement, parent);11 var childNodes = htmlElement.childNodes;12 for(var i = 0; i < childNodes.length; i++)13 {14 this.traverseHtmlElement(childNodes[i], htmlElement);15 }16 if (htmlElement.cssModel != null)17 {18 this.traverseCssModel(htmlElement.cssModel, htmlElement);19 }20 if (htmlElement.pathAndModel != null)21 {22 this.traverseProgram(htmlElement.pathAndModel.model, htmlElement);23 }24 },25 NODE_ID: 0,26 traverseProgram: function(program, htmlElement)27 {28 this.establishParentChildRelationshipAndSetChildId(program, htmlElement);29 var body = program.body;30 for (var i = 0; i < body.length; i++)31 {32 this.traverseStatement(body[i], program);33 }34 },35 traverseStatement: function(statement, parent)36 {37 if (statement == null) { return; }38 this.establishParentChildRelationshipAndSetChildId(statement, parent);39 switch (statement.type)40 {41 case "BlockStatement":42 this.traverseBlockStatement(statement);43 break;44 case "BreakStatement":45 this.traverseBreakStatement(statement);46 break;47 case "ContinueStatement":48 this.traverseContinueStatement(statement);49 break;50 case "DebuggerStatement":51 this.traverseDebuggerStatement(statement);52 break;53 case "DoWhileStatement":54 this.traverseDoWhileStatement(statement);55 break;56 case "EmptyStatement":57 this.traverseEmptyStatement(statement);58 break;59 case "ExpressionStatement":60 this.traverseExpressionStatement(statement);61 break;62 case "ForInStatement":63 this.traverseForInStatement(statement);64 break;65 case "ForOfStatement":66 this.traverseForOfStatement(statement);67 break;68 case "ForStatement":69 this.traverseForStatement(statement);70 break;71 case "WhileStatement":72 this.traverseWhileStatement(statement);73 break;74 case "IfStatement":75 this.traverseIfStatement(statement);76 break;77 case "LabeledStatement":78 this.traverseLabeledStatement(statement);79 break;80 case "LetStatement":81 this.traverseLetStatement(statement);82 break;83 case "ReturnStatement":84 this.traverseReturnStatement(statement);85 break;86 case "SwitchStatement":87 this.traverseSwitchStatement(statement);88 break;89 case "ThrowStatement":90 this.traverseThrowStatement(statement);91 break;92 case "TryStatement":93 this.traverseTryStatement(statement);94 break;95 case "WithStatement":96 this.traverseWithStatement(statement);97 break;98 case "FunctionDeclaration":99 this.traverseFunctionDeclaration(statement);100 break;101 case "VariableDeclaration":102 this.traverseVariableDeclaration(statement);103 break;104 default:105 alert("Can not recognized statement");106 }107 },108 traverseVariableDeclaration: function(variableDeclaration)109 {110 var declarations = variableDeclaration.declarations;111 for(var i = 0; i < declarations.length; i++)112 {113 var variableDeclarator = declarations[i];114 this.establishParentChildRelationshipAndSetChildId(variableDeclarator, variableDeclaration);115 this.traverseExpression(variableDeclarator.id, variableDeclarator);116 this.traverseExpression(variableDeclarator.init, variableDeclarator);117 }118 },119 traverseTryStatement: function(tryStatement)120 {121 this.traverseStatement(tryStatement.block, tryStatement);122 this.traverseCatch(tryStatement.handler, tryStatement);123 this.traverseStatement(tryStatement.finalizer, tryStatement);124 },125 traverseCatch: function(catchClause, tryStatement)126 {127 this.establishParentChildRelationshipAndSetChildId(catchClause, tryStatement);128 this.traverseExpression(catchClause.param, catchClause);129 var oldBranchingConstruct = this._currentBranchingConstruct;130 this._currentBranchingConstruct = catchClause;131 this.traverseStatement(catchClause.body, catchClause);132 this._currentBranchingConstruct = oldBranchingConstruct;133 },134 traverseFunctionDeclaration: function(functionDeclaration)135 {136 var parameters = functionDeclaration.params;137 for(var i = 0; i < parameters.length; i++)138 {139 this.traverseExpression(parameters[i], functionDeclaration);140 }141 this.traverseExpression(functionDeclaration.rest, functionDeclaration);142 var oldBranchingConstruct = this._currentBranchingConstruct;143 this._currentBranchingConstruct = functionDeclaration;144 this.traverseStatement(functionDeclaration.body, functionDeclaration);145 this._currentBranchingConstruct = oldBranchingConstruct;146 },147 traverseWithStatement: function(withStatement)148 {149 this.traverseExpression(withStatement.object, withStatement);150 var oldBranchingConstruct = this._currentBranchingConstruct;151 this._currentBranchingConstruct = withStatement;152 this.traverseStatement(withStatement.body, withStatement);153 this._currentBranchingConstruct = oldBranchingConstruct;154 },155 traverseThrowStatement: function(throwStatement)156 {157 this.traverseExpression(throwStatement.argument, throwStatement);158 },159 traverseSwitchStatement: function(switchStatement)160 {161 var oldBranchingConstruct = this._currentBranchingConstruct;162 this._currentBranchingConstruct = switchStatement;163 this.traverseExpression(switchStatement.discriminant, switchStatement);164 var areAllTestsNumbers = true;165 var cases = switchStatement.cases;166 for(var i = 0; i < cases.Count; i++)167 {168 var switchCase = cases[i];169 this.traverseCase(switchCase, switchStatement, i);170 if (switchCase.test != null && !_IsNumeric(switchCase.test))171 {172 areAllTestsNumbers = false;173 }174 }175 switchStatement.areAllTestsNumbers = areAllTestsNumbers;176 this._currentBranchingConstruct = oldBranchingConstruct;177 },178 traverseCase: function(switchCase, switchStatement, index)179 {180 this.establishParentChildRelationshipAndSetChildId(switchCase, switchStatement);181 switchCase.index = index;182 this.traverseExpression(switchCase.test, switchCase);183 var oldBranchingConstruct;184 if(switchCase.test != null)185 {186 oldBranchingConstruct = this._currentBranchingConstruct;187 this._currentBranchingConstruct = switchCase;188 }189 var consequent = switchCase.consequent;190 for(var i = 0; i < consequent.length; i++)191 {192 this.traverseStatement(consequent[i], switchCase);193 }194 if(switchCase.test != null)195 {196 this._currentBranchingConstruct = oldBranchingConstruct;197 }198 },199 traverseReturnStatement: function(returnStatement)200 {201 this.traverseExpression(returnStatement.argument, returnStatement);202 },203 traverseLetStatement: function(letStatement)204 {205 var head = letStatement.head;206 for(var i = 0; i < head.length; i++)207 {208 var item = head[i];209 this.establishParentChildRelationshipAndSetChildId(item, letStatement);210 this.traverseExpression(item.id, head);211 this.traverseExpression(item.init, head);212 }213 this.traverseStatement(letStatement.body, letStatement);214 },215 traverseLabeledStatement: function(labeledStatement)216 {217 this.traverseExpression(labeledStatement.label, labeledStatement);218 },219 traverseIfStatement: function(ifStatement)220 {221 this.traverseExpression(ifStatement.test, ifStatement);222 var oldBranchingConstruct = this._currentBranchingConstruct;223 this._currentBranchingConstruct = ifStatement;224 this.traverseStatement(ifStatement.consequent, ifStatement);225 this.traverseStatement(ifStatement.alternate, ifStatement);226 this._currentBranchingConstruct = oldBranchingConstruct;227 },228 traverseWhileStatement: function(whileStatement)229 {230 this.traverseExpression(whileStatement.test, whileStatement);231 var oldBranchingConstruct = this._currentBranchingConstruct;232 this._currentBranchingConstruct = whileStatement;233 this.traverseStatement(whileStatement.body, whileStatement);234 this._currentBranchingConstruct = oldBranchingConstruct;235 },236 traverseForStatement: function(forStatement)237 {238 this.traverseVarDeclarationExpression(forStatement.init, forStatement);239 this.traverseExpression(forStatement.test, forStatement);240 this.traverseExpression(forStatement.update, forStatement);241 var oldBranchingConstruct = this._currentBranchingConstruct;242 this._currentBranchingConstruct = forStatement;243 this.traverseStatement(forStatement.body, forStatement);244 this._currentBranchingConstruct = oldBranchingConstruct;245 },246 traverseForOfStatement: function(forOfStatement)247 {248 this.traverseVarDeclarationExpression(forOfStatement.left, forOfStatement);249 this.traverseExpression(forOfStatement.right, forOfStatement);250 var oldBranchingConstruct = this._currentBranchingConstruct;251 this._currentBranchingConstruct = forOfStatement;252 this.traverseStatement(forOfStatement.body, forOfStatement);253 this._currentBranchingConstruct = oldBranchingConstruct;254 },255 traverseForInStatement: function(forInStatement)256 {257 this.traverseVarDeclarationExpression(forInStatement.left, forInStatement);258 this.traverseExpression(forInStatement.right, forInStatement);259 var oldBranchingConstruct = this._currentBranchingConstruct;260 this._currentBranchingConstruct = forInStatement;261 this.traverseStatement(forInStatement.body, forInStatement);262 this._currentBranchingConstruct = oldBranchingConstruct;263 },264 traverseVarDeclarationExpression: function(node, parent)265 {266 node.type == "VariableDeclaration" ? this.traverseStatement(node, parent)267 : this.traverseExpression(node, parent);268 },269 traverseExpressionStatement: function(expressionStatement)270 {271 this.traverseExpression(expressionStatement.expression, expressionStatement);272 },273 traverseEmptyStatement: function(emptyStatement) { },274 traverseDoWhileStatement: function(doWhileStatement)275 {276 var oldBranchingConstruct = this._currentBranchingConstruct;277 this._currentBranchingConstruct = doWhileStatement;278 this.traverseStatement(doWhileStatement.body, doWhileStatement);279 this._currentBranchingConstruct = oldBranchingConstruct;280 this.traverseExpression(doWhileStatement.test, doWhileStatement);281 },282 traverseDebuggerStatement: function(debuggerStatement) { },283 traverseContinueStatement: function(continueStatement)284 {285 this.traverseExpression(continueStatement.label, continueStatement);286 },287 traverseBreakStatement: function(breakStatement)288 {289 this.traverseExpression(breakStatement.label, breakStatement);290 },291 traverseBlockStatement: function(statement)292 {293 var body = statement.body;294 for(var i = 0; i < body.length; i++)295 {296 this.traverseStatement(body[i], statement);297 }298 },299 traverseExpression: function(expression, parent)300 {301 if (expression == null) { return; }302 this.establishParentChildRelationshipAndSetChildId(expression, parent);303 switch (expression.type)304 {305 case "ThisExpression":306 break;307 case "ArrayExpression":308 this.traverseArrayExpression(expression);309 break;310 case "ObjectExpression":311 this.traverseObjectExpression(expression);312 break;313 case "FunctionExpression":314 this.traverseFunctionDeclaration(expression);315 break;316 case "ArrowExpression":317 alert("ArrowExpression not yet implemented!");318 break;319 case "SequenceExpression":320 this.traverseSequenceExpression(expression);321 break;322 case "UnaryExpression":323 this.traverseUnaryExpression(expression);324 break;325 case "BinaryExpression":326 this.traverseBinaryExpression(expression);327 break;328 case "LogicalExpression":329 this.traverseLogicalExpression(expression);330 break;331 case "AssignmentExpression":332 this.traverseAssignmentExpression(expression);333 break;334 case "UpdateExpression":335 this.traverseUpdateExpression(expression);336 break;337 case "ConditionalExpression":338 this.traverseConditionalExpression(expression);339 break;340 case "CallExpression":341 this.traverseCallExpression(expression);342 break;343 case "MemberExpression":344 this.traverseMemberExpression(expression);345 break;346 case "YieldExpression":347 this.traverseYieldExpression(expression);348 break;349 case "ComprehensionExpression":350 this.traverseComprehensionExpression(expression);351 break;352 case "Identifier":353 this.traverseIdentifier(expression);354 break;355 case "Literal":356 this.traverseLiteral(expression);357 break;358 default:359 alert("Unknown expression!");360 }361 },362 traverseLiteral: function(literal)363 {364 if(Firecrow.ASTHelper.isMemberExpression(literal.parent))365 {366 var memberExpression = literal.parent;367 if(memberExpression.property == literal)368 {369 literal.isMemberExpressionProperty = true;370 if(Firecrow.ASTHelper.isAssignmentExpression(memberExpression.parent))371 {372 literal.isAssignProperty = (memberExpression.parent).left == memberExpression;373 }374 }375 }376 },377 traverseIdentifier: function(identifier)378 {379 if(Firecrow.ASTHelper.isMemberExpression(identifier.parent))380 {381 var memberExpression = identifier.parent;382 if(memberExpression.property == identifier)383 {384 identifier.isMemberExpressionProperty = true;385 if(Firecrow.ASTHelper.isAssignmentExpression(memberExpression.parent))386 {387 identifier.isAssignProperty = memberExpression.parent.left == memberExpression;388 }389 }390 }391 },392 traverseArrayExpression: function(arrayExpression)393 {394 var elements = arrayExpression.elements;395 for (var i = 0; i < elements.length; i++)396 {397 this.traverseExpression(elements[i], arrayExpression);398 }399 },400 traverseObjectExpression: function(objectExpression)401 {402 var properties = objectExpression.properties;403 for(var i = 0; i < properties.length; i++)404 {405 var property = properties[i];406 this.establishParentChildRelationshipAndSetChildId(property, objectExpression);407 this.traverseExpression(property.key, property);408 this.traverseExpression(property.value, property);409 }410 },411 traverseSequenceExpression: function(sequenceExpression)412 {413 var expressions = sequenceExpression.expressions;414 for(var i = 0; i < expressions.length; i++)415 {416 this.traverseExpression(expressions[i], sequenceExpression);417 }418 },419 traverseUnaryExpression: function(unaryExpression)420 {421 this.traverseExpression(unaryExpression.argument, unaryExpression);422 },423 traverseBinaryExpression: function(binaryExpression)424 {425 this.traverseExpression(binaryExpression.left, binaryExpression);426 this.traverseExpression(binaryExpression.right, binaryExpression);427 },428 traverseLogicalExpression: function(logicalExpression)429 {430 this.traverseExpression(logicalExpression.left, logicalExpression);431 this.traverseExpression(logicalExpression.right, logicalExpression);432 },433 traverseAssignmentExpression: function(assignmentExpression)434 {435 this.traverseExpression(assignmentExpression.right, assignmentExpression);436 this.traverseExpression(assignmentExpression.left, assignmentExpression);437 },438 traverseUpdateExpression: function(updateExpression)439 {440 this.traverseExpression(updateExpression.argument, updateExpression);441 },442 traverseConditionalExpression: function(conditionalExpression)443 {444 this.traverseExpression(conditionalExpression.test, conditionalExpression);445 var oldBranchingConstruct = this._currentBranchingConstruct;446 this._currentBranchingConstruct = conditionalExpression;447 this.traverseExpression(conditionalExpression.consequent, conditionalExpression);448 this.traverseExpression(conditionalExpression.alternate, conditionalExpression);449 this._currentBranchingConstruct = oldBranchingConstruct;450 },451 traverseCallExpression: function(callExpression)452 {453 this.traverseExpression(callExpression.callee, callExpression);454 var args = callExpression.arguments;455 for(var i = 0; i < args.length; i++)456 {457 this.traverseExpression(args[i], callExpression);458 }459 },460 traverseMemberExpression: function(memberExpression)461 {462 this.traverseExpression(memberExpression.object, memberExpression);463 this.traverseExpression(memberExpression.property, memberExpression);464 memberExpression.isAssignLeftHand = Firecrow.ASTHelper.isAssignmentExpression(memberExpression.parent)465 && memberExpression.parent.left == memberExpression;466 },467 traverseCssModel: function(cssModel, htmlElement)468 {469 this.establishParentChildRelationshipAndSetChildId(cssModel, htmlElement);470 var rules = cssModel.rules;471 for(var i = 0; i < rules.length; i++)472 {473 this.establishParentChildRelationshipAndSetChildId(rules[i], cssModel);474 }475 },476 establishParentChildRelationshipAndSetChildId: function(child, parent)477 {478 if(child == null) { return; }479 child.parent = parent;480 child.children = [];481 child.parentBranching = this._currentBranchingConstruct;482 child.nodeId = this.NODE_ID++;483 if(parent != null) { parent.children.push(child); }484 }485 };...
traverse_content.js
Source:traverse_content.js
1// Copyright 2014 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4/**5 * @fileoverview A DOM traversal interface for moving a selection around a6 * webpage. Provides multiple granularities:7 * 1. Move by paragraph.8 * 2. Move by sentence.9 * 3. Move by line.10 * 4. Move by word.11 * 5. Move by character.12 */13goog.provide('cvox.TraverseContent');14goog.require('cvox.CursorSelection');15goog.require('cvox.DomUtil');16goog.require('cvox.SelectionUtil');17goog.require('cvox.TraverseUtil');18/**19 * Moves a selection around a document or within a provided DOM object.20 *21 * @constructor22 * @param {Node=} domObj a DOM node (optional).23 */24cvox.TraverseContent = function(domObj) {25 if (domObj != null) {26 this.currentDomObj = domObj;27 } else {28 this.currentDomObj = document.body;29 }30 var range = document.createRange();31 // TODO (dmazzoni): Switch this to avoid using range methods. Range methods32 // can cause exceptions (such as if the node is not attached to the DOM).33 try {34 range.selectNode(this.currentDomObj);35 this.startCursor_ = new cvox.Cursor(36 range.startContainer, range.startOffset,37 cvox.TraverseUtil.getNodeText(range.startContainer));38 this.endCursor_ = new cvox.Cursor(39 range.endContainer, range.endOffset,40 cvox.TraverseUtil.getNodeText(range.endContainer));41 } catch (e) {42 // Ignoring this error so that it will not break everything else.43 window.console.log('Error: Unselectable node:');44 window.console.log(domObj);45 }46};47goog.addSingletonGetter(cvox.TraverseContent);48/**49 * Whether the last navigated selection only contained whitespace.50 * @type {boolean}51 */52cvox.TraverseContent.prototype.lastSelectionWasWhitespace = false;53/**54 * Whether we should skip whitespace when traversing individual characters.55 * @type {boolean}56 */57cvox.TraverseContent.prototype.skipWhitespace = false;58/**59 * If moveNext and movePrev should skip past an invalid selection,60 * so the user never gets stuck. Ideally the navigation code should never61 * return a range that's not a valid selection, but this keeps the user from62 * getting stuck if that code fails. This is set to false for unit testing.63 * @type {boolean}64 */65cvox.TraverseContent.prototype.skipInvalidSelections = true;66/**67 * If line and sentence navigation should break at <a> links.68 * @type {boolean}69 */70cvox.TraverseContent.prototype.breakAtLinks = true;71/**72 * The string constant for character granularity.73 * @type {string}74 * @const75 */76cvox.TraverseContent.kCharacter = 'character';77/**78 * The string constant for word granularity.79 * @type {string}80 * @const81 */82cvox.TraverseContent.kWord = 'word';83/**84 * The string constant for sentence granularity.85 * @type {string}86 * @const87 */88cvox.TraverseContent.kSentence = 'sentence';89/**90 * The string constant for line granularity.91 * @type {string}92 * @const93 */94cvox.TraverseContent.kLine = 'line';95/**96 * The string constant for paragraph granularity.97 * @type {string}98 * @const99 */100cvox.TraverseContent.kParagraph = 'paragraph';101/**102 * A constant array of all granularities.103 * @type {Array<string>}104 * @const105 */106cvox.TraverseContent.kAllGrains =107 [cvox.TraverseContent.kParagraph,108 cvox.TraverseContent.kSentence,109 cvox.TraverseContent.kLine,110 cvox.TraverseContent.kWord,111 cvox.TraverseContent.kCharacter];112/**113 * Set the current position to match the current WebKit selection.114 */115cvox.TraverseContent.prototype.syncToSelection = function() {116 this.normalizeSelection();117 var selection = window.getSelection();118 if (!selection || !selection.anchorNode || !selection.focusNode) {119 return;120 }121 this.startCursor_ = new cvox.Cursor(122 selection.anchorNode, selection.anchorOffset,123 cvox.TraverseUtil.getNodeText(selection.anchorNode));124 this.endCursor_ = new cvox.Cursor(125 selection.focusNode, selection.focusOffset,126 cvox.TraverseUtil.getNodeText(selection.focusNode));127};128/**129 * Set the start and end cursors to the selection.130 * @param {cvox.CursorSelection} sel The selection.131 */132cvox.TraverseContent.prototype.syncToCursorSelection = function(sel) {133 this.startCursor_ = sel.start.clone();134 this.endCursor_ = sel.end.clone();135};136/**137 * Get the cursor selection.138 * @return {cvox.CursorSelection} The selection.139 */140cvox.TraverseContent.prototype.getCurrentCursorSelection = function() {141 return new cvox.CursorSelection(this.startCursor_, this.endCursor_);142};143/**144 * Set the WebKit selection based on the current position.145 */146cvox.TraverseContent.prototype.updateSelection = function() {147 cvox.TraverseUtil.setSelection(this.startCursor_, this.endCursor_);148 cvox.SelectionUtil.scrollToSelection(window.getSelection());149};150/**151 * Get the current position as a range.152 * @return {Range} The current range.153 */154cvox.TraverseContent.prototype.getCurrentRange = function() {155 var range = document.createRange();156 try {157 range.setStart(this.startCursor_.node, this.startCursor_.index);158 range.setEnd(this.endCursor_.node, this.endCursor_.index);159 } catch (e) {160 console.log('Invalid range ');161 }162 return range;163};164/**165 * Get the current text content as a string.166 * @return {string} The current spanned content.167 */168cvox.TraverseContent.prototype.getCurrentText = function() {169 return cvox.SelectionUtil.getRangeText(this.getCurrentRange());170};171/**172 * Collapse to the end of the range.173 */174cvox.TraverseContent.prototype.collapseToEnd = function() {175 this.startCursor_ = this.endCursor_.clone();176};177/**178 * Collapse to the start of the range.179 */180cvox.TraverseContent.prototype.collapseToStart = function() {181 this.endCursor_ = this.startCursor_.clone();182};183/**184 * Moves selection forward.185 *186 * @param {string} grain specifies "sentence", "word", "character",187 * or "paragraph" granularity.188 * @return {?string} Either:189 * 1) The new selected text.190 * 2) null if the end of the domObj has been reached.191 */192cvox.TraverseContent.prototype.moveNext = function(grain) {193 var breakTags = this.getBreakTags();194 // As a special case, if the current selection is empty or all195 // whitespace, ensure that the next returned selection will NOT be196 // only whitespace - otherwise you can get trapped.197 var skipWhitespace = this.skipWhitespace;198 var range = this.getCurrentRange();199 if (!cvox.SelectionUtil.isRangeValid(range)) {200 skipWhitespace = true;201 }202 var elementsEntered = [];203 var elementsLeft = [];204 var str;205 do {206 if (grain === cvox.TraverseContent.kSentence) {207 str = cvox.TraverseUtil.getNextSentence(208 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,209 breakTags);210 } else if (grain === cvox.TraverseContent.kWord) {211 str = cvox.TraverseUtil.getNextWord(212 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);213 } else if (grain === cvox.TraverseContent.kCharacter) {214 str = cvox.TraverseUtil.getNextChar(215 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,216 skipWhitespace);217 } else if (grain === cvox.TraverseContent.kParagraph) {218 str = cvox.TraverseUtil.getNextParagraph(219 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);220 } else if (grain === cvox.TraverseContent.kLine) {221 str = cvox.TraverseUtil.getNextLine(222 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,223 breakTags);224 } else {225 // User has provided an invalid string.226 // Fall through to default: extend by sentence227 window.console.log('Invalid selection granularity: "' + grain + '"');228 grain = cvox.TraverseContent.kSentence;229 str = cvox.TraverseUtil.getNextSentence(230 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,231 breakTags);232 }233 if (str == null) {234 // We reached the end of the document.235 return null;236 }237 range = this.getCurrentRange();238 var isInvalid = !range.getBoundingClientRect();239 } while (this.skipInvalidSelections && isInvalid);240 if (!cvox.SelectionUtil.isRangeValid(range)) {241 // It's OK if the selection navigation lands on whitespace once (in242 // character granularity), but if it hits whitespace more than once, then243 // skip forward until there is real content.244 if (!this.lastSelectionWasWhitespace &&245 grain == cvox.TraverseContent.kCharacter) {246 this.lastSelectionWasWhitespace = true;247 } else {248 while (!cvox.SelectionUtil.isRangeValid(this.getCurrentRange())) {249 if (this.moveNext(grain) == null) {250 break;251 }252 }253 }254 } else {255 this.lastSelectionWasWhitespace = false;256 }257 return this.getCurrentText();258};259/**260 * Moves selection backward.261 *262 * @param {string} grain specifies "sentence", "word", "character",263 * or "paragraph" granularity.264 * @return {?string} Either:265 * 1) The new selected text.266 * 2) null if the beginning of the domObj has been reached.267 */268cvox.TraverseContent.prototype.movePrev = function(grain) {269 var breakTags = this.getBreakTags();270 // As a special case, if the current selection is empty or all271 // whitespace, ensure that the next returned selection will NOT be272 // only whitespace - otherwise you can get trapped.273 var skipWhitespace = this.skipWhitespace;274 var range = this.getCurrentRange();275 if (!cvox.SelectionUtil.isRangeValid(range)) {276 skipWhitespace = true;277 }278 var elementsEntered = [];279 var elementsLeft = [];280 var str;281 do {282 if (grain === cvox.TraverseContent.kSentence) {283 str = cvox.TraverseUtil.getPreviousSentence(284 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,285 breakTags);286 } else if (grain === cvox.TraverseContent.kWord) {287 str = cvox.TraverseUtil.getPreviousWord(288 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);289 } else if (grain === cvox.TraverseContent.kCharacter) {290 str = cvox.TraverseUtil.getPreviousChar(291 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,292 skipWhitespace);293 } else if (grain === cvox.TraverseContent.kParagraph) {294 str = cvox.TraverseUtil.getPreviousParagraph(295 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);296 } else if (grain === cvox.TraverseContent.kLine) {297 str = cvox.TraverseUtil.getPreviousLine(298 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,299 breakTags);300 } else {301 // User has provided an invalid string.302 // Fall through to default: extend by sentence303 window.console.log('Invalid selection granularity: "' + grain + '"');304 grain = cvox.TraverseContent.kSentence;305 str = cvox.TraverseUtil.getPreviousSentence(306 this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,307 breakTags);308 }309 if (str == null) {310 // We reached the end of the document.311 return null;312 }313 range = this.getCurrentRange();314 var isInvalid = !range.getBoundingClientRect();315 } while (this.skipInvalidSelections && isInvalid);316 if (!cvox.SelectionUtil.isRangeValid(range)) {317 // It's OK if the selection navigation lands on whitespace once (in318 // character granularity), but if it hits whitespace more than once, then319 // skip forward until there is real content.320 if (!this.lastSelectionWasWhitespace &&321 grain == cvox.TraverseContent.kCharacter) {322 this.lastSelectionWasWhitespace = true;323 } else {324 while (!cvox.SelectionUtil.isRangeValid(this.getCurrentRange())) {325 if (this.movePrev(grain) == null) {326 break;327 }328 }329 }330 } else {331 this.lastSelectionWasWhitespace = false;332 }333 return this.getCurrentText();334};335/**336 * Get the tag names that should break a sentence or line. Currently337 * just an anchor 'A' should break a sentence or line if the breakAtLinks338 * flag is true, but in the future we might have other rules for breaking.339 *340 * @return {Object} An associative array mapping a tag name to true if341 * it should break a sentence or line.342 */343cvox.TraverseContent.prototype.getBreakTags = function() {344 return {345 'A': this.breakAtLinks,346 'BR': true,347 'HR': true348 };349};350/**351 * Selects the next element of the document or within the provided DOM object.352 * Scrolls the window as appropriate.353 *354 * @param {string} grain specifies "sentence", "word", "character",355 * or "paragraph" granularity.356 * @param {Node=} domObj a DOM node (optional).357 * @return {?string} Either:358 * 1) The new selected text.359 * 2) null if the end of the domObj has been reached.360 */361cvox.TraverseContent.prototype.nextElement = function(grain, domObj) {362 if (domObj != null) {363 this.currentDomObj = domObj;364 }365 var result = this.moveNext(grain);366 if (result != null &&367 (!cvox.DomUtil.isDescendantOfNode(368 this.startCursor_.node, this.currentDomObj) ||369 !cvox.DomUtil.isDescendantOfNode(370 this.endCursor_.node, this.currentDomObj))) {371 return null;372 }373 return result;374};375/**376 * Selects the previous element of the document or within the provided DOM377 * object. Scrolls the window as appropriate.378 *379 * @param {string} grain specifies "sentence", "word", "character",380 * or "paragraph" granularity.381 * @param {Node=} domObj a DOM node (optional).382 * @return {?string} Either:383 * 1) The new selected text.384 * 2) null if the beginning of the domObj has been reached.385 */386cvox.TraverseContent.prototype.prevElement = function(grain, domObj) {387 if (domObj != null) {388 this.currentDomObj = domObj;389 }390 var result = this.movePrev(grain);391 if (result != null &&392 (!cvox.DomUtil.isDescendantOfNode(393 this.startCursor_.node, this.currentDomObj) ||394 !cvox.DomUtil.isDescendantOfNode(395 this.endCursor_.node, this.currentDomObj))) {396 return null;397 }398 return result;399};400/**401 * Make sure that exactly one item is selected. If there's no selection,402 * set the selection to the start of the document.403 */404cvox.TraverseContent.prototype.normalizeSelection = function() {405 var selection = window.getSelection();406 if (selection.rangeCount < 1) {407 // Before the user has clicked a freshly-loaded page408 var range = document.createRange();409 range.setStart(this.currentDomObj, 0);410 range.setEnd(this.currentDomObj, 0);411 selection.removeAllRanges();412 selection.addRange(range);413 } else if (selection.rangeCount > 1) {414 // Multiple ranges exist - remove all ranges but the last one415 for (var i = 0; i < (selection.rangeCount - 1); i++) {416 selection.removeRange(selection.getRangeAt(i));417 }418 }419};420/**421 * Resets the selection.422 *423 * @param {Node=} domObj a DOM node. Optional.424 *425 */426cvox.TraverseContent.prototype.reset = function(domObj) {427 window.getSelection().removeAllRanges();...
traverseAllChildren-test.js
Source:traverseAllChildren-test.js
1/**2 * Copyright 2013-2015, Facebook, Inc.3 * All rights reserved.4 *5 * This source code is licensed under the BSD-style license found in the6 * LICENSE file in the root directory of this source tree. An additional grant7 * of patent rights can be found in the PATENTS file in the same directory.8 *9 * @emails react-core10 */11'use strict';12describe('traverseAllChildren', function() {13 var traverseAllChildren;14 var React;15 var ReactFragment;16 beforeEach(function() {17 traverseAllChildren = require('traverseAllChildren');18 React = require('React');19 ReactFragment = require('ReactFragment');20 });21 function frag(obj) {22 return ReactFragment.create(obj);23 }24 it('should support identity for simple', function() {25 var traverseContext = [];26 var traverseFn =27 jasmine.createSpy().andCallFake(function(context, kid, key, index) {28 context.push(true);29 });30 var simpleKid = <span key="simple" />;31 // Jasmine doesn't provide a way to test that the fn was invoked with scope.32 var instance = <div>{simpleKid}</div>;33 traverseAllChildren(instance.props.children, traverseFn, traverseContext);34 expect(traverseFn).toHaveBeenCalledWith(35 traverseContext,36 simpleKid,37 '.$simple',38 039 );40 expect(traverseContext.length).toEqual(1);41 });42 it('should treat single arrayless child as being in array', function() {43 var traverseContext = [];44 var traverseFn =45 jasmine.createSpy().andCallFake(function(context, kid, key, index) {46 context.push(true);47 });48 var simpleKid = <span />;49 var instance = <div>{simpleKid}</div>;50 traverseAllChildren(instance.props.children, traverseFn, traverseContext);51 expect(traverseFn).toHaveBeenCalledWith(52 traverseContext,53 simpleKid,54 '.0',55 056 );57 expect(traverseContext.length).toEqual(1);58 });59 it('should treat single child in array as expected', function() {60 var traverseContext = [];61 var traverseFn =62 jasmine.createSpy().andCallFake(function(context, kid, key, index) {63 context.push(true);64 });65 var simpleKid = <span />;66 var instance = <div>{[simpleKid]}</div>;67 traverseAllChildren(instance.props.children, traverseFn, traverseContext);68 expect(traverseFn).toHaveBeenCalledWith(69 traverseContext,70 simpleKid,71 '.0',72 073 );74 expect(traverseContext.length).toEqual(1);75 });76 it('should be called for each child', function() {77 var zero = <div key="keyZero" />;78 var one = null;79 var two = <div key="keyTwo" />;80 var three = null;81 var four = <div key="keyFour" />;82 var traverseContext = [];83 var traverseFn =84 jasmine.createSpy().andCallFake(function(context, kid, key, index) {85 context.push(true);86 });87 var instance = (88 <div>89 {zero}90 {one}91 {two}92 {three}93 {four}94 </div>95 );96 traverseAllChildren(instance.props.children, traverseFn, traverseContext);97 expect(traverseFn).toHaveBeenCalledWith(98 traverseContext,99 zero,100 '.$keyZero',101 0102 );103 expect(traverseFn).toHaveBeenCalledWith(traverseContext, one, '.1', 1);104 expect(traverseFn).toHaveBeenCalledWith(105 traverseContext,106 two,107 '.$keyTwo',108 2109 );110 expect(traverseFn).toHaveBeenCalledWith(traverseContext, three, '.3', 3);111 expect(traverseFn).toHaveBeenCalledWith(112 traverseContext,113 four,114 '.$keyFour',115 4116 );117 });118 it('should traverse children of different kinds', function() {119 var div = <div key="divNode" />;120 var span = <span key="spanNode" />;121 var a = <a key="aNode" />;122 var traverseContext = [];123 var traverseFn =124 jasmine.createSpy().andCallFake(function(context, kid, key, index) {125 context.push(true);126 });127 var instance = (128 <div>129 {div}130 {[frag({span})]}131 {frag({a: a})}132 {'string'}133 {1234}134 {true}135 {false}136 {null}137 {undefined}138 </div>139 );140 traverseAllChildren(instance.props.children, traverseFn, traverseContext);141 expect(traverseFn.calls.length).toBe(9);142 expect(traverseContext.length).toEqual(9);143 expect(traverseFn).toHaveBeenCalledWith(144 traverseContext, div, '.$divNode', 0145 );146 expect(traverseFn).toHaveBeenCalledWith(147 traverseContext, span, '.1:0:$span:$spanNode', 1148 );149 expect(traverseFn).toHaveBeenCalledWith(150 traverseContext, a, '.2:$a:$aNode', 2151 );152 expect(traverseFn).toHaveBeenCalledWith(153 traverseContext, 'string', '.3', 3154 );155 expect(traverseFn).toHaveBeenCalledWith(156 traverseContext, 1234, '.4', 4157 );158 expect(traverseFn).toHaveBeenCalledWith(159 traverseContext, null, '.5', 5160 );161 expect(traverseFn).toHaveBeenCalledWith(162 traverseContext, null, '.6', 6163 );164 expect(traverseFn).toHaveBeenCalledWith(165 traverseContext, null, '.7', 7166 );167 expect(traverseFn).toHaveBeenCalledWith(168 traverseContext, null, '.8', 8169 );170 });171 it('should be called for each child in nested structure', function() {172 var zero = <div key="keyZero" />;173 var one = null;174 var two = <div key="keyTwo" />;175 var three = null;176 var four = <div key="keyFour" />;177 var five = <div key="keyFiveInner" />;178 // five is placed into a JS object with a key that is joined to the179 // component key attribute.180 // Precedence is as follows:181 // 1. If grouped in an Object, the object key combined with `key` prop182 // 2. If grouped in an Array, the `key` prop, falling back to array index183 var traverseContext = [];184 var traverseFn =185 jasmine.createSpy().andCallFake(function(context, kid, key, index) {186 context.push(true);187 });188 var instance = (189 <div>{190 [frag({191 firstHalfKey: [zero, one, two],192 secondHalfKey: [three, four],193 keyFive: five194 })]195 }</div>196 );197 traverseAllChildren(instance.props.children, traverseFn, traverseContext);198 expect(traverseFn.calls.length).toBe(6);199 expect(traverseContext.length).toEqual(6);200 expect(traverseFn).toHaveBeenCalledWith(201 traverseContext,202 zero,203 '.0:$firstHalfKey:0:$keyZero',204 0205 );206 expect(traverseFn)207 .toHaveBeenCalledWith(traverseContext, one, '.0:$firstHalfKey:0:1', 1);208 expect(traverseFn).toHaveBeenCalledWith(209 traverseContext,210 two,211 '.0:$firstHalfKey:0:$keyTwo',212 2213 );214 expect(traverseFn).toHaveBeenCalledWith(215 traverseContext,216 three,217 '.0:$secondHalfKey:0:0',218 3219 );220 expect(traverseFn).toHaveBeenCalledWith(221 traverseContext,222 four,223 '.0:$secondHalfKey:0:$keyFour',224 4225 );226 expect(traverseFn).toHaveBeenCalledWith(227 traverseContext,228 five,229 '.0:$keyFive:$keyFiveInner',230 5231 );232 });233 it('should retain key across two mappings', function() {234 var zeroForceKey = <div key="keyZero" />;235 var oneForceKey = <div key="keyOne" />;236 var traverseContext = [];237 var traverseFn =238 jasmine.createSpy().andCallFake(function(context, kid, key, index) {239 context.push(true);240 });241 var forcedKeys = (242 <div>243 {zeroForceKey}244 {oneForceKey}245 </div>246 );247 traverseAllChildren(forcedKeys.props.children, traverseFn, traverseContext);248 expect(traverseContext.length).toEqual(2);249 expect(traverseFn).toHaveBeenCalledWith(250 traverseContext,251 zeroForceKey,252 '.$keyZero',253 0254 );255 expect(traverseFn).toHaveBeenCalledWith(256 traverseContext,257 oneForceKey,258 '.$keyOne',259 1260 );261 });262 it('should be called for each child in an iterable without keys', function() {263 var threeDivIterable = {264 '@@iterator': function() {265 var i = 0;266 return {267 next: function() {268 if (i++ < 3) {269 return {value: <div />, done: false};270 } else {271 return {value: undefined, done: true};272 }273 }274 };275 }276 };277 var traverseContext = [];278 var traverseFn =279 jasmine.createSpy().andCallFake(function(context, kid, key, index) {280 context.push(kid);281 });282 var instance = (283 <div>284 {threeDivIterable}285 </div>286 );287 traverseAllChildren(instance.props.children, traverseFn, traverseContext);288 expect(traverseFn.calls.length).toBe(3);289 expect(traverseFn).toHaveBeenCalledWith(290 traverseContext,291 traverseContext[0],292 '.0',293 0294 );295 expect(traverseFn).toHaveBeenCalledWith(296 traverseContext,297 traverseContext[1],298 '.1',299 1300 );301 expect(traverseFn).toHaveBeenCalledWith(302 traverseContext,303 traverseContext[2],304 '.2',305 2306 );307 });308 it('should be called for each child in an iterable with keys', function() {309 var threeDivIterable = {310 '@@iterator': function() {311 var i = 0;312 return {313 next: function() {314 if (i++ < 3) {315 return {value: <div key={'#' + i} />, done: false};316 } else {317 return {value: undefined, done: true};318 }319 }320 };321 }322 };323 var traverseContext = [];324 var traverseFn =325 jasmine.createSpy().andCallFake(function(context, kid, key, index) {326 context.push(kid);327 });328 var instance = (329 <div>330 {threeDivIterable}331 </div>332 );333 traverseAllChildren(instance.props.children, traverseFn, traverseContext);334 expect(traverseFn.calls.length).toBe(3);335 expect(traverseFn).toHaveBeenCalledWith(336 traverseContext,337 traverseContext[0],338 '.$#1',339 0340 );341 expect(traverseFn).toHaveBeenCalledWith(342 traverseContext,343 traverseContext[1],344 '.$#2',345 1346 );347 expect(traverseFn).toHaveBeenCalledWith(348 traverseContext,349 traverseContext[2],350 '.$#3',351 2352 );353 });354 it('should use keys from entry iterables', function() {355 spyOn(console, 'warn');356 var threeDivEntryIterable = {357 '@@iterator': function() {358 var i = 0;359 return {360 next: function() {361 if (i++ < 3) {362 return {value: ['#' + i, <div />], done: false};363 } else {364 return {value: undefined, done: true};365 }366 }367 };368 }369 };370 threeDivEntryIterable.entries = threeDivEntryIterable['@@iterator'];371 var traverseContext = [];372 var traverseFn =373 jasmine.createSpy().andCallFake(function(context, kid, key, index) {374 context.push(kid);375 });376 var instance = (377 <div>378 {threeDivEntryIterable}379 </div>380 );381 traverseAllChildren(instance.props.children, traverseFn, traverseContext);382 expect(traverseFn.calls.length).toBe(3);383 expect(traverseFn).toHaveBeenCalledWith(384 traverseContext,385 traverseContext[0],386 '.$#1:0',387 0388 );389 expect(traverseFn).toHaveBeenCalledWith(390 traverseContext,391 traverseContext[1],392 '.$#2:0',393 1394 );395 expect(traverseFn).toHaveBeenCalledWith(396 traverseContext,397 traverseContext[2],398 '.$#3:0',399 2400 );401 expect(console.warn.argsForCall.length).toBe(1);402 expect(console.warn.argsForCall[0][0]).toContain(403 'Warning: Using Maps as children is not yet fully supported. It is an ' +404 'experimental feature that might be removed. Convert it to a sequence ' +405 '/ iterable of keyed ReactElements instead.'406 );407 });...
ReactChildren.js
Source:ReactChildren.js
1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 */7import invariant from 'shared/invariant';8import warning from 'shared/warning';9import {10 getIteratorFn,11 REACT_ELEMENT_TYPE,12 REACT_PORTAL_TYPE,13} from 'shared/ReactSymbols';14import {isValidElement, cloneAndReplaceKey} from './ReactElement';15import ReactDebugCurrentFrame from './ReactDebugCurrentFrame';16const SEPARATOR = '.';17const SUBSEPARATOR = ':';18/**19 * Escape and wrap key so it is safe to use as a reactid20 *21 * @param {string} key to be escaped.22 * @return {string} the escaped key.23 */24function escape(key) {25 const escapeRegex = /[=:]/g;26 const escaperLookup = {27 '=': '=0',28 ':': '=2',29 };30 const escapedString = ('' + key).replace(escapeRegex, function(match) {31 return escaperLookup[match];32 });33 return '$' + escapedString;34}35/**36 * TODO: Test that a single child and an array with one item have the same key37 * pattern.38 */39let didWarnAboutMaps = false;40const userProvidedKeyEscapeRegex = /\/+/g;41function escapeUserProvidedKey(text) {42 return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');43}44const POOL_SIZE = 10;45const traverseContextPool = [];46function getPooledTraverseContext(47 mapResult,48 keyPrefix,49 mapFunction,50 mapContext,51) {52 if (traverseContextPool.length) {53 const traverseContext = traverseContextPool.pop();54 traverseContext.result = mapResult;55 traverseContext.keyPrefix = keyPrefix;56 traverseContext.func = mapFunction;57 traverseContext.context = mapContext;58 traverseContext.count = 0;59 return traverseContext;60 } else {61 return {62 result: mapResult,63 keyPrefix: keyPrefix,64 func: mapFunction,65 context: mapContext,66 count: 0,67 };68 }69}70function releaseTraverseContext(traverseContext) {71 traverseContext.result = null;72 traverseContext.keyPrefix = null;73 traverseContext.func = null;74 traverseContext.context = null;75 traverseContext.count = 0;76 if (traverseContextPool.length < POOL_SIZE) {77 traverseContextPool.push(traverseContext);78 }79}80/**81 * @param {?*} children Children tree container.82 * @param {!string} nameSoFar Name of the key path so far.83 * @param {!function} callback Callback to invoke with each child found.84 * @param {?*} traverseContext Used to pass information throughout the traversal85 * process.86 * @return {!number} The number of children in this subtree.87 */88function traverseAllChildrenImpl(89 children,90 nameSoFar,91 callback,92 traverseContext,93) {94 const type = typeof children;95 if (type === 'undefined' || type === 'boolean') {96 // All of the above are perceived as null.97 children = null;98 }99 let invokeCallback = false;100 if (children === null) {101 invokeCallback = true;102 } else {103 switch (type) {104 case 'string':105 case 'number':106 invokeCallback = true;107 break;108 case 'object':109 switch (children.$$typeof) {110 case REACT_ELEMENT_TYPE:111 case REACT_PORTAL_TYPE:112 invokeCallback = true;113 }114 }115 }116 if (invokeCallback) {117 callback(118 traverseContext,119 children,120 // If it's the only child, treat the name as if it was wrapped in an array121 // so that it's consistent if the number of children grows.122 nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar,123 );124 return 1;125 }126 let child;127 let nextName;128 let subtreeCount = 0; // Count of children found in the current subtree.129 const nextNamePrefix =130 nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;131 if (Array.isArray(children)) {132 for (let i = 0; i < children.length; i++) {133 child = children[i];134 nextName = nextNamePrefix + getComponentKey(child, i);135 subtreeCount += traverseAllChildrenImpl(136 child,137 nextName,138 callback,139 traverseContext,140 );141 }142 } else {143 const iteratorFn = getIteratorFn(children);144 if (typeof iteratorFn === 'function') {145 if (__DEV__) {146 // Warn about using Maps as children147 if (iteratorFn === children.entries) {148 warning(149 didWarnAboutMaps,150 'Using Maps as children is unsupported and will likely yield ' +151 'unexpected results. Convert it to a sequence/iterable of keyed ' +152 'ReactElements instead.',153 );154 didWarnAboutMaps = true;155 }156 }157 const iterator = iteratorFn.call(children);158 let step;159 let ii = 0;160 while (!(step = iterator.next()).done) {161 child = step.value;162 nextName = nextNamePrefix + getComponentKey(child, ii++);163 subtreeCount += traverseAllChildrenImpl(164 child,165 nextName,166 callback,167 traverseContext,168 );169 }170 } else if (type === 'object') {171 let addendum = '';172 if (__DEV__) {173 addendum =174 ' If you meant to render a collection of children, use an array ' +175 'instead.' +176 ReactDebugCurrentFrame.getStackAddendum();177 }178 const childrenString = '' + children;179 invariant(180 false,181 'Objects are not valid as a React child (found: %s).%s',182 childrenString === '[object Object]'183 ? 'object with keys {' + Object.keys(children).join(', ') + '}'184 : childrenString,185 addendum,186 );187 }188 }189 return subtreeCount;190}191/**192 * Traverses children that are typically specified as `props.children`, but193 * might also be specified through attributes:194 *195 * - `traverseAllChildren(this.props.children, ...)`196 * - `traverseAllChildren(this.props.leftPanelChildren, ...)`197 *198 * The `traverseContext` is an optional argument that is passed through the199 * entire traversal. It can be used to store accumulations or anything else that200 * the callback might find relevant.201 *202 * @param {?*} children Children tree object.203 * @param {!function} callback To invoke upon traversing each child.204 * @param {?*} traverseContext Context for traversal.205 * @return {!number} The number of children in this subtree.206 */207function traverseAllChildren(children, callback, traverseContext) {208 if (children == null) {209 return 0;210 }211 return traverseAllChildrenImpl(children, '', callback, traverseContext);212}213/**214 * Generate a key string that identifies a component within a set.215 *216 * @param {*} component A component that could contain a manual key.217 * @param {number} index Index that is used if a manual key is not provided.218 * @return {string}219 */220function getComponentKey(component, index) {221 // Do some typechecking here since we call this blindly. We want to ensure222 // that we don't block potential future ES APIs.223 if (224 typeof component === 'object' &&225 component !== null &&226 component.key != null227 ) {228 // Explicit key229 return escape(component.key);230 }231 // Implicit key determined by the index in the set232 return index.toString(36);233}234function forEachSingleChild(bookKeeping, child, name) {235 const {func, context} = bookKeeping;236 func.call(context, child, bookKeeping.count++);237}238/**239 * Iterates through children that are typically specified as `props.children`.240 *241 * See https://reactjs.org/docs/react-api.html#reactchildrenforeach242 *243 * The provided forEachFunc(child, index) will be called for each244 * leaf child.245 *246 * @param {?*} children Children tree container.247 * @param {function(*, int)} forEachFunc248 * @param {*} forEachContext Context for forEachContext.249 */250function forEachChildren(children, forEachFunc, forEachContext) {251 if (children == null) {252 return children;253 }254 const traverseContext = getPooledTraverseContext(255 null,256 null,257 forEachFunc,258 forEachContext,259 );260 traverseAllChildren(children, forEachSingleChild, traverseContext);261 releaseTraverseContext(traverseContext);262}263function mapSingleChildIntoContext(bookKeeping, child, childKey) {264 const {result, keyPrefix, func, context} = bookKeeping;265 let mappedChild = func.call(context, child, bookKeeping.count++);266 if (Array.isArray(mappedChild)) {267 mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, c => c);268 } else if (mappedChild != null) {269 if (isValidElement(mappedChild)) {270 mappedChild = cloneAndReplaceKey(271 mappedChild,272 // Keep both the (mapped) and old keys if they differ, just as273 // traverseAllChildren used to do for objects as children274 keyPrefix +275 (mappedChild.key && (!child || child.key !== mappedChild.key)276 ? escapeUserProvidedKey(mappedChild.key) + '/'277 : '') +278 childKey,279 );280 }281 result.push(mappedChild);282 }283}284function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {285 let escapedPrefix = '';286 if (prefix != null) {287 escapedPrefix = escapeUserProvidedKey(prefix) + '/';288 }289 const traverseContext = getPooledTraverseContext(290 array,291 escapedPrefix,292 func,293 context,294 );295 traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);296 releaseTraverseContext(traverseContext);297}298/**299 * Maps children that are typically specified as `props.children`.300 *301 * See https://reactjs.org/docs/react-api.html#reactchildrenmap302 *303 * The provided mapFunction(child, key, index) will be called for each304 * leaf child.305 *306 * @param {?*} children Children tree container.307 * @param {function(*, int)} func The map function.308 * @param {*} context Context for mapFunction.309 * @return {object} Object containing the ordered map of results.310 */311function mapChildren(children, func, context) {312 if (children == null) {313 return children;314 }315 const result = [];316 mapIntoWithKeyPrefixInternal(children, result, null, func, context);317 return result;318}319/**320 * Count the number of children that are typically specified as321 * `props.children`.322 *323 * See https://reactjs.org/docs/react-api.html#reactchildrencount324 *325 * @param {?*} children Children tree container.326 * @return {number} The number of children.327 */328function countChildren(children) {329 return traverseAllChildren(children, () => null, null);330}331/**332 * Flatten a children object (typically specified as `props.children`) and333 * return an array with appropriately re-keyed children.334 *335 * See https://reactjs.org/docs/react-api.html#reactchildrentoarray336 */337function toArray(children) {338 const result = [];339 mapIntoWithKeyPrefixInternal(children, result, null, child => child);340 return result;341}342/**343 * Returns the first child in a collection of children and verifies that there344 * is only one child in the collection.345 *346 * See https://reactjs.org/docs/react-api.html#reactchildrenonly347 *348 * The current implementation of this function assumes that a single child gets349 * passed without a wrapper, but the purpose of this helper function is to350 * abstract away the particular structure of children.351 *352 * @param {?object} children Child collection structure.353 * @return {ReactElement} The first and only `ReactElement` contained in the354 * structure.355 */356function onlyChild(children) {357 invariant(358 isValidElement(children),359 'React.Children.only expected to receive a single React element child.',360 );361 return children;362}363export {364 forEachChildren as forEach,365 mapChildren as map,366 countChildren as count,367 onlyChild as only,368 toArray,...
traverse_manager.js
Source:traverse_manager.js
1// Copyright 2012 Google Inc.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview TraverseManager16 * Traverse manager is the part of ChromeVox extensions framework to add support17 * for custom navigation with ChromeVox. This uses the tree created by the18 * speakables to create the custom navigation system. For websites that already19 * have navigation in them this is not enabled.20 * @author: cagriy@google.com (Cagri Yildirim)21 */22cvoxExt.TraverseManager = {};23var TraverseManager = cvoxExt.TraverseManager;24/**25 * the order which speakables are traversed.26 */27TraverseManager.orderedSpeakables = [];28/** key to switch to next speakable29 */30TraverseManager.coarseScrollNextKey = null;31/** key to switch to previous speakable32 */33TraverseManager.coarseScrollPrevKey = null;34/** key to switch to next element of35 * current speakable, switch to null36 * to disable37 */38TraverseManager.fineScrollNextKey = null;39/** key to switch to prev element of40 * current speakable, switch to null41 * to disable42 */43TraverseManager.fineScrollPrevKey = null;44/**45 * pointer to current speakable46 */47TraverseManager.currSpeakable = 0;48/**49 * index of element of current speakable50 */51TraverseManager.currElementOfSpeakable = 0;52/** disable keyboard shortcuts for extension managed traversal */53TraverseManager.disableManagedTraversal = function() {54 TraverseManager.fineScrollNextKey = null;55 TraverseManager.fineScrollPrevKey = null;56 TraverseManager.coarseScrollNextKey = null;57 TraverseManager.coarseScrollPrevKey = null;58};59/** enable default keyboard shortcuts for extension60 managed traversal */61TraverseManager.enableDefaultManagedTraversal = function() {62 TraverseManager.fineScrollNextKey = 'n';63 TraverseManager.fineScrollPrevKey = 'p';64 TraverseManager.coarseScrollNextKey = 'j';65 TraverseManager.coarseScrollPrevKey = 'k';66};67/** When using the n/p navigation enables scrolling by element. That means if68 * a selector selects an array of objects it will scroll by each element69 */70TraverseManager.enableElementFineScroll = function() {71 TraverseManager.fineScrollMode = 'scrollByElement';72};73/** Enables scrolling of child speakables. This means when user presses n/p74 the extension will focus on the child speakables of the current speakable75 as referenced in the parent speakable's formatter76 */77TraverseManager.enableChildSpeakableFineScroll = function() {78 TraverseManager.fineScrollMode = 'scrollByChildSpeakable';79};80/**81 * update the order of speakables according to which elements are visible82 */83TraverseManager.updateOrderedSpeakables = function() {84 TraverseManager.orderedSpeakables = [];85 for (var i in SpeakableManager.speakables) {86 SpeakableManager.speakables[i].visible = false;87 if (SpeakableManager.speakables[i].traversable) {88 TraverseManager.orderedSpeakables.push(SpeakableManager.speakables[i]);89 }90 }91 TraverseManager.orderedSpeakables = cvoxExt.Util.filterVisibleSpeakables(92 TraverseManager.orderedSpeakables);93 for (var i = 0, o; o = TraverseManager.orderedSpeakables[i]; i++) {94 var speakable = SpeakableManager.speakables[o.name];95 speakable.visible = true;96 speakable.index = i;97 }98};99/** focus on the first selected DOM element of a speakable object100 * for this to work, the speakable must either be selected by ID or a unique101 * class name102@param {cvoxExt.Speakable} speakable the relevant speakable.103*/104TraverseManager.focusSpeakable = function(speakable) {105 var newFocus = Util.getVisibleDomObjectsFromSelector(speakable)[0];106 if (newFocus) {107 var dummyNode = document.createElement('div');108 newFocus.parentNode.insertBefore(dummyNode, newFocus);109 SpeakableManager.updateSpeak(newFocus);110 dummyNode.setAttribute('cvoxnodedesc',111 newFocus.getAttribute('cvoxnodedesc'));112 newFocus.removeAttribute('cvoxnodedesc');113 //close the div in listener114 var onDummyBlur = function() {115 //remove this event listener116 dummyNode.removeEventListener('blur', arguments.callee, false);117 var removeChild = function() {118 if (dummyNode.parentNode) {119 dummyNode.parentNode.removeChild(dummyNode);120 }121 };122 setTimeout(removeChild, 50);123 }124 dummyNode.addEventListener('blur', onDummyBlur, true);125 dummyNode.setAttribute('tabindex', -1);126 cvoxExt.TraverseManager.skipFocusCheckThisTime = true;127 dummyNode.focus();128 TraverseManager.focusedElement = newFocus;129 }130};131/**132 * moves to the next speakable133 * @param {Number} next the index of speakable to move to.134 */135TraverseManager.coarseScroll = function(next) {136 TraverseManager.updateOrderedSpeakables();137 TraverseManager.currElementOfSpeakable = 0;138 if (TraverseManager.orderedSpeakables.length != 0) {139 TraverseManager.currSpeakable = next;140 if (TraverseManager.currSpeakable >=141 TraverseManager.orderedSpeakables.length) {142 TraverseManager.currSpeakable = 0;143 } else if (TraverseManager.currSpeakable < 0) {144 TraverseManager.currSpeakable =145 TraverseManager.orderedSpeakables.length - 1;146 }147 var coarseScroll =148 TraverseManager.orderedSpeakables[TraverseManager.currSpeakable];149 TraverseManager.focusSpeakable(coarseScroll);150 }151};152/** gets the next speakable object by speakable name153 * @param {string} type type string of speakable.154*/155TraverseManager.coarseScrollByType = function(type) {156 TraverseManager.coarseScroll(TraverseManager.157 orderedSpeakables.indexOf(TraverseManager.speakables[type]));158};159/** go to the next element in the current speakable160 * @param {number} next element's index.161 */162TraverseManager.fineScroll = function(next) {163 TraverseManager.currElementOfSpeakable = next;164 var currSpeakable =165 TraverseManager.orderedSpeakables[TraverseManager.currSpeakable];166 if (TraverseManager.fineScrollMode == 'scrollByChildSpeakable') {167 var childSpeakables = currSpeakable.getAllChildSpeakables();168 var childSpeakablesArr = [];169 for (sp in childSpeakables) {170 childSpeakablesArr.push(SpeakableManager.speakables[sp]);171 }172 if (TraverseManager.currElementOfSpeakable >= childSpeakablesArr.length) {173 TraverseManager.currElementOfSpeakable = 0;174 } else if (TraverseManager.currElementOfSpeakable < 0) {175 TraverseManager.currElementOfSpeakable = childSpeakablesArr.length - 1;176 }177 var newFocus = Util.getVisibleDomObjectsFromSelector(178 childSpeakablesArr[TraverseManager.currElementOfSpeakable],179 TraverseManager.focusedElement)[0];180 } else if (TraverseManager.fineScrollMode == 'scrollByElement') {181 for (var childSpeakableName in currSpeakable.getAllChildSpeakables()) {182 break;183 }184 var childSpeakable = SpeakableManager.speakables[childSpeakableName];185 //get the first child speakable to select the array of elements from.186 var elements = Util.getVisibleDomObjectsFromSelector(childSpeakable,187 Util.getVisibleDomObjectsFromSelector(currSpeakable)[0]);188 if (TraverseManager.currElementOfSpeakable >= elements.length) {189 TraverseManager.currElementOfSpeakable = 0;190 } else if (TraverseManager.currElementOfSpeakable < 0) {191 TraverseManager.currElementOfSpeakable = elements.length - 1;192 }193 newFocus = elements[TraverseManager.currElementOfSpeakable];194 }195 newFocus.setAttribute('tabindex', -1);196 newFocus.focus();197};198/** switches to the next speakable if the speakable key is pressed199 * implements addSpeakableKeyListener functionality200 * @param {event} evt DOM event.201 * @return {boolean} event suppressor.202 */203TraverseManager.keyHandler = function(evt) {204 TraverseManager.updateOrderedSpeakables();205 //TODO make a more robust check for inputtable elements206 if (document.activeElement.tagName == 'INPUT') {207 return true;208 }209 var orderedSpeakables = TraverseManager.orderedSpeakables;210 var currSpeakable = TraverseManager.currSpeakable;211 var speakableKeyToFunction = SpeakableManager.speakableToKeyFunction;212 if (!orderedSpeakables[currSpeakable]) {return;}213 var keyToFunction =214 speakableKeyToFunction[orderedSpeakables[currSpeakable].type];215 if (keyToFunction) {216 var func = keyToFunction[String.fromCharCode(evt.charCode)];217 if (func) {218 func();219 evt.stopPropagation();220 return false;221 }222 }223 if (TraverseManager.coarseScrollNextKey && evt.charCode ==224 TraverseManager.coarseScrollNextKey.charCodeAt(0)) {225 TraverseManager.coarseScroll(TraverseManager.currSpeakable + 1);226 evt.stopPropagation();227 return false;228 } else if (TraverseManager.coarseScrollPrevKey && evt.charCode ==229 TraverseManager.coarseScrollPrevKey.charCodeAt(0)) {230 TraverseManager.coarseScroll(TraverseManager.currSpeakable - 1);231 evt.stopPropagation();232 return false;233 } else if (TraverseManager.fineScrollNextKey && evt.charCode ==234 TraverseManager.fineScrollNextKey.charCodeAt(0)) {235 TraverseManager.fineScroll(236 TraverseManager.currElementOfSpeakable + 1);237 evt.stopPropagation();238 return false;239 } else if (TraverseManager.fineScrollPrevKey && evt.charCode ==240 TraverseManager.fineScrollPrevKey.charCodeAt(0)) {241 TraverseManager.fineScroll(242 TraverseManager.currElementOfSpeakable - 1);243 evt.stopPropagation();244 return false;245 }246 return true;...
traverse_vx.x.x.js
Source:traverse_vx.x.x.js
1// flow-typed signature: 7a36f68cb574ba77c6b3a9c1599cf88a2// flow-typed version: <<STUB>>/@babel/traverse_v^7.1.6/flow_v0.87.03/**4 * This is an autogenerated libdef stub for:5 *6 * '@babel/traverse'7 *8 * Fill this stub out by replacing all the `any` types.9 *10 * Once filled out, we encourage you to share your work with the11 * community by sending a pull request to:12 * https://github.com/flowtype/flow-typed13 */14declare module '@babel/traverse' {15 declare module.exports: any;16}17/**18 * We include stubs for each file inside this npm package in case you need to19 * require those files directly. Feel free to delete any files that aren't20 * needed.21 */22declare module '@babel/traverse/lib/cache' {23 declare module.exports: any;24}25declare module '@babel/traverse/lib/context' {26 declare module.exports: any;27}28declare module '@babel/traverse/lib/hub' {29 declare module.exports: any;30}31declare module '@babel/traverse/lib/index' {32 declare module.exports: any;33}34declare module '@babel/traverse/lib/path/ancestry' {35 declare module.exports: any;36}37declare module '@babel/traverse/lib/path/comments' {38 declare module.exports: any;39}40declare module '@babel/traverse/lib/path/context' {41 declare module.exports: any;42}43declare module '@babel/traverse/lib/path/conversion' {44 declare module.exports: any;45}46declare module '@babel/traverse/lib/path/evaluation' {47 declare module.exports: any;48}49declare module '@babel/traverse/lib/path/family' {50 declare module.exports: any;51}52declare module '@babel/traverse/lib/path/index' {53 declare module.exports: any;54}55declare module '@babel/traverse/lib/path/inference/index' {56 declare module.exports: any;57}58declare module '@babel/traverse/lib/path/inference/inferer-reference' {59 declare module.exports: any;60}61declare module '@babel/traverse/lib/path/inference/inferers' {62 declare module.exports: any;63}64declare module '@babel/traverse/lib/path/introspection' {65 declare module.exports: any;66}67declare module '@babel/traverse/lib/path/lib/hoister' {68 declare module.exports: any;69}70declare module '@babel/traverse/lib/path/lib/removal-hooks' {71 declare module.exports: any;72}73declare module '@babel/traverse/lib/path/lib/virtual-types' {74 declare module.exports: any;75}76declare module '@babel/traverse/lib/path/modification' {77 declare module.exports: any;78}79declare module '@babel/traverse/lib/path/removal' {80 declare module.exports: any;81}82declare module '@babel/traverse/lib/path/replacement' {83 declare module.exports: any;84}85declare module '@babel/traverse/lib/scope/binding' {86 declare module.exports: any;87}88declare module '@babel/traverse/lib/scope/index' {89 declare module.exports: any;90}91declare module '@babel/traverse/lib/scope/lib/renamer' {92 declare module.exports: any;93}94declare module '@babel/traverse/lib/visitors' {95 declare module.exports: any;96}97// Filename aliases98declare module '@babel/traverse/lib/cache.js' {99 declare module.exports: $Exports<'@babel/traverse/lib/cache'>;100}101declare module '@babel/traverse/lib/context.js' {102 declare module.exports: $Exports<'@babel/traverse/lib/context'>;103}104declare module '@babel/traverse/lib/hub.js' {105 declare module.exports: $Exports<'@babel/traverse/lib/hub'>;106}107declare module '@babel/traverse/lib/index.js' {108 declare module.exports: $Exports<'@babel/traverse/lib/index'>;109}110declare module '@babel/traverse/lib/path/ancestry.js' {111 declare module.exports: $Exports<'@babel/traverse/lib/path/ancestry'>;112}113declare module '@babel/traverse/lib/path/comments.js' {114 declare module.exports: $Exports<'@babel/traverse/lib/path/comments'>;115}116declare module '@babel/traverse/lib/path/context.js' {117 declare module.exports: $Exports<'@babel/traverse/lib/path/context'>;118}119declare module '@babel/traverse/lib/path/conversion.js' {120 declare module.exports: $Exports<'@babel/traverse/lib/path/conversion'>;121}122declare module '@babel/traverse/lib/path/evaluation.js' {123 declare module.exports: $Exports<'@babel/traverse/lib/path/evaluation'>;124}125declare module '@babel/traverse/lib/path/family.js' {126 declare module.exports: $Exports<'@babel/traverse/lib/path/family'>;127}128declare module '@babel/traverse/lib/path/index.js' {129 declare module.exports: $Exports<'@babel/traverse/lib/path/index'>;130}131declare module '@babel/traverse/lib/path/inference/index.js' {132 declare module.exports: $Exports<'@babel/traverse/lib/path/inference/index'>;133}134declare module '@babel/traverse/lib/path/inference/inferer-reference.js' {135 declare module.exports: $Exports<'@babel/traverse/lib/path/inference/inferer-reference'>;136}137declare module '@babel/traverse/lib/path/inference/inferers.js' {138 declare module.exports: $Exports<'@babel/traverse/lib/path/inference/inferers'>;139}140declare module '@babel/traverse/lib/path/introspection.js' {141 declare module.exports: $Exports<'@babel/traverse/lib/path/introspection'>;142}143declare module '@babel/traverse/lib/path/lib/hoister.js' {144 declare module.exports: $Exports<'@babel/traverse/lib/path/lib/hoister'>;145}146declare module '@babel/traverse/lib/path/lib/removal-hooks.js' {147 declare module.exports: $Exports<'@babel/traverse/lib/path/lib/removal-hooks'>;148}149declare module '@babel/traverse/lib/path/lib/virtual-types.js' {150 declare module.exports: $Exports<'@babel/traverse/lib/path/lib/virtual-types'>;151}152declare module '@babel/traverse/lib/path/modification.js' {153 declare module.exports: $Exports<'@babel/traverse/lib/path/modification'>;154}155declare module '@babel/traverse/lib/path/removal.js' {156 declare module.exports: $Exports<'@babel/traverse/lib/path/removal'>;157}158declare module '@babel/traverse/lib/path/replacement.js' {159 declare module.exports: $Exports<'@babel/traverse/lib/path/replacement'>;160}161declare module '@babel/traverse/lib/scope/binding.js' {162 declare module.exports: $Exports<'@babel/traverse/lib/scope/binding'>;163}164declare module '@babel/traverse/lib/scope/index.js' {165 declare module.exports: $Exports<'@babel/traverse/lib/scope/index'>;166}167declare module '@babel/traverse/lib/scope/lib/renamer.js' {168 declare module.exports: $Exports<'@babel/traverse/lib/scope/lib/renamer'>;169}170declare module '@babel/traverse/lib/visitors.js' {171 declare module.exports: $Exports<'@babel/traverse/lib/visitors'>;...
equal.js
Source:equal.js
1var assert = require('assert');2var traverse = require('traverse');3exports.deepDates = function () {4 assert.ok(5 traverse.deepEqual(6 { d : new Date, x : [ 1, 2, 3 ] },7 { d : new Date, x : [ 1, 2, 3 ] }8 ),9 'dates should be equal'10 );11 12 var d0 = new Date;13 setTimeout(function () {14 assert.ok(15 !traverse.deepEqual(16 { d : d0, x : [ 1, 2, 3 ], },17 { d : new Date, x : [ 1, 2, 3 ] }18 ),19 'microseconds should count in date equality'20 );21 }, 5);22};23exports.deepCircular = function () {24 var a = [1];25 a.push(a); // a = [ 1, *a ]26 27 var b = [1];28 b.push(a); // b = [ 1, [ 1, *a ] ]29 30 assert.ok(31 !traverse.deepEqual(a, b),32 'circular ref mount points count towards equality'33 );34 35 var c = [1];36 c.push(c); // c = [ 1, *c ]37 assert.ok(38 traverse.deepEqual(a, c),39 'circular refs are structurally the same here'40 );41 42 var d = [1];43 d.push(a); // c = [ 1, [ 1, *d ] ]44 assert.ok(45 traverse.deepEqual(b, d),46 'non-root circular ref structural comparison'47 );48};49exports.deepInstances = function () {50 assert.ok(51 !traverse.deepEqual([ new Boolean(false) ], [ false ]),52 'boolean instances are not real booleans'53 );54 55 assert.ok(56 !traverse.deepEqual([ new String('x') ], [ 'x' ]),57 'string instances are not real strings'58 );59 60 assert.ok(61 !traverse.deepEqual([ new Number(4) ], [ 4 ]),62 'number instances are not real numbers'63 );64 65 assert.ok(66 traverse.deepEqual([ new RegExp('x') ], [ /x/ ]),67 'regexp instances are real regexps'68 );69 70 assert.ok(71 !traverse.deepEqual([ new RegExp(/./) ], [ /../ ]),72 'these regexps aren\'t the same'73 );74 75 assert.ok(76 !traverse.deepEqual(77 [ function (x) { return x * 2 } ],78 [ function (x) { return x * 2 } ]79 ),80 'functions with the same .toString() aren\'t necessarily the same'81 );82 83 var f = function (x) { return x * 2 };84 assert.ok(85 traverse.deepEqual([ f ], [ f ]),86 'these functions are actually equal'87 );88};89exports.deepEqual = function () {90 assert.ok(91 !traverse.deepEqual([ 1, 2, 3 ], { 0 : 1, 1 : 2, 2 : 3 }),92 'arrays are not objects'93 );94};95exports.falsy = function () {96 assert.ok(97 !traverse.deepEqual([ undefined ], [ null ]),98 'null is not undefined!'99 );100 101 assert.ok(102 !traverse.deepEqual([ null ], [ undefined ]),103 'undefined is not null!'104 );105 106 assert.ok(107 !traverse.deepEqual(108 { a : 1, b : 2, c : [ 3, undefined, 5 ] },109 { a : 1, b : 2, c : [ 3, null, 5 ] }110 ),111 'undefined is not null, however deeply!'112 );113 114 assert.ok(115 !traverse.deepEqual(116 { a : 1, b : 2, c : [ 3, undefined, 5 ] },117 { a : 1, b : 2, c : [ 3, null, 5 ] }118 ),119 'null is not undefined, however deeply!'120 );121 122 assert.ok(123 !traverse.deepEqual(124 { a : 1, b : 2, c : [ 3, undefined, 5 ] },125 { a : 1, b : 2, c : [ 3, null, 5 ] }126 ),127 'null is not undefined, however deeply!'128 );129};130exports.deletedArrayEqual = function () {131 var xs = [ 1, 2, 3, 4 ];132 delete xs[2];133 134 var ys = Object.create(Array.prototype);135 ys[0] = 1;136 ys[1] = 2;137 ys[3] = 4;138 139 assert.ok(140 traverse.deepEqual(xs, ys),141 'arrays with deleted elements are only equal to'142 + ' arrays with similarly deleted elements'143 );144 145 assert.ok(146 !traverse.deepEqual(xs, [ 1, 2, undefined, 4 ]),147 'deleted array elements cannot be undefined'148 );149 150 assert.ok(151 !traverse.deepEqual(xs, [ 1, 2, null, 4 ]),152 'deleted array elements cannot be null'153 );154};155exports.deletedObjectEqual = function () {156 var obj = { a : 1, b : 2, c : 3 };157 delete obj.c;158 159 assert.ok(160 traverse.deepEqual(obj, { a : 1, b : 2 }),161 'deleted object elements should not show up'162 );163 164 assert.ok(165 !traverse.deepEqual(obj, { a : 1, b : 2, c : undefined }),166 'deleted object elements are not undefined'167 );168 169 assert.ok(170 !traverse.deepEqual(obj, { a : 1, b : 2, c : null }),171 'deleted object elements are not null'172 );173};174exports.emptyKeyEqual = function () {175 assert.ok(!traverse.deepEqual(176 { a : 1 }, { a : 1, '' : 55 }177 ));178};179exports.deepArguments = function () {180 assert.ok(181 !traverse.deepEqual(182 [ 4, 5, 6 ],183 (function () { return arguments })(4, 5, 6)184 ),185 'arguments are not arrays'186 );187 188 assert.ok(189 traverse.deepEqual(190 (function () { return arguments })(4, 5, 6),191 (function () { return arguments })(4, 5, 6)192 ),193 'arguments should equal'194 );195};196exports.deepUn = function () {197 assert.ok(!traverse.deepEqual({ a : 1, b : 2 }, undefined));198 assert.ok(!traverse.deepEqual({ a : 1, b : 2 }, {}));199 assert.ok(!traverse.deepEqual(undefined, { a : 1, b : 2 }));200 assert.ok(!traverse.deepEqual({}, { a : 1, b : 2 }));201 assert.ok(traverse.deepEqual(undefined, undefined));202 assert.ok(traverse.deepEqual(null, null));203 assert.ok(!traverse.deepEqual(undefined, null));204};205exports.deepLevels = function () {206 var xs = [ 1, 2, [ 3, 4, [ 5, 6 ] ] ];207 assert.ok(!traverse.deepEqual(xs, []));...
binary_search_tree.js
Source:binary_search_tree.js
1class BSTNode {2 constructor(value) {3 this.value = value;4 this.left = null;5 this.right = null;6 }7}8class BinarySearchTree {9 constructor() {10 this.root = null;11 }12 insert(value) {13 const _insert = function (newNode, node) {14 if (newNode.value < node.value) {15 if (node.left === null) {16 node.left = newNode;17 } else {18 _insert(newNode, node.left);19 }20 } else {21 if (node.right === null) {22 node.right = newNode;23 } else {24 _insert(newNode, node.right);25 }26 }27 };28 const newNode = new BSTNode(value);29 if (this.root === null) {30 this.root = newNode;31 } else {32 _insert(newNode, this.root);33 }34 return this;35 }36 preOrderTraverse() {37 const _preOrderTraverse = function (node, callback) {38 if (node !== null) {39 callback(node.value);40 _preOrderTraverse(node.left, callback);41 _preOrderTraverse(node.right, callback);42 }43 };44 _preOrderTraverse(this.root, console.log);45 }46 preOrderTraverseByStack(callback) {47 let node = this.root;48 const stack = [node];49 while (stack.length !== 0) {50 node = stack.pop();51 if (node) {52 callback(node.value);53 if (node.right) {54 stack.push(node.right);55 }56 if (node.left) {57 stack.push(node.left);58 }59 }60 }61 }62 inOrderTraverse() {63 const _inOrderTraverse = function (node, callback) {64 if (node !== null) {65 _inOrderTraverse(node.left, callback);66 callback(node.value);67 _inOrderTraverse(node.right, callback);68 }69 };70 _inOrderTraverse(this.root, console.log);71 }72 inOrderTraverseByStack(callback) {73 const stack = [];74 let node = this.root;75 while (node !== null || stack.length !== 0) {76 while (node !== null) {77 stack.push(node);78 node = node.left;79 }80 if (stack.length !== 0) {81 node = stack.pop();82 callback(node.value);83 node = node.right;84 }85 }86 }87 postOrderTraverse() {88 const _postOrderTraverse = function (node, callback) {89 if (node !== null) {90 _postOrderTraverse(node.left, callback);91 _postOrderTraverse(node.right, callback);92 callback(node.value);93 }94 };95 _postOrderTraverse(this.root, console.log);96 }97 postOrderTraverseByStack(callback) {98 const stack = [];99 let node = this.root;100 let lastVisit = node;101 while (node !== null || stack.length !== 0) {102 while (node !== null) {103 stack.push(node);104 node = node.left;105 }106 node = stack[stack.length - 1];107 if (node.right === null || lastVisit === node.right) {108 callback(node.value);109 node = stack.pop();110 lastVisit = node;111 node = null;112 } else {113 node = node.right;114 }115 }116 }117}118const bst = new BinarySearchTree();119bst120 .insert(11)121 .insert(7)122 .insert(15)123 .insert(5)124 .insert(3)125 .insert(9)126 .insert(8)127 .insert(10)128 .insert(13)129 .insert(12)130 .insert(14)131 .insert(20)132 .insert(18)133 .insert(25)134 .insert(6);...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const handle = await page.$('text=Get started');7 const node = await handle.evaluateHandle((node) => node);8 const internal = page._delegate;9 const { traverse } = internal._injectedScript;10 const result = await traverse(node, (node) => node.textContent);11 console.log(result);12 await browser.close();13})();14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 const handle = await page.$('text=Get started');20 const node = await handle.evaluateHandle((node) => node);21 const internal = page._delegate;22 const { traverse } = internal._injectedScript;23 const result = await traverse(node, (node) => node);24 console.log(result);25 await browser.close();26})();27const { chromium } = require('playwright');28(async () => {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 const handle = await page.$('text=Get started');33 const node = await handle.evaluateHandle((node) => node);34 const internal = page._delegate;35 const { traverse } = internal._injectedScript;36 const result = await traverse(node, (node) => node.nodeType);37 console.log(result);38 await browser.close();39})();40const { chromium } = require('playwright');41(async () => {42 const browser = await chromium.launch();43 const context = await browser.newContext();44 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await browser.close();7})();8module.exports = {9 use: {10 playwright: {11 },12 },13};
Using AI Code Generation
1const { traverse } = require('playwright/lib/client/selectorEngine');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const [element] = await traverse(page, 'css=div');7 console.log(await element.textContent());8 await browser.close();9})();10{11 "scripts": {12 },13 "dependencies": {14 }15}
Using AI Code Generation
1const { Page } = require('@playwright/test/lib/server/page');2const { ElementHandle } = require('@playwright/test/lib/server/dom');3const { Frame } = require('@playwright/test/lib/server/frame');4const { JSHandle } = require('@playwright/test/lib/server/jsHandle');5const { Page } = require('@playwright/test/lib/server/page');6const { ElementHandle } = require('@playwright/test/lib/server/dom');7const { Frame } = require('@playwright/test/lib/server/frame');8const { JSHandle } = require('@playwright/test/lib/server/jsHandle');9const { Page } = require('@playwright/test/lib/server/page');10const { ElementHandle } = require('@playwright/test/lib/server/dom');11const { Frame } = require('@playwright/test/lib/server/frame');12const { JSHandle } = require('@playwright/test/lib/server/jsHandle');13const { Page } = require('@playwright/test/lib/server/page');14const { ElementHandle } = require('@playwright/test/lib/server/dom');15const { Frame } = require('@playwright/test/lib/server/frame');16const { JSHandle } = require('@playwright/test/lib/server/jsHandle');17const { Page } = require('@playwright/test/lib/server/page');18const { ElementHandle } = require('@playwright/test/lib/server/dom');19const { Frame } = require('@playwright/test/lib/server/frame');20const { JSHandle } = require('@playwright/test/lib/server/jsHandle');21const { Page } = require('@playwright/test/lib/server/page');22const { ElementHandle } = require('@playwright/test/lib/server/dom');23const { Frame } = require('@playwright/test/lib/server/frame');24const { JSHandle } = require('@playwright/test/lib/server/jsHandle');25const { Page } = require('@playwright/test/lib/server/page');26const { ElementHandle } = require('@playwright/test/lib/server/dom');27const { Frame } = require('@playwright/test/lib/server/frame');28const { JSHandle } = require('@playwright/test/lib/server/jsHandle');
Using AI Code Generation
1const { traverse } = require('@playwright/test/lib/utils/stackTrace');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 await page.tracing.start({ screenshots: true, snapshots: true });5 await page.tracing.stop({ path: 'trace.zip' });6 const frames = await traverse(page.mainFrame());7 console.log(frames);8});9 {10 }11const { traverse } = require('@playwright/test/lib/utils/stackTrace');12const { test } = require('@playwright/test');13test('test', async ({ page }) => {14 await page.tracing.start({ screenshots: true, snapshots: true });15 await page.tracing.stop({ path: 'trace.zip' });16 const frames = await traverse(page.mainFrame());17 console.log(frames);18});19 {20 }
Using AI Code Generation
1const { traverse } = require('@playwright/test/lib/server/trace/recorder/recorderTraceEvents');2const fs = require('fs');3const path = require('path');4const tracePath = path.join(__dirname, 'trace.json');5const trace = JSON.parse(fs.readFileSync(tracePath, 'utf8'));6const events = traverse(trace.traceEvents);7for (const event of events) {8 if (event.name === 'Screenshot') {9 console.log(event.args.snapshot);10 }11}
Using AI Code Generation
1const { traverse } = require('@playwright/test/lib/utils/utils');2const { test } = require('@playwright/test');3test('My test', async ({ page }) => {4 await traverse(page, async (object, name) => {5 if (name === 'goto')6 console.log(`goto() was called with ${object.url()}`);7 });8});9const { traverse } = require('@playwright/test/lib/utils/utils');10const { test } = require('@playwright/test');11test('My test', async ({ page }) => {12 await traverse(page, async (object, name) => {13 if (name === 'goto')14 console.log(`goto() was called with ${object.url()}`);15 });16});17const { traverse } = require('@playwright/test/lib/utils/utils');18const { test } = require('@playwright/test');19test('My test', async ({ page }) => {20 await traverse(page, async (object, name) => {21 if (name === 'goto')22 console.log(`goto() was called with ${object.url()}`);23 });24});25const { traverse } = require('@playwright/test/lib/utils/utils');26const { test } = require('@playwright/test');27test('My test', async ({ page }) => {28 await traverse(page, async (object, name) => {29 if (name === 'goto')30 console.log(`goto() was called with ${object.url()}`);31 });32});33const {
Using AI Code Generation
1const { getTestState } = require('@playwright/test');2const { traverse } = getTestState().browserContext._delegate;3const button = await traverse(selector);4await button.click();5import { test } from '@playwright/test';6test('test', async ({ page }) => {7 await page.click('text=Get started');8 await page.click('text=Docs');9 await page.click('text=API');10 await page.click('text=Locator');11 await page.click('text=
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!