/**
 * From https://github.com/netlify/netlify-cms/blob/a4b7481a99f58b9abe85ab5712d27593cde20096/cypress/support/commands.js
 */ import { isMac } from '../../src/utils/navigator' ; const ctrl = isMac ( ) ? 'cmd' : 'ctrl' ; function getTextNode ( el , match ? ) { const walk = document . createTreeWalker ( el , NodeFilter . SHOW_TEXT , null ) ; if ( ! match ) { return walk . nextNode ( ) as Text ; } let node ; while ( ( node = walk . nextNode ( ) ) ) { if ( ( node as Text ) . wholeText . indexOf ( match ) >= 0 ) { return node as Text ; } } return null ; } function setBaseAndExtent ( ... args ) { const document = args [ 0 ] . ownerDocument ; document ?. getSelection ( ) ?. removeAllRanges ( ) ; document ?. getSelection ( ) ?. setBaseAndExtent ( ... args ) ; } Cypress . Commands . add ( 'selection' , { prevSubject : true } , ( ( subject , fn ) => { cy . wrap ( subject ) . trigger ( 'mousedown' , { force : true } ) . then ( fn ) . trigger ( 'mouseup' , { force : true } ) ; cy . document ( ) . trigger ( 'selectionchange' ) ; return cy . wrap ( subject ) ; } ) as any ) ; Cypress . Commands . add ( 'setSelection' , { prevSubject : true } , ( ( subject , query , endQuery ? ) => cy . wrap ( subject ) . selection ( ( $el ) => { const anchorNode = getTextNode ( $el [ 0 ] , query ) ; if ( ! anchorNode ) return ; const focusNode = endQuery ? getTextNode ( $el [ 0 ] , endQuery ) : anchorNode ; if ( ! focusNode ) return ; const anchorOffset = anchorNode . wholeText . indexOf ( query ) ; const focusOffset = endQuery ? focusNode . wholeText . indexOf ( endQuery ) + endQuery . length : anchorOffset + query . length ; setBaseAndExtent ( anchorNode , anchorOffset , focusNode , focusOffset ) ; } ) ) as any ) ; Cypress . Commands . add ( 'addLink' , { prevSubject : true } , ( ( subject , text , url ) => cy . wrap ( subject ) . setSelection ( text ) . type ( `{${ ctrl }+k}` ) . wait ( 500 ) . get ( 'input#url' , { includeShadowDom : true } ) . type ( `${ url }{enter}` , { force : true , waitForAnimations : false } ) ) as any ) ;