index.js 21 KB

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