Detalhes do pacote

tabbable

focus-trap28.9mMIT6.2.0

Returns an array of all tabbable DOM nodes within a containing node.

readme (leia-me)

tabbable CI Codecov license

All Contributors

Small utility that returns an array of all* tabbable DOM nodes within a containing node.

*all has some necessary caveats, which you'll learn about by reading below.

The following are considered tabbable:

  • <button> elements
  • <input> elements
  • <select> elements
  • <textarea> elements
  • <a> elements with an href attribute
  • <audio> and <video> elements with controls attributes
  • the first <summary> element directly under a <details> element
  • <details> element without a <summary> element
  • elements with the [contenteditable] attribute
  • anything with a non-negative tabindex attribute

Any of the above will not be considered tabbable, though, if any of the following are also true about it:

  • has a negative tabindex attribute
  • has a disabled attribute
  • either the node itself or an ancestor of it is hidden via display: none (*see "Display check" below to modify this behavior)
  • has visibility: hidden style
  • is nested under a closed <details> element (with the exception of the first <summary> element)
  • is an <input type="radio"> element and a different radio in its group is checked
  • is a form field (button, input, select, textarea) inside a disabled <fieldset>
  • is inert or in an inert container
    • ❗️ Only supported in newer browsers that support this new attribute)
    • ⚠️ Notably not (yet) supported on Firefox and Safari (Feb 2023)

If you think a node should be included in your array of tabbables but it's not, all you need to do is add tabindex="0" to deliberately include it. (Or if it is in your array but you don't want it, you can add tabindex="-1" to deliberately exclude it.) This will also result in more consistent cross-browser behavior. For information about why your special node might not be included, see "More details", below.

Goals

  • Accurate (or, as accurate as possible & reasonable)
  • No dependencies
  • Small
  • Fast

Browser Support

As old and as broad as reasonably possible, excluding browsers that are out of support or have nearly no user base.

Focused on desktop browsers, particularly Chrome, Edge, FireFox, Safari, and Opera.

Tabbable is not officially tested on any mobile browsers or devices.

⚠️ Microsoft no longer supports any version of IE, so IE is no longer supported by this library.

💬 Keep in mind that performance optimization and old browser support are often at odds, so tabbable may not always be able to use the most optimal (typically modern) APIs in all cases.

Installation

npm install tabbable

💬 Some very old browsers may need a polyfill for the CSS.escape API for tabbable to work properly with radio buttons that have name attributes containing special characters.

API

tabbable

import { tabbable } from 'tabbable';

tabbable(container, [options]);
  • container: Node (Required)
  • options:
    • All the common options.
    • includeContainer: boolean (default: false)
      • If set to true, container will be included in the returned tabbable node array, if container is tabbable.
      • Note that whether this option is true or false, if the container is inert, none of its children (deep) will be considered tabbable.

Returns an array of ordered tabbable nodes (i.e. in tab order) within the container.

Summary of ordering principles:

  • First include any nodes with positive tabindex attributes (1 or higher), ordered by ascending tabindex and source order.
  • Then include any nodes with a zero tabindex and any element that by default receives focus (listed above) and does not have a positive tabindex set, in source order.

isTabbable

import { isTabbable } from 'tabbable';

isTabbable(node, [options]);

Returns a boolean indicating whether the provided node is considered tabbable.

💬 If the node has an inert ancestor, it will not be tabbable.

focusable

import { focusable } from 'tabbable';

focusable(container, [options]);
  • container: Node: Required
  • options:
    • All the common options.
    • includeContainer: boolean (default: false)
      • If set to true, container will be included in the returned focusable node array, if container is focusable.
      • Note that whether this option is true or false, if the container is inert, none of its children (deep) will be considered focusable.

Returns an array of focusable nodes within the container, in DOM order. This will not match the order in which tabbable() returns nodes.

isFocusable

import { isFocusable } from 'tabbable';

isFocusable(node, [options]);

Returns a boolean indicating whether the provided node is considered focusable.

💬 All tabbable elements are focusable, but not all focusable elements are tabbable. For example, elements with tabindex="-1" are focusable but not tabbable. Also note that if the node has aninert ancestor, it will not be focusable.

getTabIndex

import { getTabIndex } from 'tabbable';

getTabIndex(node);
  • node: Element (Required)

Returns a negative, 0, or positive number that expresses the node's tab index in the DOM, with exceptions made where there are browser inconsistencies related to <audio>, <video>, <details>, and elements with the contenteditable="true" attribute.

The specific exceptions may change over time. See the implementation for specific behavior.

Common Options

These options apply to all APIs.

displayCheck option

Type: full | legacy-full | non-zero-area | none . Default: full.

Configures how to check if an element is displayed.

To reliably check if an element is tabbable/focusable, Tabbable defaults to the most reliable option to keep consistent with browser behavior, however this comes at a cost since every node needs to be validated as displayed using Web APIs that cause layout reflow.

For this reason Tabbable offers the ability of an alternative way to check if an element is displayed (or completely opt out of the check).

The displayCheck configuration accepts the following options:

  • full: (default) Most reliably resembling browser behavior, this option checks that an element is displayed, which requires it to be attached to the DOM, and for all of his ancestors to be displayed (notice this doesn't exclude visibility: hidden or elements with zero size). This option will cause layout reflow, however. If that is a concern, consider the none option.
    • ⚠️ If the container given to tabbable() or focusable(), or the node given to isTabbable() or isFocusable(), is not attached to the window's main document, the node will be considered hidden and neither tabbable nor focusable. This behavior is new as of v6.0.0.
    • If your code relies on the legacy behavior where detached nodes were considered visible, and you are unable to fix your code to use tabbable once the node is attached, use the legacy-full option.
  • legacy-full: Same as full but restores the legacy behavior of treating detached nodes as visible. This means that if a node is detached, it's then treated as though the display check was set to none (see below for details).
    • ❗️ Since detached nodes are not treated as tabbable/focusable by browsers, using this option is not recommended as it knowingly diverges from browser behavior.
    • ⚠️ This option may be removed in the future. Tabbable will not maintain it at the expense of new features or if having it makes the code disproportionately more complex. It only exists to make the upgrade path to the correct behavior (i.e. the full option) as long and smooth as reasonably possible.
    • The APIs used to determine a node's display are not supported unless its attached (i.e. the browser does not calculate its display unless it is attached). This has effectively been tabbable's behavior for a very long time (up until the v6.0.0 release), and you may never have encountered an issue if the nodes with which you used tabbable were always displayed anyway (i.e. the none mode assumption was coincidentally correct).
    • You may encounter the above situation if, for example, you render to a node via React, and this node is not attached to the document (or perhaps, due to timing, it is not yet attached at the time you use tabbable's APIs on it).
  • non-zero-area: This option checks display under the assumption that elements that are not displayed have zero area (width AND height equals zero). While not keeping true to browser behavior, this option may enhance accessibility, as zero-size elements with focusable content are considered a strong accessibility anti-pattern.
    • Like the full option, this option also causes layout reflow, and should have basically the same performance. Consider the none option if reflow is a concern.
    • ⚠️ As with the full option, there is a nuance in behavior depending on whether tabbable APIs are executed on attached vs detached nodes using this mode: Attached nodes that are actually displayed will be deemed visible. Detached nodes, even though displayed will always be deemed hidden because detached nodes always have a zero area as the browser does not calculate is dimensions.
  • none: This completely opts out of the display check. This option is not recommended, as it might return elements that are not displayed, and as such not tabbable/focusable and can break accessibility. Make sure you know which elements in your DOM are not displayed and can filter them out yourself before using this option.

⚠️ Testing in JSDom (e.g. with Jest): See notes about testing in JSDom.

getShadowRoot option

By default, tabbable overlooks (i.e. does not consider) all elements contained in shadow DOMs (whether open or closed). This has been the behavior since the beginning.

Setting this option to a truthy value enables Shadow DOM support, which means tabbable will consider elements inside web components as candidates, both open (automatically) and closed (provided this function returns the shadow root).

Type: boolean | (node: FocusableElement) => ShadowRoot | boolean | undefined

  • boolean:
    • true simply enables shadow DOM support for any open shadow roots, but never presumes there is an undisclosed shadow. This is the equivalent of setting getShadowRoot: () => false
    • false (default) disables shadow DOM support in so far as calculated tab order and closed shadow roots are concerned. If a child of a shadow (open or closed) is given to isTabbable() or isFocusable(), the shadow DOM is still considered for visibility and display checks.
  • function:
    • node will be a descendent of the container given to tabbable(), isTabbable(), focusable(), or isFocusable().
    • Returns: The node's ShadowRoot if available, true indicating a ShadowRoot is attached but not available (i.e. "undisclosed"), or a falsy value indicating there is no shadow attached to the node.

If set to a function, and if it returns true, Tabbable assumes a closed ShadowRoot is attached and will treat the node as a scope, iterating its children for additional tabbable/focusable candidates as though it was looking inside the shadow, but not. This will get tabbing order closer to -- but not necessarily the same as -- browser order.

Returning true from a function will also inform how the node's visibility check is done, causing tabbable to use the non-zero-area Display Check when determining if it's visible, and so tabbable/focusable.

More details

  • Tabbable tries to identify elements that are reliably tabbable across (not dead) browsers. Browsers are inconsistent in their behavior, though — especially for edge-case elements like <object> and <iframe> — so this means some elements that you can tab to in some browsers will be left out of the results. (To learn more about this inconsistency, see this amazing table). To provide better consistency across browsers and ensure the elements you want in your tabbables list show up there, try adding tabindex="0" to edge-case elements that Tabbable ignores.
  • (Exemplifying the above ^^:) The tabbability of <iframe>, <embed>, <object>, <summary>, and <svg> nodes is inconsistent across browsers, so if you need an accurate read on one of these elements you should try giving it a tabindex. (You'll also need to pay attention to the focusable attribute on SVGs in Edge.) But you also might not be able to get an accurate read — so you should avoid relying on it.
  • Radio groups have some edge cases, which you can avoid by always having a checked one in each group (and that is what you should usually do anyway). If there is no checked radio in the radio group, all of the radios will be considered tabbable. (Some browsers do this, otherwise don't — there's not consistency.)
  • If you're thinking, "Why not just use the right querySelectorAll?", you may be on to something ... but, as with most "just" statements, you're probably not. For example, a simple querySelectorAll approach will not figure out whether an element is hidden, and therefore not actually tabbable. (That said, if you do think Tabbable can be simplified or otherwise improved, I'd love to hear your idea.)
  • jQuery UI's :tabbable selector ignores elements with height and width of 0. I'm not sure why — because I've found that I can still tab to those elements. So I kept them in. Only elements hidden with display: none or visibility: hidden are left out. See "Display check" below for other options.
  • Although Tabbable tries to deal with positive tabindexes, you should not use positive tabindexes. Accessibility experts seem to be in (rare) unanimous and clear consent about this: rely on the order of elements in the document.
  • Safari on Mac OS X does not Tab to <a> elements by default: you have to change a setting to get the standard behavior. Tabbable does not know whether you've changed that setting or not, so it will include <a> elements in its list.

Help

Testing in JSDom

⚠️ JSDom is not officially supported. Your mileage may vary, and tests may break from one release to the next (even a patch or minor release).

This topic is just here to help with what we know may affect your tests.

Tabbable uses some DOM APIs such as Element.getClientRects() in order to determine node visibility, which helps in deciding whether a node is tabbable, focusable, or neither.

When using test engines such as Jest that use JSDom under the hood in order to run tests in Node.js (as opposed to using an automated browser testing tool like Cypress, Playwright, or Nightwatch where a full DOM is available), it is highly recommended (if not essential) to set the displayCheck option to none when calling any of the APIs in this library that accept it.

Using any other displayCheck setting will likely lead to failed tests due to nodes expected to be tabbable/focusable being determined to be the opposite because JSDom doesn't fully support some of the DOM APIs being used (even old ones that have been around for a long time).

You can globally overwrite the diplayCheck property by including this file in your __mocks__ folder:

// __mocks__/tabbable.js

const lib = jest.requireActual('tabbable');

const tabbable = {
   ...lib,
   tabbable: (node, options) => lib.tabbable(node, { ...options, displayCheck: 'none' }),
   focusable: (node, options) => lib.focusable(node, { ...options, displayCheck: 'none' }),
   isFocusable: (node, options) => lib.isFocusable(node, { ...options, displayCheck: 'none' }),
   isTabbable: (node, options) => lib.isTabbable(node, { ...options, displayCheck: 'none' }),
};

module.exports = tabbable;

Contributing

Feedback and contributions more than welcome!

See CONTRIBUTING.

Contributors

In alphabetical order:

Bryan Murphy
Bryan Murphy

🐛 💻
Craig Kovatch
Craig Kovatch

🐛
DaviDevMod
DaviDevMod

🐛 💻 ⚠️ 📖
David Clark
David Clark

💻 🐛 🚇 ⚠️ 📖 🚧
Dependabot
Dependabot

🚧
Erica Pramer
Erica Pramer

⚠️
Ido Rosenthal
Ido Rosenthal

🐛 💻 👀 ⚠️
Kristian Hamilton
Kristian Hamilton

🐛
Les Lim
Les Lim

🐛
Mateusz Burzyński
Mateusz Burzyński

💻 🐛 📖
Richard Všianský
Richard Všianský

📖
Stefan Cameron
Stefan Cameron

💻 🐛 🚇 ⚠️ 📖 🚧
Tyler Hawkins
Tyler Hawkins

🔧 ⚠️ 🚇 📖
bfrost
bfrost

🐛
pebble2050
pebble2050

🐛

changelog (log de mudanças)

Changelog

6.2.0

Minor Changes

  • 18a093f: Add new getTabIndex() API which enables Focus-trap to determine tab indexes in the same way as Tabbable when necessary (see focus-trap#974).

6.1.2

Patch Changes

  • b39b217: Pin jsdom downstream dependency nwsapi to v2.2.2 while awaiting fix (#982)

6.1.1

Patch Changes

  • 97373cc: Fix JSDom not supporting HTMLElement.inert and HTMLElement.contentEditable APIs, and not supporting CSS selector ':not([inert *])' resulting in no nodes found and "focus-trap must have at least one tabbable node..." error in focus-trap.

6.1.0

Minor Changes

  • 1756c90: Add support for new inert attribute (#292)

Patch Changes

  • b8c7550: Fix a corner case where a node's root node can be itself, indicating detachment from the DOM, leading to a crash in isHidden() -> isNodeAttached() -> getRootNode() if not handled properly (focus-trap-react #905)

6.0.1

Patch Changes

  • 0aab1e3: Fix crash with tabbable scoped table header elements (#832)

6.0.0

Major Changes

  • 5f40c8e: Revised and clarified official browser support (still as broad and deep as reasonably possible).
  • 5f40c8e: 🚨 Breaking: Dropped support of IE browsers, all versions.
    • IE11 was officially retired on June 15, 2022 (6 weeks ago). There are no longer any versions of IE that are still maintained or even supported by Microsoft.
  • a09ba0b: 🚨 Breaking: Default displayCheck 'full' option no longer treats detached nodes as visible. Use the new 'legacy-full' option to restore old (incorrect) behavior only if you must. Ideally, make sure tabbable only runs once all nodes of interest have been attached to the document.

5.3.3

Patch Changes

  • 0210a1c: fix: align with browser behaviour when a web component has a negative tabindex

5.3.2

Patch Changes

  • 320bfd1: Updated docs for displayCheck configuration.
  • aa2a699: Fixed an issue with displayCheck=full (default setting) determining all nodes were hidden when the container is not attached to the document. In this case, tabbable will revert to a displayCheck=none mode, which is the equivalent legacy behavior. Also updated the displayCheck option docs to add warnings about this corner case for the full and non-zero-area modes. non-zero-area behaves differently in the corner case. See the docs for more info.

5.3.1

Patch Changes

  • cf1da66: Add warnings and help in documentation about running tabbable under JSDom (e.g. with Jest). JSDom is not technically supported, and 5.3.0 introduced some changes that use DOM APIs that JSDom stubs out, which may cause some JSDom-based tests to fail. Also revamp the API docs a bit to make them clearer, and add missing getShadowRoot option to isTabbable() and isFocusable() (docs only; no code changes necessary).

5.3.0

Minor Changes

  • 685a906: Adds new Shadow DOM support (must be explicitly enabled using the new getShadowRoot option).
    • When enabled, supports open shadows by default, and can support closed shadows if the option is a function that returns the shadow for a given node. See documentation for more information.
    • Includes all updates from 5.3.0-beta.0 and 5.3.0-beta.1 releases.

Patch Changes

  • b341412: Made "isDisabledFromFieldset" more readable and concise (even marginally faster).
  • 685a906: Fixed a bug in getTabIndex: the tab index of <audio>, <video> and <details> was left to the browser default if explicitly set to a value that couldn't be parsed as integer, leading to inconsistent behavior across browsers. Also slightly modified the function's logic to make it more efficient. Finally added tests to cover the fix.
  • dd6d0ec: Optimized and extended displayCheck: "full" option (now checks for any element having no display boxes) and added test for display: "contents" property (this bug was never reported). (#592)
    • ⚠️ This will likely break your tests if you're using JSDom (e.g. with Jest). See testing in JSDom for more info.
  • 193fca2: Fixed bug in isDisabledFromFieldset. The function wasn't checking whether the disabled <fieldset> containing node is the top-most disabled <fieldset> (#596).

5.3.0-beta.1

  • Add support for setting getShadowRoot: true as an easy way to simply enable shadow DOM support. This is the equivalent of setting getShadowRoot: () => false, which means tabbable will find nodes in open shadow roots only.

5.3.0-beta.0

  • Includes new Shadow DOM support for open shadows by default
  • Includes a new getShadowRoot() configuration option, enabling support for closed shadows

5.2.1

Patch Changes

  • 1d5fcb5: Fixed: Form elements in disabled fieldsets should not be tabbable/focusable (#413)

5.2.0

Minor Changes

  • bf0a8f0: Exposed an option to select the way that an element is checked as displayed

5.1.6

Patch Changes

  • f9f6d25: Replaces Karma/Mocha/Sinon/Chai in test suite with Jest/Dom Testing Library. Removes README reference to identifying anchor tags with an xlink:href attribute as tabbable since that information is incorrect.

5.1.5

Patch Changes

  • c048203: fix crash when radio button name attributes contain CSS selector special characters (#168)

5.1.4

Patch Changes

  • a188c71: use element.matches fallback for IE11 and Webkit5
  • 0d4cdf8: Update the code to use const/let and function declarations only for the repo; this does NOT affect browser compatibility as the code is still transpiled when published into the ./dist directory for various targets.

5.1.3

Patch Changes

  • 5579825: fixes to details elements
    • ignore elements nested under a closed details element
    • ignore any extra summary elements after the first summary element
    • add details element as tabbable in case it has no direct summary element

5.1.2

Patch Changes

  • d3c6514: Fix UMD build incorrectly using focusTrap as output name.
  • 95563c2: Fix #99: Transpile ESM bundle down to the same browser target used for the CJS and UMD bundles. ESM is just the module system, not the browser target.

5.1.1

Patch Changes

  • fb49d23: Fix #96: Transpile non-minified bundles for expected browser targets.

5.1.0

Minor Changes

  • bd21d91: Add focusable() for getting all focusable nodes.

Patch Changes

  • 3665d0b: The TypeScript return type of tabbable has been fixed: Was Array<Element> (an Element is technically not focusable), is now Array<HTMLElement | SVGElement> (which are both still/also Element instances).
  • 8a25135: Fixed: Tabbable elements in fixed-position (position: fixed) containers should now be consistently found in supported browsers.
  • 9544de2: Replace prepublishOnly script with prepare script. This has the added benefit of running automatically when installing the package from GitHub (as supported by NPM) where the published ./dist directory is not automatically included.
  • 672f4a2: Add focusable() type definition.
  • 2424c0f: Small improvements for improving tree-shakeability of this package. A missing #__PURE__ annotation has been added to allow dropping one of the top-level calls (if its result stays unused) and removed minification of the file referenced as package.json#module to avoid dropping the comments (including existing #__PURE__ annotations).

5.0.0

  • Changed code formatting to use dangling commas where ES5 supports them.
  • Fixed a bug where <audio controls /> and <video controls /> elements without tabindex attribute specified would be deemed NOT tabbable in Chrome, but would be in FireFox, because Chrome has tabIndex (the DOM Element property) returning -1 (focusable, but not tabbable), while FireFox has tabIndex returning 0 (focusable, and tabbable), yet both browsers include these elements in the regular tab order (as if tabIndex was 0 for both browsers). Now these elements are considered tabbable in Chrome too!
  • Add any <summary> element directly under a <details> element as tabbable and focusable.
  • BREAKING: Changes to the isTabbableRadio() internal function in order to better support nested radio buttons:
    • In case a form parent element exists, include only nested radio inputs from that form.
    • Ignore checked radio elements from forms different from the one the validated node belongs to.
    • NOTE: This may result in less radio elements being flagged as tabbable depending on context from the "root" node given to tabbable().
  • BREAKING: The exports have changed to be all named, and separate, as follows in order to help make the module more compatible with tree shaking:
    • tabbable -> `import { tabbable } from 'tabbable';
    • tabbable.isTabbable -> `import { isTabbable } from 'tabbable';
    • tabbable.isFocusable -> `import { isFocusable } from 'tabbable';
  • Also to help with tree shaking, package.json now states sideEffects: false to mark this module as having no side effects as a result of merely importing it.
  • Added new UMD build, see ./dist/index.umd.*.

4.0.0

  • Improve performance by changing the method for detecting whether a DOM node is focusable or not. It's expected that this change will not affect results; but this is a major version bump as a warning for you to check your edge cases before upgrading.

3.1.2

  • Fix reference to root element that caused errors within Shadow DOM.

3.1.1

  • Allow module to be imported by non-browser JavaScript.

3.1.0

  • Add tabbable.isFocusable and tabbable.isTabbable functions.

3.0.0

  • Add [contenteditable] elements.

2.0.0

  • Add <audio> and <video> elements with controls attributes.
  • Only consider radio buttons tabbable if they are the checked on in their group, or if none in their group are checked.

1.1.3

  • Fix bug causing SVG elements to precede elements they should follow in the tab order in IE.

1.1.2

  • Ensure querySelectorAll receives a string argument.

1.1.1

  • Fix crash when you call tabbable(document) (passing the document element).

1.1.0

  • Add includeContainer option.

1.0.8

  • Allows operation against elements that reside within iframes, by inspecting the element to determine its correct parent document (rather than relying on the global document object).

1.0.7

  • Ensure stable sort of tabindexed elements even in browsers that have an unstable Array.prototype.sort.

1.0.6

  • Check tabindex attribute (via getAttribute), in addition to node.tabIndex, to fix handling of SVGs with tabindex="-1" in IE.

1.0.5

  • Children of visibility: hidden elements that themselves have visibility: visible are considered tabbable.

1.0.4

  • Fix IE9 compatibility.

1.0.3

  • Further improvements to caching.

1.0.2

  • Fix overaggressive caching that would prevent tabbable from knowing an element's children had changed.

1.0.1

  • Fix handling of <a> elements with tabindex="0".

1.0.0

  • Initial release.