focus-trap 6.3.0 → 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\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 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 const startOfGroupIndex = findIndex(\n state.tabbableGroups,\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 // FORWARD\n const lastOfGroupIndex = findIndex(\n state.tabbableGroups,\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 } else {\n destinationNode = getNodeForOption('fallbackFocus');\n }\n\n if (destinationNode) {\n e.preventDefault();\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 (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","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,EA5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AAO0E,kBACTA,GACFA,IAGFT,IACOQ,MAGT7B,oBAAW+B,OACJvE,EAAMK,cACFgE,KAGTG,aAAazG,GAEbkG,IACAjE,EAAMK,QAAS,EACfL,EAAMM,QAAS,EAEfrC,EAAiBU,eAAeR,OAE1BsG,EACJF,QAAwDG,IAAnCH,EAAkBE,aACnCF,EAAkBE,aAClB7E,EAAO6E,oBACTA,GACFA,KAIAF,QAAuDG,IAAlCH,EAAkB9B,YACnC8B,EAAkB9B,YAClB7C,EAAOC,0BAGXhB,GAAM,WA9Qe,IAAU8F,EA+Q7B9C,GA/Q6B8C,EA+QD3E,EAAMG,4BA9Q3BS,EAAiB,mBAET+D,OAgRZN,MAGT/F,wBACM0B,EAAMM,SAAWN,EAAMK,SAI3BL,EAAMM,QAAS,EACf2D,KAJSI,MASXzF,0BACOoB,EAAMM,QAAWN,EAAMK,QAI5BL,EAAMM,QAAS,EACfgB,IACAuC,IAEOQ,MAPEA,MAUXO,iCAAwBC,OAChBC,EAAkB,GAAGC,OAAOF,GAAmBlD,OAAOqD,gBAE5DhF,EAAMC,WAAa6E,EAAgBvD,KAAI,SAACf,SACnB,iBAAZA,EAAuBd,EAAIsB,cAAcR,GAAWA,KAGzDR,EAAMK,QACRiB,IAGK+C,QAKNO,wBAAwBpF,GAEtBrB"}
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,8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,GAAkB,GACxD1C,EAAIyE,oBAAoB,QAASN,GAAY,GAC7CnE,EAAIyE,oBAAoB,UAAWlB,GAAU,GAEtC9E,UAOTA,EAAO,CACLiG,kBAASC,MACHrE,EAAMK,cACDiE,KAGThD,IAEAtB,EAAMK,QAAS,EACfL,EAAMM,QAAS,EACfN,EAAMG,4BAA8BT,EAAIyB,kBAElCoD,EACJF,GAAmBA,EAAgBE,WAC/BF,EAAgBE,WAChB3E,EAAO2E,kBACTA,GACFA,IAGFT,IACOQ,MAGT9B,oBAAWgC,OACJxE,EAAMK,cACFiE,KAGTG,aAAa1G,GAEbmG,IACAlE,EAAMK,QAAS,EACfL,EAAMM,QAAS,EAEfrC,EAAiBU,eAAeR,OAE1BuG,EACJF,QAAwDG,IAAnCH,EAAkBE,aACnCF,EAAkBE,aAClB9E,EAAO8E,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.js CHANGED
@@ -283,6 +283,8 @@ const createFocusTrap = function (elements, userOptions) {
283
283
 
284
284
  if (state.tabbableGroups.length > 0) {
285
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
286
288
  const containerIndex = findIndex(state.tabbableGroups, ({ container }) =>
287
289
  container.contains(e.target)
288
290
  );
@@ -301,12 +303,27 @@ const createFocusTrap = function (elements, userOptions) {
301
303
  }
302
304
  } else if (e.shiftKey) {
303
305
  // REVERSE
304
- const startOfGroupIndex = findIndex(
306
+
307
+ // is the target the first tabbable node in a group?
308
+ let startOfGroupIndex = findIndex(
305
309
  state.tabbableGroups,
306
310
  ({ firstTabbableNode }) => e.target === firstTabbableNode
307
311
  );
308
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
+ }
322
+
309
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)
310
327
  const destinationGroupIndex =
311
328
  startOfGroupIndex === 0
312
329
  ? state.tabbableGroups.length - 1
@@ -317,12 +334,27 @@ const createFocusTrap = function (elements, userOptions) {
317
334
  }
318
335
  } else {
319
336
  // FORWARD
320
- const lastOfGroupIndex = findIndex(
337
+
338
+ // is the target the last tabbable node in a group?
339
+ let lastOfGroupIndex = findIndex(
321
340
  state.tabbableGroups,
322
341
  ({ lastTabbableNode }) => e.target === lastTabbableNode
323
342
  );
324
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
+ }
353
+
325
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)
326
358
  const destinationGroupIndex =
327
359
  lastOfGroupIndex === state.tabbableGroups.length - 1
328
360
  ? 0
@@ -340,6 +372,7 @@ const createFocusTrap = function (elements, userOptions) {
340
372
  e.preventDefault();
341
373
  tryFocus(destinationNode);
342
374
  }
375
+ // else, let the browser take care of [shift+]tab and move the focus
343
376
  };
344
377
 
345
378
  const checkKey = function (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "focus-trap",
3
- "version": "6.3.0",
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",
@@ -32,8 +32,9 @@
32
32
  "test:types": "tsc index.d.ts",
33
33
  "test:unit": "echo \"No unit tests to run!\"",
34
34
  "test:cypress": "start-server-and-test start 9966 'cypress open'",
35
- "test:cypress-ci": "start-server-and-test start 9966 'cypress run --browser $CYPRESS_BROWSER --headless'",
36
- "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",
37
38
  "prepare": "yarn build",
38
39
  "release": "yarn build && changeset publish"
39
40
  },
@@ -59,35 +60,35 @@
59
60
  },
60
61
  "homepage": "https://github.com/focus-trap/focus-trap#readme",
61
62
  "dependencies": {
62
- "tabbable": "^5.1.5"
63
+ "tabbable": "^5.2.0"
63
64
  },
64
65
  "devDependencies": {
65
- "@babel/cli": "^7.12.10",
66
- "@babel/core": "^7.12.10",
67
- "@babel/preset-env": "^7.12.11",
68
- "@changesets/cli": "^2.12.0",
69
- "@rollup/plugin-babel": "^5.2.2",
70
- "@rollup/plugin-commonjs": "^17.0.0",
71
- "@rollup/plugin-node-resolve": "^11.0.1",
72
- "@testing-library/cypress": "^7.0.3",
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",
73
74
  "@types/jquery": "^3.5.5",
74
- "all-contributors-cli": "^6.19.0",
75
+ "all-contributors-cli": "^6.20.0",
75
76
  "babel-eslint": "^10.1.0",
76
77
  "babel-loader": "^8.2.2",
77
78
  "babelify": "^10.0.0",
78
79
  "browserify": "^17.0.0",
79
80
  "budo": "^11.6.4",
80
- "cypress": "^6.2.1",
81
+ "cypress": "^7.1.0",
81
82
  "cypress-plugin-tab": "^1.0.5",
82
- "eslint": "^7.17.0",
83
- "eslint-config-prettier": "^7.1.0",
83
+ "eslint": "^7.24.0",
84
+ "eslint-config-prettier": "^8.2.0",
84
85
  "eslint-plugin-cypress": "^2.11.2",
85
86
  "onchange": "^7.1.0",
86
87
  "prettier": "^2.2.1",
87
- "rollup": "^2.36.1",
88
+ "rollup": "^2.45.2",
88
89
  "rollup-plugin-sourcemaps": "^0.6.3",
89
90
  "rollup-plugin-terser": "^7.0.1",
90
- "start-server-and-test": "^1.11.7",
91
- "typescript": "^4.1.3"
91
+ "start-server-and-test": "^1.12.1",
92
+ "typescript": "^4.2.4"
92
93
  }
93
94
  }