focus-trap 6.2.1 → 6.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"focus-trap.umd.min.js","sources":["../index.js"],"sourcesContent":["import { tabbable, isFocusable } from 'tabbable';\n\nlet activeFocusDelay;\n\nconst activeFocusTraps = (function () {\n const trapQueue = [];\n return {\n activateTrap(trap) {\n if (trapQueue.length > 0) {\n const activeTrap = trapQueue[trapQueue.length - 1];\n if (activeTrap !== trap) {\n activeTrap.pause();\n }\n }\n\n const trapIndex = trapQueue.indexOf(trap);\n if (trapIndex === -1) {\n trapQueue.push(trap);\n } else {\n // move this existing trap to the front of the queue\n trapQueue.splice(trapIndex, 1);\n trapQueue.push(trap);\n }\n },\n\n deactivateTrap(trap) {\n const trapIndex = trapQueue.indexOf(trap);\n if (trapIndex !== -1) {\n trapQueue.splice(trapIndex, 1);\n }\n\n if (trapQueue.length > 0) {\n trapQueue[trapQueue.length - 1].unpause();\n }\n },\n };\n})();\n\nconst isSelectableInput = function (node) {\n return (\n node.tagName &&\n node.tagName.toLowerCase() === 'input' &&\n typeof node.select === 'function'\n );\n};\n\nconst isEscapeEvent = function (e) {\n return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;\n};\n\nconst isTabEvent = function (e) {\n return e.key === 'Tab' || e.keyCode === 9;\n};\n\nconst delay = function (fn) {\n return setTimeout(fn, 0);\n};\n\nconst createFocusTrap = function (elements, userOptions) {\n const doc = document;\n\n const config = {\n returnFocusOnDeactivate: true,\n escapeDeactivates: true,\n delayInitialFocus: true,\n ...userOptions,\n };\n\n const state = {\n // @type {Array<HTMLElement>}\n containers: [],\n // @type {{ firstTabbableNode: HTMLElement, lastTabbableNode: HTMLElement }}\n tabbableGroups: [],\n nodeFocusedBeforeActivation: null,\n mostRecentlyFocusedNode: null,\n active: false,\n paused: false,\n };\n\n let trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later\n\n const containersContain = function (element) {\n return state.containers.some((container) => container.contains(element));\n };\n\n const getNodeForOption = function (optionName) {\n const optionValue = config[optionName];\n if (!optionValue) {\n return null;\n }\n\n let node = optionValue;\n\n if (typeof optionValue === 'string') {\n node = doc.querySelector(optionValue);\n if (!node) {\n throw new Error(`\\`${optionName}\\` refers to no known node`);\n }\n }\n\n if (typeof optionValue === 'function') {\n node = optionValue();\n if (!node) {\n throw new Error(`\\`${optionName}\\` did not return a node`);\n }\n }\n\n return node;\n };\n\n const getInitialFocusNode = function () {\n let node;\n\n if (getNodeForOption('initialFocus') !== null) {\n node = getNodeForOption('initialFocus');\n } else if (containersContain(doc.activeElement)) {\n node = doc.activeElement;\n } else {\n const firstTabbableGroup = state.tabbableGroups[0];\n const firstTabbableNode =\n firstTabbableGroup && firstTabbableGroup.firstTabbableNode;\n node = firstTabbableNode || getNodeForOption('fallbackFocus');\n }\n\n if (!node) {\n throw new Error(\n 'Your focus-trap needs to have at least one focusable element'\n );\n }\n\n return node;\n };\n\n const updateTabbableNodes = function () {\n state.tabbableGroups = state.containers.map((container) => {\n const tabbableNodes = tabbable(container);\n\n return {\n firstTabbableNode: tabbableNodes[0],\n lastTabbableNode: tabbableNodes[tabbableNodes.length - 1],\n };\n });\n };\n\n const tryFocus = function (node) {\n if (node === doc.activeElement) {\n return;\n }\n if (!node || !node.focus) {\n tryFocus(getInitialFocusNode());\n return;\n }\n\n node.focus({ preventScroll: !!config.preventScroll });\n state.mostRecentlyFocusedNode = node;\n\n if (isSelectableInput(node)) {\n node.select();\n }\n };\n\n const getReturnFocusNode = function (previousActiveElement) {\n const node = getNodeForOption('setReturnFocus');\n\n return node ? node : previousActiveElement;\n };\n\n // This needs to be done on mousedown and touchstart instead of click\n // so that it precedes the focus event.\n const checkPointerDown = function (e) {\n if (containersContain(e.target)) {\n // allow the click since it ocurred inside the trap\n return;\n }\n\n if (config.clickOutsideDeactivates) {\n // immediately deactivate the trap\n trap.deactivate({\n // if, on deactivation, we should return focus to the node originally-focused\n // when the trap was activated (or the configured `setReturnFocus` node),\n // then assume it's also OK to return focus to the outside node that was\n // just clicked, causing deactivation, as long as that node is focusable;\n // if it isn't focusable, then return focus to the original node focused\n // on activation (or the configured `setReturnFocus` node)\n // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,\n // which will result in the outside click setting focus to the node\n // that was clicked, whether it's focusable or not; by setting\n // `returnFocus: true`, we'll attempt to re-focus the node originally-focused\n // on activation (or the configured `setReturnFocus` node)\n returnFocus: config.returnFocusOnDeactivate && !isFocusable(e.target),\n });\n return;\n }\n\n // This is needed for mobile devices.\n // (If we'll only let `click` events through,\n // then on mobile they will be blocked anyways if `touchstart` is blocked.)\n if (\n config.allowOutsideClick &&\n (typeof config.allowOutsideClick === 'boolean'\n ? config.allowOutsideClick\n : config.allowOutsideClick(e))\n ) {\n // allow the click outside the trap to take place\n return;\n }\n\n // otherwise, prevent the click\n e.preventDefault();\n };\n\n // In case focus escapes the trap for some strange reason, pull it back in.\n const checkFocusIn = function (e) {\n // In Firefox when you Tab out of an iframe the Document is briefly focused.\n if (containersContain(e.target) || e.target instanceof Document) {\n return;\n }\n e.stopImmediatePropagation();\n tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());\n };\n\n // Hijack Tab events on the first and last focusable nodes of the trap,\n // in order to prevent focus from escaping. If it escapes for even a\n // moment it can end up scrolling the page and causing confusion so we\n // kind of need to capture the action at the keydown phase.\n const checkTab = function (e) {\n updateTabbableNodes();\n\n let destinationNode = null;\n\n if (e.shiftKey) {\n const startOfGroupIndex = state.tabbableGroups.findIndex(\n ({ firstTabbableNode }) => e.target === firstTabbableNode\n );\n\n if (startOfGroupIndex >= 0) {\n const destinationGroupIndex =\n startOfGroupIndex === 0\n ? state.tabbableGroups.length - 1\n : startOfGroupIndex - 1;\n\n const destinationGroup = state.tabbableGroups[destinationGroupIndex];\n destinationNode = destinationGroup.lastTabbableNode;\n }\n } else {\n const lastOfGroupIndex = state.tabbableGroups.findIndex(\n ({ lastTabbableNode }) => e.target === lastTabbableNode\n );\n\n if (lastOfGroupIndex >= 0) {\n const destinationGroupIndex =\n lastOfGroupIndex === state.tabbableGroups.length - 1\n ? 0\n : lastOfGroupIndex + 1;\n\n const destinationGroup = state.tabbableGroups[destinationGroupIndex];\n destinationNode = destinationGroup.firstTabbableNode;\n }\n }\n\n if (destinationNode) {\n e.preventDefault();\n\n tryFocus(destinationNode);\n }\n };\n\n const checkKey = function (e) {\n if (config.escapeDeactivates !== false && isEscapeEvent(e)) {\n e.preventDefault();\n trap.deactivate();\n return;\n }\n\n if (isTabEvent(e)) {\n checkTab(e);\n return;\n }\n };\n\n const checkClick = function (e) {\n if (config.clickOutsideDeactivates) {\n return;\n }\n if (containersContain(e.target)) {\n return;\n }\n if (\n config.allowOutsideClick &&\n (typeof config.allowOutsideClick === 'boolean'\n ? config.allowOutsideClick\n : config.allowOutsideClick(e))\n ) {\n return;\n }\n e.preventDefault();\n e.stopImmediatePropagation();\n };\n\n //\n // EVENT LISTENERS\n //\n\n const addListeners = function () {\n if (!state.active) {\n return;\n }\n\n // There can be only one listening focus trap at a time\n activeFocusTraps.activateTrap(trap);\n\n // Delay ensures that the focused element doesn't capture the event\n // that caused the focus trap activation.\n activeFocusDelay = config.delayInitialFocus\n ? delay(function () {\n tryFocus(getInitialFocusNode());\n })\n : tryFocus(getInitialFocusNode());\n\n doc.addEventListener('focusin', checkFocusIn, true);\n doc.addEventListener('mousedown', checkPointerDown, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('touchstart', checkPointerDown, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('click', checkClick, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('keydown', checkKey, {\n capture: true,\n passive: false,\n });\n\n return trap;\n };\n\n const removeListeners = function () {\n if (!state.active) {\n return;\n }\n\n doc.removeEventListener('focusin', checkFocusIn, true);\n doc.removeEventListener('mousedown', checkPointerDown, true);\n doc.removeEventListener('touchstart', checkPointerDown, true);\n doc.removeEventListener('click', checkClick, true);\n doc.removeEventListener('keydown', checkKey, true);\n\n return trap;\n };\n\n //\n // TRAP DEFINITION\n //\n\n trap = {\n activate(activateOptions) {\n if (state.active) {\n return this;\n }\n\n updateTabbableNodes();\n\n state.active = true;\n state.paused = false;\n state.nodeFocusedBeforeActivation = doc.activeElement;\n\n const onActivate =\n activateOptions && activateOptions.onActivate\n ? activateOptions.onActivate\n : config.onActivate;\n if (onActivate) {\n onActivate();\n }\n\n addListeners();\n return this;\n },\n\n deactivate(deactivateOptions) {\n if (!state.active) {\n return this;\n }\n\n clearTimeout(activeFocusDelay);\n\n removeListeners();\n state.active = false;\n state.paused = false;\n\n activeFocusTraps.deactivateTrap(trap);\n\n const onDeactivate =\n deactivateOptions && deactivateOptions.onDeactivate !== undefined\n ? deactivateOptions.onDeactivate\n : config.onDeactivate;\n if (onDeactivate) {\n onDeactivate();\n }\n\n const returnFocus =\n deactivateOptions && deactivateOptions.returnFocus !== undefined\n ? deactivateOptions.returnFocus\n : config.returnFocusOnDeactivate;\n\n if (returnFocus) {\n delay(function () {\n tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));\n });\n }\n\n return this;\n },\n\n pause() {\n if (state.paused || !state.active) {\n return this;\n }\n\n state.paused = true;\n removeListeners();\n\n return this;\n },\n\n unpause() {\n if (!state.paused || !state.active) {\n return this;\n }\n\n state.paused = false;\n updateTabbableNodes();\n addListeners();\n\n return this;\n },\n\n updateContainerElements(containerElements) {\n const elementsAsArray = [].concat(containerElements).filter(Boolean);\n\n state.containers = elementsAsArray.map((element) =>\n typeof element === 'string' ? doc.querySelector(element) : element\n );\n\n if (state.active) {\n updateTabbableNodes();\n }\n\n return this;\n },\n };\n\n // initialize container elements\n trap.updateContainerElements(elements);\n\n return trap;\n};\n\nexport { createFocusTrap };\n"],"names":["activeFocusDelay","trapQueue","activeFocusTraps","activateTrap","trap","length","activeTrap","pause","trapIndex","indexOf","splice","push","deactivateTrap","unpause","delay","fn","setTimeout","elements","userOptions","doc","document","config","returnFocusOnDeactivate","escapeDeactivates","delayInitialFocus","state","containers","tabbableGroups","nodeFocusedBeforeActivation","mostRecentlyFocusedNode","active","paused","containersContain","element","some","container","contains","getNodeForOption","optionName","optionValue","node","querySelector","Error","getInitialFocusNode","activeElement","firstTabbableGroup","firstTabbableNode","updateTabbableNodes","map","tabbableNodes","tabbable","lastTabbableNode","tryFocus","focus","preventScroll","tagName","toLowerCase","select","isSelectableInput","checkPointerDown","e","target","clickOutsideDeactivates","deactivate","returnFocus","isFocusable","allowOutsideClick","preventDefault","checkFocusIn","Document","stopImmediatePropagation","checkKey","key","keyCode","isEscapeEvent","isTabEvent","destinationNode","shiftKey","startOfGroupIndex","findIndex","destinationGroupIndex","lastOfGroupIndex","checkTab","checkClick","addListeners","addEventListener","capture","passive","removeListeners","removeEventListener","activate","activateOptions","this","onActivate","deactivateOptions","clearTimeout","onDeactivate","undefined","previousActiveElement","updateContainerElements","containerElements","elementsAsArray","concat","filter","Boolean"],"mappings":";;;;ysBAEA,IAAIA,EAGIC,EADFC,GACED,EAAY,GACX,CACLE,sBAAaC,MACPH,EAAUI,OAAS,EAAG,KAClBC,EAAaL,EAAUA,EAAUI,OAAS,GAC5CC,IAAeF,GACjBE,EAAWC,YAITC,EAAYP,EAAUQ,QAAQL,IACjB,IAAfI,GAIFP,EAAUS,OAAOF,EAAW,GAH5BP,EAAUU,KAAKP,IAQnBQ,wBAAeR,OACPI,EAAYP,EAAUQ,QAAQL,IACjB,IAAfI,GACFP,EAAUS,OAAOF,EAAW,GAG1BP,EAAUI,OAAS,GACrBJ,EAAUA,EAAUI,OAAS,GAAGQ,aAsBlCC,EAAQ,SAAUC,UACfC,WAAWD,EAAI,sBAGA,SAAUE,EAAUC,OAqBtCd,EApBEe,EAAMC,SAENC,mWACJC,yBAAyB,EACzBC,mBAAmB,EACnBC,mBAAmB,GAChBN,GAGCO,EAAQ,CAEZC,WAAY,GAEZC,eAAgB,GAChBC,4BAA6B,KA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BACOY,EAAMM,QAAWN,EAAMK,QAI5BL,EAAMM,QAAS,EACfgB,IACAqC,IAEOQ,MAPEA,MAUXO,iCAAwBC,OAChBC,EAAkB,GAAGC,OAAOF,GAAmBG,OAAOC,gBAE5D/E,EAAMC,WAAa2E,EAAgBrD,KAAI,SAACf,SACnB,iBAAZA,EAAuBd,EAAIsB,cAAcR,GAAWA,KAGzDR,EAAMK,QACRiB,IAGK6C,QAKNO,wBAAwBlF,GAEtBb"}
1
+ {"version":3,"file":"focus-trap.umd.min.js","sources":["../index.js"],"sourcesContent":["import { tabbable, isFocusable } from 'tabbable';\n\nlet activeFocusDelay;\n\nconst activeFocusTraps = (function () {\n const trapQueue = [];\n return {\n activateTrap(trap) {\n if (trapQueue.length > 0) {\n const activeTrap = trapQueue[trapQueue.length - 1];\n if (activeTrap !== trap) {\n activeTrap.pause();\n }\n }\n\n const trapIndex = trapQueue.indexOf(trap);\n if (trapIndex === -1) {\n trapQueue.push(trap);\n } else {\n // move this existing trap to the front of the queue\n trapQueue.splice(trapIndex, 1);\n trapQueue.push(trap);\n }\n },\n\n deactivateTrap(trap) {\n const trapIndex = trapQueue.indexOf(trap);\n if (trapIndex !== -1) {\n trapQueue.splice(trapIndex, 1);\n }\n\n if (trapQueue.length > 0) {\n trapQueue[trapQueue.length - 1].unpause();\n }\n },\n };\n})();\n\nconst isSelectableInput = function (node) {\n return (\n node.tagName &&\n node.tagName.toLowerCase() === 'input' &&\n typeof node.select === 'function'\n );\n};\n\nconst isEscapeEvent = function (e) {\n return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;\n};\n\nconst isTabEvent = function (e) {\n return e.key === 'Tab' || e.keyCode === 9;\n};\n\nconst delay = function (fn) {\n return setTimeout(fn, 0);\n};\n\n// Array.find/findIndex() are not supported on IE; this replicates enough\n// of Array.findIndex() for our needs\nconst findIndex = function (arr, fn) {\n let idx = -1;\n\n arr.every(function (value, i) {\n if (fn(value)) {\n idx = i;\n return false; // break\n }\n\n return true; // next\n });\n\n return idx;\n};\n\n/**\n * Get an option's value when it could be a plain value, or a handler that provides\n * the value.\n * @param {*} value Option's value to check.\n * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.\n * @returns {*} The `value`, or the handler's returned value.\n */\nconst valueOrHandler = function (value, ...params) {\n return typeof value === 'function' ? value(...params) : value;\n};\n\nconst createFocusTrap = function (elements, userOptions) {\n const doc = document;\n\n const config = {\n returnFocusOnDeactivate: true,\n escapeDeactivates: true,\n delayInitialFocus: true,\n ...userOptions,\n };\n\n const state = {\n // @type {Array<HTMLElement>}\n containers: [],\n\n // list of objects identifying the first and last tabbable nodes in all containers/groups in\n // the trap\n // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap\n // is active, but the trap should never get to a state where there isn't at least one group\n // with at least one tabbable node in it (that would lead to an error condition that would\n // result in an error being thrown)\n // @type {Array<{ container: HTMLElement, firstTabbableNode: HTMLElement|null, lastTabbableNode: HTMLElement|null }>}\n tabbableGroups: [],\n\n nodeFocusedBeforeActivation: null,\n mostRecentlyFocusedNode: null,\n active: false,\n paused: false,\n };\n\n let trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later\n\n const containersContain = function (element) {\n return state.containers.some((container) => container.contains(element));\n };\n\n const getNodeForOption = function (optionName) {\n const optionValue = config[optionName];\n if (!optionValue) {\n return null;\n }\n\n let node = optionValue;\n\n if (typeof optionValue === 'string') {\n node = doc.querySelector(optionValue);\n if (!node) {\n throw new Error(`\\`${optionName}\\` refers to no known node`);\n }\n }\n\n if (typeof optionValue === 'function') {\n node = optionValue();\n if (!node) {\n throw new Error(`\\`${optionName}\\` did not return a node`);\n }\n }\n\n return node;\n };\n\n const getInitialFocusNode = function () {\n let node;\n\n if (getNodeForOption('initialFocus') !== null) {\n node = getNodeForOption('initialFocus');\n } else if (containersContain(doc.activeElement)) {\n node = doc.activeElement;\n } else {\n const firstTabbableGroup = state.tabbableGroups[0];\n const firstTabbableNode =\n firstTabbableGroup && firstTabbableGroup.firstTabbableNode;\n node = firstTabbableNode || getNodeForOption('fallbackFocus');\n }\n\n if (!node) {\n throw new Error(\n 'Your focus-trap needs to have at least one focusable element'\n );\n }\n\n return node;\n };\n\n const updateTabbableNodes = function () {\n state.tabbableGroups = state.containers\n .map((container) => {\n const tabbableNodes = tabbable(container);\n\n if (tabbableNodes.length > 0) {\n return {\n container,\n firstTabbableNode: tabbableNodes[0],\n lastTabbableNode: tabbableNodes[tabbableNodes.length - 1],\n };\n }\n\n return undefined;\n })\n .filter((group) => !!group); // remove groups with no tabbable nodes\n\n // throw if no groups have tabbable nodes and we don't have a fallback focus node either\n if (\n state.tabbableGroups.length <= 0 &&\n !getNodeForOption('fallbackFocus')\n ) {\n throw new Error(\n 'Your focus-trap must have at least one container with at least one tabbable node in it at all times'\n );\n }\n };\n\n const tryFocus = function (node) {\n if (node === doc.activeElement) {\n return;\n }\n if (!node || !node.focus) {\n tryFocus(getInitialFocusNode());\n return;\n }\n\n node.focus({ preventScroll: !!config.preventScroll });\n state.mostRecentlyFocusedNode = node;\n\n if (isSelectableInput(node)) {\n node.select();\n }\n };\n\n const getReturnFocusNode = function (previousActiveElement) {\n const node = getNodeForOption('setReturnFocus');\n\n return node ? node : previousActiveElement;\n };\n\n // This needs to be done on mousedown and touchstart instead of click\n // so that it precedes the focus event.\n const checkPointerDown = function (e) {\n if (containersContain(e.target)) {\n // allow the click since it ocurred inside the trap\n return;\n }\n\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n // immediately deactivate the trap\n trap.deactivate({\n // if, on deactivation, we should return focus to the node originally-focused\n // when the trap was activated (or the configured `setReturnFocus` node),\n // then assume it's also OK to return focus to the outside node that was\n // just clicked, causing deactivation, as long as that node is focusable;\n // if it isn't focusable, then return focus to the original node focused\n // on activation (or the configured `setReturnFocus` node)\n // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,\n // which will result in the outside click setting focus to the node\n // that was clicked, whether it's focusable or not; by setting\n // `returnFocus: true`, we'll attempt to re-focus the node originally-focused\n // on activation (or the configured `setReturnFocus` node)\n returnFocus: config.returnFocusOnDeactivate && !isFocusable(e.target),\n });\n return;\n }\n\n // This is needed for mobile devices.\n // (If we'll only let `click` events through,\n // then on mobile they will be blocked anyways if `touchstart` is blocked.)\n if (valueOrHandler(config.allowOutsideClick, e)) {\n // allow the click outside the trap to take place\n return;\n }\n\n // otherwise, prevent the click\n e.preventDefault();\n };\n\n // In case focus escapes the trap for some strange reason, pull it back in.\n const checkFocusIn = function (e) {\n const targetContained = containersContain(e.target);\n // In Firefox when you Tab out of an iframe the Document is briefly focused.\n if (targetContained || e.target instanceof Document) {\n if (targetContained) {\n state.mostRecentlyFocusedNode = e.target;\n }\n } else {\n // escaped! pull it back in to where it just left\n e.stopImmediatePropagation();\n tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());\n }\n };\n\n // Hijack Tab events on the first and last focusable nodes of the trap,\n // in order to prevent focus from escaping. If it escapes for even a\n // moment it can end up scrolling the page and causing confusion so we\n // kind of need to capture the action at the keydown phase.\n const checkTab = function (e) {\n updateTabbableNodes();\n\n let destinationNode = null;\n\n if (state.tabbableGroups.length > 0) {\n // make sure the target is actually contained in a group\n // NOTE: the target may also be the container itself if it's tabbable\n // with tabIndex='-1' and was given initial focus\n const containerIndex = findIndex(state.tabbableGroups, ({ container }) =>\n container.contains(e.target)\n );\n\n if (containerIndex < 0) {\n // target not found in any group: quite possible focus has escaped the trap,\n // so bring it back in to...\n if (e.shiftKey) {\n // ...the last node in the last group\n destinationNode =\n state.tabbableGroups[state.tabbableGroups.length - 1]\n .lastTabbableNode;\n } else {\n // ...the first node in the first group\n destinationNode = state.tabbableGroups[0].firstTabbableNode;\n }\n } else if (e.shiftKey) {\n // REVERSE\n\n // is the target the first tabbable node in a group?\n let startOfGroupIndex = findIndex(\n state.tabbableGroups,\n ({ firstTabbableNode }) => e.target === firstTabbableNode\n );\n\n if (\n startOfGroupIndex < 0 &&\n state.tabbableGroups[containerIndex].container === e.target\n ) {\n // an exception case where the target is the container itself, in which\n // case, we should handle shift+tab as if focus were on the container's\n // first tabbable node, and go to the last tabbable node of the LAST group\n startOfGroupIndex = containerIndex;\n }\n\n if (startOfGroupIndex >= 0) {\n // YES: then shift+tab should go to the last tabbable node in the\n // previous group (and wrap around to the last tabbable node of\n // the LAST group if it's the first tabbable node of the FIRST group)\n const destinationGroupIndex =\n startOfGroupIndex === 0\n ? state.tabbableGroups.length - 1\n : startOfGroupIndex - 1;\n\n const destinationGroup = state.tabbableGroups[destinationGroupIndex];\n destinationNode = destinationGroup.lastTabbableNode;\n }\n } else {\n // FORWARD\n\n // is the target the last tabbable node in a group?\n let lastOfGroupIndex = findIndex(\n state.tabbableGroups,\n ({ lastTabbableNode }) => e.target === lastTabbableNode\n );\n\n if (\n lastOfGroupIndex < 0 &&\n state.tabbableGroups[containerIndex].container === e.target\n ) {\n // an exception case where the target is the container itself, in which\n // case, we should handle tab as if focus were on the container's\n // last tabbable node, and go to the first tabbable node of the FIRST group\n lastOfGroupIndex = containerIndex;\n }\n\n if (lastOfGroupIndex >= 0) {\n // YES: then tab should go to the first tabbable node in the next\n // group (and wrap around to the first tabbable node of the FIRST\n // group if it's the last tabbable node of the LAST group)\n const destinationGroupIndex =\n lastOfGroupIndex === state.tabbableGroups.length - 1\n ? 0\n : lastOfGroupIndex + 1;\n\n const destinationGroup = state.tabbableGroups[destinationGroupIndex];\n destinationNode = destinationGroup.firstTabbableNode;\n }\n }\n } else {\n destinationNode = getNodeForOption('fallbackFocus');\n }\n\n if (destinationNode) {\n e.preventDefault();\n tryFocus(destinationNode);\n }\n // else, let the browser take care of [shift+]tab and move the focus\n };\n\n const checkKey = function (e) {\n if (config.escapeDeactivates !== false && isEscapeEvent(e)) {\n e.preventDefault();\n trap.deactivate();\n return;\n }\n\n if (isTabEvent(e)) {\n checkTab(e);\n return;\n }\n };\n\n const checkClick = function (e) {\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n return;\n }\n\n if (containersContain(e.target)) {\n return;\n }\n\n if (valueOrHandler(config.allowOutsideClick, e)) {\n return;\n }\n\n e.preventDefault();\n e.stopImmediatePropagation();\n };\n\n //\n // EVENT LISTENERS\n //\n\n const addListeners = function () {\n if (!state.active) {\n return;\n }\n\n // There can be only one listening focus trap at a time\n activeFocusTraps.activateTrap(trap);\n\n // Delay ensures that the focused element doesn't capture the event\n // that caused the focus trap activation.\n activeFocusDelay = config.delayInitialFocus\n ? delay(function () {\n tryFocus(getInitialFocusNode());\n })\n : tryFocus(getInitialFocusNode());\n\n doc.addEventListener('focusin', checkFocusIn, true);\n doc.addEventListener('mousedown', checkPointerDown, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('touchstart', checkPointerDown, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('click', checkClick, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('keydown', checkKey, {\n capture: true,\n passive: false,\n });\n\n return trap;\n };\n\n const removeListeners = function () {\n if (!state.active) {\n return;\n }\n\n doc.removeEventListener('focusin', checkFocusIn, true);\n doc.removeEventListener('mousedown', checkPointerDown, true);\n doc.removeEventListener('touchstart', checkPointerDown, true);\n doc.removeEventListener('click', checkClick, true);\n doc.removeEventListener('keydown', checkKey, true);\n\n return trap;\n };\n\n //\n // TRAP DEFINITION\n //\n\n trap = {\n activate(activateOptions) {\n if (state.active) {\n return this;\n }\n\n updateTabbableNodes();\n\n state.active = true;\n state.paused = false;\n state.nodeFocusedBeforeActivation = doc.activeElement;\n\n const onActivate =\n activateOptions && activateOptions.onActivate\n ? activateOptions.onActivate\n : config.onActivate;\n if (onActivate) {\n onActivate();\n }\n\n addListeners();\n return this;\n },\n\n deactivate(deactivateOptions) {\n if (!state.active) {\n return this;\n }\n\n clearTimeout(activeFocusDelay);\n\n removeListeners();\n state.active = false;\n state.paused = false;\n\n activeFocusTraps.deactivateTrap(trap);\n\n const onDeactivate =\n deactivateOptions && deactivateOptions.onDeactivate !== undefined\n ? deactivateOptions.onDeactivate\n : config.onDeactivate;\n if (onDeactivate) {\n onDeactivate();\n }\n\n const returnFocus =\n deactivateOptions && deactivateOptions.returnFocus !== undefined\n ? deactivateOptions.returnFocus\n : config.returnFocusOnDeactivate;\n\n if (returnFocus) {\n delay(function () {\n tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));\n });\n }\n\n return this;\n },\n\n pause() {\n if (state.paused || !state.active) {\n return this;\n }\n\n state.paused = true;\n removeListeners();\n\n return this;\n },\n\n unpause() {\n if (!state.paused || !state.active) {\n return this;\n }\n\n state.paused = false;\n updateTabbableNodes();\n addListeners();\n\n return this;\n },\n\n updateContainerElements(containerElements) {\n const elementsAsArray = [].concat(containerElements).filter(Boolean);\n\n state.containers = elementsAsArray.map((element) =>\n typeof element === 'string' ? doc.querySelector(element) : element\n );\n\n if (state.active) {\n updateTabbableNodes();\n }\n\n return this;\n },\n };\n\n // initialize container elements\n trap.updateContainerElements(elements);\n\n return trap;\n};\n\nexport { createFocusTrap };\n"],"names":["activeFocusDelay","trapQueue","activeFocusTraps","activateTrap","trap","length","activeTrap","pause","trapIndex","indexOf","splice","push","deactivateTrap","unpause","delay","fn","setTimeout","findIndex","arr","idx","every","value","i","valueOrHandler","params","elements","userOptions","doc","document","config","returnFocusOnDeactivate","escapeDeactivates","delayInitialFocus","state","containers","tabbableGroups","nodeFocusedBeforeActivation","mostRecentlyFocusedNode","active","paused","containersContain","element","some","container","contains","getNodeForOption","optionName","optionValue","node","querySelector","Error","getInitialFocusNode","activeElement","firstTabbableGroup","firstTabbableNode","updateTabbableNodes","map","tabbableNodes","tabbable","lastTabbableNode","filter","group","tryFocus","focus","preventScroll","tagName","toLowerCase","select","isSelectableInput","checkPointerDown","e","target","clickOutsideDeactivates","deactivate","returnFocus","isFocusable","allowOutsideClick","preventDefault","checkFocusIn","targetContained","Document","stopImmediatePropagation","checkKey","key","keyCode","isEscapeEvent","isTabEvent","destinationNode","containerIndex","shiftKey","startOfGroupIndex","destinationGroupIndex","lastOfGroupIndex","checkTab","checkClick","addListeners","addEventListener","capture","passive","removeListeners","removeEventListener","activate","activateOptions","this","onActivate","deactivateOptions","clearTimeout","onDeactivate","undefined","previousActiveElement","updateContainerElements","containerElements","elementsAsArray","concat","Boolean"],"mappings":";;;;ysBAEA,IAAIA,EAGIC,EADFC,GACED,EAAY,GACX,CACLE,sBAAaC,MACPH,EAAUI,OAAS,EAAG,KAClBC,EAAaL,EAAUA,EAAUI,OAAS,GAC5CC,IAAeF,GACjBE,EAAWC,YAITC,EAAYP,EAAUQ,QAAQL,IACjB,IAAfI,GAIFP,EAAUS,OAAOF,EAAW,GAH5BP,EAAUU,KAAKP,IAQnBQ,wBAAeR,OACPI,EAAYP,EAAUQ,QAAQL,IACjB,IAAfI,GACFP,EAAUS,OAAOF,EAAW,GAG1BP,EAAUI,OAAS,GACrBJ,EAAUA,EAAUI,OAAS,GAAGQ,aAsBlCC,EAAQ,SAAUC,UACfC,WAAWD,EAAI,IAKlBE,EAAY,SAAUC,EAAKH,OAC3BI,GAAO,SAEXD,EAAIE,OAAM,SAAUC,EAAOC,UACrBP,EAAGM,KACLF,EAAMG,GACC,MAMJH,GAUHI,EAAiB,SAAUF,8BAAUG,mCAAAA,0BACjB,mBAAVH,EAAuBA,eAASG,GAAUH,qBAGlC,SAAUI,EAAUC,OA6BtCtB,EA5BEuB,EAAMC,SAENC,mWACJC,yBAAyB,EACzBC,mBAAmB,EACnBC,mBAAmB,GAChBN,GAGCO,EAAQ,CAEZC,WAAY,GASZC,eAAgB,GAEhBC,4BAA6B,KAC7BC,wBAAyB,KACzBC,QAAQ,EACRC,QAAQ,GAKJC,EAAoB,SAAUC,UAC3BR,EAAMC,WAAWQ,MAAK,SAACC,UAAcA,EAAUC,SAASH,OAG3DI,EAAmB,SAAUC,OAC3BC,EAAclB,EAAOiB,OACtBC,SACI,SAGLC,EAAOD,KAEgB,iBAAhBA,KACTC,EAAOrB,EAAIsB,cAAcF,UAEjB,IAAIG,iBAAWJ,mCAIE,mBAAhBC,KACTC,E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AAO8E,oBACTA,GACFA,KAIAF,QAAuDG,IAAlCH,EAAkB/B,YACnC+B,EAAkB/B,YAClB7C,EAAOC,0BAGXhB,GAAM,WA/Se,IAAU+F,EAgT7B/C,GAhT6B+C,EAgTD5E,EAAMG,4BA/S3BS,EAAiB,mBAETgE,OAiTZN,MAGThG,wBACM0B,EAAMM,SAAWN,EAAMK,SAI3BL,EAAMM,QAAS,EACf4D,KAJSI,MASX1F,0BACOoB,EAAMM,QAAWN,EAAMK,QAI5BL,EAAMM,QAAS,EACfgB,IACAwC,IAEOQ,MAPEA,MAUXO,iCAAwBC,OAChBC,EAAkB,GAAGC,OAAOF,GAAmBnD,OAAOsD,gBAE5DjF,EAAMC,WAAa8E,EAAgBxD,KAAI,SAACf,SACnB,iBAAZA,EAAuBd,EAAIsB,cAAcR,GAAWA,KAGzDR,EAAMK,QACRiB,IAGKgD,QAKNO,wBAAwBrF,GAEtBrB"}
package/index.d.ts CHANGED
@@ -51,19 +51,20 @@ declare module 'focus-trap' {
51
51
  */
52
52
  escapeDeactivates?: boolean;
53
53
  /**
54
- * Default: `false`. If `true`, a click outside the focus trap will
55
- * deactivate the focus trap and allow the click event to do its thing.
56
- * This option **takes precedence** over `allowOutsideClick` when it's set
57
- * to `true`.
54
+ * If `true` or returns `true`, a click outside the focus trap will
55
+ * deactivate the focus trap and allow the click event to do its thing (i.e.
56
+ * to pass-through to the element that was clicked). This option **takes
57
+ * precedence** over `allowOutsideClick` when it's set to `true`, causing
58
+ * that option to be ignored. Default: `false`.
58
59
  */
59
- clickOutsideDeactivates?: boolean;
60
+ clickOutsideDeactivates?: boolean | MouseEventToBoolean;
60
61
  /**
61
62
  * If set and is or returns `true`, a click outside the focus trap will not
62
63
  * be prevented, even when `clickOutsideDeactivates` is `false`. When
63
64
  * `clickOutsideDeactivates` is `true`, this option is **ignored** (i.e.
64
65
  * if it's a function, it will not be called). Use this option to control
65
66
  * if (and even which) clicks are allowed outside the trap in conjunction
66
- * with `clickOutsideDeactivates: false`.
67
+ * with `clickOutsideDeactivates: false`. Default: `false`.
67
68
  */
68
69
  allowOutsideClick?: boolean | MouseEventToBoolean;
69
70
  /**
package/index.js CHANGED
@@ -56,6 +56,34 @@ const delay = function (fn) {
56
56
  return setTimeout(fn, 0);
57
57
  };
58
58
 
59
+ // Array.find/findIndex() are not supported on IE; this replicates enough
60
+ // of Array.findIndex() for our needs
61
+ const findIndex = function (arr, fn) {
62
+ let idx = -1;
63
+
64
+ arr.every(function (value, i) {
65
+ if (fn(value)) {
66
+ idx = i;
67
+ return false; // break
68
+ }
69
+
70
+ return true; // next
71
+ });
72
+
73
+ return idx;
74
+ };
75
+
76
+ /**
77
+ * Get an option's value when it could be a plain value, or a handler that provides
78
+ * the value.
79
+ * @param {*} value Option's value to check.
80
+ * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.
81
+ * @returns {*} The `value`, or the handler's returned value.
82
+ */
83
+ const valueOrHandler = function (value, ...params) {
84
+ return typeof value === 'function' ? value(...params) : value;
85
+ };
86
+
59
87
  const createFocusTrap = function (elements, userOptions) {
60
88
  const doc = document;
61
89
 
@@ -69,8 +97,16 @@ const createFocusTrap = function (elements, userOptions) {
69
97
  const state = {
70
98
  // @type {Array<HTMLElement>}
71
99
  containers: [],
72
- // @type {{ firstTabbableNode: HTMLElement, lastTabbableNode: HTMLElement }}
100
+
101
+ // list of objects identifying the first and last tabbable nodes in all containers/groups in
102
+ // the trap
103
+ // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap
104
+ // is active, but the trap should never get to a state where there isn't at least one group
105
+ // with at least one tabbable node in it (that would lead to an error condition that would
106
+ // result in an error being thrown)
107
+ // @type {Array<{ container: HTMLElement, firstTabbableNode: HTMLElement|null, lastTabbableNode: HTMLElement|null }>}
73
108
  tabbableGroups: [],
109
+
74
110
  nodeFocusedBeforeActivation: null,
75
111
  mostRecentlyFocusedNode: null,
76
112
  active: false,
@@ -132,14 +168,31 @@ const createFocusTrap = function (elements, userOptions) {
132
168
  };
133
169
 
134
170
  const updateTabbableNodes = function () {
135
- state.tabbableGroups = state.containers.map((container) => {
136
- const tabbableNodes = tabbable(container);
171
+ state.tabbableGroups = state.containers
172
+ .map((container) => {
173
+ const tabbableNodes = tabbable(container);
174
+
175
+ if (tabbableNodes.length > 0) {
176
+ return {
177
+ container,
178
+ firstTabbableNode: tabbableNodes[0],
179
+ lastTabbableNode: tabbableNodes[tabbableNodes.length - 1],
180
+ };
181
+ }
137
182
 
138
- return {
139
- firstTabbableNode: tabbableNodes[0],
140
- lastTabbableNode: tabbableNodes[tabbableNodes.length - 1],
141
- };
142
- });
183
+ return undefined;
184
+ })
185
+ .filter((group) => !!group); // remove groups with no tabbable nodes
186
+
187
+ // throw if no groups have tabbable nodes and we don't have a fallback focus node either
188
+ if (
189
+ state.tabbableGroups.length <= 0 &&
190
+ !getNodeForOption('fallbackFocus')
191
+ ) {
192
+ throw new Error(
193
+ 'Your focus-trap must have at least one container with at least one tabbable node in it at all times'
194
+ );
195
+ }
143
196
  };
144
197
 
145
198
  const tryFocus = function (node) {
@@ -173,7 +226,7 @@ const createFocusTrap = function (elements, userOptions) {
173
226
  return;
174
227
  }
175
228
 
176
- if (config.clickOutsideDeactivates) {
229
+ if (valueOrHandler(config.clickOutsideDeactivates, e)) {
177
230
  // immediately deactivate the trap
178
231
  trap.deactivate({
179
232
  // if, on deactivation, we should return focus to the node originally-focused
@@ -195,12 +248,7 @@ const createFocusTrap = function (elements, userOptions) {
195
248
  // This is needed for mobile devices.
196
249
  // (If we'll only let `click` events through,
197
250
  // then on mobile they will be blocked anyways if `touchstart` is blocked.)
198
- if (
199
- config.allowOutsideClick &&
200
- (typeof config.allowOutsideClick === 'boolean'
201
- ? config.allowOutsideClick
202
- : config.allowOutsideClick(e))
203
- ) {
251
+ if (valueOrHandler(config.allowOutsideClick, e)) {
204
252
  // allow the click outside the trap to take place
205
253
  return;
206
254
  }
@@ -211,12 +259,17 @@ const createFocusTrap = function (elements, userOptions) {
211
259
 
212
260
  // In case focus escapes the trap for some strange reason, pull it back in.
213
261
  const checkFocusIn = function (e) {
262
+ const targetContained = containersContain(e.target);
214
263
  // In Firefox when you Tab out of an iframe the Document is briefly focused.
215
- if (containersContain(e.target) || e.target instanceof Document) {
216
- return;
264
+ if (targetContained || e.target instanceof Document) {
265
+ if (targetContained) {
266
+ state.mostRecentlyFocusedNode = e.target;
267
+ }
268
+ } else {
269
+ // escaped! pull it back in to where it just left
270
+ e.stopImmediatePropagation();
271
+ tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
217
272
  }
218
- e.stopImmediatePropagation();
219
- tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
220
273
  };
221
274
 
222
275
  // Hijack Tab events on the first and last focusable nodes of the trap,
@@ -228,41 +281,98 @@ const createFocusTrap = function (elements, userOptions) {
228
281
 
229
282
  let destinationNode = null;
230
283
 
231
- if (e.shiftKey) {
232
- const startOfGroupIndex = state.tabbableGroups.findIndex(
233
- ({ firstTabbableNode }) => e.target === firstTabbableNode
284
+ if (state.tabbableGroups.length > 0) {
285
+ // make sure the target is actually contained in a group
286
+ // NOTE: the target may also be the container itself if it's tabbable
287
+ // with tabIndex='-1' and was given initial focus
288
+ const containerIndex = findIndex(state.tabbableGroups, ({ container }) =>
289
+ container.contains(e.target)
234
290
  );
235
291
 
236
- if (startOfGroupIndex >= 0) {
237
- const destinationGroupIndex =
238
- startOfGroupIndex === 0
239
- ? state.tabbableGroups.length - 1
240
- : startOfGroupIndex - 1;
241
-
242
- const destinationGroup = state.tabbableGroups[destinationGroupIndex];
243
- destinationNode = destinationGroup.lastTabbableNode;
244
- }
245
- } else {
246
- const lastOfGroupIndex = state.tabbableGroups.findIndex(
247
- ({ lastTabbableNode }) => e.target === lastTabbableNode
248
- );
292
+ if (containerIndex < 0) {
293
+ // target not found in any group: quite possible focus has escaped the trap,
294
+ // so bring it back in to...
295
+ if (e.shiftKey) {
296
+ // ...the last node in the last group
297
+ destinationNode =
298
+ state.tabbableGroups[state.tabbableGroups.length - 1]
299
+ .lastTabbableNode;
300
+ } else {
301
+ // ...the first node in the first group
302
+ destinationNode = state.tabbableGroups[0].firstTabbableNode;
303
+ }
304
+ } else if (e.shiftKey) {
305
+ // REVERSE
306
+
307
+ // is the target the first tabbable node in a group?
308
+ let startOfGroupIndex = findIndex(
309
+ state.tabbableGroups,
310
+ ({ firstTabbableNode }) => e.target === firstTabbableNode
311
+ );
312
+
313
+ if (
314
+ startOfGroupIndex < 0 &&
315
+ state.tabbableGroups[containerIndex].container === e.target
316
+ ) {
317
+ // an exception case where the target is the container itself, in which
318
+ // case, we should handle shift+tab as if focus were on the container's
319
+ // first tabbable node, and go to the last tabbable node of the LAST group
320
+ startOfGroupIndex = containerIndex;
321
+ }
249
322
 
250
- if (lastOfGroupIndex >= 0) {
251
- const destinationGroupIndex =
252
- lastOfGroupIndex === state.tabbableGroups.length - 1
253
- ? 0
254
- : lastOfGroupIndex + 1;
323
+ if (startOfGroupIndex >= 0) {
324
+ // YES: then shift+tab should go to the last tabbable node in the
325
+ // previous group (and wrap around to the last tabbable node of
326
+ // the LAST group if it's the first tabbable node of the FIRST group)
327
+ const destinationGroupIndex =
328
+ startOfGroupIndex === 0
329
+ ? state.tabbableGroups.length - 1
330
+ : startOfGroupIndex - 1;
331
+
332
+ const destinationGroup = state.tabbableGroups[destinationGroupIndex];
333
+ destinationNode = destinationGroup.lastTabbableNode;
334
+ }
335
+ } else {
336
+ // FORWARD
337
+
338
+ // is the target the last tabbable node in a group?
339
+ let lastOfGroupIndex = findIndex(
340
+ state.tabbableGroups,
341
+ ({ lastTabbableNode }) => e.target === lastTabbableNode
342
+ );
343
+
344
+ if (
345
+ lastOfGroupIndex < 0 &&
346
+ state.tabbableGroups[containerIndex].container === e.target
347
+ ) {
348
+ // an exception case where the target is the container itself, in which
349
+ // case, we should handle tab as if focus were on the container's
350
+ // last tabbable node, and go to the first tabbable node of the FIRST group
351
+ lastOfGroupIndex = containerIndex;
352
+ }
255
353
 
256
- const destinationGroup = state.tabbableGroups[destinationGroupIndex];
257
- destinationNode = destinationGroup.firstTabbableNode;
354
+ if (lastOfGroupIndex >= 0) {
355
+ // YES: then tab should go to the first tabbable node in the next
356
+ // group (and wrap around to the first tabbable node of the FIRST
357
+ // group if it's the last tabbable node of the LAST group)
358
+ const destinationGroupIndex =
359
+ lastOfGroupIndex === state.tabbableGroups.length - 1
360
+ ? 0
361
+ : lastOfGroupIndex + 1;
362
+
363
+ const destinationGroup = state.tabbableGroups[destinationGroupIndex];
364
+ destinationNode = destinationGroup.firstTabbableNode;
365
+ }
258
366
  }
367
+ } else {
368
+ destinationNode = getNodeForOption('fallbackFocus');
259
369
  }
260
370
 
261
371
  if (destinationNode) {
262
372
  e.preventDefault();
263
-
264
373
  tryFocus(destinationNode);
265
374
  }
375
+ // else, let the browser take care of [shift+]tab and move the focus
266
376
  };
267
377
 
268
378
  const checkKey = function (e) {
@@ -279,20 +389,18 @@ const createFocusTrap = function (elements, userOptions) {
279
389
  };
280
390
 
281
391
  const checkClick = function (e) {
282
- if (config.clickOutsideDeactivates) {
392
+ if (valueOrHandler(config.clickOutsideDeactivates, e)) {
283
393
  return;
284
394
  }
395
+
285
396
  if (containersContain(e.target)) {
286
397
  return;
287
398
  }
288
- if (
289
- config.allowOutsideClick &&
290
- (typeof config.allowOutsideClick === 'boolean'
291
- ? config.allowOutsideClick
292
- : config.allowOutsideClick(e))
293
- ) {
399
+
400
+ if (valueOrHandler(config.allowOutsideClick, e)) {
294
401
  return;
295
402
  }
403
+
296
404
  e.preventDefault();
297
405
  e.stopImmediatePropagation();
298
406
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "focus-trap",
3
- "version": "6.2.1",
3
+ "version": "6.4.0",
4
4
  "description": "Trap focus within a DOM node.",
5
5
  "main": "dist/focus-trap.js",
6
6
  "module": "dist/focus-trap.esm.js",
@@ -20,6 +20,7 @@
20
20
  "demo-bundle": "browserify demo/js/index.js -o demo/demo-bundle.js",
21
21
  "format": "prettier --write \"{*,src/**/*,test/**/*,demo/js/**/*,.github/workflows/*,cypress/**/*}.+(js|yml)\"",
22
22
  "format:check": "prettier --check \"{*,src/**/*,test/**/*,demo/js/**/*,.github/workflows/*,cypress/**/*}.+(js|yml)\"",
23
+ "format:watch": "onchange \"{*,src/**/*,test/**/*,demo/js/**/*,.github/workflows/*,cypress/**/*}.+(js|yml)\" -- prettier --write {{changed}}",
23
24
  "lint": "eslint \"*.js\" \"demo/**/*.js\" \"cypress/**/*.js\"",
24
25
  "clean": "rm -rf ./dist",
25
26
  "compile:esm": "BUILD_ENV=esm BABEL_ENV=esm rollup -c",
@@ -31,8 +32,9 @@
31
32
  "test:types": "tsc index.d.ts",
32
33
  "test:unit": "echo \"No unit tests to run!\"",
33
34
  "test:cypress": "start-server-and-test start 9966 'cypress open'",
34
- "test:cypress-ci": "start-server-and-test start 9966 'cypress run --browser $CYPRESS_BROWSER --headless'",
35
- "test": "yarn format:check && yarn lint && yarn test:unit && yarn test:types && CYPRESS_BROWSER=chrome yarn test:cypress-ci",
35
+ "test:cypress:ci": "start-server-and-test start 9966 'cypress run --browser $CYPRESS_BROWSER --headless'",
36
+ "test:chrome": "CYPRESS_BROWSER=chrome yarn test:cypress:ci",
37
+ "test": "yarn format:check && yarn lint && yarn test:unit && yarn test:types && CYPRESS_BROWSER=chrome yarn test:cypress:ci",
36
38
  "prepare": "yarn build",
37
39
  "release": "yarn build && changeset publish"
38
40
  },
@@ -58,34 +60,35 @@
58
60
  },
59
61
  "homepage": "https://github.com/focus-trap/focus-trap#readme",
60
62
  "dependencies": {
61
- "tabbable": "^5.1.4"
63
+ "tabbable": "^5.2.0"
62
64
  },
63
65
  "devDependencies": {
64
- "@babel/cli": "^7.12.8",
65
- "@babel/core": "^7.12.9",
66
- "@babel/preset-env": "^7.12.7",
67
- "@changesets/cli": "^2.11.2",
68
- "@rollup/plugin-babel": "^5.2.1",
69
- "@rollup/plugin-commonjs": "^16.0.0",
70
- "@rollup/plugin-node-resolve": "^10.0.0",
71
- "@testing-library/cypress": "^7.0.2",
72
- "@types/jquery": "^3.5.4",
73
- "all-contributors-cli": "^6.19.0",
66
+ "@babel/cli": "^7.13.14",
67
+ "@babel/core": "^7.13.15",
68
+ "@babel/preset-env": "^7.13.15",
69
+ "@changesets/cli": "^2.16.0",
70
+ "@rollup/plugin-babel": "^5.3.0",
71
+ "@rollup/plugin-commonjs": "^18.0.0",
72
+ "@rollup/plugin-node-resolve": "^11.2.1",
73
+ "@testing-library/cypress": "^7.0.5",
74
+ "@types/jquery": "^3.5.5",
75
+ "all-contributors-cli": "^6.20.0",
74
76
  "babel-eslint": "^10.1.0",
75
- "babel-loader": "^8.2.1",
77
+ "babel-loader": "^8.2.2",
76
78
  "babelify": "^10.0.0",
77
79
  "browserify": "^17.0.0",
78
80
  "budo": "^11.6.4",
79
- "cypress": "^5.6.0",
81
+ "cypress": "^7.1.0",
80
82
  "cypress-plugin-tab": "^1.0.5",
81
- "eslint": "^7.14.0",
82
- "eslint-config-prettier": "^6.15.0",
83
+ "eslint": "^7.24.0",
84
+ "eslint-config-prettier": "^8.2.0",
83
85
  "eslint-plugin-cypress": "^2.11.2",
84
- "prettier": "^2.2.0",
85
- "rollup": "^2.33.3",
86
+ "onchange": "^7.1.0",
87
+ "prettier": "^2.2.1",
88
+ "rollup": "^2.45.2",
86
89
  "rollup-plugin-sourcemaps": "^0.6.3",
87
90
  "rollup-plugin-terser": "^7.0.1",
88
- "start-server-and-test": "^1.11.6",
89
- "typescript": "^4.1.2"
91
+ "start-server-and-test": "^1.12.1",
92
+ "typescript": "^4.2.4"
90
93
  }
91
94
  }