Best JavaScript code snippet using testcafe
content-editable.js
Source:content-editable.js
...37function hasVisibleChildren (node) {38 return arrayUtils.some(node.childNodes, isVisibleNode);39}40function hasSelectableChildren (node) {41 return arrayUtils.some(node.childNodes, child => isNodeSelectable(child, true));42}43//NOTE: before such elements (like div or p) adds line breaks before and after it44// (except line break before first visible element in contentEditable parent)45// this line breaks is not contained in node values46//so we should take it into account manually47function isNodeBlockWithBreakLine (parent, node) {48 let parentFirstVisibleChild = null;49 let firstVisibleChild = null;50 if (domUtils.isShadowUIElement(parent) || domUtils.isShadowUIElement(node))51 return false;52 if (!domUtils.isTheSameNode(node, parent) && domUtils.getChildNodesLength(node.childNodes) &&53 /div|p/.test(domUtils.getTagName(node))) {54 parentFirstVisibleChild = getOwnFirstVisibleNode(parent);55 if (!parentFirstVisibleChild || domUtils.isTheSameNode(node, parentFirstVisibleChild))56 return false;57 firstVisibleChild = getFirstVisibleTextNode(parentFirstVisibleChild);58 if (!firstVisibleChild || domUtils.isTheSameNode(node, firstVisibleChild))59 return false;60 return getOwnFirstVisibleTextNode(node);61 }62 return false;63}64function isNodeAfterNodeBlockWithBreakLine (parent, node) {65 const isRenderedNode = domUtils.isRenderedNode(node);66 let parentFirstVisibleChild = null;67 let firstVisibleChild = null;68 let previousSibling = null;69 if (domUtils.isShadowUIElement(parent) || domUtils.isShadowUIElement(node))70 return false;71 if (!domUtils.isTheSameNode(node, parent) &&72 (isRenderedNode && domUtils.isElementNode(node) && domUtils.getChildNodesLength(node.childNodes) &&73 !/div|p/.test(domUtils.getTagName(node)) ||74 isVisibleTextNode(node) && !domUtils.isTheSameNode(node, parent) && node.nodeValue.length)) {75 if (isRenderedNode && domUtils.isElementNode(node)) {76 parentFirstVisibleChild = getOwnFirstVisibleNode(parent);77 if (!parentFirstVisibleChild || domUtils.isTheSameNode(node, parentFirstVisibleChild))78 return false;79 firstVisibleChild = getFirstVisibleTextNode(parentFirstVisibleChild);80 if (!firstVisibleChild || domUtils.isTheSameNode(node, firstVisibleChild))81 return false;82 }83 previousSibling = getOwnPreviousVisibleSibling(node);84 return previousSibling && domUtils.isElementNode(previousSibling) &&85 /div|p/.test(domUtils.getTagName(previousSibling)) && getOwnFirstVisibleTextNode(previousSibling);86 }87 return false;88}89function getFirstTextNode (el, onlyVisible) {90 const children = el.childNodes;91 const childrenLength = domUtils.getChildNodesLength(children);92 let curNode = null;93 let child = null;94 let isNotContentEditableElement = null;95 const checkTextNode = onlyVisible ? isVisibleTextNode : domUtils.isTextNode;96 if (!childrenLength && checkTextNode(el))97 return el;98 for (let i = 0; i < childrenLength; i++) {99 curNode = children[i];100 isNotContentEditableElement = domUtils.isElementNode(curNode) && !domUtils.isContentEditableElement(curNode);101 if (checkTextNode(curNode))102 return curNode;103 else if (domUtils.isRenderedNode(curNode) && hasVisibleChildren(curNode) && !isNotContentEditableElement) {104 child = getFirstTextNode(curNode, onlyVisible);105 if (child)106 return child;107 }108 }109 return child;110}111export function getFirstVisibleTextNode (el) {112 return getFirstTextNode(el, true);113}114export function getLastTextNode (el, onlyVisible) {115 const children = el.childNodes;116 const childrenLength = domUtils.getChildNodesLength(children);117 let curNode = null;118 let child = null;119 let isNotContentEditableElement = null;120 let visibleTextNode = null;121 if (!childrenLength && isVisibleTextNode(el))122 return el;123 for (let i = childrenLength - 1; i >= 0; i--) {124 curNode = children[i];125 isNotContentEditableElement = domUtils.isElementNode(curNode) && !domUtils.isContentEditableElement(curNode);126 visibleTextNode = domUtils.isTextNode(curNode) &&127 (onlyVisible ? !isInvisibleTextNode(curNode) : true);128 if (visibleTextNode)129 return curNode;130 else if (domUtils.isRenderedNode(curNode) && hasVisibleChildren(curNode) && !isNotContentEditableElement) {131 child = getLastTextNode(curNode, false);132 if (child)133 return child;134 }135 }136 return child;137}138export function getFirstNonWhitespaceSymbolIndex (nodeValue, startFrom) {139 if (!nodeValue || !nodeValue.length)140 return 0;141 const valueLength = nodeValue.length;142 let index = startFrom || 0;143 for (let i = index; i < valueLength; i++) {144 if (nodeValue.charCodeAt(i) === 10 || nodeValue.charCodeAt(i) === 32)145 index++;146 else147 break;148 }149 return index;150}151export function getLastNonWhitespaceSymbolIndex (nodeValue) {152 if (!nodeValue || !nodeValue.length)153 return 0;154 const valueLength = nodeValue.length;155 let index = valueLength;156 for (let i = valueLength - 1; i >= 0; i--) {157 if (nodeValue.charCodeAt(i) === 10 || nodeValue.charCodeAt(i) === 32)158 index--;159 else160 break;161 }162 return index;163}164export function isInvisibleTextNode (node) {165 if (!domUtils.isTextNode(node))166 return false;167 const nodeValue = node.nodeValue;168 const firstVisibleIndex = getFirstNonWhitespaceSymbolIndex(nodeValue);169 const lastVisibleIndex = getLastNonWhitespaceSymbolIndex(nodeValue);170 return firstVisibleIndex === nodeValue.length && lastVisibleIndex === 0;171}172function isVisibleTextNode (node) {173 return domUtils.isTextNode(node) && !isInvisibleTextNode(node);174}175function isSkippableNode (node) {176 return !domUtils.isRenderedNode(node) || domUtils.isShadowUIElement(node);177}178//dom utils179function hasContentEditableAttr (el) {180 const attrValue = el.getAttribute ? el.getAttribute('contenteditable') : null;181 return attrValue === '' || attrValue === 'true';182}183export function findContentEditableParent (element) {184 const elParents = domUtils.getParents(element);185 if (hasContentEditableAttr(element) && domUtils.isContentEditableElement(element))186 return element;187 const currentDocument = domUtils.findDocument(element);188 if (currentDocument.designMode === 'on')189 return currentDocument.body;190 return arrayUtils.find(elParents, parent => hasContentEditableAttr(parent) &&191 domUtils.isContentEditableElement(parent));192}193export function getNearestCommonAncestor (node1, node2) {194 if (domUtils.isTheSameNode(node1, node2)) {195 if (domUtils.isTheSameNode(node2, findContentEditableParent(node1)))196 return node1;197 return nativeMethods.nodeParentNodeGetter.call(node1);198 }199 const ancestors = [];200 const contentEditableParent = findContentEditableParent(node1);201 let curNode = null;202 if (!domUtils.isElementContainsNode(contentEditableParent, node2))203 return null;204 for (curNode = node1; curNode !== contentEditableParent; curNode = nativeMethods.nodeParentNodeGetter.call(curNode))205 ancestors.push(curNode);206 for (curNode = node2; curNode !== contentEditableParent; curNode = nativeMethods.nodeParentNodeGetter.call(curNode)) {207 if (arrayUtils.indexOf(ancestors, curNode) !== -1)208 return curNode;209 }210 return contentEditableParent;211}212//selection utils213function getSelectedPositionInParentByOffset (node, offset) {214 let currentNode = null;215 let currentOffset = null;216 const childCount = domUtils.getChildNodesLength(node.childNodes);217 let isSearchForLastChild = offset >= childCount;218 // NOTE: we get a child element by its offset index in the parent219 if (domUtils.isShadowUIElement(node))220 return { node, offset };221 // NOTE: IE behavior222 if (isSearchForLastChild)223 currentNode = node.childNodes[childCount - 1];224 else {225 currentNode = node.childNodes[offset];226 currentOffset = 0;227 }228 // NOTE: skip shadowUI elements229 if (domUtils.isShadowUIElement(currentNode)) {230 if (childCount <= 1)231 return { node, offset: 0 };232 isSearchForLastChild = offset - 1 >= childCount;233 if (isSearchForLastChild)234 currentNode = node.childNodes[childCount - 2];235 else {236 currentNode = node.childNodes[offset - 1];237 currentOffset = 0;238 }239 }240 // NOTE: we try to find text node241 while (!isSkippableNode(currentNode) && domUtils.isElementNode(currentNode)) {242 const visibleChildren = getVisibleChildren(currentNode);243 if (visibleChildren.length)244 currentNode = visibleChildren[isSearchForLastChild ? visibleChildren.length - 1 : 0];245 else {246 //NOTE: if we didn't find a text node then always set offset to zero247 currentOffset = 0;248 break;249 }250 }251 if (currentOffset !== 0 && !isSkippableNode(currentNode))252 currentOffset = currentNode.nodeValue ? currentNode.nodeValue.length : 0;253 return {254 node: currentNode,255 offset: currentOffset256 };257}258function getSelectionStart (el, selection, inverseSelection) {259 const startNode = inverseSelection ? selection.focusNode : selection.anchorNode;260 const startOffset = inverseSelection ? selection.focusOffset : selection.anchorOffset;261 let correctedStartPosition = {262 node: startNode,263 offset: startOffset264 };265 //NOTE: window.getSelection() can't returns not rendered node like selected node, so we shouldn't check it266 if ((domUtils.isTheSameNode(el, startNode) || domUtils.isElementNode(startNode)) && hasSelectableChildren(startNode))267 correctedStartPosition = getSelectedPositionInParentByOffset(startNode, startOffset);268 return {269 node: correctedStartPosition.node,270 offset: correctedStartPosition.offset271 };272}273function getSelectionEnd (el, selection, inverseSelection) {274 const endNode = inverseSelection ? selection.anchorNode : selection.focusNode;275 const endOffset = inverseSelection ? selection.anchorOffset : selection.focusOffset;276 let correctedEndPosition = {277 node: endNode,278 offset: endOffset279 };280 //NOTE: window.getSelection() can't returns not rendered node like selected node, so we shouldn't check it281 if ((domUtils.isTheSameNode(el, endNode) || domUtils.isElementNode(endNode)) && hasSelectableChildren(endNode))282 correctedEndPosition = getSelectedPositionInParentByOffset(endNode, endOffset);283 return {284 node: correctedEndPosition.node,285 offset: correctedEndPosition.offset286 };287}288export function getSelection (el, selection, inverseSelection) {289 return {290 startPos: getSelectionStart(el, selection, inverseSelection),291 endPos: getSelectionEnd(el, selection, inverseSelection)292 };293}294export function getSelectionStartPosition (el, selection, inverseSelection) {295 const correctedSelectionStart = getSelectionStart(el, selection, inverseSelection);296 return calculatePositionByNodeAndOffset(el, correctedSelectionStart);297}298export function getSelectionEndPosition (el, selection, inverseSelection) {299 const correctedSelectionEnd = getSelectionEnd(el, selection, inverseSelection);300 return calculatePositionByNodeAndOffset(el, correctedSelectionEnd);301}302function getElementOffset (target) {303 let offset = 0;304 const firstBreakElement = arrayUtils.find(target.childNodes, (node, index) => {305 offset = index;306 return domUtils.getTagName(node) === 'br';307 });308 return firstBreakElement ? offset : 0;309}310function isNodeSelectable (node, includeDescendants) {311 if (styleUtils.isNotVisibleNode(node))312 return false;313 if (domUtils.isTextNode(node))314 return true;315 if (!domUtils.isElementNode(node))316 return false;317 if (hasSelectableChildren(node))318 return includeDescendants;319 const parent = nativeMethods.nodeParentNodeGetter.call(node);320 const isContentEditableRoot = !domUtils.isContentEditableElement(parent);321 const visibleChildren = getVisibleChildren(node);322 const hasBreakLineElements = arrayUtils.some(visibleChildren, child => domUtils.getTagName(child) === 'br');323 return isContentEditableRoot || hasBreakLineElements;324}325export function calculateNodeAndOffsetByPosition (el, offset) {326 let point = {327 node: null,328 offset: offset329 };330 function checkChildNodes (target) {331 const childNodes = target.childNodes;332 const childNodesLength = domUtils.getChildNodesLength(childNodes);333 if (point.node)334 return point;335 if (isSkippableNode(target))336 return point;337 if (domUtils.isTextNode(target)) {338 if (point.offset <= target.nodeValue.length) {339 point.node = target;340 return point;341 }342 else if (target.nodeValue.length) {343 if (!point.node && isNodeAfterNodeBlockWithBreakLine(el, target))344 point.offset--;345 point.offset -= target.nodeValue.length;346 }347 }348 else if (domUtils.isElementNode(target)) {349 if (!isVisibleNode(target))350 return point;351 if (point.offset === 0 && isNodeSelectable(target, false)) {352 point.node = target;353 point.offset = getElementOffset(target);354 return point;355 }356 if (!point.node && (isNodeBlockWithBreakLine(el, target) || isNodeAfterNodeBlockWithBreakLine(el, target)))357 point.offset--;358 else if (!childNodesLength && domUtils.getTagName(target) === 'br')359 point.offset--;360 }361 for (let i = 0; i < childNodesLength; i++)362 point = checkChildNodes(childNodes[i]);363 return point;364 }365 return checkChildNodes(el);...
index.js
Source:index.js
1// @flow2import {Input} from 'antd';3import Color from 'color';4import memoizeOne from 'memoize-one';5import Radium from 'radium';6import * as React from 'react';7import {REMOVED_CATEGORY, WITHOUT_CATEGORY} from 'stores/NoteStore';8import type {ThemeType} from 'stores/ThemeStore';9import type {CategoryType} from 'types/NoteType';10import styles from './styles.scss';11const STYLES = memoizeOne((theme: ThemeType) => (12 {13 input: {14 background: 'transparent',15 color: 'white',16 border: 'none',17 outline: 'none',18 boxShadow: 'none',19 marginLeft: '0',20 paddingLeft: '0',21 },22 item: {23 display: 'flex',24 cursor: 'pointer',25 height: theme.measure.rowCategoryHeight,26 alignItems: 'center',27 border: '1px dashed transparent',28 borderTopLeftRadius: '0.25em',29 borderBottomLeftRadius: '0.25em',30 overflow: 'hidden',31 ':hover': {32 color: theme.color.white,33 },34 },35 toolbarButton: {36 marginRight: '0.5em',37 marginLeft: '0.4em',38 fontSize: '1.1em',39 },40 draggingItem : {41 cursor: 'copy',42 },43 overItem: {44 border: '1px dashed white',45 },46 selectedItem: {47 backgroundColor: Color(theme.color.textMain).alpha(0.2),48 },49 }50));51type PropsType = {52 title: string | Object,53 rowTitleClassName: string,54 rowLabelClassName: string,55 isNodeSelectable?: boolean,56 categoryIsEditing: boolean,57 isLandingPadActive?: boolean,58 isDraggedDescendant?: boolean,59 isDragging?: boolean,60 canDrop?: boolean,61 canDrag?: boolean,62 isSearchMatch?: boolean,63 isSearchFocus?: boolean,64 isNodeSelected: boolean,65 category: CategoryType,66 scaffold?: Array<React.Node>,67 icons?: Array<React.Node>,68 buttons?: Array<React.Node>,69 changeNoteCategory: (noteUUID: string, categoryUUIDs: Array<string>) => void,70 updateCategoryName: (categoryName: string) => void,71 onSelectCategory: (category: CategoryType) => void,72 connectDragPreview?: (node: React.Node) => React.Node,73 theme: ThemeType,74};75@Radium76export default class CategoryItem extends React.Component<PropsType> {77 static defaultProps = {78 isNodeSelectable: true,79 isDraggedDescendant: false,80 isSearchMatch: false,81 isSearchFocus: false,82 canDrop: false,83 canDrag: false,84 isLandingPadActive: false,85 scaffold: [],86 icons: [],87 buttons: [],88 connectDragPreview: (node: React.Node) => node,89 };90 state = {91 isOver: false,92 categoryName: null,93 };94 onDragLeave = () => this.setState({isOver: false});95 onDragOver = event => {96 event.stopPropagation();97 event.preventDefault();98 const {category} = this.props;99 if (event.dataTransfer.items.length !== 2100 || event.dataTransfer.items[1].type !== 'category'101 || category.uuid === WITHOUT_CATEGORY102 || category.uuid === REMOVED_CATEGORY) return true;103 event.dataTransfer.dropEffect = 'move';104 this.setState({isOver: true});105 return false;106 };107 onDrop = event => {108 const text = event.dataTransfer.getData('Text');109 if (!text) return true;110 const {noteUUID, categoryUUIDs} = JSON.parse(text);111 if (!noteUUID) return true;112 const {changeNoteCategory, category} = this.props;113 if (category.uuid === WITHOUT_CATEGORY || category.uuid === REMOVED_CATEGORY) return true;114 this.onDragLeave();115 if (categoryUUIDs.indexOf(category.uuid) !== -1) return true;116 event.stopPropagation();117 event.preventDefault();118 changeNoteCategory(noteUUID, category.uuid);119 return false;120 };121 onChangeCategoryName = event => this.setState({categoryName: event.currentTarget.value});122 handleKeyPress = event => {123 const isEscape = event.key === 'Escape';124 if (event.key === 'Enter' || isEscape) {125 const {categoryIsEditing, isNodeSelected, updateCategoryName} = this.props;126 const {categoryName} = this.state;127 if (categoryIsEditing128 && isNodeSelected129 && (130 categoryName || categoryName === null || isEscape131 )) {132 this.setState({categoryName: null});133 event.preventDefault();134 updateCategoryName(isEscape ? null : categoryName);135 }136 }137 };138 editCancel = event => {139 event.preventDefault();140 event.stopPropagation();141 this.setState({categoryName: null});142 const {updateCategoryName} = this.props;143 updateCategoryName(null);144 };145 handleFocus = event => event.target.select();146 render() {147 const {isOver, categoryName} = this.state;148 const {149 rowLabelClassName, rowTitleClassName, title, categoryIsEditing, isSearchFocus,150 isNodeSelected, category, theme, isNodeSelectable, canDrop, isSearchMatch,151 onSelectCategory, canDrag, connectDragPreview, scaffold, isLandingPadActive,152 isDraggedDescendant, icons, buttons, isDragging,153 } = this.props;154 const style = STYLES(theme);155 let styleItem = style.item;156 if (isNodeSelected && isNodeSelectable) styleItem = {...styleItem, ...style.selectedItem};157 if (isOver) styleItem = {...styleItem, ...style.overItem};158 if (isDragging) styleItem = {...styleItem, ...style.draggingItem};159 return (160 <div161 onClick={event => {162 if (isNodeSelected) {163 event.stopPropagation();164 } else if (!categoryIsEditing) {165 event.stopPropagation();166 onSelectCategory(category);167 }168 }}169 style={styleItem}170 onDragLeave={this.onDragLeave}171 onDragOver={this.onDragOver}172 onDrop={this.onDrop}173 className={174 styles.rowWrapper175 + (176 !canDrag && isDragging ? ` ${styles.rowWrapperDragDisabled}` : ''177 )178 }179 >180 {/* Set the row preview to be used during drag and drop */}181 <div style={{display: 'flex', flex: 1, height: '100%'}}>182 {scaffold}183 <div184 className={185 styles.row186 + (187 isLandingPadActive && !canDrop188 ? ` ${styles.rowCancelPad}`189 : ''190 )191 + (192 isSearchMatch ? ` ${styles.rowSearchMatch}` : ''193 )194 + (195 isSearchFocus ? ` ${styles.rowSearchFocus}` : ''196 )197 + (198 isLandingPadActive ? ` ${styles.rowLandingPad}` : ''199 )200 }201 style={{202 opacity: isDraggedDescendant ? 0.5 : 1,203 ...style,204 }}205 >206 <div207 className={208 styles.rowContents209 + (210 !canDrag && isDragging ? ` ${styles.rowWrapperDragDisabled}` : ''211 )212 }213 >214 <div className={styles.rowToolbar}>215 {icons.map((icon: React.Node, index: number) => (216 <div217 key={index} // eslint-disable-line react/no-array-index-key218 className={styles.toolbarButton}219 style={style.toolbarButton}220 >221 {icon}222 </div>223 ))}224 </div>225 {categoryIsEditing && isNodeSelected ? (226 <div>227 <Input228 autoFocus229 onKeyDown={this.handleKeyPress}230 onChange={this.onChangeCategoryName}231 onBlur={this.editCancel}232 value={categoryName || category.title}233 defaultValue={category.title}234 onFocus={this.handleFocus}235 style={style.input}236 />237 </div>238 ) : (239 <div className={rowLabelClassName}>240 <span className={rowTitleClassName}>241 {title}242 </span>243 </div>244 )}245 <div className={styles.rowToolbar}>246 {buttons.map((btn: React.Node, index: number) => (247 <div248 key={index} // eslint-disable-line react/no-array-index-key249 className={styles.toolbarButton}250 >251 {btn}252 </div>253 ))}254 </div>255 </div>256 </div>257 </div>258 </div>259 );260 }...
Accordion.js
Source:Accordion.js
...114 var node = null;115 if (!this.view.isDisabled()) {116 var inspectedNode = this.view.getRootNode();117 while (inspectedNode) {118 if (this.isNodeSelectable(inspectedNode)) {119 node = inspectedNode;120 break;121 } else {122 inspectedNode = inspectedNode.firstChild;123 }124 }125 }126 return node;127 },128 /**129 * @returns {Void}130 */131 accordionFirstSelectableNodeSelect: function () {132 var firstSelectableNode = this.cmfg('accordionFirtsSelectableNodeGet');133 if (Ext.isObject(firstSelectableNode) && !Ext.Object.isEmpty(firstSelectableNode)) {134 this.cmfg('accordionDeselect');135 this.cmfg('accordionNodeByIdSelect', { id: firstSelectableNode.get(CMDBuild.core.constants.Proxy.ID) });136 }137 },138 /**139 * @returns {String or null}140 */141 accordionIdentifierGet: function () {142 if (!Ext.isEmpty(this.identifier))143 return this.identifier;144 return null;145 },146 // Node by Id manage methods147 /**148 * @param {Number or String} id149 *150 * @returns {Boolean}151 */152 accordionNodeByIdExists: function (id) {153 return !Ext.isEmpty(this.cmfg('accordionNodeByIdGet', id));154 },155 /**156 * Search in entityId and id parameter157 *158 * @param {Number or String} id159 *160 * @returns {CMDBuild.model.common.Accordion}161 */162 accordionNodeByIdGet: function (id) {163 return (164 this.view.getStore().getRootNode().findChild(CMDBuild.core.constants.Proxy.ID, id, true)165 || this.view.getStore().getRootNode().findChild(CMDBuild.core.constants.Proxy.ENTITY_ID, id, true)166 );167 },168 /**169 * @param {Object} parameters170 * @param {Number or String} parameters.id171 * @param {String} parameters.mode [normal || silently]172 *173 * @returns {Void}174 */175 accordionNodeByIdSelect: function (parameters) {176 parameters = Ext.isObject(parameters) ? parameters : {};177 parameters.mode = Ext.isString(parameters.mode) ? parameters.mode : 'normal';178 if (!Ext.Object.isEmpty(parameters) && !Ext.isEmpty(parameters.id)) {179 var node = this.cmfg('accordionNodeByIdGet', parameters.id);180 // Error handling181 if (!Ext.isObject(node) || Ext.Object.isEmpty(node))182 return _error('accordionNodeByIdSelect(): unmanaged node', this, node);183 // END: Error handling184 node.bubble(function () {185 this.expand();186 });187 this.view.getSelectionModel().select(node);188 if (parameters.mode != 'silently')189 this.eventForwardSelection();190 }191 },192 /**193 * @param {Object} parameters194 * @param {Boolean} parameters.loadMask195 * @param {Number} parameters.selectionId196 *197 * @returns {Void}198 *199 * @abstract200 */201 accordionUpdateStore: Ext.emptyFn,202 /**203 * @returns {Void}204 *205 * @private206 */207 eventForwardSelection: function () {208 if (this.view.getSelectionModel().hasSelection()) {209 var selection = this.view.getSelectionModel().getSelection()[0];210 if (211 !this.cmfg('mainViewportModuleShow', {212 identifier: selection.get('cmName'),213 params: {214 node: selection215 }216 })217 ) {218 // If the panel was not brought to front (report from the navigation menu), select the previous node or deselect the tree219 if (!Ext.isEmpty(this.lastSelection)) {220 this.view.getSelectionModel().select(this.lastSelection);221 } else {222 this.view.getSelectionModel().deselectAll(true);223 }224 } else {225 this.lastSelection = selection;226 }227 // Notify accordion selection event to mainViewport's controller (accordion selection synchronizations)228 this.cmfg('onMainViewportAccordionSelect', {229 id: this.cmfg('accordionIdentifierGet'),230 node: selection231 });232 }233 },234 /**235 * @returns {Boolean}236 *237 * @private238 */239 isEmpty: function () {240 return !this.view.getStore().getRootNode().hasChildNodes();241 },242 /**243 * @param {CMDBuild.model.common.Accordion} node244 *245 * @returns {Boolean}246 *247 * @private248 */249 isNodeSelectable: function (node) {250 return (251 !node.isRoot() // Root is hidden by default252 && node.get(CMDBuild.core.constants.Proxy.SELECTABLE)253 && !Ext.isEmpty(node.get(CMDBuild.core.constants.Proxy.ID)) // Node without id property are not selectable254 );255 },256 /**257 * If node is already selected launch selection change event to be able to reselect same node without switch selection258 *259 * @param {CMDBuild.model.common.Accordion} node260 *261 * @returns {Void}262 */263 onAccordionBeforeItemClick: function (node) {264 // Error handling265 if (!Ext.isObject(node) || Ext.Object.isEmpty(node))266 return _error('onAccordionBeforeItemClick(): unmanaged node', this, node);267 // END: Error handling268 this.eventForwardSelection();269 },270 /**271 * @param {CMDBuild.model.common.Accordion} node272 *273 * @returns {Boolean}274 */275 onAccordionBeforeSelect: function (node) {276 return this.isNodeSelectable(node);277 },278 /**279 * @returns {Void}280 */281 onAccordionExpand: function () {282 this.cmfg('mainViewportModuleShow', { identifier: this.cmfg('accordionIdentifierGet') });283 // Update store284 if (!this.disableStoreLoad)285 if (this.view.getSelectionModel().hasSelection()) {286 var selection = this.view.getSelectionModel().getSelection()[0];287 this.cmfg('accordionDeselect');288 this.cmfg('accordionUpdateStore', { selectionId: selection.get(CMDBuild.core.constants.Proxy.ENTITY_ID) || selection.get(CMDBuild.core.constants.Proxy.ID) });289 } else {290 this.cmfg('accordionUpdateStore');...
Selector.js
Source:Selector.js
...51 function select(dbId) {52 var it = getInstanceTree();53 if (it) {54 dbId = it.findNodeForSelection(dbId, _this.selectionMode);55 if (!it.isNodeSelectable(dbId))56 return;57 }58 var found = isSelected(dbId);59 if (!found) {60 _this.selectedObjectIds[dbId] = dbId;61 _this.selectionCount++;62 markObject(dbId);63 }64 }65 function deselect(dbId) {66 var found = isSelected(dbId);67 if (found) {68 unmarkObject(dbId);69 _this.selectedObjectIds[dbId] = 0;...
view-tree-select.directive.js
Source:view-tree-select.directive.js
...53 return $scope.collapsedTreeNodes.indexOf(nodeId) > -154 }55 $scope.attachHoverEffectClass = {};56 $scope.toggleNodeSelected = function (node) {57 if ($scope.isNodeSelectable(node.id) || $scope.isRecordSelected(node.recordId)) {58 $timeout(function(){59 $rootScope.$emit("webvellaAdmin-toggleTreeNode-selected", node);60 },0);61 }62 }63 $scope.toggleNodeCollapse = function (node) {64 $timeout(function(){65 $rootScope.$emit("webvellaAdmin-toggleTreeNode-collapsed", node);66 },0);67 }68 }...
Node.js
Source:Node.js
...7export function Node({ cluster, index }) {8 const { state, dispatch } = useContext(CalculatorContext);9 const nodeInfo = { cluster, index };10 const isSelected = isNodeSelected(nodeInfo, state);11 const isSelectable = !isSelected && isNodeSelectable(nodeInfo, state);12 const selectedSubnode = isSelected && getSelectedSubnode(nodeInfo, state);13 const node = CLUSTERS[cluster].nodes[index];14 let text = node.description;15 if (node.subnodes) text += node.subnodes.join(' ');16 text = text.toLowerCase();17 const matchesFilter = !state.filter || text.includes(state.filter);18 function handler(subnode) {19 if (!isSelected) {20 dispatch({21 type: 'select',22 node: { subnode, ...nodeInfo },23 });24 } else if (subnode != selectedSubnode) {25 dispatch({...
selection.js
Source:selection.js
...22 const newPoints = { ...state.points };23 const bonusPoint = getBonusPoint(node);24 switch (type) {25 case 'select':26 if (!isNodeSelectable(node, state)) break;27 newNodes[nodeId] = node.subnode;28 if (isClusterComplete(cluster, { ...state, nodes: newNodes })) {29 for (let embodiment in cluster.rewards) {30 newPoints[embodiment] += cluster.rewards[embodiment];31 }32 }33 if (bonusPoint) newPoints[bonusPoint] += 1;34 break;35 case 'deselect':36 if (!isNodeDeselectable(node, state)) break;37 if (cluster && isClusterComplete(cluster, { ...state, nodes: newNodes })) {38 for (let embodiment in cluster.rewards) {39 newPoints[embodiment] -= cluster.rewards[embodiment];40 }...
util.js
Source:util.js
1import { CLUSTERS } from '../dataset';2export function isNodeSelected(node, state) {3 return `${node.cluster}.${node.index}` in state.nodes;4}5export function isNodeSelectable(node, state) {6 if (node.cluster == 'root') return true;7 const cluster = CLUSTERS[node.cluster];8 const clusterAvailable = isClusterAvailable(cluster, state);9 return (10 (clusterAvailable && node.index == 0) ||11 (clusterAvailable && isNodeSelected({ ...node, index: node.index - 1 }, state))12 );13}14export function isNodeDeselectable(node, state) {15 return !isNodeSelected({ ...node, index: node.index + 1 }, state);16}17export function getNodeId(node) {18 return `${node.cluster}.${node.index}`;19}...
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 const developerName = Selector('#developer-name');4 const submitButton = Selector('#submit-button');5 .typeText(developerName, 'John Smith')6 .click(submitButton);7});8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.type('#developer-name', 'John Smith');13 await page.click('#submit-button');14 await browser.close();15})();16Your name to display (optional):17Your name to display (optional):18const puppeteer = require('puppeteer');19(async () => {20 const browser = await puppeteer.launch();21 const page = await browser.newPage();22 const checkbox = await page.$('#tried-test-cafe');23 const isChecked = await page.evaluate(checkbox => checkbox.checked, checkbox);24 await browser.close();25})();26Your name to display (optional):
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .click(Selector('label').withText('I have tried TestCafe'))4 .click('#tried-test-cafe')5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button')7 .wait(3000);8});9import { Selector } from 'testcafe';10test('My first test', async t => {11 .click(Selector('label').withText('I have tried TestCafe'))12 .click('#tried-test-cafe')13 .typeText('#developer-name', 'John Smith')14 .click('#submit-button')15 .wait(3000);16});17import { Selector } from 'testcafe';18test('My first test', async t => {19 .click(Selector('label').withText('I have tried TestCafe'))20 .click('#tried-test-cafe')21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button')23 .wait(3000);24});25import { Selector } from 'testcafe';26test('My first test', async t => {27 .click(Selector('label').withText('I have tried TestCafe'))28 .click('#tried-test-cafe')29 .typeText('#developer-name', 'John Smith')30 .click('#submit-button')31 .wait(3000);32});33import { Selector } from 'testcafe';34test('My first test', async t => {
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3 const isNodeSelectable = Selector(node => node.getAttribute('id') === 'tried-test-cafe');4 .click(isNodeSelectable)5 .expect(isNodeSelectable.checked).ok()6 .expect(isNodeSelectable.value).eql('on');7});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3 .click(Selector('input').withAttribute('id', 'remote-testing'))4 .click(Selector('input').withAttribute('id', 'reusing-js-code'))5 .click(Selector('input').withAttribute('id', 'continuous-integration-embedding'))6 .click(Selector('input').withAttribute('id', 'background-parallel-testing'))7 .click(Selector('input').withAttribute('id', 'testcafe-studio'))8 .click(Selector('input').withAttribute('id', 'using-testcafe'))9 .click(Selector('input').withAttribute('id', 'running-tests'))10 .click(Selector('input').withAttribute('id', 'coding-your-own'))11 .click(Selector('input').withAttribute('id', 'building-testing-environment'))12 .click(Selector('input').withAttribute('id', 'testcafe-recommendations'))13 .click(Selector('input').withAttribute('id', 'testcafe-basics'));14});15import { Selector } from 'testcafe';16test('My test', async t => {17 .click(Selector('input').withAttribute('id', 'remote-testing'))18 .click(Selector('input').withAttribute('id', 'reusing-js-code'))19 .click(Selector('input').withAttribute('id', 'continuous-integration-embedding'))20 .click(Selector('input').withAttribute('id', 'background-parallel-testing'))21 .click(Selector('input').withAttribute('id', 'testcafe-studio'))22 .click(Selector('input').withAttribute('id', 'using-testcafe'))23 .click(Selector('input').withAttribute('id', 'running-tests'))24 .click(Selector('input').withAttribute('id', 'coding-your-own'))25 .click(Selector('input').withAttribute('id', 'building-testing-environment'))26 .click(Selector('input').withAttribute('id',
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3 const select = Selector('.column.col-2').find('option').with({visibilityCheck: true, timeout: 5000});4 const isNodeSelectable = await select.isNodeSelectable();5 await t.expect(isNodeSelectable).ok();6});
Using AI Code Generation
1const { Selector } = require('testcafe');2const isNodeSelectable = (node) => {3 if (node.tagName === 'DIV') {4 return true;5 }6 return false;7};8test('My Test', async t => {9 const node = Selector('div').with({ visibilityCheck: true, timeout: 5000 });10 await t.expect(await node.exists).ok();11 await t.expect(await node.visible).ok();12 await t.expect(await node.isNodeSelectable()).ok();13});14 √ My Test (1s)151 passed (1s)16#### Selector.with(options)17#### SelectorBuilder.with(options)18#### ClientFunctionBuilder.with(options)19#### ClientFunction.with(options)
Using AI Code Generation
1import { Selector } from 'testcafe';2const isNodeSelectable = Selector((node, selector) => {3 const parentNode = node.parentNode;4 return parentNode && parentNode.matches(selector);5});6test('My test', async t => {7 .click(isNodeSelectable('a').withText('Click me'));8});9 .click(Selector('a').with({ isNodeSelectable: true }).withText('Click me'));10 .click(Selector('a').with({ isNodeSelectable: (node, selector) => node.parentNode && node.parentNode.matches(selector) }).withText('Click me'));11import { Selector } from 'testcafe';12const isNodeSelectable = Selector((node, selector) => {13 const parentNode = node.parentNode;14 return parentNode && parentNode.matches(selector);15});16test('My test', async t => {17 .click(isNodeSelectable('a').withText('Click me'));18});19 .click(Selector('a').with({ isNodeSelectable: true }).withText('Click me'));
Using AI Code Generation
1import {Selector} from 'testcafe';2const getSelector = Selector((el) => {3 if (el.nodeName === 'A' || el.nodeName === 'BUTTON') {4 return el;5 }6 return null;7}, {8 dependencies: { isNodeSelectable },9 textFilter: (node, text) => isNodeSelectable(node) && node.innerText === text10});11const isNodeSelectable = (node) => {12 if (node.nodeName === 'A' || node.nodeName === 'BUTTON') {13 return true;14 }15 return false;16};17test('My first test', async t => {18 .click(getSelector('Submit'));19});20const select = Selector('div').withText('Select').parent(1).find('div').withAttribute('class','Select-control');21const selectOption = Selector('div').withText('Select').parent(1).find('div').withAttribute('class','Select-menu-outer').find('div').withAttribute('class','Select-option').withText('Option 1');22await t.click(select).click(selectOption);23const select = Selector('div').withText('Select').parent(1).find('div').withAttribute('class','Select-control');24const selectOption = Selector('div').withText('Select').parent(1).find('div').withAttribute('class','Select-menu-outer').find('div').withAttribute('class','Select-option').withText('Option 1');25await t.click(select).click(selectOption);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!