index.umd.js 22 KB

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