index.esm.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*!
  2. * tabbable 6.0.1
  3. * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
  4. */
  5. var candidateSelectors = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]:not(slot)', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])', 'details>summary:first-of-type', 'details'];
  6. var candidateSelector = /* #__PURE__ */candidateSelectors.join(',');
  7. var NoElement = typeof Element === 'undefined';
  8. var matches = NoElement ? function () {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
  9. var getRootNode = !NoElement && Element.prototype.getRootNode ? function (element) {
  10. return element.getRootNode();
  11. } : function (element) {
  12. return element.ownerDocument;
  13. };
  14. /**
  15. * @param {Element} el container to check in
  16. * @param {boolean} includeContainer add container to check
  17. * @param {(node: Element) => boolean} filter filter candidates
  18. * @returns {Element[]}
  19. */
  20. var getCandidates = function getCandidates(el, includeContainer, filter) {
  21. var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));
  22. if (includeContainer && matches.call(el, candidateSelector)) {
  23. candidates.unshift(el);
  24. }
  25. candidates = candidates.filter(filter);
  26. return candidates;
  27. };
  28. /**
  29. * @callback GetShadowRoot
  30. * @param {Element} element to check for shadow root
  31. * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.
  32. */
  33. /**
  34. * @callback ShadowRootFilter
  35. * @param {Element} shadowHostNode the element which contains shadow content
  36. * @returns {boolean} true if a shadow root could potentially contain valid candidates.
  37. */
  38. /**
  39. * @typedef {Object} CandidateScope
  40. * @property {Element} scopeParent contains inner candidates
  41. * @property {Element[]} candidates list of candidates found in the scope parent
  42. */
  43. /**
  44. * @typedef {Object} IterativeOptions
  45. * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;
  46. * if a function, implies shadow support is enabled and either returns the shadow root of an element
  47. * or a boolean stating if it has an undisclosed shadow root
  48. * @property {(node: Element) => boolean} filter filter candidates
  49. * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list
  50. * @property {ShadowRootFilter} shadowRootFilter filter shadow roots;
  51. */
  52. /**
  53. * @param {Element[]} elements list of element containers to match candidates from
  54. * @param {boolean} includeContainer add container list to check
  55. * @param {IterativeOptions} options
  56. * @returns {Array.<Element|CandidateScope>}
  57. */
  58. var getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) {
  59. var candidates = [];
  60. var elementsToCheck = Array.from(elements);
  61. while (elementsToCheck.length) {
  62. var element = elementsToCheck.shift();
  63. if (element.tagName === 'SLOT') {
  64. // add shadow dom slot scope (slot itself cannot be focusable)
  65. var assigned = element.assignedElements();
  66. var content = assigned.length ? assigned : element.children;
  67. var nestedCandidates = getCandidatesIteratively(content, true, options);
  68. if (options.flatten) {
  69. candidates.push.apply(candidates, nestedCandidates);
  70. } else {
  71. candidates.push({
  72. scopeParent: element,
  73. candidates: nestedCandidates
  74. });
  75. }
  76. } else {
  77. // check candidate element
  78. var validCandidate = matches.call(element, candidateSelector);
  79. if (validCandidate && options.filter(element) && (includeContainer || !elements.includes(element))) {
  80. candidates.push(element);
  81. }
  82. // iterate over shadow content if possible
  83. var shadowRoot = element.shadowRoot ||
  84. // check for an undisclosed shadow
  85. typeof options.getShadowRoot === 'function' && options.getShadowRoot(element);
  86. var validShadowRoot = !options.shadowRootFilter || options.shadowRootFilter(element);
  87. if (shadowRoot && validShadowRoot) {
  88. // add shadow dom scope IIF a shadow root node was given; otherwise, an undisclosed
  89. // shadow exists, so look at light dom children as fallback BUT create a scope for any
  90. // child candidates found because they're likely slotted elements (elements that are
  91. // children of the web component element (which has the shadow), in the light dom, but
  92. // slotted somewhere _inside_ the undisclosed shadow) -- the scope is created below,
  93. // _after_ we return from this recursive call
  94. var _nestedCandidates = getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options);
  95. if (options.flatten) {
  96. candidates.push.apply(candidates, _nestedCandidates);
  97. } else {
  98. candidates.push({
  99. scopeParent: element,
  100. candidates: _nestedCandidates
  101. });
  102. }
  103. } else {
  104. // there's not shadow so just dig into the element's (light dom) children
  105. // __without__ giving the element special scope treatment
  106. elementsToCheck.unshift.apply(elementsToCheck, element.children);
  107. }
  108. }
  109. }
  110. return candidates;
  111. };
  112. var getTabindex = function getTabindex(node, isScope) {
  113. if (node.tabIndex < 0) {
  114. // in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default
  115. // `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
  116. // yet they are still part of the regular tab order; in FF, they get a default
  117. // `tabIndex` of 0; since Chrome still puts those elements in the regular tab
  118. // order, consider their tab index to be 0.
  119. // Also browsers do not return `tabIndex` correctly for contentEditable nodes;
  120. // so if they don't have a tabindex attribute specifically set, assume it's 0.
  121. //
  122. // isScope is positive for custom element with shadow root or slot that by default
  123. // have tabIndex -1, but need to be sorted by document order in order for their
  124. // content to be inserted in the correct position
  125. if ((isScope || /^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || node.isContentEditable) && isNaN(parseInt(node.getAttribute('tabindex'), 10))) {
  126. return 0;
  127. }
  128. }
  129. return node.tabIndex;
  130. };
  131. var sortOrderedTabbables = function sortOrderedTabbables(a, b) {
  132. return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;
  133. };
  134. var isInput = function isInput(node) {
  135. return node.tagName === 'INPUT';
  136. };
  137. var isHiddenInput = function isHiddenInput(node) {
  138. return isInput(node) && node.type === 'hidden';
  139. };
  140. var isDetailsWithSummary = function isDetailsWithSummary(node) {
  141. var r = node.tagName === 'DETAILS' && Array.prototype.slice.apply(node.children).some(function (child) {
  142. return child.tagName === 'SUMMARY';
  143. });
  144. return r;
  145. };
  146. var getCheckedRadio = function getCheckedRadio(nodes, form) {
  147. for (var i = 0; i < nodes.length; i++) {
  148. if (nodes[i].checked && nodes[i].form === form) {
  149. return nodes[i];
  150. }
  151. }
  152. };
  153. var isTabbableRadio = function isTabbableRadio(node) {
  154. if (!node.name) {
  155. return true;
  156. }
  157. var radioScope = node.form || getRootNode(node);
  158. var queryRadios = function queryRadios(name) {
  159. return radioScope.querySelectorAll('input[type="radio"][name="' + name + '"]');
  160. };
  161. var radioSet;
  162. if (typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.escape === 'function') {
  163. radioSet = queryRadios(window.CSS.escape(node.name));
  164. } else {
  165. try {
  166. radioSet = queryRadios(node.name);
  167. } catch (err) {
  168. // eslint-disable-next-line no-console
  169. console.error('Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s', err.message);
  170. return false;
  171. }
  172. }
  173. var checked = getCheckedRadio(radioSet, node.form);
  174. return !checked || checked === node;
  175. };
  176. var isRadio = function isRadio(node) {
  177. return isInput(node) && node.type === 'radio';
  178. };
  179. var isNonTabbableRadio = function isNonTabbableRadio(node) {
  180. return isRadio(node) && !isTabbableRadio(node);
  181. };
  182. // determines if a node is ultimately attached to the window's document
  183. var isNodeAttached = function isNodeAttached(node) {
  184. var _nodeRootHost;
  185. // The root node is the shadow root if the node is in a shadow DOM; some document otherwise
  186. // (but NOT _the_ document; see second 'If' comment below for more).
  187. // If rootNode is shadow root, it'll have a host, which is the element to which the shadow
  188. // is attached, and the one we need to check if it's in the document or not (because the
  189. // shadow, and all nodes it contains, is never considered in the document since shadows
  190. // behave like self-contained DOMs; but if the shadow's HOST, which is part of the document,
  191. // is hidden, or is not in the document itself but is detached, it will affect the shadow's
  192. // visibility, including all the nodes it contains). The host could be any normal node,
  193. // or a custom element (i.e. web component). Either way, that's the one that is considered
  194. // part of the document, not the shadow root, nor any of its children (i.e. the node being
  195. // tested).
  196. // To further complicate things, we have to look all the way up until we find a shadow HOST
  197. // that is attached (or find none) because the node might be in nested shadows...
  198. // If rootNode is not a shadow root, it won't have a host, and so rootNode should be the
  199. // document (per the docs) and while it's a Document-type object, that document does not
  200. // appear to be the same as the node's `ownerDocument` for some reason, so it's safer
  201. // to ignore the rootNode at this point, and use `node.ownerDocument`. Otherwise,
  202. // using `rootNode.contains(node)` will _always_ be true we'll get false-positives when
  203. // node is actually detached.
  204. var nodeRootHost = getRootNode(node).host;
  205. var attached = !!((_nodeRootHost = nodeRootHost) !== null && _nodeRootHost !== void 0 && _nodeRootHost.ownerDocument.contains(nodeRootHost) || node.ownerDocument.contains(node));
  206. while (!attached && nodeRootHost) {
  207. var _nodeRootHost2;
  208. // since it's not attached and we have a root host, the node MUST be in a nested shadow DOM,
  209. // which means we need to get the host's host and check if that parent host is contained
  210. // in (i.e. attached to) the document
  211. nodeRootHost = getRootNode(nodeRootHost).host;
  212. attached = !!((_nodeRootHost2 = nodeRootHost) !== null && _nodeRootHost2 !== void 0 && _nodeRootHost2.ownerDocument.contains(nodeRootHost));
  213. }
  214. return attached;
  215. };
  216. var isZeroArea = function isZeroArea(node) {
  217. var _node$getBoundingClie = node.getBoundingClientRect(),
  218. width = _node$getBoundingClie.width,
  219. height = _node$getBoundingClie.height;
  220. return width === 0 && height === 0;
  221. };
  222. var isHidden = function isHidden(node, _ref) {
  223. var displayCheck = _ref.displayCheck,
  224. getShadowRoot = _ref.getShadowRoot;
  225. // NOTE: visibility will be `undefined` if node is detached from the document
  226. // (see notes about this further down), which means we will consider it visible
  227. // (this is legacy behavior from a very long way back)
  228. // NOTE: we check this regardless of `displayCheck="none"` because this is a
  229. // _visibility_ check, not a _display_ check
  230. if (getComputedStyle(node).visibility === 'hidden') {
  231. return true;
  232. }
  233. var isDirectSummary = matches.call(node, 'details>summary:first-of-type');
  234. var nodeUnderDetails = isDirectSummary ? node.parentElement : node;
  235. if (matches.call(nodeUnderDetails, 'details:not([open]) *')) {
  236. return true;
  237. }
  238. if (!displayCheck || displayCheck === 'full' || displayCheck === 'legacy-full') {
  239. if (typeof getShadowRoot === 'function') {
  240. // figure out if we should consider the node to be in an undisclosed shadow and use the
  241. // 'non-zero-area' fallback
  242. var originalNode = node;
  243. while (node) {
  244. var parentElement = node.parentElement;
  245. var rootNode = getRootNode(node);
  246. if (parentElement && !parentElement.shadowRoot && getShadowRoot(parentElement) === true // check if there's an undisclosed shadow
  247. ) {
  248. // node has an undisclosed shadow which means we can only treat it as a black box, so we
  249. // fall back to a non-zero-area test
  250. return isZeroArea(node);
  251. } else if (node.assignedSlot) {
  252. // iterate up slot
  253. node = node.assignedSlot;
  254. } else if (!parentElement && rootNode !== node.ownerDocument) {
  255. // cross shadow boundary
  256. node = rootNode.host;
  257. } else {
  258. // iterate up normal dom
  259. node = parentElement;
  260. }
  261. }
  262. node = originalNode;
  263. }
  264. // else, `getShadowRoot` might be true, but all that does is enable shadow DOM support
  265. // (i.e. it does not also presume that all nodes might have undisclosed shadows); or
  266. // it might be a falsy value, which means shadow DOM support is disabled
  267. // Since we didn't find it sitting in an undisclosed shadow (or shadows are disabled)
  268. // now we can just test to see if it would normally be visible or not, provided it's
  269. // attached to the main document.
  270. // NOTE: We must consider case where node is inside a shadow DOM and given directly to
  271. // `isTabbable()` or `isFocusable()` -- regardless of `getShadowRoot` option setting.
  272. if (isNodeAttached(node)) {
  273. // this works wherever the node is: if there's at least one client rect, it's
  274. // somehow displayed; it also covers the CSS 'display: contents' case where the
  275. // node itself is hidden in place of its contents; and there's no need to search
  276. // up the hierarchy either
  277. return !node.getClientRects().length;
  278. }
  279. // Else, the node isn't attached to the document, which means the `getClientRects()`
  280. // API will __always__ return zero rects (this can happen, for example, if React
  281. // is used to render nodes onto a detached tree, as confirmed in this thread:
  282. // https://github.com/facebook/react/issues/9117#issuecomment-284228870)
  283. //
  284. // It also means that even window.getComputedStyle(node).display will return `undefined`
  285. // because styles are only computed for nodes that are in the document.
  286. //
  287. // NOTE: THIS HAS BEEN THE CASE FOR YEARS. It is not new, nor is it caused by tabbable
  288. // somehow. Though it was never stated officially, anyone who has ever used tabbable
  289. // APIs on nodes in detached containers has actually implicitly used tabbable in what
  290. // was later (as of v5.2.0 on Apr 9, 2021) called `displayCheck="none"` mode -- essentially
  291. // considering __everything__ to be visible because of the innability to determine styles.
  292. //
  293. // v6.0.0: As of this major release, the default 'full' option __no longer treats detached
  294. // nodes as visible with the 'none' fallback.__
  295. if (displayCheck !== 'legacy-full') {
  296. return true; // hidden
  297. }
  298. // else, fallback to 'none' mode and consider the node visible
  299. } else if (displayCheck === 'non-zero-area') {
  300. // NOTE: Even though this tests that the node's client rect is non-zero to determine
  301. // whether it's displayed, and that a detached node will __always__ have a zero-area
  302. // client rect, we don't special-case for whether the node is attached or not. In
  303. // this mode, we do want to consider nodes that have a zero area to be hidden at all
  304. // times, and that includes attached or not.
  305. return isZeroArea(node);
  306. }
  307. // visible, as far as we can tell, or per current `displayCheck=none` mode, we assume
  308. // it's visible
  309. return false;
  310. };
  311. // form fields (nested) inside a disabled fieldset are not focusable/tabbable
  312. // unless they are in the _first_ <legend> element of the top-most disabled
  313. // fieldset
  314. var isDisabledFromFieldset = function isDisabledFromFieldset(node) {
  315. if (/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(node.tagName)) {
  316. var parentNode = node.parentElement;
  317. // check if `node` is contained in a disabled <fieldset>
  318. while (parentNode) {
  319. if (parentNode.tagName === 'FIELDSET' && parentNode.disabled) {
  320. // look for the first <legend> among the children of the disabled <fieldset>
  321. for (var i = 0; i < parentNode.children.length; i++) {
  322. var child = parentNode.children.item(i);
  323. // when the first <legend> (in document order) is found
  324. if (child.tagName === 'LEGEND') {
  325. // if its parent <fieldset> is not nested in another disabled <fieldset>,
  326. // return whether `node` is a descendant of its first <legend>
  327. return matches.call(parentNode, 'fieldset[disabled] *') ? true : !child.contains(node);
  328. }
  329. }
  330. // the disabled <fieldset> containing `node` has no <legend>
  331. return true;
  332. }
  333. parentNode = parentNode.parentElement;
  334. }
  335. }
  336. // else, node's tabbable/focusable state should not be affected by a fieldset's
  337. // enabled/disabled state
  338. return false;
  339. };
  340. var isNodeMatchingSelectorFocusable = function isNodeMatchingSelectorFocusable(options, node) {
  341. if (node.disabled || isHiddenInput(node) || isHidden(node, options) ||
  342. // For a details element with a summary, the summary element gets the focus
  343. isDetailsWithSummary(node) || isDisabledFromFieldset(node)) {
  344. return false;
  345. }
  346. return true;
  347. };
  348. var isNodeMatchingSelectorTabbable = function isNodeMatchingSelectorTabbable(options, node) {
  349. if (isNonTabbableRadio(node) || getTabindex(node) < 0 || !isNodeMatchingSelectorFocusable(options, node)) {
  350. return false;
  351. }
  352. return true;
  353. };
  354. var isValidShadowRootTabbable = function isValidShadowRootTabbable(shadowHostNode) {
  355. var tabIndex = parseInt(shadowHostNode.getAttribute('tabindex'), 10);
  356. if (isNaN(tabIndex) || tabIndex >= 0) {
  357. return true;
  358. }
  359. // If a custom element has an explicit negative tabindex,
  360. // browsers will not allow tab targeting said element's children.
  361. return false;
  362. };
  363. /**
  364. * @param {Array.<Element|CandidateScope>} candidates
  365. * @returns Element[]
  366. */
  367. var sortByOrder = function sortByOrder(candidates) {
  368. var regularTabbables = [];
  369. var orderedTabbables = [];
  370. candidates.forEach(function (item, i) {
  371. var isScope = !!item.scopeParent;
  372. var element = isScope ? item.scopeParent : item;
  373. var candidateTabindex = getTabindex(element, isScope);
  374. var elements = isScope ? sortByOrder(item.candidates) : element;
  375. if (candidateTabindex === 0) {
  376. isScope ? regularTabbables.push.apply(regularTabbables, elements) : regularTabbables.push(element);
  377. } else {
  378. orderedTabbables.push({
  379. documentOrder: i,
  380. tabIndex: candidateTabindex,
  381. item: item,
  382. isScope: isScope,
  383. content: elements
  384. });
  385. }
  386. });
  387. return orderedTabbables.sort(sortOrderedTabbables).reduce(function (acc, sortable) {
  388. sortable.isScope ? acc.push.apply(acc, sortable.content) : acc.push(sortable.content);
  389. return acc;
  390. }, []).concat(regularTabbables);
  391. };
  392. var tabbable = function tabbable(el, options) {
  393. options = options || {};
  394. var candidates;
  395. if (options.getShadowRoot) {
  396. candidates = getCandidatesIteratively([el], options.includeContainer, {
  397. filter: isNodeMatchingSelectorTabbable.bind(null, options),
  398. flatten: false,
  399. getShadowRoot: options.getShadowRoot,
  400. shadowRootFilter: isValidShadowRootTabbable
  401. });
  402. } else {
  403. candidates = getCandidates(el, options.includeContainer, isNodeMatchingSelectorTabbable.bind(null, options));
  404. }
  405. return sortByOrder(candidates);
  406. };
  407. var focusable = function focusable(el, options) {
  408. options = options || {};
  409. var candidates;
  410. if (options.getShadowRoot) {
  411. candidates = getCandidatesIteratively([el], options.includeContainer, {
  412. filter: isNodeMatchingSelectorFocusable.bind(null, options),
  413. flatten: true,
  414. getShadowRoot: options.getShadowRoot
  415. });
  416. } else {
  417. candidates = getCandidates(el, options.includeContainer, isNodeMatchingSelectorFocusable.bind(null, options));
  418. }
  419. return candidates;
  420. };
  421. var isTabbable = function isTabbable(node, options) {
  422. options = options || {};
  423. if (!node) {
  424. throw new Error('No node provided');
  425. }
  426. if (matches.call(node, candidateSelector) === false) {
  427. return false;
  428. }
  429. return isNodeMatchingSelectorTabbable(options, node);
  430. };
  431. var focusableCandidateSelector = /* #__PURE__ */candidateSelectors.concat('iframe').join(',');
  432. var isFocusable = function isFocusable(node, options) {
  433. options = options || {};
  434. if (!node) {
  435. throw new Error('No node provided');
  436. }
  437. if (matches.call(node, focusableCandidateSelector) === false) {
  438. return false;
  439. }
  440. return isNodeMatchingSelectorFocusable(options, node);
  441. };
  442. export { focusable, isFocusable, isTabbable, tabbable };
  443. //# sourceMappingURL=index.esm.js.map