diff --git a/.changeset/esm-only.md b/.changeset/esm-only.md new file mode 100644 index 0000000000..012773b788 --- /dev/null +++ b/.changeset/esm-only.md @@ -0,0 +1,7 @@ +--- +'react-tabs': major +--- + +`react-tabs` now ships a single native ES module build. Import components from `react-tabs` and stylesheets from `react-tabs/style/`. Replace deep imports from `react-tabs/lib/` or `react-tabs/esm/` with imports from the package root. + +If your CommonJS app uses `require('react-tabs')`, use a Node version with synchronous ESM support, such as Node 22.12 or newer, or load the package with dynamic `import()`. diff --git a/.changeset/hidden-inactive-panels.md b/.changeset/hidden-inactive-panels.md new file mode 100644 index 0000000000..0dbe1f7dd3 --- /dev/null +++ b/.changeset/hidden-inactive-panels.md @@ -0,0 +1,5 @@ +--- +'react-tabs': major +--- + +Inactive tab panels now use the HTML `hidden` attribute, so they stay hidden without a stylesheet. `forceRender` and `forceRenderTabPanel` still keep their contents mounted. See the [migration guide](https://github.com/reactjs/react-tabs/blob/main/MIGRATION.md#account-for-hidden-panels-in-exit-animations) for custom styles and exit animations. diff --git a/.changeset/keep-disabled-tab-selection.md b/.changeset/keep-disabled-tab-selection.md new file mode 100644 index 0000000000..0028fe3e7e --- /dev/null +++ b/.changeset/keep-disabled-tab-selection.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Keep the current selection and skip `onSelect` when Home or End is pressed and all tabs are disabled. diff --git a/.changeset/keyed-tabs.md b/.changeset/keyed-tabs.md new file mode 100644 index 0000000000..b9f49bfa7e --- /dev/null +++ b/.changeset/keyed-tabs.md @@ -0,0 +1,24 @@ +--- +'react-tabs': major +--- + +Tabs and panels now pair by a shared `itemKey` instead of their positions. The key can be a string or a finite number. Give each item a stable key so selection survives reorder, insertion, and removal of another tab. Keyboard navigation still follows the tab list's rendered order. + +For uncontrolled tabs, replace `defaultIndex` with `defaultKey`. An explicit initial key is required, even if you previously relied on the first tab being selected automatically. + +```tsx + + + Overview + Billing + + Overview content + Billing content + +``` + +For controlled tabs, replace `selectedIndex={index}` with `selectedKey={key}`. Keep `onSelect`, but update handlers to receive keys instead of positions. For example, use `` and give the matching tab and panel the same key. TypeScript state can use the exported `TabKey` type. + +If an uncontrolled selection disappears, the group selects the first enabled tab with a matching panel and calls `onSelect` with an undefined event. Controlled callers choose their own replacement. Returning `false` still cancels mouse and keyboard selections. + +`TabsProps` is now a union. If your TypeScript wrapper used `interface CustomProps extends TabsProps`, use `type CustomProps = TabsProps & { … }` instead. diff --git a/.changeset/numeric-tab-index.md b/.changeset/numeric-tab-index.md new file mode 100644 index 0000000000..75cbea0955 --- /dev/null +++ b/.changeset/numeric-tab-index.md @@ -0,0 +1,7 @@ +--- +'react-tabs': major +--- + +`Tab` now uses React's numeric `tabIndex` type. Replace string values such as `Overview` with numbers such as `Overview`. + +When `tabIndex` is omitted, the selected tab still gets `0`. If there is no selection, the first enabled tab with a matching panel gets `0` so keyboard users can enter the group. diff --git a/.changeset/react-server-components.md b/.changeset/react-server-components.md new file mode 100644 index 0000000000..8430fc913f --- /dev/null +++ b/.changeset/react-server-components.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Mark the `react-tabs` entry point with `'use client'` so React Server Components can import it directly. Put event handlers such as `onSelect` in a Client Component. diff --git a/.changeset/restore-tab-focus.md b/.changeset/restore-tab-focus.md new file mode 100644 index 0000000000..14b1d05994 --- /dev/null +++ b/.changeset/restore-tab-focus.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Restore keyboard focus to the replacement when a focused tab is removed and selection changes. `defaultFocus` now waits for a selected tab to become available, including when an invalid default key falls back to the first enabled tab. diff --git a/.changeset/skip-unrelated-tab-events.md b/.changeset/skip-unrelated-tab-events.md new file mode 100644 index 0000000000..e7c8364644 --- /dev/null +++ b/.changeset/skip-unrelated-tab-events.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Skip tab collection scans for clicks and key presses outside the group's tabs, and for keys that the group doesn't handle. Consumer event handlers still receive these events. diff --git a/.changeset/skip-unused-tab-diagnostics.md b/.changeset/skip-unused-tab-diagnostics.md new file mode 100644 index 0000000000..266b0589ed --- /dev/null +++ b/.changeset/skip-unused-tab-diagnostics.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Skip collecting developer warnings when scanning tabs for interactions, focus, or production rendering. diff --git a/.changeset/skip-unused-tab-fallback.md b/.changeset/skip-unused-tab-fallback.md new file mode 100644 index 0000000000..2264084cf1 --- /dev/null +++ b/.changeset/skip-unused-tab-fallback.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Avoid an extra render when the first enabled tab changes and the current selection still has a matching tab and panel. diff --git a/.changeset/standard-keyboard-events.md b/.changeset/standard-keyboard-events.md new file mode 100644 index 0000000000..b95c478109 --- /dev/null +++ b/.changeset/standard-keyboard-events.md @@ -0,0 +1,7 @@ +--- +'react-tabs': patch +--- + +Use the standard `KeyboardEvent.key` value for tab navigation and activation, including when a key has been remapped. + +This removes the fallback for legacy browsers that only report `keyCode`. Every browser version listed in the README’s compatibility table already supports `KeyboardEvent.key`, so the documented browser support stays the same. [Browser compatibility for `KeyboardEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#browser_compatibility) diff --git a/.changeset/tab-panel-class-defaults.md b/.changeset/tab-panel-class-defaults.md new file mode 100644 index 0000000000..d94383b53c --- /dev/null +++ b/.changeset/tab-panel-class-defaults.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +Apply the default `TabPanel` classes when `className` or `selectedClassName` is explicitly `undefined`. diff --git a/.changeset/tabs-event-handlers.md b/.changeset/tabs-event-handlers.md new file mode 100644 index 0000000000..c659f5b6ef --- /dev/null +++ b/.changeset/tabs-event-handlers.md @@ -0,0 +1,5 @@ +--- +'react-tabs': patch +--- + +`Tabs` now calls the provided `onClick` and `onKeyDown` handlers before its own handlers. Calling `event.preventDefault()` skips the built-in tab handling for that event. diff --git a/.changeset/tabs-item-context.md b/.changeset/tabs-item-context.md new file mode 100644 index 0000000000..b1f489f29b --- /dev/null +++ b/.changeset/tabs-item-context.md @@ -0,0 +1,39 @@ +--- +'react-tabs': major +--- + +Tab and panel state comes from React context. Custom wrappers render the built-in component and forward `itemKey`. Remove the old `tabsRole` assignment and use ordinary React component types in place of `ReactTabsFunctionComponent`. + +If your wrapper reads `selected` to apply a CSS class, move that class to the built-in `selectedClassName` prop. + +**Before** + +```jsx +import { Tab } from 'react-tabs'; + +function CustomTab({ selected, ...props }) { + return ( + + ); +} + +CustomTab.tabsRole = 'Tab'; +``` + +**After** + +```tsx +import { Tab } from 'react-tabs'; +import type { TabProps } from 'react-tabs'; + +function CustomTab(props: TabProps) { + return ( + + ); +} +``` + +The built-in `Tab` applies `is-active` when selected. If your custom UI needs the selection in JavaScript, control `` with `selectedKey` and `onSelect`. diff --git a/.changeset/tabs-rendered-direction.md b/.changeset/tabs-rendered-direction.md new file mode 100644 index 0000000000..985596048a --- /dev/null +++ b/.changeset/tabs-rendered-direction.md @@ -0,0 +1,7 @@ +--- +'react-tabs': major +--- + +Left and right arrow navigation now follows the tab group's rendered direction, including the HTML `dir` attribute and inherited direction. + +If your group needs to stay left-to-right on an RTL page, set `dir="ltr"` on `Tabs` and make sure any CSS `direction` rule agrees. diff --git a/.changeset/typed-tabs-callbacks.md b/.changeset/typed-tabs-callbacks.md new file mode 100644 index 0000000000..c70db65564 --- /dev/null +++ b/.changeset/typed-tabs-callbacks.md @@ -0,0 +1,7 @@ +--- +'react-tabs': major +--- + +Build `react-tabs` with TypeScript and generate its declarations from source. + +The callback types now match their runtime values. For user interactions, `onSelect` receives a React mouse or keyboard event. Use `event.nativeEvent` for the underlying DOM event. Automatic recovery in an uncontrolled group reports an undefined event. `domRef` receives the root `HTMLDivElement` or `null`, so typed callbacks must handle `null` on unmount. diff --git a/.changeset/v7-migration-guide.md b/.changeset/v7-migration-guide.md new file mode 100644 index 0000000000..a99d1b5d03 --- /dev/null +++ b/.changeset/v7-migration-guide.md @@ -0,0 +1,5 @@ +--- +'react-tabs': major +--- + +Upgrading from v6? See the [v6 to v7 migration guide](https://github.com/reactjs/react-tabs/blob/main/MIGRATION.md#v6-to-v7) for the breaking changes and migration examples. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 667843702d..245a0ba907 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -58,4 +58,15 @@ jobs: run: pnpm install --frozen-lockfile - name: Lint - run: pnpm lint + run: pnpm run lint + + - name: Type check + run: pnpm run typecheck + + - name: Build library + run: pnpm run build + + - name: Check native Node entry points + run: | + node --input-type=module -e "import { Tabs } from 'react-tabs'; if (typeof Tabs !== 'function') process.exit(1)" + node --input-type=commonjs -e "if (typeof require('react-tabs').Tabs !== 'function') process.exit(1)" diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000000..26aebfd2f4 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,216 @@ +# Migration guide + +## v6 to v7 + +### Match each tab and panel with `itemKey` + +**What changed** + +v6 matched tabs and panels by render order. v7 matches them by an explicit `itemKey`, so panels can render in a different order from their tabs. + +**How to migrate** + +Give each `` and its `` the same `itemKey`. Use a unique key per pair within the group. Old indexes work as numeric keys for a fixed list. For a dynamic list, use a stable item ID so the key stays with the item through reordering or removal. + +```tsx +import { Tab, TabList, TabPanel, Tabs } from 'react-tabs'; + +function AccountTabs() { + return ( + + + Overview + Billing + + Account overview + Billing settings + + ); +} +``` + +Keys can be nonempty strings or finite numbers. Match the type on both sides, since `1` and `'1'` are different keys. Keep the panel element mounted even if its contents load on demand. + +### Account for hidden panels in exit animations + +**What changed** + +In v6, CSS controlled whether an inactive panel was visible. Inactive panels now get the HTML `hidden` attribute as soon as selection changes, even with `forceRender` or `forceRenderTabPanel`. The default stylesheet no longer sets panel visibility. + +**How to migrate** + +Check custom panel styles that set `display` so they respect `[hidden]`. For example, apply `display: grid` only to `.my-panel:not([hidden])`. + +If you animate an outgoing panel, keep `forceRender` or `forceRenderTabPanel` enabled for its contents and override `display` on that panel's `[hidden]` element only while its exit animation runs. Mark the outgoing panel `inert` during that interval to keep it out of keyboard navigation and the accessibility tree. Remove the display override when the animation ends. + +### Replace `defaultIndex` with `defaultKey` + +**What changed** + +In v6, uncontrolled tabs used `defaultIndex` and selected the first tab when it was omitted. In v7, they require an explicit `defaultKey`. + +**How to migrate** + +Set `defaultKey` to the `itemKey` of the tab you want to open first. Add it even if you previously omitted `defaultIndex`. + +```diff +- ++ +``` + +### Replace `selectedIndex` with `selectedKey` + +**What changed** + +In v6, `selectedIndex` identified the controlled selection by position. In v7, `selectedKey` identifies it by `itemKey`. + +**How to migrate** + +Store the active `itemKey` in state, pass it as `selectedKey`, and update it in `onSelect`. If you remove the selected tab, set a replacement key yourself. The group shows no selection while the key is missing. + +```diff +- ++ +``` + +### Use keys in `onSelect` + +**What changed** + +The first two `onSelect` arguments changed from the next and previous numeric indexes to the next and previous `itemKey` values. + +**How to migrate** + +Update handlers that use the arguments as array indexes. For example, replace `tabs[nextIndex]` with `tabs.find((tab) => tab.id === nextKey)` if you use each item's `id` as its `itemKey`. Import `TabKey` from `react-tabs` for explicit TypeScript annotations. + +### Use `nativeEvent` when you need a DOM event + +**What changed** + +v6 declared the `onSelect` event as a DOM `Event`. v7 types user interactions as the React mouse or keyboard events the callback receives at runtime. + +**How to migrate** + +Let TypeScript infer the event type in your handler. If a helper expects a DOM `Event`, guard against `undefined` and pass `event.nativeEvent`. + +### Handle automatic selection when a tab is removed + +**What changed** + +In v6, removing a tab could shift the selection to another item at the same index. In v7, removing another tab preserves the selected key. If you remove the selected tab from an uncontrolled group, v7 selects the first enabled tab with a matching panel and calls `onSelect` with `undefined` as the event. + +**How to migrate** + +Check that the event exists before reading it in `onSelect`. Returning `false` still cancels mouse and keyboard selections. The callback reports an automatic replacement after it has already been selected. + +### Match horizontal arrow navigation to the tab group's direction + +**What changed** + +In v6, left and right arrow keys used the `direction` prop and defaulted to LTR, even when the tab group displayed right-to-left. In v7, the keys follow the group's rendered direction, which can come from HTML or CSS. A group that inherits RTL from the page now also uses RTL arrow navigation. + +**How to migrate** + +If horizontal navigation should follow the page, let the group inherit its direction. If the group should stay left-to-right on an RTL page, set `dir="ltr"` on `` and make sure any CSS `direction` rule on the group also uses `ltr`. + +### Pass a number for the HTML `tabindex` attribute + +**What changed** + +`Tab`'s `tabIndex` prop changed from a string in v6 to a number in v7. It sets the HTML `tabindex` attribute, which controls keyboard tab order. + +**How to migrate** + +Replace string values with numbers. Keep the same numeric value to preserve the tab order. + +```diff +- tabIndex="0" ++ tabIndex={0} +``` + +### Handle `null` in `domRef` + +**What changed** + +v6 typed the `domRef` argument as an optional `HTMLElement`. v7 types it as `HTMLDivElement | null`, including the `null` React passes on unmount. + +**How to migrate** + +Check for `null` before using the element. If you annotate the callback parameter, use `HTMLDivElement | null`. + +### Remove `tabsRole` assignments + +**What changed** + +v6 used the `tabsRole` static property to recognize custom wrappers. v7 removed it. + +**How to migrate** + +Delete assignments such as `CustomTab.tabsRole = 'Tab'`. Render the built-in component inside your wrapper and forward the props it needs, including `itemKey` for tabs and panels. + +### Replace `ReactTabsFunctionComponent` + +**What changed** + +v7 removed the `ReactTabsFunctionComponent` type, which v6 used to describe components with a `tabsRole` static. + +**How to migrate** + +Remove the type import and annotate your wrapper's props with the type of the component it renders. + +```tsx +import { Tab } from 'react-tabs'; +import type { TabProps } from 'react-tabs'; + +function CustomTab(props: TabProps) { + return ; +} +``` + +### Replace reads of private wrapper props + +**What changed** + +v6 passed private props such as `selected`, `focus`, and `tabRef` to custom wrappers. In v7, the built-in components get their state from context. + +**How to migrate** + +Remove reads of those private props. Use `selectedClassName` for styling and let the built-in `Tab` handle focus. If custom logic needs to know which tab is active, read the key from your controlled `Tabs` state. + +### Use a type intersection to extend `TabsProps` + +**What changed** + +`TabsProps` changed from an interface to a union of controlled and uncontrolled props. + +**How to migrate** + +Replace `interface TrackedTabsProps extends TabsProps` with a type alias that uses `&` to add your own props. + +```tsx +import type { TabsProps } from 'react-tabs'; + +type TrackedTabsProps = TabsProps & { analyticsName: string }; +``` + +### Switch to the ESM package entry point + +**What changed** + +v6 shipped a CommonJS build and an ESM build for bundlers. v7 ships a single native ES module build and declares its public entry points with `exports`. + +**How to migrate** + +Import components from `react-tabs`. If you used a deep import from `react-tabs/lib/` or `react-tabs/esm/`, switch to the package root. The documented stylesheet paths, such as `react-tabs/style/react-tabs.css`, still work. + +If your CommonJS app calls `require('react-tabs')`, use a Node version with synchronous ESM support, such as Node 22.12 or newer. On older versions, load the package with dynamic `import('react-tabs')`. + +### Import types from the package root + +**What changed** + +v6 shipped an `index.d.ts` at the package root. v7 generates its declarations alongside the ESM build and points TypeScript to them through the package metadata. + +**How to migrate** + +If you imported `react-tabs/index.d.ts` directly, change the import to `import type { TabsProps } from 'react-tabs'`. diff --git a/README.md b/README.md index e5f5076a5c..c49aa80fd5 100644 --- a/README.md +++ b/README.md @@ -25,23 +25,57 @@ or npm install --save react-tabs ``` +## Compatibility (December 2026) + +`react-tabs` supports React 18 and 19. + +### Browsers + +`react-tabs` targets the current and previous stable releases of Chrome, Edge, Firefox, and Safari on desktop, Chrome on Android, and Safari on iOS. Firefox ESR is also supported. + +The npm package ships ES2020 JavaScript as native ESM. The table shows the earliest versions that can parse the optional chaining (`?.`) and nullish coalescing (`??`) used in the published code. [Optional chaining support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#browser_compatibility) · [Nullish coalescing support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing#browser_compatibility) + +| Browser | Earliest version that parses the published syntax | Released | +| ----------------------------- | ------------------------------------------------: | -------------------------------------------------------------------------------------------------------------- | +| Chrome on desktop and Android | 80 | [February 2020](https://chromereleases.googleblog.com/2020/02/stable-channel-update-for-desktop.html) | +| Edge | 80 | [February 2020](https://learn.microsoft.com/en-us/deployedge/microsoft-edge-relnotes-security#february-7-2020) | +| Firefox | 74 | [March 2020](https://www.firefox.com/en-US/firefox/74.0/releasenotes/) | +| Safari on macOS | 13.1 | [March 2020](https://developer.apple.com/documentation/safari-release-notes) | +| Safari on iOS | 13.4 | [March 2020](https://support.apple.com/en-ca/103828) | + +These browser versions are roughly seven years old as of December 2026. + +The library also uses `Element.closest()` for tab navigation and `MutationObserver` to track changes to tabs and panels. Both are available in the versions above, and the default CSS adds no newer browser requirement. [Element.closest() support](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#browser_compatibility) · [MutationObserver support](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#browser_compatibility) + +These versions describe the package's feature requirements. Your React renderer and application build can set a higher minimum. A browser build tool also needs to resolve the package's React and `clsx` imports and handle `process.env.NODE_ENV`. + +### Server-side rendering + +Use the latest patch of Node.js **22.x**, **24.x**, or **26.x**. These are the supported [Node.js LTS release lines](https://nodejs.org/en/about/previous-releases) as of December 2026. + +Load the package with `import`. CommonJS servers can use `require('react-tabs')` on Node.js 22.12 and later, which can load [synchronous ES modules](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require). + +In frameworks with React Server Components, such as the Next.js App Router, you can import `react-tabs` from a Server Component. Define event handlers such as `onSelect` in a Client Component that renders the tabs. + ## Basic Example +`react-tabs` ships as native ESM. Import components from `react-tabs` and stylesheets from `react-tabs/style/`. See the [migration guide](https://github.com/reactjs/react-tabs/blob/main/MIGRATION.md#switch-to-the-esm-package-entry-point) for CommonJS consumers. + ```js import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import 'react-tabs/style/react-tabs.css'; export default () => ( - + - Title 1 - Title 2 + Overview + Details - +

Any content 1

- +

Any content 2

@@ -52,12 +86,14 @@ export default () => ( ## Components -react-tabs consists of 4 components which all need to be used together. +Each group uses one `TabList`. Every `Tab` in the list needs a `TabPanel` with the same `itemKey`. Panels can be rendered in a different order from the tabs. ### <Tabs /> If you specify additional props on the `` component they will be forwarded to the rendered `
`. +`onClick` and `onKeyDown` run before the built-in tab handlers. Call `event.preventDefault()` to skip the built-in handling for that event. + #### className: `string | Array | { [string]: boolean }` > default: `"react-tabs"` @@ -72,19 +108,13 @@ Provide a custom class name for the outer `
` of the tabs. If set to `true` the tabs will be focused on initial render. This allows immediate use of keyboard keys to switch tabs after the first render. -#### defaultIndex: `number` - -> default: `0` +#### defaultKey: `TabKey` -This allows changing the tab that should be open on initial render. This is a zero-based index, so first tab is `0`, second tab is `1`, ... +Required in uncontrolled mode. Use the key of the tab to select on the initial render. Set either `defaultKey` or `selectedKey` for each group. -> This can only be used in uncontrolled mode when react-tabs handles the current selected tab internally and for this reason cannot be used together with `selectedIndex`. See [here](#controlled-vs-uncontrolled-mode) for more info on modes. +#### direction: `"ltr" | "rtl"` -#### direction: `string` - -> default: `"ltr"` - -Provide the direction of the component, can be either rtl or ltr. +Sets the tab group's HTML direction when the `dir` prop is omitted. When both props are omitted, the group inherits its direction from the page. Left and right arrow navigation follows the group's rendered direction, including changes made through CSS. #### disabledTabClassName: `string` @@ -100,7 +130,7 @@ Provide a custom class name for disabled tabs. Disable up & down arrow keys to change tabs. -#### domRef: `(node: ?HTMLElement) => void` +#### domRef: `(node: HTMLDivElement | null) => void` > default: `null` @@ -122,29 +152,19 @@ By default the tab that is clicked will also be focused in the DOM. If set to `f > default: `false` -By default only the current active tab will be rendered to DOM. If set to `true` all tabs will be rendered to the DOM always. +Panel elements stay mounted. By default only the selected panel renders its contents. Set this to `true` to keep all panel contents mounted, including in hidden panels. > This can also be enabled for each individual `` component with its prop `forceRender`. -#### onSelect: `(index: number, lastIndex: number, event: Event) => ?boolean` - -> default: `undefined` +#### onSelect: `(nextKey: TabKey, previousKey: TabKey, event: TabEvent | undefined) => boolean | void` -This event handler is called every time a tab is about to change. It will be called with the `index` that it will be changed to, the `lastIndex` which was selected before and the underlying `event` which is usually either a `keydown` or `click` event. When `index` and `lastIndex` are equal it means the user clicked on the currently active tab. +Called before a mouse or keyboard selection, including when a user activates the current tab. Return `false` to cancel the selection. The event is a React mouse or keyboard event. -The callback can optionally return `false` to cancel the change to the new tab. +If an uncontrolled group loses the selected tab, the first enabled tab with a matching panel becomes selected. The callback fires once after that selection is applied, with `event` set to `undefined`. The return value has no effect on automatic recovery. If no replacement is available, the group waits until one appears. -> Returning `false` when the change to the new tab should be canceled is also important in controlled mode, as react-tabs still internally handles the focus of the tabs. +#### selectedKey: `TabKey` -> In controlled mode the `onSelect` handler is a required prop. - -#### selectedIndex: `number` - -> default: `null` - -Set the currently selected tab. This is a zero-based index, so first tab is `0`, second tab is `1`, ... - -This enables controlled mode, which also requires `onSelect` to be set. See [here](#controlled-vs-uncontrolled-mode) for more info on modes. +Required in controlled mode along with `onSelect`. Set this to the key of the selected tab. If the key has no matching pair, the group shows no selection and gives the first enabled pair the default keyboard entry point. #### selectedTabClassName: `string` @@ -178,6 +198,10 @@ Provide a custom class name for the `
    `. If you specify additional props on the `` component they will be forwarded to the rendered `
  • `. +#### itemKey: `TabKey` + +Required. Use a nonempty string or finite number that identifies this tab within its group. Give the corresponding panel the same key. For dynamic lists, keep the key attached to the item when it moves. The number `1` and the string `'1'` are distinct keys. + #### className: `string | Array | { [string]: boolean }` > default: `"react-tabs__tab"` @@ -208,16 +232,22 @@ Provide a custom class name for the active tab. > This option can also be set for all `` components with the prop `selectedTabClassName` on ``. -#### tabIndex: `string` +#### tabIndex: `number` -> default: if selected `"0"` otherwise `null` +> default: `0` for the selected tab. If there is no selection, the first enabled tab with a matching panel gets `0`. Other tabs omit the attribute. -Overrides the tabIndex to enabled tabbing between tabs. +Overrides the tab's position in the keyboard tab order. Use `tabIndex={0}` to include a tab in the tab order or `tabIndex={-1}` to leave it out while keeping it programmatically focusable. ### <TabPanel /> If you specify additional props on the `` component they will be forwarded to the rendered `
    `. +Inactive panels get the HTML `hidden` attribute and are hidden without the default stylesheet. See the [migration guide](https://github.com/reactjs/react-tabs/blob/main/MIGRATION.md#account-for-hidden-panels-in-exit-animations) if you animate panels when they become inactive. + +#### itemKey: `TabKey` + +Required. Use the same key as exactly one `Tab` in the same group. Keep the panel element mounted when its contents load on demand so the tab's ARIA link has a target. + #### className: `string | Array | { [string]: boolean }` > default: `"react-tabs__tab-panel"` @@ -230,7 +260,7 @@ Provide a custom class name for the `
    ` containing the tab content. > default: `false` -By default the tab content will only be rendered when the tab is active. If set to `true` the tab will also be rendered if inactive. +By default the panel renders its contents when selected. Set this to `true` to keep the contents mounted while inactive. > This can also be enabled for all `` components with the prop `forceRenderTabPanel` on ``. @@ -244,48 +274,32 @@ Provide a custom class name for the active tab panel. ## Controlled vs Uncontrolled mode -React tabs has two different modes it can operate in, which change the way how much you need to take care about the state yourself. - ### Uncontrolled mode -This is the default mode of react-tabs and makes the react-tabs components handle its state internally. You can change the starting tab with `defaultIndex` and you can listen for changes with `onSelect`. - -In this mode you cannot force a tab change during runtime. - -```js - console.log(index)}> - - Title 1 - Title 2 - - - - -``` +Set `defaultKey` to the initial selection. The group manages selection after that. You can listen for changes with `onSelect`. See the [basic example](#basic-example). ### Controlled mode -This mode has to be enabled by supplying `selectedIndex` to the `` component. +Set `selectedKey` and update it from `onSelect`. Use controlled mode when other parts of your app need to set the selection, such as routing or removing the currently selected item. -In this mode react-tabs does not handle any tab selection state internally and leaves all the state management up to the outer application. +```jsx +import { useState } from 'react'; +import { Tab, TabList, TabPanel, Tabs } from 'react-tabs'; -This mode also enforces you to set a handler for `onSelect`. `defaultIndex` does not have any effect and will therefore throw an error. - -```js -const App = () => { - const [tabIndex, setTabIndex] = useState(0); +function AccountTabs() { + const [selectedKey, setSelectedKey] = useState('overview'); return ( - setTabIndex(index)}> + - Title 1 - Title 2 + Overview + Billing - - + Account overview + Billing settings ); -}; +} ``` ## Styling @@ -326,47 +340,19 @@ You can also always just simply copy the default style to your own css/scss/less ### Custom Components -#### Set `tabsRole` - -In case you want to create your own component wrapping the ones that the library provides, you have to set its `tabsRole`. This value is used inside react-tabs to check the role of a component inside ``. - -Possible values for tabsRole are: - -- Tab -- TabPanel -- TabList -- Tabs - -#### Pass through properties - -Note: Because of how react-tabs works internally (it uses cloning to opaquely control various parts of the tab state), you need to pass any incoming props to the component you're wrapping. The easiest way to do this is to use the rest and spread operators, e.g. see `{...otherProps}` below. +Render the built-in component in your wrapper, forwarding `itemKey` and the other public props your wrapper accepts. ```tsx -import { Tabs, TabList, Tab, TabPanel } from 'react-tabs'; -import type { ReactTabsFunctionComponent, TabProps } from 'react-tabs'; - -// All custom elements should pass through other props -const CustomTab: ReactTabsFunctionComponent = ({ - children, - ...otherProps -}) => ( - -

    {children}

    -
    -); - -CustomTab.tabsRole = 'Tab'; // Required field to use your custom Tab +import { Tab } from 'react-tabs'; +import type { TabProps } from 'react-tabs'; -const App = () => ( - - - Custom Tab 1 - Custom Tab 2 - - Panel 1 - Panel 2 - -); +function CustomTab({ children, ...props }: TabProps) { + return ( + + {children} + + ); +} ``` ## Contributing diff --git a/eslint.config.mjs b/eslint.config.mjs index bc6ca5684c..a3a45fb46e 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -3,8 +3,10 @@ import js from '@eslint/js'; import importPlugin, { createNodeResolver } from 'eslint-plugin-import-x'; import jsxA11yPlugin from 'eslint-plugin-jsx-a11y-x'; import prettierRecommended from 'eslint-plugin-prettier/recommended'; +import { defineConfig } from 'eslint/config'; +import tseslint from 'typescript-eslint'; -export default [ +export default defineConfig([ js.configs.recommended, reactPlugin.configs.recommended, importPlugin.flatConfigs.recommended, @@ -22,39 +24,22 @@ export default [ }, }, { - files: ['src/components/Tabs.jsx'], + files: ['src/components/Tabs.tsx'], languageOptions: { globals: { process: 'readonly' } }, }, - { - files: ['src/components/UncontrolledTabs.jsx'], - languageOptions: { globals: { window: 'readonly' } }, - }, { files: ['src/**/__tests__/**/*.{js,jsx}'], languageOptions: { globals: { console: 'readonly' } }, }, - { - files: [ - 'src/components/UncontrolledTabs.jsx', - 'src/helpers/childrenDeepMap.js', - ], - rules: { - // Tab selection and focus are passed through to caller-provided elements. - '@eslint-react/no-clone-element': 'off', - }, - }, - { - files: ['src/helpers/childrenDeepMap.js'], - rules: { - // React.Children handles the children shapes accepted by Tabs. - '@eslint-react/no-children-map': 'off', - '@eslint-react/no-children-for-each': 'off', - }, - }, { settings: { + // Lint against the oldest supported React version. + 'react-x': { version: '18.0.0' }, 'import-x/resolver-next': [ - createNodeResolver({ extensions: ['.js', '.jsx'] }), + createNodeResolver({ + extensions: ['.js', '.jsx', '.ts', '.tsx'], + extensionAlias: { '.js': ['.js', '.ts', '.tsx'] }, + }), ], }, @@ -63,6 +48,8 @@ export default [ 'jsx-a11y-x/no-static-element-interactions': 'off', + 'import-x/no-duplicates': ['error', { 'prefer-inline': true }], + 'import-x/no-extraneous-dependencies': [ 'error', { @@ -87,5 +74,22 @@ export default [ 'no-console': 'error', }, }, + { + files: ['src/**/*.{ts,tsx}'], + extends: [ + importPlugin.flatConfigs.typescript, + tseslint.configs.recommended, + ], + rules: { + '@typescript-eslint/consistent-type-imports': [ + 'error', + { prefer: 'type-imports', fixStyle: 'inline-type-imports' }, + ], + '@typescript-eslint/no-unused-vars': [ + 'error', + { ignoreRestSiblings: true }, + ], + }, + }, prettierRecommended, -]; +]); diff --git a/.babelrc.js b/examples/.babelrc.js similarity index 74% rename from .babelrc.js rename to examples/.babelrc.js index d916cb0864..9236fc56d7 100644 --- a/.babelrc.js +++ b/examples/.babelrc.js @@ -1,8 +1,6 @@ 'use strict'; -const output = process.env.BABEL_OUTPUT; const env = process.env.NODE_ENV; -const modules = output == null ? false : output; const targets = env === 'test' ? { node: 'current' } : undefined; @@ -24,19 +22,15 @@ const options = { { bugfixes: true, loose: true, - modules, + modules: false, targets, corejs: '3', useBuiltIns: 'entry', }, ], ['@babel/react', { runtime: 'automatic' }], + '@babel/typescript', ], - plugins: [], }; -if (env !== 'test') { - options.plugins.push(['transform-react-remove-prop-types', { mode: 'wrap' }]); -} - module.exports = options; diff --git a/examples/package.json b/examples/package.json index efea5d6e88..781e9bd5d9 100644 --- a/examples/package.json +++ b/examples/package.json @@ -8,7 +8,6 @@ "dependencies": { "clsx": "^2.0.0", "prism-react-renderer": "2.4.1", - "prop-types": "^15.5.0", "react": "19.3.1", "react-dom": "19.3.1", "react-live": "4.1.8", @@ -16,8 +15,10 @@ }, "devDependencies": { "@babel/core": "7.29.13", + "@babel/preset-env": "7.29.14", + "@babel/preset-react": "7.29.7", + "@babel/preset-typescript": "7.29.7", "babel-loader": "10.1.1", - "babel-plugin-transform-react-remove-prop-types": "0.4.24", "cross-env": "10.1.0", "css-loader": "7.1.5", "css-minimizer-webpack-plugin": "8.0.0", diff --git a/examples/src/components/ExampleItem.js b/examples/src/components/ExampleItem.js index d037e6a01c..ae45bb18cb 100644 --- a/examples/src/components/ExampleItem.js +++ b/examples/src/components/ExampleItem.js @@ -1,5 +1,4 @@ import { Component } from 'react'; -import T from 'prop-types'; import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; // eslint-disable-line import { LiveProvider, LiveEditor, LivePreview, LiveError } from 'react-live'; import classNames from 'clsx'; @@ -12,12 +11,6 @@ export default class ExampleItem extends Component { editorOpen: false, }; - toggleCheckbox({ target: { name, checked } }) { - this.setState({ - [name]: checked, - }); - } - handleEditSourceChange = () => { this.setState({ editorOpen: !this.state.editorOpen, @@ -74,9 +67,3 @@ export default class ExampleItem extends Component { ); } } - -ExampleItem.propTypes = { - label: T.string.isRequired, - hint: T.string.isRequired, - code: T.string.isRequired, -}; diff --git a/examples/src/components/examples/Avengers.js b/examples/src/components/examples/Avengers.js index e60f3829a8..96af7f4b76 100644 --- a/examples/src/components/examples/Avengers.js +++ b/examples/src/components/examples/Avengers.js @@ -35,20 +35,22 @@ const code = `class Component extends React.Component { "Iron Man": true, Thor: true, "War Machine": true, - selectedIndex: 0 + selectedKey: "Ant-Man" }; this.handleCheckClicked = this.handleCheckClicked.bind(this); } handleCheckClicked(e) { - const state = { - [e.target.name]: e.target.checked - }; - if (this.characters.findIndex(({name}) => name === e.target.name) <= this.state.selectedIndex) { - state.selectedIndex = this.state.selectedIndex + (e.target.checked ? 1 : -1); - } - this.setState(state); + const { name, checked } = e.target; + this.setState((state) => { + const next = { ...state, [name]: checked }; + if (!next[state.selectedKey]) { + const first = this.characters.find(({ name }) => next[name]); + if (first) next.selectedKey = first.name; + } + return next; + }); } render() { @@ -72,13 +74,13 @@ const code = `class Component extends React.Component { if (!this.state[name]) return; tabs.push( - + {name} ); tabPanels.push( - + {desc} ); @@ -88,8 +90,8 @@ const code = `class Component extends React.Component {

    {links}

    this.setState({ selectedIndex })} + selectedKey={this.state.selectedKey} + onSelect={(selectedKey) => this.setState({ selectedKey })} selectedTabClassName="avengers-tab--selected" selectedTabPanelClassName="avengers-tab-panel--selected" > diff --git a/examples/src/components/examples/MattGroening.js b/examples/src/components/examples/MattGroening.js index 258669ef91..4ad91dab9b 100644 --- a/examples/src/components/examples/MattGroening.js +++ b/examples/src/components/examples/MattGroening.js @@ -1,72 +1,72 @@ import ExampleItem from '../ExampleItem'; const code = `const Component = ( - + - The Simpsons - Futurama + The Simpsons + Futurama - - + + - Homer Simpson - Marge Simpson - Bart Simpson - Lisa Simpson - Maggie Simpson + Homer Simpson + Marge Simpson + Bart Simpson + Lisa Simpson + Maggie Simpson - +

    Husband of Marge; father of Bart, Lisa, and Maggie.

    Homer Simpson
    - +

    Wife of Homer; mother of Bart, Lisa, and Maggie.

    Marge Simpson
    - +

    Oldest child and only son of Homer and Marge; brother of Lisa and Maggie.

    Bart Simpson
    - +

    Middle child and eldest daughter of Homer and Marge; sister of Bart and Maggie.

    Lisa Simpson
    - +

    Youngest child and daughter of Homer and Marge; sister of Bart and Lisa.

    Maggie Simpson
    - - + + - Philip J. Fry - Turanga Leela - Bender Bending Rodriguez - Amy Wong - Professor Hubert J. Farnsworth - Doctor John Zoidberg + Philip J. Fry + Turanga Leela + Bender Bending Rodriguez + Amy Wong + Professor Hubert J. Farnsworth + Doctor John Zoidberg - +

    Protagonist, from the 20th Century. Delivery boy. Many times great-uncle to Professor Hubert Farnsworth. Suitor of Leela.

    Philip J. Fry
    - +

    Mutant cyclops. Captain of the Planet Express Ship. Love interest of Fry.

    Turanga Leela
    - +

    A kleptomaniacal, lazy, cigar-smoking, heavy-drinking robot who is Fry's best friend. Built in Tijuana, Mexico, he is the Planet Express Ship's cook.

    Bender Bending Rodriguez
    - +

    Chinese-Martian intern at Planet Express. Fonfon Ru of Kif Kroker.

    - +

    Many times great-nephew of Fry. CEO and owner of Planet Express delivery company. Tenured professor of Mars University.

    Professor Hubert J. Farnsworth
    - +

    Alien from Decapod 10. Planet Express' staff doctor and steward. Has a medical degree and Ph.D in art history.

    Doctor John Zoidberg
    diff --git a/examples/src/components/examples/RightToLeft.js b/examples/src/components/examples/RightToLeft.js index 7946eafbe1..df2cae62c5 100644 --- a/examples/src/components/examples/RightToLeft.js +++ b/examples/src/components/examples/RightToLeft.js @@ -2,14 +2,14 @@ import ExampleItem from '../ExampleItem'; const code = `const Component = (
    - + - כותרת - כותרת כבויה - כותרת שנייה - כותרת שלישית + כותרת + כותרת כבויה + כותרת שנייה + כותרת שלישית - +

    לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.

    @@ -20,7 +20,7 @@ const code = `const Component = (

    - +

    לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.

    @@ -31,7 +31,7 @@ const code = `const Component = (

    - +

    לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. @@ -44,7 +44,7 @@ const code = `const Component = (

    - +

    תת כותרת

    לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. diff --git a/examples/src/components/examples/SuperMario.js b/examples/src/components/examples/SuperMario.js index a5bbdab03c..afea5a76ad 100644 --- a/examples/src/components/examples/SuperMario.js +++ b/examples/src/components/examples/SuperMario.js @@ -1,16 +1,16 @@ import ExampleItem from '../ExampleItem'; const code = `const Component = ( - + - Mario - Luigi - Peach - Yoshi - Toad + Mario + Luigi + Peach + Yoshi + Toad - +

    Mario (Japanese: マリオ Hepburn: Mario, [ma.ɾʲi.o]) (English: /ˈmɑːrioʊ/; Italian: [ˈmaːrjo]) is a fictional character in the Mario video @@ -28,7 +28,7 @@ const code = `const Component = (

    - +

    Luigi (Japanese: ルイージ Hepburn: Ruīji, [ɾɯ.iː.dʑi̥]) (English: /luˈiːdʒi/; Italian: [luˈiːdʒi]) is a fictional character featured in video games and related media @@ -43,7 +43,7 @@ const code = `const Component = (

    - +

    Princess Peach (Japanese: ピーチ姫 Hepburn: Pīchi-hime, [piː.tɕi̥ çi̥.me]) is a character in Nintendo's Mario franchise. Originally created by Shigeru Miyamoto, @@ -59,7 +59,7 @@ const code = `const Component = (

    - +

    Yoshi (ヨッシー Yosshī, [joɕ.ɕiː]) (English: /ˈjoʊʃi/ or /ˈjɒʃi/), once romanized as Yossy, is a fictional anthropomorphic dinosaur who appears in @@ -78,7 +78,7 @@ const code = `const Component = (

    - +

    Toad (Japanese: キノピオ Hepburn: Kinopio) is a fictional character who primarily appears in Nintendo's Mario franchise. Created by Japanese video game designer Shigeru Miyamoto, diff --git a/examples/webpack.config.js b/examples/webpack.config.js index dbd8d38af0..fee087b0be 100644 --- a/examples/webpack.config.js +++ b/examples/webpack.config.js @@ -63,22 +63,14 @@ module.exports = { module: { rules: [ { - test: /\.jsx?$/, + test: /\.[jt]sx?$/, exclude: [/node_modules/], use: [ { loader: 'babel-loader', options: { babelrc: false, - extends: path.join(libraryDirectory, '.babelrc.js'), - plugins: isDev - ? [] - : [ - [ - 'transform-react-remove-prop-types', - { removeImport: true }, - ], - ], + extends: path.join(__dirname, '.babelrc.js'), }, }, ], @@ -104,7 +96,8 @@ module.exports = { ], }, resolve: { - extensions: ['.js', '.jsx', '.json', '.wasm'], + extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '.wasm'], + extensionAlias: { '.js': ['.js', '.ts', '.tsx'] }, alias: { 'react-tabs$': path.join(libraryDirectory, 'src/index'), }, diff --git a/index.d.ts b/index.d.ts deleted file mode 100644 index cf7af97c66..0000000000 --- a/index.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { FunctionComponent, HTMLProps } from 'react'; - -export interface TabsProps - extends Omit, 'className' | 'onSelect' | 'ref'> { - className?: string | string[] | { [name: string]: boolean } | undefined; - defaultFocus?: boolean | undefined; - defaultIndex?: number | undefined; - direction?: 'rtl' | 'ltr' | undefined; - disabledTabClassName?: string | undefined; - disableUpDownKeys?: boolean | undefined; - disableLeftRightKeys?: boolean | undefined; - domRef?: ((node?: HTMLElement) => void) | undefined; - environment?: Window | undefined; - focusTabOnClick?: boolean | undefined; - forceRenderTabPanel?: boolean | undefined; - onSelect?: - | ((index: number, last: number, event: Event) => boolean | void) - | undefined; - selectedIndex?: number | undefined; - selectedTabClassName?: string | undefined; - selectedTabPanelClassName?: string | undefined; -} - -export interface TabListProps - extends Omit, 'className'> { - className?: string | string[] | { [name: string]: boolean } | undefined; -} - -export interface TabProps - extends Omit, 'className' | 'tabIndex'> { - className?: string | string[] | { [name: string]: boolean } | undefined; - disabled?: boolean | undefined; - disabledClassName?: string | undefined; - selectedClassName?: string | undefined; - tabIndex?: string | undefined; -} - -export interface TabPanelProps - extends Omit, 'className'> { - className?: string | string[] | { [name: string]: boolean } | undefined; - forceRender?: boolean | undefined; - selectedClassName?: string | undefined; -} - -export interface ReactTabsFunctionComponent

    extends FunctionComponent

    { - tabsRole: 'Tabs' | 'TabList' | 'Tab' | 'TabPanel'; -} - -export const Tabs: FunctionComponent; -export const TabList: FunctionComponent; -export const Tab: FunctionComponent; -export const TabPanel: FunctionComponent; diff --git a/package.json b/package.json index c06a4f7a6c..ed403c7397 100644 --- a/package.json +++ b/package.json @@ -2,20 +2,24 @@ "name": "react-tabs", "version": "6.1.3", "description": "An accessible and easy tab component for ReactJS", - "main": "lib/index.js", - "module": "esm/index.js", - "typings": "index.d.ts", + "type": "module", + "types": "./esm/index.d.ts", + "exports": { + ".": { + "types": "./esm/index.d.ts", + "default": "./esm/index.js" + }, + "./style/*": "./style/*", + "./package.json": "./package.json" + }, "scripts": { - "clean:commonjs": "rm -rf lib", - "clean:esm": "rm -rf esm", - "build:commonjs": "cross-env BABEL_OUTPUT=commonjs babel src/ --out-dir lib/ --ignore **/__tests__,**/__mocks__", - "build:esm": "babel src/ --out-dir esm/ --ignore **/__tests__,**/__mocks__", - "build": "pnpm run --sequential '/clean:.*|build:.*/'", + "build": "rm -rf esm && tsc", "format": "eslint src --fix --report-unused-disable-directives", "lint": "eslint src --report-unused-disable-directives", - "prepublishOnly": "pnpm run build", + "prepack": "pnpm run build", "test": "vitest run", - "start": "pnpm --filter react-tabs-examples start" + "start": "pnpm --filter react-tabs-examples start", + "typecheck": "tsc --noEmit" }, "packageManager": "pnpm@12.23.0", "repository": { @@ -29,9 +33,7 @@ }, "files": [ "esm", - "lib", - "style", - "index.d.ts" + "style" ], "homepage": "https://github.com/reactjs/react-tabs", "keywords": [ @@ -44,10 +46,6 @@ "react": "^18.0.0 || ^19.0.0" }, "devDependencies": { - "@babel/cli": "7.29.7", - "@babel/core": "7.29.13", - "@babel/preset-env": "7.29.14", - "@babel/preset-react": "7.29.7", "@changesets/changelog-github": "1.0.1", "@changesets/cli": "3.0.3", "@eslint-react/eslint-plugin": "5.30.6", @@ -56,23 +54,23 @@ "@testing-library/jest-dom": "8.0.0", "@testing-library/react": "16.3.3", "@testing-library/user-event": "14.6.13", + "@types/node": "24.19.2", + "@types/react": "19.3.0", "@vitest/coverage-v8": "5.1.2", - "babel-plugin-transform-react-remove-prop-types": "0.4.24", - "cross-env": "10.1.0", "eslint": "10.15.0", "eslint-config-prettier": "10.1.8", "eslint-plugin-import-x": "4.18.1", "eslint-plugin-jsx-a11y-x": "0.2.0", "eslint-plugin-prettier": "5.5.7", "happy-dom": "21.0.4", - "hoist-non-react-statics": "3.3.2", "prettier": "3.10.1", "react": "19.3.1", "react-dom": "19.3.1", + "typescript": "6.0.3", + "typescript-eslint": "8.74.0", "vitest": "5.1.2" }, "dependencies": { - "clsx": "^2.0.0", - "prop-types": "^15.5.0" + "clsx": "^2.0.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 42a27aa519..a5b418e387 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -188,22 +188,7 @@ importers: clsx: specifier: ^2.0.0 version: 2.1.1 - prop-types: - specifier: ^15.5.0 - version: 15.8.1 devDependencies: - '@babel/cli': - specifier: 7.29.7 - version: 7.29.7(@babel/core@7.29.13(supports-color@8.1.1)) - '@babel/core': - specifier: 7.29.13 - version: 7.29.13(supports-color@8.1.1) - '@babel/preset-env': - specifier: 7.29.14 - version: 7.29.14(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) - '@babel/preset-react': - specifier: 7.29.7 - version: 7.29.7(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) '@changesets/changelog-github': specifier: 1.0.1 version: 1.0.1 @@ -224,19 +209,19 @@ importers: version: 8.0.0(@testing-library/dom@10.4.2)(vitest@5.1.2) '@testing-library/react': specifier: 16.3.3 - version: 16.3.3(@testing-library/dom@10.4.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@testing-library/user-event': specifier: 14.6.13 version: 14.6.13(@testing-library/dom@10.4.2) + '@types/node': + specifier: 24.19.2 + version: 24.19.2 + '@types/react': + specifier: 19.3.0 + version: 19.3.0 '@vitest/coverage-v8': specifier: 5.1.2 version: 5.1.2(vitest@5.1.2) - babel-plugin-transform-react-remove-prop-types: - specifier: 0.4.24 - version: 0.4.24 - cross-env: - specifier: 10.1.0 - version: 10.1.0 eslint: specifier: 10.15.0 version: 10.15.0(supports-color@8.1.1) @@ -255,9 +240,6 @@ importers: happy-dom: specifier: 21.0.4 version: 21.0.4 - hoist-non-react-statics: - specifier: 3.3.2 - version: 3.3.2 prettier: specifier: 3.10.1 version: 3.10.1 @@ -267,9 +249,15 @@ importers: react-dom: specifier: 19.3.1 version: 19.3.1(react@19.3.1) + typescript: + specifier: 6.0.3 + version: 6.0.3 + typescript-eslint: + specifier: 8.74.0 + version: 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) vitest: specifier: 5.1.2 - version: 5.1.2(@types/node@26.6.6)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) + version: 5.1.2(@types/node@24.19.2)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) examples: dependencies: @@ -279,9 +267,6 @@ importers: prism-react-renderer: specifier: 2.4.1 version: 2.4.1(react@19.3.1) - prop-types: - specifier: ^15.5.0 - version: 15.8.1 react: specifier: 19.3.1 version: 19.3.1 @@ -298,12 +283,18 @@ importers: '@babel/core': specifier: 7.29.13 version: 7.29.13(supports-color@8.1.1) + '@babel/preset-env': + specifier: 7.29.14 + version: 7.29.14(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/preset-react': + specifier: 7.29.7 + version: 7.29.7(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/preset-typescript': + specifier: 7.29.7 + version: 7.29.7(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) babel-loader: specifier: 10.1.1 version: 10.1.1(@babel/core@7.29.13(supports-color@8.1.1))(webpack@5.113.0) - babel-plugin-transform-react-remove-prop-types: - specifier: 0.4.24 - version: 0.4.24 cross-env: specifier: 10.1.0 version: 10.1.0 @@ -343,13 +334,6 @@ packages: '@adobe/css-tools@4.5.0': resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==} - '@babel/cli@7.29.7': - resolution: {integrity: sha512-/75HwRbAYPqXv/Ax1h7Fg3IZfXgdU98jnA8H93/m/QBaPV3Hp5ICoLqzGYye1yHBCgpmXvtqgSUN8oOKX5tojQ==} - engines: {node: '>=6.9.0'} - hasBin: true - peerDependencies: - '@babel/core': ^7.0.0-0 - '@babel/code-frame@7.29.7': resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} engines: {node: '>=6.9.0'} @@ -518,6 +502,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-syntax-typescript@7.29.7': + resolution: {integrity: sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + '@babel/plugin-syntax-unicode-sets-regex@7.18.6': resolution: {integrity: sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==} engines: {node: '>=6.9.0'} @@ -830,6 +820,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-typescript@7.29.15': + resolution: {integrity: sha512-FFuMssbHj8DFMDsTH8xrgKBiE1eXuDvO9jLqav7/vsIe6YdoyPQbWCgLNzQxkcIkOv5itBD17TvZkHGIjUMzLg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-unicode-escapes@7.29.7': resolution: {integrity: sha512-jCfXxSjf94lf4E0hKE0AByxF6F3/pVFqRdUUNkDJhsY0m1ZKjnN6ZYyMeHNpzflxb/0q5b7t3p+BE+SLF1WOtA==} engines: {node: '>=6.9.0'} @@ -871,6 +867,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/preset-typescript@7.29.7': + resolution: {integrity: sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + '@babel/runtime@7.29.14': resolution: {integrity: sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==} engines: {node: '>=6.9.0'} @@ -1310,9 +1312,6 @@ packages: '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 - '@nicolo-ribaudo/chokidar-2@2.1.8-no-fsevents.3': - resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==} - '@noble/hashes@1.8.0': resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} @@ -1574,6 +1573,9 @@ packages: '@types/less@3.0.8': resolution: {integrity: sha512-Gjm4+H9noDJgu5EdT3rUw5MhPBag46fiOy27BefvWkNL8mlZnKnCaVVVTLKj6RYXed9b62CPKnPav9govyQDzA==} + '@types/node@24.19.2': + resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==} + '@types/node@26.6.6': resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} @@ -1586,6 +1588,9 @@ packages: '@types/range-parser@1.2.7': resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==} + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + '@types/send@1.2.1': resolution: {integrity: sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==} @@ -1607,6 +1612,21 @@ packages: '@types/yargs@17.0.35': resolution: {integrity: sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==} + '@typescript-eslint/eslint-plugin@8.74.0': + resolution: {integrity: sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.74.0 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.74.0': + resolution: {integrity: sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/project-service@8.74.0': resolution: {integrity: sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1623,6 +1643,13 @@ packages: peerDependencies: typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/type-utils@8.74.0': + resolution: {integrity: sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/types@8.74.0': resolution: {integrity: sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1900,10 +1927,6 @@ packages: any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - anymatch@3.1.3: - resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} - engines: {node: '>= 8'} - argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} @@ -1981,12 +2004,6 @@ packages: peerDependencies: '@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0 - babel-plugin-transform-react-remove-prop-types@0.4.24: - resolution: {integrity: sha512-eqj0hVcJUR57/Ug2zE1Yswsw4LhuqqHhD+8v120T1cl3kjg76QwtyBrdIk4WVwK+lAhBJVYCd/v+4nc4y+8JsA==} - - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -1999,10 +2016,6 @@ packages: batch@0.6.1: resolution: {integrity: sha512-x+VAiMRL6UPkx+kudNvxTl6hB2XNNCG2r+7wixVfIYwu/2HKRXimwQyaumLjMveWvT2Hkd/cAJw+QBMfJ/EKVw==} - binary-extensions@2.3.0: - resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} - engines: {node: '>=8'} - body-parser@2.4.0: resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} engines: {node: '>=18'} @@ -2013,9 +2026,6 @@ packages: boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} - brace-expansion@1.1.22: - resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==} - brace-expansion@5.1.0: resolution: {integrity: sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg==} engines: {node: 20 || >=22} @@ -2084,10 +2094,6 @@ packages: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} - chokidar@3.6.0: - resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} - engines: {node: '>= 8.10.0'} - chokidar@5.0.0: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} @@ -2141,10 +2147,6 @@ packages: resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} engines: {node: '>= 6'} - commander@6.2.1: - resolution: {integrity: sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==} - engines: {node: '>= 6'} - commander@8.3.0: resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} engines: {node: '>= 12'} @@ -2164,9 +2166,6 @@ packages: resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==} engines: {node: '>= 0.8.0'} - concat-map@0.0.1: - resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} - connect-history-api-fallback@2.0.0: resolution: {integrity: sha512-U73+6lQFmfiNPrYbXqr6kZ1i1wiRqXnp2nhMsINseWXO8lDau0LGEffJ8kQi4EjLZympVgRdvqjAgiZ1tgzDDA==} engines: {node: '>=0.8'} @@ -2302,6 +2301,9 @@ packages: resolution: {integrity: sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'} + csstype@3.2.4: + resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==} + damerau-levenshtein@1.0.8: resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==} @@ -2760,12 +2762,6 @@ packages: resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} engines: {node: '>= 0.8'} - fs-readdir-recursive@1.1.0: - resolution: {integrity: sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==} - - fs.realpath@1.0.0: - resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} - fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -2804,10 +2800,6 @@ packages: get-tsconfig@4.14.3: resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==} - glob-parent@5.1.2: - resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} - engines: {node: '>= 6'} - glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -2818,10 +2810,6 @@ packages: peerDependencies: tslib: '2' - glob@7.2.3: - resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me - globalthis@1.0.4: resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} engines: {node: '>= 0.4'} @@ -2872,9 +2860,6 @@ packages: resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} hasBin: true - hoist-non-react-statics@3.3.2: - resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==} - hookified@1.15.1: resolution: {integrity: sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==} @@ -2957,6 +2942,10 @@ packages: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} + ignore@7.0.16: + resolution: {integrity: sha512-52N+Y4HRMOJmbLmr+DqO4iSRyyB7N52gm7PWCT6h0p978+oKbqHCB7gIJIwZvBUsjlSdWbrBFqUSmIFNZMpn0A==} + engines: {node: '>= 4'} + import-meta-resolve@4.2.0: resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} @@ -2968,10 +2957,6 @@ packages: resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==} engines: {node: '>=8'} - inflight@1.0.6: - resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} - deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. - inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -3003,10 +2988,6 @@ packages: resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} engines: {node: '>= 0.4'} - is-binary-path@2.1.0: - resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} - engines: {node: '>=8'} - is-boolean-object@1.2.2: resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==} engines: {node: '>= 0.4'} @@ -3340,10 +3321,6 @@ packages: lodash@4.18.1: resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} - loose-envify@1.4.0: - resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} - hasBin: true - lower-case@2.0.2: resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==} @@ -3360,10 +3337,6 @@ packages: magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} - make-dir@2.1.0: - resolution: {integrity: sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==} - engines: {node: '>=6'} - make-dir@5.1.0: resolution: {integrity: sha512-IfpFq6UM39dUNiphpA6uDezNx/AvWyhwfICWPR3t1VspkgkMZrL+Rk1RbN1bx+aeNYwOrqGJgEgV3yotk+ZUVw==} engines: {node: '>=18'} @@ -3435,9 +3408,6 @@ packages: resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} engines: {node: 20 || >=22} - minimatch@3.1.5: - resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} - minimizer-webpack-plugin@5.14.0: resolution: {integrity: sha512-PnvQXCJxhgH2ZVVO7Lj0sM6q8L1XGxnUvd8wVQIRwi8khMCLq5wg0Ngxe44bcuZL2FSN81RdVE7YHEVzTKsQDQ==} engines: {node: '>= 10.13.0'} @@ -3552,10 +3522,6 @@ packages: resolution: {integrity: sha512-PfvofsGQ+MiOQIPkX9fU8ELUWmy5zL74CdQaph/ismKszfFkfwXaw0cGiwbwym2hT9k5+mdyl8O5WQ1MD8EHmA==} engines: {node: '>=18'} - normalize-path@3.0.0: - resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} - engines: {node: '>=0.10.0'} - nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} @@ -3642,10 +3608,6 @@ packages: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} - path-is-absolute@1.0.1: - resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} - engines: {node: '>=0.10.0'} - path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} @@ -3667,10 +3629,6 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} - pify@4.0.1: - resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==} - engines: {node: '>=6'} - pirates@4.0.7: resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} engines: {node: '>= 6'} @@ -3912,9 +3870,6 @@ packages: probe-image-size@7.5.0: resolution: {integrity: sha512-ietdx4XPgmnzHRZOq1/KtcnsBkL4bRsBe+Szj5Tuq1/KPqDG42OspG1IhJb7vz6Z9pSzhp0J6UPnw6hujJTWoQ==} - prop-types@15.8.1: - resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} - proxy-addr@2.0.8: resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} @@ -3954,9 +3909,6 @@ packages: peerDependencies: react: ^19.3.1 - react-is@16.13.1: - resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} - react-is@17.0.2: resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} @@ -3971,10 +3923,6 @@ packages: resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} engines: {node: '>=0.10.0'} - readdirp@3.6.0: - resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} - engines: {node: '>=8.10.0'} - readdirp@5.1.1: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} @@ -4092,10 +4040,6 @@ packages: resolution: {integrity: sha512-ftnu3TW4+3eBfLRFnDEkzGxSF/10BJBkaLJuBHZX0kiPS7bRdlpZGu6YGt4KngMkdTwJE6MbjavFpqHvqVt+Ew==} engines: {node: '>=18'} - semver@5.7.3: - resolution: {integrity: sha512-kM18BPOqTi0+TB68703/GJRpAML5Me+IDQsR1J26YB3EFKKNEyHIVZuWDX7+WKQB3tHwDwgk24BfhdpWUbytvQ==} - hasBin: true - semver@6.3.2: resolution: {integrity: sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==} hasBin: true @@ -4172,10 +4116,6 @@ packages: resolution: {integrity: sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg==} engines: {node: '>=20'} - slash@2.0.0: - resolution: {integrity: sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==} - engines: {node: '>=6'} - source-map-js@1.2.4: resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==} engines: {node: '>=6.0.0'} @@ -4362,6 +4302,13 @@ packages: resolution: {integrity: sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==} engines: {node: '>= 0.4'} + typescript-eslint@8.74.0: + resolution: {integrity: sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + typescript@6.0.3: resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} engines: {node: '>=14.17'} @@ -4371,6 +4318,9 @@ packages: resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} engines: {node: '>= 0.4'} + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + undici-types@8.9.0: resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} @@ -4650,20 +4600,6 @@ snapshots: '@adobe/css-tools@4.5.0': {} - '@babel/cli@7.29.7(@babel/core@7.29.13(supports-color@8.1.1))': - dependencies: - '@babel/core': 7.29.13(supports-color@8.1.1) - '@jridgewell/trace-mapping': 0.3.31 - commander: 6.2.1 - convert-source-map: 2.0.0 - fs-readdir-recursive: 1.1.0 - glob: 7.2.3 - make-dir: 2.1.0 - slash: 2.0.0 - optionalDependencies: - '@nicolo-ribaudo/chokidar-2': 2.1.8-no-fsevents.3 - chokidar: 3.6.0 - '@babel/code-frame@7.29.7': dependencies: '@babel/helper-validator-identifier': 7.29.7 @@ -4885,6 +4821,11 @@ snapshots: '@babel/core': 7.29.13(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 + '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.13(supports-color@8.1.1))': + dependencies: + '@babel/core': 7.29.13(supports-color@8.1.1) + '@babel/helper-plugin-utils': 7.29.7 + '@babel/plugin-syntax-unicode-sets-regex@7.18.6(@babel/core@7.29.13(supports-color@8.1.1))': dependencies: '@babel/core': 7.29.13(supports-color@8.1.1) @@ -5230,6 +5171,17 @@ snapshots: '@babel/core': 7.29.13(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 + '@babel/plugin-transform-typescript@7.29.15(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1)': + dependencies: + '@babel/core': 7.29.13(supports-color@8.1.1) + '@babel/helper-annotate-as-pure': 7.29.7 + '@babel/helper-create-class-features-plugin': 7.29.13(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/helper-plugin-utils': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.13(supports-color@8.1.1) + '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.13(supports-color@8.1.1)) + transitivePeerDependencies: + - supports-color + '@babel/plugin-transform-unicode-escapes@7.29.7(@babel/core@7.29.13(supports-color@8.1.1))': dependencies: '@babel/core': 7.29.13(supports-color@8.1.1) @@ -5349,6 +5301,17 @@ snapshots: transitivePeerDependencies: - supports-color + '@babel/preset-typescript@7.29.7(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1)': + dependencies: + '@babel/core': 7.29.13(supports-color@8.1.1) + '@babel/helper-plugin-utils': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.13(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.29.14(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-typescript': 7.29.15(@babel/core@7.29.13(supports-color@8.1.1))(supports-color@8.1.1) + transitivePeerDependencies: + - supports-color + '@babel/runtime@7.29.14': {} '@babel/template@7.29.7': @@ -5895,9 +5858,6 @@ snapshots: '@tybys/wasm-util': 0.10.5 optional: true - '@nicolo-ribaudo/chokidar-2@2.1.8-no-fsevents.3': - optional: true - '@noble/hashes@1.8.0': {} '@oxc-project/types@0.156.0': {} @@ -6077,14 +6037,16 @@ snapshots: picocolors: 1.1.1 redent: 3.0.0 optionalDependencies: - vitest: 5.1.2(@types/node@26.6.6)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) + vitest: 5.1.2(@types/node@24.19.2)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) - '@testing-library/react@16.3.3(@testing-library/dom@10.4.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + '@testing-library/react@16.3.3(@testing-library/dom@10.4.2)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: '@babel/runtime': 7.29.14 '@testing-library/dom': 10.4.2 react: 19.3.1 react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 '@testing-library/user-event@14.6.13(@testing-library/dom@10.4.2)': dependencies: @@ -6157,6 +6119,10 @@ snapshots: '@types/less@3.0.8': {} + '@types/node@24.19.2': + dependencies: + undici-types: 7.24.6 + '@types/node@26.6.6': dependencies: undici-types: 8.9.0 @@ -6167,6 +6133,10 @@ snapshots: '@types/range-parser@1.2.7': {} + '@types/react@19.3.0': + dependencies: + csstype: 3.2.4 + '@types/send@1.2.1': dependencies: '@types/node': 26.6.6 @@ -6192,6 +6162,36 @@ snapshots: dependencies: '@types/yargs-parser': 21.0.3 + '@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3))(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3)': + dependencies: + '@eslint-community/regexpp': 4.12.3 + '@typescript-eslint/parser': 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/scope-manager': 8.74.0 + '@typescript-eslint/type-utils': 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.74.0 + eslint: 10.15.0(supports-color@8.1.1) + ignore: 7.0.16 + natural-compare: 1.4.0 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - '@typescript/native' + - supports-color + + '@typescript-eslint/parser@8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/scope-manager': 8.74.0 + '@typescript-eslint/types': 8.74.0 + '@typescript-eslint/typescript-estree': 8.74.0(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.74.0 + debug: 4.4.3(supports-color@8.1.1) + eslint: 10.15.0(supports-color@8.1.1) + typescript: 6.0.3 + transitivePeerDependencies: + - '@typescript/native' + - supports-color + '@typescript-eslint/project-service@8.74.0(supports-color@8.1.1)(typescript@6.0.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.74.0(typescript@6.0.3) @@ -6210,6 +6210,19 @@ snapshots: dependencies: typescript: 6.0.3 + '@typescript-eslint/type-utils@8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/types': 8.74.0 + '@typescript-eslint/typescript-estree': 8.74.0(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + debug: 4.4.3(supports-color@8.1.1) + eslint: 10.15.0(supports-color@8.1.1) + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - '@typescript/native' + - supports-color + '@typescript-eslint/types@8.74.0': {} '@typescript-eslint/typescript-estree@8.74.0(supports-color@8.1.1)(typescript@6.0.3)': @@ -6319,7 +6332,7 @@ snapshots: obug: 3.0.0 std-env: 4.3.0 tinyrainbow: 3.2.0 - vitest: 5.1.2(@types/node@26.6.6)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) + vitest: 5.1.2(@types/node@24.19.2)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) '@vitest/istanbul-lib-coverage@2.1.1': {} @@ -6327,14 +6340,14 @@ snapshots: dependencies: '@vitest/istanbul-lib-coverage': 2.1.1 - '@vitest/mocker@5.1.2(vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1))': + '@vitest/mocker@5.1.2(vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.1.2 estree-walker: 3.0.3 magic-string: 1.4.5 optionalDependencies: - vite: 8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1) + vite: 8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1) '@vitest/spy@5.1.2': {} @@ -6467,12 +6480,6 @@ snapshots: any-promise@1.3.0: {} - anymatch@3.1.3: - dependencies: - normalize-path: 3.0.0 - picomatch: 2.3.2 - optional: true - argparse@2.0.1: optional: true @@ -6564,19 +6571,12 @@ snapshots: transitivePeerDependencies: - supports-color - babel-plugin-transform-react-remove-prop-types@0.4.24: {} - - balanced-match@1.0.2: {} - balanced-match@4.0.4: {} baseline-browser-mapping@2.11.39: {} batch@0.6.1: {} - binary-extensions@2.3.0: - optional: true - body-parser@2.4.0(supports-color@8.1.1): dependencies: bytes: 3.1.2 @@ -6598,11 +6598,6 @@ snapshots: boolbase@1.0.0: {} - brace-expansion@1.1.22: - dependencies: - balanced-match: 1.0.2 - concat-map: 0.0.1 - brace-expansion@5.1.0: dependencies: balanced-match: 4.0.4 @@ -6682,19 +6677,6 @@ snapshots: ansi-styles: 4.3.0 supports-color: 7.2.0 - chokidar@3.6.0: - dependencies: - anymatch: 3.1.3 - braces: 3.0.3 - glob-parent: 5.1.2 - is-binary-path: 2.1.0 - is-glob: 4.0.3 - normalize-path: 3.0.0 - readdirp: 3.6.0 - optionalDependencies: - fsevents: 2.3.3 - optional: true - chokidar@5.0.0: dependencies: readdirp: 5.1.1 @@ -6733,8 +6715,6 @@ snapshots: commander@4.1.1: {} - commander@6.2.1: {} - commander@8.3.0: {} comment-parser@1.4.9: {} @@ -6758,8 +6738,6 @@ snapshots: transitivePeerDependencies: - supports-color - concat-map@0.0.1: {} - connect-history-api-fallback@2.0.0: {} content-disposition@2.0.1: {} @@ -6904,6 +6882,8 @@ snapshots: dependencies: css-tree: 2.2.1 + csstype@3.2.4: {} + damerau-levenshtein@1.0.8: {} data-view-buffer@1.0.2: @@ -7513,10 +7493,6 @@ snapshots: fresh@2.0.0: {} - fs-readdir-recursive@1.1.0: {} - - fs.realpath@1.0.0: {} - fsevents@2.3.3: optional: true @@ -7572,11 +7548,6 @@ snapshots: dependencies: resolve-pkg-maps: 1.0.0 - glob-parent@5.1.2: - dependencies: - is-glob: 4.0.3 - optional: true - glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -7585,15 +7556,6 @@ snapshots: dependencies: tslib: 2.9.1 - glob@7.2.3: - dependencies: - fs.realpath: 1.0.0 - inflight: 1.0.6 - inherits: 2.0.4 - minimatch: 3.1.5 - once: 1.4.0 - path-is-absolute: 1.0.1 - globalthis@1.0.4: dependencies: define-properties: 1.2.1 @@ -7649,10 +7611,6 @@ snapshots: he@1.2.0: {} - hoist-non-react-statics@3.3.2: - dependencies: - react-is: 16.13.1 - hookified@1.15.1: {} hookified@2.2.0: {} @@ -7752,17 +7710,14 @@ snapshots: ignore@5.3.2: {} + ignore@7.0.16: {} + import-meta-resolve@4.2.0: {} imurmurhash@0.1.4: {} indent-string@4.0.0: {} - inflight@1.0.6: - dependencies: - once: 1.4.0 - wrappy: 1.0.2 - inherits@2.0.4: {} internal-slot@1.1.0: @@ -7799,11 +7754,6 @@ snapshots: has-bigints: 1.1.0 optional: true - is-binary-path@2.1.0: - dependencies: - binary-extensions: 2.3.0 - optional: true - is-boolean-object@1.2.2: dependencies: call-bound: 1.0.4 @@ -8110,10 +8060,6 @@ snapshots: lodash@4.18.1: {} - loose-envify@1.4.0: - dependencies: - js-tokens: 4.0.0 - lower-case@2.0.2: dependencies: tslib: 2.9.1 @@ -8134,11 +8080,6 @@ snapshots: '@babel/types': 7.29.14 source-map-js: 1.2.4 - make-dir@2.1.0: - dependencies: - pify: 4.0.1 - semver: 5.7.3 - make-dir@5.1.0: optional: true @@ -8208,10 +8149,6 @@ snapshots: '@isaacs/nonrecursive-glob-match': 1.1.0 brace-expansion: 5.1.0 - minimatch@3.1.5: - dependencies: - brace-expansion: 1.1.22 - minimizer-webpack-plugin@5.14.0(clean-css@5.3.3)(cssnano@7.1.9(postcss@8.5.33))(csso@5.0.5)(html-minifier-terser@7.2.0)(lightningcss@1.33.0)(postcss@8.5.33)(svgo@4.1.0)(webpack@5.113.0): dependencies: jest-worker: 27.5.1 @@ -8286,9 +8223,6 @@ snapshots: node-releases@2.0.65: {} - normalize-path@3.0.0: - optional: true - nth-check@2.1.1: dependencies: boolbase: 1.0.0 @@ -8390,8 +8324,6 @@ snapshots: path-exists@4.0.0: {} - path-is-absolute@1.0.1: {} - path-key@3.1.1: {} path-parse@1.0.7: {} @@ -8404,8 +8336,6 @@ snapshots: picomatch@4.0.7: {} - pify@4.0.1: {} - pirates@4.0.7: {} pkijs@3.4.3: @@ -8639,12 +8569,6 @@ snapshots: - supports-color optional: true - prop-types@15.8.1: - dependencies: - loose-envify: 1.4.0 - object-assign: 4.1.1 - react-is: 16.13.1 - proxy-addr@2.0.8: dependencies: forwarded: 0.2.0 @@ -8684,8 +8608,6 @@ snapshots: react: 19.3.1 scheduler: 0.28.0 - react-is@16.13.1: {} - react-is@17.0.2: {} react-live@4.1.8(react-dom@19.3.1(react@19.3.1))(react@19.3.1): @@ -8698,11 +8620,6 @@ snapshots: react@19.3.1: {} - readdirp@3.6.0: - dependencies: - picomatch: 2.3.2 - optional: true - readdirp@5.1.1: {} rechoir@1.0.0: {} @@ -8866,8 +8783,6 @@ snapshots: '@peculiar/x509': 1.14.3 pkijs: 3.4.3 - semver@5.7.3: {} - semver@6.3.2: {} semver@7.8.6: {} @@ -8980,8 +8895,6 @@ snapshots: sisteransi@2.0.0: {} - slash@2.0.0: {} - source-map-js@1.2.4: {} source-map-support@0.5.21: @@ -9189,6 +9102,18 @@ snapshots: reflect.getprototypeof: 1.0.10 optional: true + typescript-eslint@8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3): + dependencies: + '@typescript-eslint/eslint-plugin': 8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3))(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/parser': 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/typescript-estree': 8.74.0(supports-color@8.1.1)(typescript@6.0.3) + '@typescript-eslint/utils': 8.74.0(eslint@10.15.0(supports-color@8.1.1))(supports-color@8.1.1)(typescript@6.0.3) + eslint: 10.15.0(supports-color@8.1.1) + typescript: 6.0.3 + transitivePeerDependencies: + - '@typescript/native' + - supports-color + typescript@6.0.3: {} unbox-primitive@1.1.0: @@ -9199,6 +9124,8 @@ snapshots: which-boxed-primitive: 1.1.1 optional: true + undici-types@7.24.6: {} + undici-types@8.9.0: {} unicode-canonical-property-names-ecmascript@2.0.1: {} @@ -9260,7 +9187,7 @@ snapshots: vary@1.1.2: {} - vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1): + vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -9268,16 +9195,16 @@ snapshots: rolldown: 1.2.19 tinyglobby: 0.2.17 optionalDependencies: - '@types/node': 26.6.6 + '@types/node': 24.19.2 fsevents: 2.3.3 less: 4.9.1(supports-color@8.1.1) terser: 5.51.2 yaml: 2.9.1 - vitest@5.1.2(@types/node@26.6.6)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)): + vitest@5.1.2(@types/node@24.19.2)(@vitest/coverage-v8@5.1.2)(happy-dom@21.0.4)(vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.1.2(vite@8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) + '@vitest/mocker': 5.1.2(vite@8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1)) chai: 6.3.0 es-module-lexer: 2.3.2 expect-type: 1.4.0 @@ -9288,10 +9215,10 @@ snapshots: tinybench: 6.2.4 tinyexec: 1.3.1 tinyglobby: 0.2.17 - vite: 8.3.8(@types/node@26.6.6)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1) + vite: 8.3.8(@types/node@24.19.2)(less@4.9.1(supports-color@8.1.1))(terser@5.51.2)(yaml@2.9.1) why-is-node-running: 3.2.1 optionalDependencies: - '@types/node': 26.6.6 + '@types/node': 24.19.2 '@vitest/coverage-v8': 5.1.2(vitest@5.1.2) happy-dom: 21.0.4 transitivePeerDependencies: diff --git a/src/components/Tab.jsx b/src/components/Tab.jsx deleted file mode 100644 index 5d8abc1a50..0000000000 --- a/src/components/Tab.jsx +++ /dev/null @@ -1,88 +0,0 @@ -import { useEffect, useRef } from 'react'; -import cx from 'clsx'; - -const DEFAULT_CLASS = 'react-tabs__tab'; -const defaultProps = { - className: DEFAULT_CLASS, - disabledClassName: `${DEFAULT_CLASS}--disabled`, - focus: false, - id: null, - selected: false, - selectedClassName: `${DEFAULT_CLASS}--selected`, -}; - -/* -Left for TS migration -const propTypes = { - children: PropTypes.oneOfType([ - PropTypes.array, - PropTypes.object, - PropTypes.string, - ]), - className: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.array, - PropTypes.object, - ]), - disabled: PropTypes.bool, - disabledClassName: PropTypes.string, - focus: PropTypes.bool, // private - id: PropTypes.string, // private - selected: PropTypes.bool, // private - selectedClassName: PropTypes.string, - tabIndex: PropTypes.string, - tabRef: PropTypes.func, // private -};*/ - -const Tab = (props) => { - let nodeRef = useRef(); - const { - children, - className, - disabled, - disabledClassName, - focus, - id, - selected, - selectedClassName, - tabIndex, - tabRef, - ...attributes - } = { - ...defaultProps, - ...props, - }; - - useEffect(() => { - if (selected && focus) { - nodeRef.current.focus(); - } - }, [selected, focus]); - - return ( -

  • { - nodeRef.current = node; - if (tabRef) tabRef(node); - }} - role="tab" - id={`tab${id}`} - aria-selected={selected ? 'true' : 'false'} - aria-disabled={disabled ? 'true' : 'false'} - aria-controls={`panel${id}`} - tabIndex={tabIndex || (selected ? '0' : null)} - data-rttab - > - {children} -
  • - ); -}; - -Tab.tabsRole = 'Tab'; - -export default Tab; diff --git a/src/components/Tab.tsx b/src/components/Tab.tsx new file mode 100644 index 0000000000..77688286ed --- /dev/null +++ b/src/components/Tab.tsx @@ -0,0 +1,53 @@ +import { useContext } from 'react'; +import type { TabProps } from '../types.js'; +import { getItemIdentity, TabsContext } from './TabsContext.js'; +import cx from 'clsx'; + +const DEFAULT_CLASS = 'react-tabs__tab'; +const defaultProps = { + className: DEFAULT_CLASS, + disabledClassName: `${DEFAULT_CLASS}--disabled`, + selectedClassName: `${DEFAULT_CLASS}--selected`, +}; + +const Tab = (props: TabProps) => { + const group = useContext(TabsContext); + const { + children, + className, + disabled, + disabledClassName, + id: ownId, + itemKey, + selectedClassName, + tabIndex, + ...attributes + } = { + ...defaultProps, + ...props, + }; + const { tabId, panelId, token } = getItemIdentity(group?.id, itemKey); + const selected = group?.selectedKey === itemKey; + const tabbable = selected || group?.fallbackKey === itemKey; + + return ( + + ); +}; + +export default Tab; diff --git a/src/components/TabList.jsx b/src/components/TabList.tsx similarity index 52% rename from src/components/TabList.jsx rename to src/components/TabList.tsx index 81d08f4de7..c32e372cb9 100644 --- a/src/components/TabList.jsx +++ b/src/components/TabList.tsx @@ -1,32 +1,21 @@ import cx from 'clsx'; +import type { TabListProps } from '../types.js'; const defaultProps = { className: 'react-tabs__tab-list', }; -/* -Left for TS migration -const propTypes = { - children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), - className: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.array, - PropTypes.object, - ]), -};*/ -const TabList = (props) => { +const TabList = (props: TabListProps) => { const { children, className, ...attributes } = { ...defaultProps, ...props, }; return ( -
      +
        {children}
      ); }; -TabList.tabsRole = 'TabList'; - export default TabList; diff --git a/src/components/TabPanel.jsx b/src/components/TabPanel.jsx deleted file mode 100644 index 52718388d5..0000000000 --- a/src/components/TabPanel.jsx +++ /dev/null @@ -1,56 +0,0 @@ -import cx from 'clsx'; - -const DEFAULT_CLASS = 'react-tabs__tab-panel'; -const defaultProps = { - className: DEFAULT_CLASS, - forceRender: false, - selectedClassName: `${DEFAULT_CLASS}--selected`, -}; - -/* -Left for TS migration -const propTypes = { - children: PropTypes.node, - className: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.array, - PropTypes.object, - ]), - forceRender: PropTypes.bool, - id: PropTypes.string, // private - selected: PropTypes.bool, // private - selectedClassName: PropTypes.string, -}; -*/ -const TabPanel = (props) => { - const { - children, - className, - forceRender, - id, - selected, - selectedClassName, - ...attributes - } = { - ...defaultProps, - ...props, - }; - - return ( -
      - {forceRender || selected ? children : null} -
      - ); -}; - -TabPanel.tabsRole = 'TabPanel'; - -export default TabPanel; diff --git a/src/components/TabPanel.tsx b/src/components/TabPanel.tsx new file mode 100644 index 0000000000..31964f3e0b --- /dev/null +++ b/src/components/TabPanel.tsx @@ -0,0 +1,39 @@ +import cx from 'clsx'; +import { useContext } from 'react'; +import type { TabPanelProps } from '../types.js'; +import { getItemIdentity, TabsContext } from './TabsContext.js'; + +const DEFAULT_CLASS = 'react-tabs__tab-panel'; + +const TabPanel = ({ + children, + className = DEFAULT_CLASS, + forceRender, + hidden, + id: ownId, + itemKey, + selectedClassName = `${DEFAULT_CLASS}--selected`, + ...attributes +}: TabPanelProps) => { + const group = useContext(TabsContext); + const { tabId, panelId, token } = getItemIdentity(group?.id, itemKey); + const selected = group?.selectedKey === itemKey; + + return ( + + ); +}; + +export default TabPanel; diff --git a/src/components/Tabs.jsx b/src/components/Tabs.jsx deleted file mode 100644 index c9b7713c0d..0000000000 --- a/src/components/Tabs.jsx +++ /dev/null @@ -1,137 +0,0 @@ -import { checkPropTypes } from 'prop-types'; -import { useEffect, useState } from 'react'; -import { - childrenPropType, - onSelectPropType, - selectedIndexPropType, -} from '../helpers/propTypes'; -import UncontrolledTabs from './UncontrolledTabs'; -import { getTabsCount } from '../helpers/count'; - -const MODE_CONTROLLED = 0; -const MODE_UNCONTROLLED = 1; -const propTypes = { - children: childrenPropType, - onSelect: onSelectPropType, - selectedIndex: selectedIndexPropType, - /* -Left for TS migration - className: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.array, - PropTypes.object, - ]), - defaultFocus: PropTypes.bool, - defaultIndex: PropTypes.number, - direction: PropTypes.oneOf(['rtl', 'ltr']), - disabledTabClassName: PropTypes.string, - disableUpDownKeys: PropTypes.bool, - disableLeftRightKeys: PropTypes.bool, - domRef: PropTypes.func, - environment: PropTypes.object, - focusTabOnClick: PropTypes.bool, - forceRenderTabPanel: PropTypes.bool, - selectedTabClassName: PropTypes.string, - selectedTabPanelClassName: PropTypes.string,*/ -}; -const defaultProps = { - defaultFocus: false, - focusTabOnClick: true, - forceRenderTabPanel: false, - selectedIndex: null, - defaultIndex: null, - environment: null, - disableUpDownKeys: false, - disableLeftRightKeys: false, -}; - -const getModeFromProps = (props) => { - return props.selectedIndex === null ? MODE_UNCONTROLLED : MODE_CONTROLLED; -}; - -const checkForIllegalModeChange = (props, mode) => { - if ( - process.env.NODE_ENV !== 'production' && - mode != undefined && - mode !== getModeFromProps(props) - ) { - throw new Error( - `Switching between controlled mode (by using \`selectedIndex\`) and uncontrolled mode is not supported in \`Tabs\`. -For more information about controlled and uncontrolled mode of react-tabs see https://github.com/reactjs/react-tabs#controlled-vs-uncontrolled-mode.`, - ); - } -}; - -/** - * State: - * mode: Initialized only once from props and never changes - * selectedIndex: null if controlled mode, otherwise initialized with prop defaultIndex, changed on selection of tabs, has effect to ensure it never gets out of bound - * focus: Whether a tab interaction has requested focus on the selected tab. - */ -const Tabs = (props) => { - checkPropTypes(propTypes, props, 'prop', 'Tabs'); - const { - children, - defaultFocus, - defaultIndex, - focusTabOnClick, - onSelect, - ...attributes - } = { - ...defaultProps, - ...props, - }; - - const [focus, setFocus] = useState(false); - const [mode] = useState(() => getModeFromProps(attributes)); - const [selectedIndex, setSelectedIndex] = useState( - mode === MODE_UNCONTROLLED ? defaultIndex || 0 : null, - ); - - const tabsCount = mode === MODE_UNCONTROLLED ? getTabsCount(children) : 0; - useEffect(() => { - if (mode === MODE_UNCONTROLLED) { - // Removing tabs can move the current selection past the last tab. - const maxTabIndex = Math.max(0, tabsCount - 1); - // eslint-disable-next-line @eslint-react/set-state-in-effect - setSelectedIndex((index) => Math.min(index, maxTabIndex)); - } - }, [mode, tabsCount]); - - checkForIllegalModeChange(attributes, mode); - - const handleSelected = (index, last, event) => { - // Call change event handler - if (typeof onSelect === 'function') { - // Check if the change event handler cancels the tab change - if (onSelect(index, last, event) === false) return; - } - - // Always set focus on tabs unless it is disabled - if (focusTabOnClick) { - setFocus(true); - } - - if (mode === MODE_UNCONTROLLED) { - // Update selected index - setSelectedIndex(index); - } - }; - - let subProps = { ...props, ...attributes }; - - subProps.defaultFocus = defaultFocus; - subProps.focus = focus; - subProps.onSelect = handleSelected; - - if (selectedIndex != null) { - subProps.selectedIndex = selectedIndex; - } - delete subProps.defaultIndex; - delete subProps.focusTabOnClick; - return {children}; -}; - -Tabs.tabsRole = 'Tabs'; - -export default Tabs; diff --git a/src/components/Tabs.tsx b/src/components/Tabs.tsx new file mode 100644 index 0000000000..a56ada37a2 --- /dev/null +++ b/src/components/Tabs.tsx @@ -0,0 +1,347 @@ +import cx from 'clsx'; +import { + useCallback, + useEffect, + useId, + useRef, + useState, + type KeyboardEvent, + type MouseEvent, +} from 'react'; +import { + getTabCollection, + getTabEntries, + getTabEventTarget, + getTabProblems, +} from '../helpers/tabCollection.js'; +import type { TabEvent, TabKey, TabsProps } from '../types.js'; +import { isTabKey, TabsContext } from './TabsContext.js'; + +interface Availability { + key: TabKey; + paired: boolean; + firstEnabled: TabKey | undefined; +} + +interface Recovery { + key: TabKey; + previousKey: TabKey; +} + +const Tabs = (props: TabsProps) => { + const { + children, + className = 'react-tabs', + defaultFocus = false, + defaultKey, + direction, + disabledTabClassName, + disableUpDownKeys, + disableLeftRightKeys, + domRef, + environment, + focusTabOnClick = true, + forceRenderTabPanel, + onClick, + onKeyDown, + onSelect, + selectedKey: controlledKey, + selectedTabClassName, + selectedTabPanelClassName, + ...attributes + } = props; + + const controlled = controlledKey !== undefined; + const [isControlled] = useState(controlled); + const initialKey = controlledKey ?? defaultKey; + if (!isTabKey(initialKey) || (controlled && defaultKey !== undefined)) { + throw new Error( + 'Tabs requires either selectedKey or defaultKey with a nonempty string or finite numeric key.', + ); + } + if ('selectedIndex' in props || 'defaultIndex' in props) { + throw new Error( + 'Use selectedKey or defaultKey instead of selectedIndex or defaultIndex.', + ); + } + if (onSelect !== undefined && typeof onSelect !== 'function') { + throw new Error('Tabs onSelect must be a function.'); + } + if (controlled && typeof onSelect !== 'function') { + throw new Error('Tabs requires onSelect when selectedKey is provided.'); + } + if (isControlled !== controlled) { + throw new Error( + 'Tabs cannot switch between controlled and uncontrolled mode.', + ); + } + + const [localKey, setLocalKey] = useState(initialKey); + const [availability, setAvailability] = useState(); + const [focusRequest, setFocusRequest] = useState<{ key: TabKey }>(); + const handledFocusRequestRef = useRef(focusRequest); + const previousSelectionRef = useRef(undefined); + const initialFocusPendingRef = useRef(defaultFocus); + const lastFocusedTabRef = useRef(null); + const pendingRecoveryRef = useRef(undefined); + const reportedProblemsRef = useRef | undefined>(undefined); + const rootRef = useRef(null); + const id = useId(); + const setRoot = useCallback( + (node: HTMLDivElement | null) => { + rootRef.current = node; + domRef?.(node); + }, + [domRef], + ); + + const requestedKey = controlledKey ?? localKey; + const missing = availability?.key === requestedKey && !availability.paired; + const selectedKey = missing ? undefined : requestedKey; + const fallbackKey = missing ? availability.firstEnabled : undefined; + + useEffect(() => { + const root = rootRef.current; + if (!root) return; + const document = root.ownerDocument; + + function trackFocus(event: FocusEvent) { + const target = event.target as Element | null; + lastFocusedTabRef.current = + target?.nodeType === 1 && + target.matches('li[data-rttab]') && + target.closest('[data-rttabs]') === root + ? target + : null; + initialFocusPendingRef.current = false; + } + + const trackBlur = (event: FocusEvent) => { + const tab = lastFocusedTabRef.current; + if (!tab || event.target !== tab) return; + // Some browsers blur before detaching a focused node. + queueMicrotask(() => { + if ( + lastFocusedTabRef.current === tab && + root.contains(tab) && + document.activeElement !== tab + ) { + lastFocusedTabRef.current = null; + } + }); + }; + + document.addEventListener('focusin', trackFocus, true); + document.addEventListener('focusout', trackBlur, true); + return () => { + document.removeEventListener('focusin', trackFocus, true); + document.removeEventListener('focusout', trackBlur, true); + }; + }, []); + + useEffect(() => { + const root = rootRef.current; + if (!root) return; + + const refresh = () => { + const collection = getTabCollection(root); + const entries = getTabEntries(collection); + if (process.env.NODE_ENV !== 'production') { + const problems = getTabProblems(collection); + for (const problem of problems) { + if (reportedProblemsRef.current?.has(problem)) continue; + // eslint-disable-next-line no-console + console.error(problem); + } + reportedProblemsRef.current = problems; + } + const paired = entries.some(({ key }) => key === requestedKey); + const firstEnabled = paired + ? undefined + : entries.find(({ disabled }) => !disabled)?.key; + if (!isControlled && !paired && firstEnabled !== undefined) { + pendingRecoveryRef.current = { + key: firstEnabled, + previousKey: pendingRecoveryRef.current?.previousKey ?? requestedKey, + }; + setLocalKey(firstEnabled); + return; + } + setAvailability((current) => + current?.key === requestedKey && + current.paired === paired && + current.firstEnabled === firstEnabled + ? current + : { key: requestedKey, paired, firstEnabled }, + ); + }; + + const Observer = root.ownerDocument.defaultView?.MutationObserver; + const observer = Observer && new Observer(refresh); + observer?.observe(root, { + subtree: true, + childList: true, + attributes: true, + attributeFilter: [ + 'aria-disabled', + 'data-rttab', + 'data-rttabpanel', + 'data-rttablist', + ], + }); + refresh(); + return () => observer?.disconnect(); + }, [children, isControlled, requestedKey]); + + useEffect(() => { + const recovery = pendingRecoveryRef.current; + if ( + recovery && + recovery.key === selectedKey && + availability?.key === selectedKey && + availability.paired + ) { + pendingRecoveryRef.current = undefined; + onSelect?.(recovery.key, recovery.previousKey, undefined); + } + }, [availability, onSelect, selectedKey]); + + useEffect(() => { + const root = rootRef.current; + if (!root) return; + const initialFocus = initialFocusPendingRef.current; + const explicitFocus = + focusRequest !== handledFocusRequestRef.current && + focusRequest?.key === selectedKey; + handledFocusRequestRef.current = focusRequest; + const selectionChanged = previousSelectionRef.current !== selectedKey; + previousSelectionRef.current = selectedKey; + if ( + selectedKey === undefined || + (!initialFocus && !explicitFocus && !selectionChanged) + ) + return; + + const entries = getTabEntries(getTabCollection(root)); + const selected = entries.find(({ key }) => key === selectedKey); + if (!selected) return; + if (initialFocus || explicitFocus) { + initialFocusPendingRef.current = false; + selected.node.focus(); + } else { + // Reading activeElement may fail in a detached or cross-origin frame. + let hadTabFocus: boolean; + try { + const document = environment?.document ?? root.ownerDocument; + const active = document.activeElement; + const lastFocusedTab = lastFocusedTabRef.current; + hadTabFocus = + entries.some(({ node }) => node === active) || + (lastFocusedTab !== null && + !root.contains(lastFocusedTab) && + (active === document.body || active === null)); + } catch { + return; + } + if (hadTabFocus) selected.node.focus(); + } + }, [availability, environment, focusRequest, selectedKey]); + + function select(key: TabKey, event: TabEvent) { + if (onSelect?.(key, requestedKey, event) === false) return; + if (focusTabOnClick) setFocusRequest({ key }); + if (!isControlled) { + pendingRecoveryRef.current = undefined; + setLocalKey(key); + } + } + + function handleClick(event: MouseEvent) { + onClick?.(event); + if (event.defaultPrevented) return; + + const target = getTabEventTarget(event.currentTarget, event.target); + if (target && !target.entry.disabled) select(target.entry.key, event); + } + + function handleKeyDown(event: KeyboardEvent) { + onKeyDown?.(event); + if (event.defaultPrevented) return; + + const { key } = event; + const activate = key === 'Enter' || key === ' '; + const jump = key === 'Home' || key === 'End'; + const horizontal = key === 'ArrowLeft' || key === 'ArrowRight'; + const vertical = key === 'ArrowUp' || key === 'ArrowDown'; + if ( + !activate && + !jump && + !(horizontal && !disableLeftRightKeys) && + !(vertical && !disableUpDownKeys) + ) + return; + + const root = event.currentTarget; + const target = getTabEventTarget(root, event.target); + if (!target) return; + const { entry, entries } = target; + + event.preventDefault(); + if (activate) { + if (!entry.disabled) select(entry.key, event); + return; + } + + if (jump) { + const enabled = key === 'Home' ? entries : entries.reverse(); + const next = enabled.find(({ disabled }) => !disabled); + if (next) select(next.key, event); + return; + } + + const movesForward = key === 'ArrowRight' || key === 'ArrowDown'; + const rtl = horizontal + ? (root.ownerDocument.defaultView?.getComputedStyle(root).direction ?? + root.dir) === 'rtl' + : direction === 'rtl'; + const step = movesForward !== rtl ? 1 : -1; + const start = entries.findIndex((entry) => entry.key === selectedKey); + const origin = start === -1 ? entries.indexOf(entry) : start; + for (let distance = 1; distance <= entries.length; distance++) { + const next = + entries[(origin + step * distance + entries.length) % entries.length]; + if (!next.disabled) { + select(next.key, event); + return; + } + } + } + + return ( +
      + + {children} + +
      + ); +}; + +export default Tabs; diff --git a/src/components/TabsContext.ts b/src/components/TabsContext.ts new file mode 100644 index 0000000000..c683b95b0d --- /dev/null +++ b/src/components/TabsContext.ts @@ -0,0 +1,39 @@ +import { createContext } from 'react'; +import type { TabKey } from '../types.js'; + +export const TabsContext = createContext<{ + id: string; + selectedKey: TabKey | undefined; + fallbackKey: TabKey | undefined; + disabledTabClassName?: string; + selectedTabClassName?: string; + selectedTabPanelClassName?: string; + forceRenderTabPanel?: boolean; +} | null>(null); + +export function isTabKey(key: unknown): key is TabKey { + return ( + (typeof key === 'string' && key.length > 0) || + (typeof key === 'number' && Number.isFinite(key)) + ); +} + +export function getItemIdentity(groupId: string | undefined, itemKey: TabKey) { + if (!isTabKey(itemKey)) { + throw new Error( + 'Tab and TabPanel require a nonempty string or finite numeric itemKey.', + ); + } + + const token = JSON.stringify(itemKey); + if (groupId === undefined) { + return { token, tabId: undefined, panelId: undefined }; + } + + const suffix = `${groupId}-${encodeURIComponent(token)}`; + return { + token, + tabId: `tab${suffix}`, + panelId: `panel${suffix}`, + }; +} diff --git a/src/components/UncontrolledTabs.jsx b/src/components/UncontrolledTabs.jsx deleted file mode 100644 index c33a1b6ad0..0000000000 --- a/src/components/UncontrolledTabs.jsx +++ /dev/null @@ -1,418 +0,0 @@ -import { checkPropTypes } from 'prop-types'; -import { cloneElement, useEffect, useRef, useId } from 'react'; -import cx from 'clsx'; -import { childrenPropType } from '../helpers/propTypes'; -import { getTabsCount as getTabsCountHelper } from '../helpers/count'; -import { deepMap } from '../helpers/childrenDeepMap'; -import { isTabList, isTabPanel } from '../helpers/elementTypes'; - -function isNode(node) { - return node && 'getAttribute' in node; -} - -// Determine if a node from event.target is a Tab element -function isTabNode(node) { - return isNode(node) && node.getAttribute('data-rttab'); -} - -// Determine if a tab node is disabled -function isTabDisabled(node) { - return isNode(node) && node.getAttribute('aria-disabled') === 'true'; -} - -let canUseActiveElement; - -function determineCanUseActiveElement(environment) { - const env = - environment || (typeof window !== 'undefined' ? window : undefined); - - try { - canUseActiveElement = !!( - typeof env !== 'undefined' && - env.document && - env.document.activeElement - ); - // eslint-disable-next-line no-unused-vars - } catch (e) { - // Work around for IE bug when accessing document.activeElement in an iframe - // Refer to the following resources: - // http://stackoverflow.com/a/10982960/369687 - // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12733599 - // istanbul ignore next - canUseActiveElement = false; - } -} - -const defaultProps = { - className: 'react-tabs', - focus: false, -}; - -const propTypes = { - children: childrenPropType, - /* - Left for TS migration - direction: PropTypes.oneOf(['rtl', 'ltr']), - className: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.array, - PropTypes.object, - ]), - disabledTabClassName: PropTypes.string, - disableUpDownKeys: PropTypes.bool, - disableLeftRightKeys: PropTypes.bool, - domRef: PropTypes.func, - focus: PropTypes.bool, - forceRenderTabPanel: PropTypes.bool, - onSelect: PropTypes.func.isRequired, - selectedIndex: PropTypes.number.isRequired, - selectedTabClassName: PropTypes.string, - selectedTabPanelClassName: PropTypes.string, - environment: PropTypes.object,*/ -}; - -const UncontrolledTabs = (props) => { - checkPropTypes(propTypes, props, 'prop', 'UncontrolledTabs'); - const tabNodesRef = useRef([]); - const tabIdsRef = useRef([]); - const ref = useRef(); - const id = useId(); - const initialFocusIndexRef = useRef( - props.defaultFocus ? props.selectedIndex : null, - ); - - useEffect(() => { - const index = initialFocusIndexRef.current; - if (Number.isInteger(index)) tabNodesRef.current[index]?.focus(); - }, []); - - function setSelected(index, event) { - // Check index boundary - if (index < 0 || index >= getTabsCount()) return; - - const { onSelect, selectedIndex } = props; - - // Call change event handler - onSelect(index, selectedIndex, event); - } - - function getNextTab(index) { - const count = getTabsCount(); - - // Look for non-disabled tab from index to the last tab on the right - for (let i = index + 1; i < count; i++) { - if (!isTabDisabled(getTab(i))) { - return i; - } - } - - // If no tab found, continue searching from first on left to index - for (let i = 0; i < index; i++) { - if (!isTabDisabled(getTab(i))) { - return i; - } - } - - // All tabs are disabled, return index - /* istanbul ignore next */ - return index; - } - - function getPrevTab(index) { - let i = index; - - // Look for non-disabled tab from index to first tab on the left - while (i--) { - if (!isTabDisabled(getTab(i))) { - return i; - } - } - - // If no tab found, continue searching from last tab on right to index - i = getTabsCount(); - while (i-- > index) { - if (!isTabDisabled(getTab(i))) { - return i; - } - } - - // All tabs are disabled, return index - /* istanbul ignore next */ - return index; - } - - function getFirstTab() { - const count = getTabsCount(); - - // Look for non disabled tab from the first tab - for (let i = 0; i < count; i++) { - if (!isTabDisabled(getTab(i))) { - return i; - } - } - - /* istanbul ignore next */ - return null; - } - - function getLastTab() { - let i = getTabsCount(); - - // Look for non disabled tab from the last tab - while (i--) { - if (!isTabDisabled(getTab(i))) { - return i; - } - } - - /* istanbul ignore next */ - return null; - } - - function getTabsCount() { - const { children } = props; - return getTabsCountHelper(children); - } - - function getTab(index) { - return tabNodesRef.current[index]; - } - - function getChildren() { - let index = 0; - const { - children, - disabledTabClassName, - focus, - forceRenderTabPanel, - selectedIndex, - selectedTabClassName, - selectedTabPanelClassName, - environment, - } = props; - - tabIdsRef.current = tabIdsRef.current || []; - let diff = tabIdsRef.current.length - getTabsCount(); - - // Add ids if new tabs have been added - // Don't bother removing ids, just keep them in case they are added again - // This is more efficient, and keeps the uuid counter under control - while (diff++ < 0) { - tabIdsRef.current.push(`${id}${tabIdsRef.current.length}`); - } - - // Map children to dynamically setup refs - return deepMap(children, (child) => { - let result = child; - - // Clone TabList and Tab components to have refs - if (isTabList(child)) { - let listIndex = 0; - - // Figure out if the current focus in the DOM is set on a Tab - // If it is we should keep the focus on the next selected tab - let wasTabFocused = false; - - if (canUseActiveElement == null) { - determineCanUseActiveElement(environment); - } - - const env = - environment || (typeof window !== 'undefined' ? window : undefined); - if (canUseActiveElement && env) { - wasTabFocused = Object.keys(tabNodesRef.current).some( - (key) => env.document.activeElement === tabNodesRef.current[key], - ); - } - - result = cloneElement(child, { - children: deepMap(child.props.children, (tab) => { - const index = listIndex++; - const selected = selectedIndex === index; - - const props = { - tabRef: (node) => { - tabNodesRef.current[index] = node; - }, - id: tabIdsRef.current[index], - selected, - focus: selected && (focus || wasTabFocused), - }; - - if (selectedTabClassName) - props.selectedClassName = selectedTabClassName; - if (disabledTabClassName) - props.disabledClassName = disabledTabClassName; - - return cloneElement(tab, props); - }), - }); - } else if (isTabPanel(child)) { - const props = { - id: tabIdsRef.current[index], - selected: selectedIndex === index, - }; - - if (forceRenderTabPanel) props.forceRender = forceRenderTabPanel; - if (selectedTabPanelClassName) - props.selectedClassName = selectedTabPanelClassName; - - index++; - - result = cloneElement(child, props); - } - - return result; - }); - } - - function handleKeyDown(e) { - const { direction, disableUpDownKeys, disableLeftRightKeys } = props; - if (isTabFromContainer(e.target)) { - let { selectedIndex: index } = props; - let preventDefault = false; - let useSelectedIndex = false; - - if ( - e.code === 'Space' || - e.keyCode === 32 /* space */ || - e.code === 'Enter' || - e.keyCode === 13 /* enter */ - ) { - preventDefault = true; - useSelectedIndex = false; - handleClick(e); - } - - // keyCode is deprecated and only used here for IE - - if ( - (!disableLeftRightKeys && - (e.keyCode === 37 || e.code === 'ArrowLeft')) /* arrow left */ || - (!disableUpDownKeys && - (e.keyCode === 38 || e.code === 'ArrowUp')) /* arrow up */ - ) { - // Select next tab to the left, validate if up arrow is not disabled - if (direction === 'rtl') { - index = getNextTab(index); - } else { - index = getPrevTab(index); - } - preventDefault = true; - useSelectedIndex = true; - } else if ( - (!disableLeftRightKeys && - (e.keyCode === 39 || e.code === 'ArrowRight')) /* arrow right */ || - (!disableUpDownKeys && - (e.keyCode === 40 || e.code === 'ArrowDown')) /* arrow down */ - ) { - // Select next tab to the right, validate if down arrow is not disabled - if (direction === 'rtl') { - index = getPrevTab(index); - } else { - index = getNextTab(index); - } - preventDefault = true; - useSelectedIndex = true; - } else if (e.keyCode === 35 || e.code === 'End') { - // Select last tab (End key) - index = getLastTab(); - preventDefault = true; - useSelectedIndex = true; - } else if (e.keyCode === 36 || e.code === 'Home') { - // Select first tab (Home key) - index = getFirstTab(); - preventDefault = true; - useSelectedIndex = true; - } - - // This prevents scrollbars from moving around - if (preventDefault) { - e.preventDefault(); - } - - // Only use the selected index in the state if we're not using the tabbed index - if (useSelectedIndex) { - setSelected(index, e); - } - } - } - - function handleClick(e) { - let node = e.target; - do { - if (isTabFromContainer(node)) { - if (isTabDisabled(node)) { - return; - } - - const index = [].slice - .call(node.parentNode.children) - .filter(isTabNode) - .indexOf(node); - setSelected(index, e); - return; - } - } while ((node = node.parentNode) != null); - } - - /** - * Determine if a node from event.target is a Tab element for the current Tabs container. - * If the clicked element is not a Tab, it returns false. - * If it finds another Tabs container between the Tab and `this`, it returns false. - */ - function isTabFromContainer(node) { - // return immediately if the clicked element is not a Tab. - if (!isTabNode(node)) { - return false; - } - - // Check if the first occurrence of a Tabs container is `this` one. - let nodeAncestor = node.parentElement; - do { - if (nodeAncestor === ref.current) return true; - if (nodeAncestor.getAttribute('data-rttabs')) break; - - nodeAncestor = nodeAncestor.parentElement; - } while (nodeAncestor); - - return false; - } - const { - children, // unused - className, - defaultFocus, // unused - disabledTabClassName, // unused - domRef, - focus, // unused - forceRenderTabPanel, // unused - onSelect, // unused - selectedIndex, // unused - selectedTabClassName, // unused - selectedTabPanelClassName, // unused - environment, // unused - disableUpDownKeys, // unused - disableLeftRightKeys, // unused - ...attributes - } = { - ...defaultProps, - ...props, - }; - return ( -
      { - ref.current = node; - if (domRef) domRef(node); - }} - data-rttabs - > - {getChildren()} -
      - ); -}; - -export default UncontrolledTabs; diff --git a/src/components/__tests__/Tab-test.jsx b/src/components/__tests__/Tab-test.jsx index a6e5c9ef10..3d95e3f671 100644 --- a/src/components/__tests__/Tab-test.jsx +++ b/src/components/__tests__/Tab-test.jsx @@ -1,6 +1,7 @@ import { afterEach, beforeAll, describe, expect, test } from 'vitest'; import { cleanup, render } from '@testing-library/react'; import Tab from '../Tab'; +import { TabsContext } from '../TabsContext'; import { TabWrapper } from './helpers/higherOrder'; function expectToMatchSnapshot(component) { @@ -10,6 +11,8 @@ function expectToMatchSnapshot(component) { afterEach(cleanup); +const selectedTab = { id: 'group', selectedKey: 0 }; + describe('', () => { beforeAll(() => { // eslint-disable-next-line no-console @@ -19,47 +22,69 @@ describe('', () => { }); test('should have sane defaults', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should accept className', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should support being selected', () => { expectToMatchSnapshot( - - Hello - , + + Hello + , ); }); test('should support being selected with custom class', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot( + + + , + ); }); test('should support being disabled', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should support being disabled with custom class name', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot( + , + ); }); test('should pass through custom properties', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should not allow overriding all default properties', () => { // eslint-disable-next-line jsx-a11y-x/aria-role - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should allow to be wrapped in higher-order-component', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('override the tabIndex if it was provided', () => { - expectToMatchSnapshot(Hello); + expectToMatchSnapshot( + + Hello + , + ); + }); + + test('should honor tabIndex -1 on a selected tab', () => { + const { getByRole } = render( + + + Hello + + , + ); + + expect(getByRole('tab').getAttribute('tabindex')).toBe('-1'); }); }); diff --git a/src/components/__tests__/TabList-test.jsx b/src/components/__tests__/TabList-test.jsx index 7776458032..7d0924644a 100644 --- a/src/components/__tests__/TabList-test.jsx +++ b/src/components/__tests__/TabList-test.jsx @@ -49,13 +49,15 @@ describe('', () => { test('should retain the default classnames for active and disabled tab', () => { expectToMatchSnapshot( - + - Foo - Bar + Foo + + Bar + - Foo - Bar + Foo + Bar , ); }); @@ -63,46 +65,57 @@ describe('', () => { test('should display the custom classnames for selected and disabled tab specified on tabs', () => { expectToMatchSnapshot( - Foo - Bar + Foo + + Bar + - Foo - Bar + Foo + Bar , ); }); test('should display the custom classnames for selected and disabled tab', () => { expectToMatchSnapshot( - + - + Foo - + Bar - Foo - Bar + Foo + Bar , ); }); test('should allow for higher order components', () => { expectToMatchSnapshot( - + - Foo - Bar + Foo + Bar - Foo - Bar + Foo + Bar , ); }); diff --git a/src/components/__tests__/TabPanel-test.jsx b/src/components/__tests__/TabPanel-test.jsx index d7076ac3ba..65c8091741 100644 --- a/src/components/__tests__/TabPanel-test.jsx +++ b/src/components/__tests__/TabPanel-test.jsx @@ -1,6 +1,8 @@ import { afterEach, beforeAll, describe, expect, test } from 'vitest'; -import { cleanup, render } from '@testing-library/react'; +import { cleanup, render, screen } from '@testing-library/react'; +import '@testing-library/jest-dom/vitest'; import TabPanel from '../TabPanel'; +import { TabsContext } from '../TabsContext'; import { TabPanelWrapper } from './helpers/higherOrder'; function expectToMatchSnapshot(component) { @@ -19,47 +21,83 @@ describe('', () => { }); test('should have sane defaults', () => { - expectToMatchSnapshot(Hola); + expectToMatchSnapshot(Hola); }); test('should render when selected', () => { - expectToMatchSnapshot(Hola); + expectToMatchSnapshot( + + Hola + , + ); }); - test('should render when forced', () => { - expectToMatchSnapshot(Hola); + test('keeps forced contents mounted when the panel becomes hidden', () => { + function panel(selectedKey) { + return ( + + + + ); + } + + const { rerender } = render(panel(0)); + const button = screen.getByRole('button', { name: 'Hola' }); + expect(button).toBeVisible(); + + rerender(panel(1)); + + expect(screen.getByRole('tabpanel', { hidden: true })).toHaveAttribute( + 'hidden', + ); + expect(screen.getByText('Hola')).toBe(button); + expect(button).not.toBeVisible(); }); test('should accept className', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); - test('should support being selected', () => { - expectToMatchSnapshot( - - Hola - , + test('applies the default classes when explicitly passed undefined', () => { + render( + + + , + ); + expect(screen.getByRole('tabpanel')).toHaveClass( + 'react-tabs__tab-panel react-tabs__tab-panel--selected', + { exact: true }, ); }); test('should support being selected with custom class name', () => { expectToMatchSnapshot( - - Hola - , + + + Hola + + , ); }); test('should pass through custom properties', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot( + , + ); }); test('should not allow overriding all default properties', () => { // eslint-disable-next-line jsx-a11y-x/aria-role - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should allow for higher-order components', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); }); diff --git a/src/components/__tests__/Tabs-errors-test.jsx b/src/components/__tests__/Tabs-errors-test.jsx index 4dc7b8fa77..f421f7bd5c 100644 --- a/src/components/__tests__/Tabs-errors-test.jsx +++ b/src/components/__tests__/Tabs-errors-test.jsx @@ -1,181 +1,169 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { cleanup, render } from '@testing-library/react'; -import '@testing-library/jest-dom/vitest'; -import Tab from '../Tab'; -import TabList from '../TabList'; -import TabPanel from '../TabPanel'; -import Tabs from '../Tabs'; - -vi.mock('react', async (importOriginal) => { - const originalModule = await importOriginal('react'); - - return { - ...originalModule, - useId: () => ':r0:', - }; +import { afterEach, expect, test, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; +import { Tab, TabList, TabPanel, Tabs } from '../../index'; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); -afterEach(cleanup); +test.each([ + [{}, 'requires either selectedKey or defaultKey'], + [{ defaultKey: '' }, 'requires either selectedKey or defaultKey'], + [ + { defaultKey: 1, selectedKey: 1 }, + 'requires either selectedKey or defaultKey', + ], + [ + { defaultKey: 1, selectedIndex: 1 }, + 'instead of selectedIndex or defaultIndex', + ], + [{ selectedKey: 1 }, 'requires onSelect'], + [{ defaultKey: 1, onSelect: true }, 'onSelect must be a function'], +])('rejects invalid selection props %j', (props, message) => { + expect(() => render()).toThrow(message); +}); -describe('', () => { - let consoleErrorMock; +test('rejects switching between controlled and uncontrolled mode', () => { + const { rerender } = render(); + expect(() => rerender( {}} />)).toThrow( + 'cannot switch between controlled and uncontrolled mode', + ); +}); - function assertPropTypeWarning(message, nth = 1) { - expect(consoleErrorMock).toHaveBeenNthCalledWith( - nth, - expect.stringMatching(message), +test.each([undefined, '', NaN, Infinity])( + 'rejects an invalid item key %s', + (itemKey) => { + expect(() => render()).toThrow( + 'require a nonempty string or finite numeric itemKey', + ); + expect(() => render()).toThrow( + 'require a nonempty string or finite numeric itemKey', + ); + }, +); + +test.each(['development', 'production'])( + 'skips invalid pairs during activation in %s', + async (mode) => { + vi.stubEnv('NODE_ENV', mode); + const report = vi.spyOn(console, 'error').mockImplementation(() => {}); + const onSelect = vi.fn(); + render( + + +
      Extra content
      + Duplicate A + Duplicate B + Unpaired + Multiple panels + Valid tab +
      + + + + + +
      , ); - } - - beforeEach(() => { - consoleErrorMock = vi.spyOn(console, 'error').mockImplementation(() => {}); - }); - - afterEach(() => { - consoleErrorMock.mockRestore(); - }); - - describe('errors', () => { - test('should result with warning when tabs/panels are imbalanced and it should ignore non tab children', () => { - render( - - - Foo -
      +
      -
      - - Hello Foo - Hello Bar -
      , - ); - - assertPropTypeWarning( - "There should be an equal number of 'Tab' and 'TabPanel' in `Tabs`. Received 1 'Tab' and 2 'TabPanel'.", - 1, - ); - assertPropTypeWarning( - "There should be an equal number of 'Tab' and 'TabPanel' in `UncontrolledTabs`. Received 1 'Tab' and 2 'TabPanel'.", - 2, - ); - }); - - test('should result with warning when multiple tablist components exist', () => { - render( - - - Foo - - - Foo - - - - , - ); - - assertPropTypeWarning( - "Found multiple 'TabList' components inside 'Tabs'. Only one is allowed.", - ); - }); - - test('should result with warning when tab outside of tablist', () => { - render( - - - Foo - - Foo - - - , - ); - - assertPropTypeWarning( - "Found a 'Tab' component outside of the 'TabList' component. 'Tab' components have to be inside the 'TabList' component.", - ); - }); - - test('should result with warning when defaultIndex and selectedIndex set', () => { - render( - {}}> - - Foo - - Foo - , - ); - - assertPropTypeWarning( - 'The prop `selectedIndex` cannot be used together with `defaultIndex` in `Tabs`.\nEither remove `selectedIndex` to let `Tabs` handle the selected tab internally or remove `defaultIndex` to handle it yourself.', - ); - }); - - test('should throw when mode of component changes', () => { - const onSelect = () => {}; - const { rerender } = render( - - - Foo - Foo2 - - Foo - Foo2 - , - ); - - const consoleLogMock = vi.spyOn(console, 'log').mockImplementation(); - try { - rerender( - - - Foo - Foo2 - - Foo - Foo2 - , - ); - } catch (e) { - expect(e.message).toContain( - 'Switching between controlled mode (by using `selectedIndex`) and uncontrolled mode is not supported in `Tabs`.', - ); - } finally { - consoleLogMock.mockRestore(); - } - }); - - test('should result with warning when tabs/panels are imbalanced', () => { - render( - - - Foo - - , - ); - assertPropTypeWarning( - "There should be an equal number of 'Tab' and 'TabPanel' in `Tabs`. Received 1 'Tab' and 0 'TabPanel'.", - 1, - ); - assertPropTypeWarning( - "There should be an equal number of 'Tab' and 'TabPanel' in `UncontrolledTabs`. Received 1 'Tab' and 0 'TabPanel'.", - 2, - ); - }); + expect(report.mock.calls).toEqual( + mode === 'development' + ? [ + ['Duplicate Tab key "duplicate".'], + ['Tab key "missing" has no matching TabPanel.'], + ['TabPanel key "orphan" has no matching Tab.'], + ['Duplicate TabPanel key "multi-panel".'], + ] + : [], + ); + await userEvent.click(screen.getByRole('tab', { name: 'Duplicate A' })); + await userEvent.click(screen.getByRole('tab', { name: 'Unpaired' })); + await userEvent.click(screen.getByRole('tab', { name: 'Multiple panels' })); + expect(onSelect).not.toHaveBeenCalled(); + }, +); + +test('diagnoses tabs outside a TabList and multiple owned lists', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}); + render( + + + + + + , + ); + expect(report).toHaveBeenCalledWith( + 'Only one TabList is allowed in a Tabs group.', + ); + expect(report).toHaveBeenCalledWith( + 'Every Tab must be inside its group’s TabList.', + ); +}); - test('should result with warning when onSelect missing when selectedIndex set', () => { - render( - - - Foo - - Foo - , - ); +test('rejects activation across two owned TabLists even when every tab has a panel', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}); + const onSelect = vi.fn(); + render( + + + First + + + Second + + + + , + ); + + const second = screen.getByRole('tab', { name: 'Second' }); + fireEvent.click(second); + fireEvent.keyDown(second, { key: 'Enter' }); + + expect(onSelect).not.toHaveBeenCalled(); + expect(screen.queryByRole('tab', { selected: true })).toBeNull(); + expect(report.mock.calls).toEqual([ + ['Only one TabList is allowed in a Tabs group.'], + ]); +}); - assertPropTypeWarning( - 'The prop `onSelect` is marked as required in `Tabs`, but its value is `undefined` or `null`.\n`onSelect` is required when `selectedIndex` is also set. Not doing so will make the tabs not do anything, as `selectedIndex` indicates that you want to handle the selected tab yourself.\nIf you only want to set the inital tab replace `selectedIndex` with `defaultIndex`.', - ); - }); - }); +test('skips DOM entries whose keys cannot identify a tab', async () => { + const onSelect = vi.fn(); + render( + + + First +
    • + Malformed JSON +
    • +
    • + Boolean key +
    • + Second +
      +
      +
      + First panel + Second panel + , + ); + + await userEvent.click(screen.getByRole('tab', { name: 'Malformed JSON' })); + await userEvent.click(screen.getByRole('tab', { name: 'Boolean key' })); + expect(onSelect).not.toHaveBeenCalled(); + + await userEvent.tab(); + await userEvent.keyboard('[ArrowRight]'); + expect(onSelect).toHaveBeenCalledWith( + 'second', + 'first', + expect.objectContaining({ type: 'keydown' }), + ); + expect(screen.getByRole('tab', { selected: true })).toBe( + screen.getByRole('tab', { name: 'Second' }), + ); }); diff --git a/src/components/__tests__/Tabs-hydration-test.jsx b/src/components/__tests__/Tabs-hydration-test.jsx index 044a089fce..632ef4640d 100644 --- a/src/components/__tests__/Tabs-hydration-test.jsx +++ b/src/components/__tests__/Tabs-hydration-test.jsx @@ -13,22 +13,29 @@ afterEach(() => { test('hydrates server markup and keeps tabs linked to their panels', async () => { const tabs = ( - + - Overview - Details + Overview + Details - Overview content - Details content + Details content + Overview content ); const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); const onRecoverableError = vi.fn(); const container = document.body.appendChild(document.createElement('div')); container.innerHTML = renderToString(tabs); - const { getByRole } = within(container); + const { getAllByRole, getByRole } = within(container); const serverTab = getByRole('tab', { name: 'Details' }); - const serverPanel = getByRole('tabpanel', { name: 'Details' }); + const serverPanel = getAllByRole('tabpanel', { hidden: true }).find( + (panel) => panel.id === serverTab.getAttribute('aria-controls'), + ); + expect(getByRole('tabpanel', { name: 'Overview' })).toHaveTextContent( + 'Overview content', + ); + expect(serverPanel).toHaveAttribute('hidden'); + expect(serverPanel).toBeEmptyDOMElement(); render(tabs, { container, hydrate: true, onRecoverableError }); diff --git a/src/components/__tests__/Tabs-keyed-test.jsx b/src/components/__tests__/Tabs-keyed-test.jsx new file mode 100644 index 0000000000..92f2d54bfa --- /dev/null +++ b/src/components/__tests__/Tabs-keyed-test.jsx @@ -0,0 +1,309 @@ +import { Profiler, StrictMode, useState } from 'react'; +import { afterEach, expect, test, vi } from 'vitest'; +import { + cleanup, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; +import '@testing-library/jest-dom/vitest'; +import { Tab, TabList, TabPanel, Tabs } from '../../index'; + +afterEach(cleanup); + +function group(keys, props = { defaultKey: 'active' }) { + return ( + + + {keys.map((key) => ( + + {key} + + ))} + + {keys.map((key) => ( + + {key} content + + ))} + + ); +} + +test('distinguishes numeric and string keys during selection and ARIA linking', async () => { + const onSelect = vi.fn(); + render( + + + Numeric + String + + String panel + Numeric panel + , + ); + + const numeric = screen.getByRole('tab', { name: 'Numeric' }); + const string = screen.getByRole('tab', { name: 'String' }); + expect(numeric.id).not.toBe(string.id); + expect(numeric).toHaveAttribute('aria-selected', 'true'); + + await userEvent.click(string); + + expect(onSelect).toHaveBeenCalledWith( + '1', + 1, + expect.objectContaining({ type: 'click' }), + ); + expect(string).toHaveAttribute( + 'aria-controls', + screen.getByRole('tabpanel', { name: 'String' }).id, + ); + expect(screen.getByText('String panel')).toBeVisible(); + expect(screen.queryByText('Numeric panel')).not.toBeInTheDocument(); +}); + +test('preserves the selected item when another tab is inserted or removed before it', () => { + const onSelect = vi.fn(); + const props = { defaultKey: 'active', onSelect }; + const { rerender } = render(group(['before', 'active', 'after'], props)); + const active = screen.getByRole('tab', { name: 'active', selected: true }); + const panel = screen.getByRole('tabpanel', { name: 'active' }); + + rerender(group(['active', 'after'], props)); + rerender(group(['inserted', 'active', 'after'], props)); + + expect(screen.getByRole('tab', { name: 'active', selected: true })).toBe( + active, + ); + expect(screen.getByRole('tabpanel', { name: 'active' })).toBe(panel); + expect(onSelect).not.toHaveBeenCalled(); +}); + +test('does not commit again when an earlier unselected tab becomes disabled', () => { + const onRender = vi.fn(); + const renderTabs = (disabled) => ( + + + + + Before + + Active + + + + + + ); + + const { rerender } = render(renderTabs(false)); + onRender.mockClear(); + rerender(renderTabs(true)); + + expect(onRender).toHaveBeenCalledTimes(1); + expect(screen.getByRole('tab', { selected: true })).toHaveTextContent( + 'Active', + ); +}); + +test('recovers from removal inside a wrapper and notifies once after the replacement is applied', async () => { + function Items() { + const [showActive, setShowActive] = useState(true); + return ( + <> + + + + Disabled + + {showActive && Active} + Replacement + + Replacement content + {showActive && Active content} + + + ); + } + const onSelect = vi.fn(() => { + expect(screen.getByRole('tab', { selected: true })).toHaveTextContent( + 'Replacement', + ); + return false; + }); + render( + + + + + , + ); + + await userEvent.click( + screen.getByRole('button', { name: 'Remove active tab' }), + ); + + await waitFor(() => + expect(onSelect).toHaveBeenCalledWith('replacement', 'active', undefined), + ); + expect(onSelect).toHaveBeenCalledTimes(1); + expect(screen.getByText('Replacement content')).toBeVisible(); + expect(screen.getByRole('button')).toHaveFocus(); +}); + +test('waits for an enabled replacement after removal leaves only disabled tabs', async () => { + const onSelect = vi.fn(); + function renderTabs(active, disabled) { + return ( + + + {active && Active} + + Replacement + + + {active && Active content} + Replacement content + + ); + } + const { rerender } = render(renderTabs(true, true)); + screen.getByRole('tab', { name: 'Active' }).focus(); + + rerender(renderTabs(false, true)); + expect(screen.queryByRole('tab', { selected: true })).not.toBeInTheDocument(); + expect(onSelect).not.toHaveBeenCalled(); + + rerender(renderTabs(false, false)); + await waitFor(() => + expect(onSelect).toHaveBeenCalledWith(0, 'active', undefined), + ); + expect(onSelect).toHaveBeenCalledTimes(1); + expect(screen.getByRole('tab', { name: 'Replacement' })).toHaveFocus(); +}); + +test('restores keyboard focus to the selected replacement after removal', () => { + const { rerender } = render(group(['active', 'first', 'second'])); + screen.getByRole('tab', { name: 'active' }).focus(); + + rerender(group(['first', 'second'])); + + expect( + screen.getByRole('tab', { name: 'first', selected: true }), + ).toHaveFocus(); +}); + +test('applies defaultFocus to the replacement when the default key is missing', () => { + render( + group(['first', 'second'], { defaultKey: 'missing', defaultFocus: true }), + ); + + expect( + screen.getByRole('tab', { name: 'first', selected: true }), + ).toHaveFocus(); +}); + +test('leaves focus outside when tabs appear after the user has moved on', () => { + const props = { defaultKey: 'first', defaultFocus: true }; + const renderTabs = (keys) => ( + <> + + {group(keys, props)} + + ); + const { rerender } = render(renderTabs([])); + const outside = screen.getByRole('textbox', { name: 'Outside' }); + outside.focus(); + + rerender(renderTabs(['first'])); + + expect( + screen.getByRole('tab', { name: 'first', selected: true }), + ).toBeVisible(); + expect(outside).toHaveFocus(); +}); + +test('keeps a controlled group unselected when its key disappears but leaves a keyboard entry point', async () => { + const onSelect = vi.fn(); + const props = { selectedKey: 'active', onSelect }; + const { rerender } = render(group(['active', 'first', 'second'], props)); + rerender(group(['first', 'second'], props)); + + expect(screen.queryByRole('tab', { selected: true })).not.toBeInTheDocument(); + expect(screen.queryByText('first content')).not.toBeInTheDocument(); + expect(onSelect).not.toHaveBeenCalled(); + + await userEvent.tab(); + expect(screen.getByRole('tab', { name: 'first' })).toHaveFocus(); + await userEvent.keyboard('[ArrowRight]'); + + expect(onSelect).toHaveBeenCalledWith( + 'second', + 'active', + expect.objectContaining({ type: 'keydown' }), + ); + expect(screen.queryByRole('tab', { selected: true })).not.toBeInTheDocument(); + + rerender(group(['first', 'second'], { ...props, selectedKey: 'second' })); + expect( + screen.getByRole('tab', { name: 'second', selected: true }), + ).toHaveFocus(); +}); + +test('scopes identical keys and ARIA IDs to their nearest group', () => { + render( + + + Outer + + +
      + + + Inner + + Inner content + +
      +
      +
      , + ); + + const inner = within(screen.getByRole('region', { name: 'Inner group' })); + const outerTab = screen.getByRole('tab', { name: 'Outer' }); + const innerTab = inner.getByRole('tab', { name: 'Inner' }); + expect(outerTab.id).not.toBe(innerTab.id); + expect(innerTab).toHaveAttribute( + 'aria-controls', + inner.getByRole('tabpanel').id, + ); +}); + +test('updates controlled selection when the supplied environment blocks focus inspection', () => { + const readActiveElement = vi.fn(() => { + throw new Error('Frame is no longer accessible'); + }); + const environment = { + document: Object.defineProperty({}, 'activeElement', { + get: readActiveElement, + }), + }; + const props = { selectedKey: 'first', environment, onSelect: vi.fn() }; + const { rerender } = render(group(['first', 'second'], props)); + const first = screen.getByRole('tab', { name: 'first' }); + first.focus(); + readActiveElement.mockClear(); + + rerender(group(['first', 'second'], { ...props, selectedKey: 'second' })); + + expect(readActiveElement).toHaveBeenCalledOnce(); + expect( + screen.getByRole('tab', { name: 'second', selected: true }), + ).toBeVisible(); + expect(first).toHaveFocus(); +}); diff --git a/src/components/__tests__/Tabs-node-test.jsx b/src/components/__tests__/Tabs-node-test.jsx index 3535cb3bc3..957cfe41a2 100644 --- a/src/components/__tests__/Tabs-node-test.jsx +++ b/src/components/__tests__/Tabs-node-test.jsx @@ -7,13 +7,13 @@ import { Tab, TabList, TabPanel, Tabs } from '../../index'; test('server renders the selected panel without a DOM', () => { const html = renderToString( - + - Overview - Details + Overview + Details - Overview content - Details content + Overview content + Details content , ); diff --git a/src/components/__tests__/Tabs-test.jsx b/src/components/__tests__/Tabs-test.jsx index 55b5e665cd..f73d8ed0f2 100644 --- a/src/components/__tests__/Tabs-test.jsx +++ b/src/components/__tests__/Tabs-test.jsx @@ -1,6 +1,12 @@ import { afterEach, describe, expect, test, vi } from 'vitest'; import React from 'react'; -import { cleanup, render, screen, within } from '@testing-library/react'; +import { + cleanup, + fireEvent, + render, + screen, + within, +} from '@testing-library/react'; import { userEvent } from '@testing-library/user-event'; import '@testing-library/jest-dom/vitest'; import Tab from '../Tab'; @@ -28,21 +34,36 @@ function expectToMatchSnapshot(component) { function createTabs(props = {}) { return ( - + - Tab1 - Tab2 - + + Tab1 + + + Tab2 + + Tab3 - + Tab4 - Hello Tab1 - Hello Tab2 - Hello Tab3 - Hello Tab4 + + Hello Tab1 + + + Hello Tab2 + + + Hello Tab3 + + + Hello Tab4 + ); } @@ -63,68 +84,129 @@ describe('', () => { expectToMatchSnapshot(createTabs()); }); - test('should honor positive defaultIndex prop', () => { - expectToMatchSnapshot(createTabs({ defaultIndex: 1 })); + test('should honor positive defaultKey prop', () => { + expectToMatchSnapshot(createTabs({ defaultKey: 1 })); }); - test('should honor negative defaultIndex prop', () => { - expectToMatchSnapshot(createTabs({ defaultIndex: -1 })); + test('should select the first enabled tab when the default key is missing', () => { + render(createTabs({ defaultKey: -1 })); + assertTabSelected(1); }); - test('should call onSelect when selection changes', async () => { - const called = { index: -1, last: -1 }; - render( - createTabs({ - onSelect(index, last) { - called.index = index; - called.last = last; - }, + test('should call onSelect with the React event when selection changes', async () => { + const onSelect = vi.fn(); + render(createTabs({ onSelect })); + + await userEvent.click(screen.getByTestId('tab2')); + + expect(onSelect).toHaveBeenLastCalledWith( + 1, + 0, + expect.objectContaining({ + type: 'click', + nativeEvent: expect.objectContaining({ type: 'click' }), }), ); - await userEvent.click(screen.getByTestId('tab2')); + await userEvent.keyboard('[ArrowRight]'); - expect(called.index).toBe(1); - expect(called.last).toBe(0); + expect(onSelect).toHaveBeenLastCalledWith( + 2, + 1, + expect.objectContaining({ + key: 'ArrowRight', + nativeEvent: expect.objectContaining({ type: 'keydown' }), + }), + ); }); test('should accept className', () => { expectToMatchSnapshot(createTabs({ className: 'foobar' })); }); - test('should accept domRef', () => { - let domNode; - render( - createTabs({ - domRef: (node) => { - domNode = node; - }, - }), - ); + test.each([ + ['onClick', () => fireEvent.click(screen.getByTestId('tab2'))], + [ + 'onKeyDown', + () => + fireEvent.keyDown(screen.getByTestId('tab1'), { key: 'ArrowRight' }), + ], + ])( + 'calls %s before selecting and respects preventDefault', + (prop, dispatch) => { + const handler = vi.fn().mockImplementationOnce((event) => { + event.preventDefault(); + }); + const onSelect = vi.fn(); + render(createTabs({ [prop]: handler, onSelect })); + + dispatch(); + + expect(handler).toHaveBeenCalledOnce(); + expect(onSelect).not.toHaveBeenCalled(); + assertTabSelected(1); + + handler.mockClear(); + dispatch(); + + expect(handler).toHaveBeenCalledOnce(); + expect(handler).toHaveBeenCalledBefore(onSelect); + expect(onSelect).toHaveBeenCalledWith(1, 0, handler.mock.calls[0][0]); + assertTabSelected(2); + }, + ); - expect(domNode).not.toBeUndefined(); - expect(domNode.className).toBe('react-tabs'); + test('should call domRef with the root on mount and null on unmount', () => { + const domRef = vi.fn(); + const { container, unmount } = render(createTabs({ domRef })); + + expect(domRef).toHaveBeenLastCalledWith(container.firstElementChild); + + unmount(); + + expect(domRef).toHaveBeenLastCalledWith(null); }); }); describe('interaction', () => { + test('skips collection queries for panel events and unused tab keys', () => { + const onClick = vi.fn(); + const onKeyDown = vi.fn(); + const { container } = render( + createTabs({ onClick, onKeyDown, disableUpDownKeys: true }), + ); + const query = vi.spyOn(container.firstElementChild, 'querySelectorAll'); + const panel = screen.getByTestId('panel1'); + const tab = screen.getByTestId('tab1'); + + fireEvent.click(panel); + fireEvent.keyDown(panel, { key: 'ArrowRight' }); + fireEvent.keyDown(tab, { key: 'a' }); + fireEvent.keyDown(tab, { key: 'ArrowDown' }); + + expect(query).not.toHaveBeenCalled(); + expect(onClick).toHaveBeenCalledOnce(); + expect(onKeyDown).toHaveBeenCalledTimes(3); + assertTabSelected(1); + }); + describe('mouse', () => { - test('should update selectedIndex when clicked', async () => { + test('should update selectedKey when clicked', async () => { render(createTabs()); await userEvent.click(screen.getByTestId('tab2')); assertTabSelected(2); }); - test('should update selectedIndex when tab child is clicked', async () => { + test('should update selectedKey when tab child is clicked', async () => { render(createTabs()); await userEvent.click(screen.getByTestId('tab3')); assertTabSelected(3); }); - test('should not change selectedIndex when clicking a disabled tab', async () => { - render(createTabs({ defaultIndex: 0 })); + test('should not change selectedKey when clicking a disabled tab', async () => { + render(createTabs({ defaultKey: 0 })); await userEvent.click(screen.getByTestId('tab4')); assertTabSelected(1); @@ -134,21 +216,27 @@ describe('', () => { describe('keyboard', () => { test('should change focus on tab and tabindex set', async () => { render( - + - + Tab1 - + Tab2 - + Tab3 - Hello Tab1 - Hello Tab2 - Hello Tab3 + + Hello Tab1 + + + Hello Tab2 + + + Hello Tab3 + , ); const element = screen.getByTestId('tab1'); @@ -167,7 +255,7 @@ describe('', () => { assertTabSelected(3); }); - test('should update selectedIndex when arrow right key pressed', async () => { + test('should update selectedKey when arrow right key pressed', async () => { render(createTabs()); const element = screen.getByTestId('tab1'); await userEvent.click(element); @@ -176,6 +264,16 @@ describe('', () => { assertTabSelected(2); }); + test('uses the logical key when it differs from the physical key', () => { + render(createTabs()); + fireEvent.keyDown(screen.getByTestId('tab1'), { + key: 'ArrowRight', + code: 'KeyL', + }); + + assertTabSelected(2); + }); + test('should overflow when arrow right key pressed and no right tab available', async () => { render(createTabs()); const element = screen.getByTestId('tab3'); @@ -187,15 +285,21 @@ describe('', () => { test('should not do anything when arrow right key pressed and no other tab available', async () => { render( - + - Tab1 - + + Tab1 + + Tab2 - Hello Tab1 - Hello Tab2 + + Hello Tab1 + + + Hello Tab2 + , ); const element = screen.getByTestId('tab1'); @@ -216,15 +320,21 @@ describe('', () => { test('should not do anything when arrow left key pressed and no other tab available', async () => { render( - + - + Tab1 - Tab2 + + Tab2 + - Hello Tab1 - Hello Tab2 + + Hello Tab1 + + + Hello Tab2 + , ); const element = screen.getByTestId('tab2'); @@ -252,25 +362,60 @@ describe('', () => { assertTabSelected(3); }); - test('should update selectedIndex when arrow left key pressed (RTL)', async () => { - render(createTabs({ direction: 'rtl' })); - const element = screen.getByTestId('tab1'); - await userEvent.click(element); - await userEvent.type(element, '[ArrowLeft]'); - - assertTabSelected(2); - }); - - test('should update selectedIndex when arrow right key pressed (RTL)', async () => { - render(createTabs({ direction: 'rtl' })); - const element = screen.getByTestId('tab2'); - await userEvent.click(element); - await userEvent.type(element, '[ArrowRight]'); + test.each(['Home', 'End'])( + 'should keep selection on %s when every tab is disabled', + async (key) => { + const onSelect = vi.fn(); + render( + + + + Tab1 + + + Tab2 + + + + Hello Tab1 + + Hello Tab2 + , + ); + + expect(screen.getByTestId('tab1')).toHaveFocus(); + await userEvent.keyboard(`[${key}]`); + + expect(onSelect).not.toHaveBeenCalled(); + assertTabSelected(1); + }, + ); - assertTabSelected(1); - }); + test.each([ + ['the direction prop', { direction: 'rtl' }, undefined], + ['the HTML dir prop', { dir: 'rtl', direction: 'ltr' }, undefined], + ['an inherited dir attribute', {}, 'rtl'], + ['inherited CSS direction', {}, undefined, { direction: 'rtl' }], + ])( + 'reverses horizontal navigation with RTL from %s', + (_, props, dir, style) => { + render( +
      + {/* Happy DOM does not apply HTML direction attributes to computed style. */} + + {createTabs(props)} +
      , + ); + + fireEvent.keyDown(screen.getByTestId('tab1'), { key: 'ArrowLeft' }); + assertTabSelected(2); + + fireEvent.keyDown(screen.getByTestId('tab2'), { key: 'ArrowRight' }); + assertTabSelected(1); + }, + ); - test('should not change selectedIndex when arrow left key pressed on a disabled tab', async () => { + test('should not change selectedKey when arrow left key pressed on a disabled tab', async () => { render(createTabs()); const element = screen.getByTestId('tab4'); await userEvent.click(element); @@ -284,7 +429,7 @@ describe('', () => { describe('performance', () => { test('should only render the selected tab panel', async () => { render(createTabs()); - const tabPanels = screen.getAllByRole('tabpanel'); + const tabPanels = screen.getAllByRole('tabpanel', { hidden: true }); expect(tabPanels[0]).toHaveTextContent('Hello Tab1'); expect(tabPanels[1]).toHaveTextContent(''); @@ -314,36 +459,36 @@ describe('', () => { describe('validation', () => { test('should allow random order for elements', () => { expectToMatchSnapshot( - - Hello Foo + + Hello Foo - Foo - Bar + Foo + Bar - Hello Bar + Hello Bar , ); }); test('should not throw a warning when wrong element is found', () => { expectToMatchSnapshot( - + - +
      - + , ); }); test('should be okay with rendering without any children', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should be okay with rendering just TabList', () => { expectToMatchSnapshot( - + , ); @@ -351,38 +496,40 @@ describe('', () => { test('should gracefully render null', () => { expectToMatchSnapshot( - + - Tab A + Tab A {/* eslint-disable-next-line no-constant-binary-expression*/} - {false && Tab B} + {false && Tab B} - Content A + Content A {/* eslint-disable-next-line no-constant-binary-expression*/} - {false && Content B} + {false && Content B} , ); }); test('should support nested tabs', async () => { render( - + - - + + - + Hello Tab1 - + - - + + - - Hello Tab2 + + + Hello Tab2 + - + , ); @@ -394,22 +541,102 @@ describe('', () => { assertTabSelected(2, within(screen.getByTestId('second'))); }); + test('should preserve the selected key and pairing when tabs reorder independently', async () => { + function renderTabs(labels) { + return ( + + + {labels.map((label) => ( + + {label} + + ))} + + Overview content + Details content + + ); + } + + const { rerender } = render(renderTabs(['Overview', 'Details'])); + const details = screen.getByRole('tab', { name: 'Details' }); + await userEvent.click(details); + const detailsId = details.id; + + rerender(renderTabs(['Details', 'Overview'])); + + const panel = screen.getByRole('tabpanel', { name: 'Details' }); + expect(screen.getByRole('tab', { name: 'Details' })).toBe(details); + expect(details).toHaveAttribute('id', detailsId); + expect(details).toHaveAttribute('aria-selected', 'true'); + expect(details).toHaveAttribute('aria-controls', panel.id); + expect(panel).toHaveTextContent('Details content'); + }); + + test('should give wrapped tabs and panels their state without forwarding hidden props', async () => { + function WrappedTab({ children, itemKey }) { + return ( + + {children} + + ); + } + + function WrappedPanel({ children, itemKey }) { + return ( + + {children} + + ); + } + + render( + + + Overview + Details + + Overview content + Details content + , + ); + + const details = screen.getByRole('tab', { name: 'Details' }); + const panel = screen.getByText('Details content'); + expect(panel).not.toBeVisible(); + expect(panel).not.toHaveClass('active-panel'); + + await userEvent.click(details); + + expect(details).toHaveFocus(); + expect(details).toHaveClass('active-tab'); + expect(details).toHaveAttribute('aria-controls', panel.id); + expect(panel).toBeVisible(); + expect(panel).toHaveClass('active-panel'); + expect(panel).not.toHaveClass('local-panel'); + }); + test('should allow other DOM nodes', () => { expectToMatchSnapshot( - +
      - - + +
      - - + +
      , ); @@ -417,11 +644,13 @@ describe('', () => { }); test('should pass through custom properties', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot( + , + ); }); test('should not add known props to dom', () => { - expectToMatchSnapshot(); + expectToMatchSnapshot(); }); test('should cancel if event handler returns false', async () => { @@ -496,47 +725,47 @@ describe('', () => { test('should allow for higher order components', () => { expectToMatchSnapshot( - + - Foo - Bar + Foo + Bar - Foo - Bar + Foo + Bar , ); }); test('should allow string children', () => { expectToMatchSnapshot( - + Foo Foo - Foo + Foo Foo - Bar + Bar Foo - Bar - Foo + Bar + Foo Foo , ); }); test('should focus the initially selected uncontrolled tab', () => { - render(createTabs({ defaultFocus: true, defaultIndex: 1 })); + render(createTabs({ defaultFocus: true, defaultKey: 1 })); expect(screen.getByTestId('tab2')).toHaveFocus(); }); test('should focus the initially selected controlled tab only on mount', () => { const onSelect = vi.fn(); - const renderTabs = (selectedIndex, defaultFocus) => ( + const renderTabs = (selectedKey, defaultFocus) => ( <> - {createTabs({ defaultFocus, selectedIndex, onSelect })} + {createTabs({ defaultFocus, selectedKey, onSelect })} ); const { rerender } = render(renderTabs(1, true)); @@ -621,16 +850,16 @@ describe('', () => { }); test('should retain tab focus when controlled tabs are inside a fragment', () => { - const renderTabs = (selectedIndex) => ( - {}}> + const renderTabs = (selectedKey) => ( + {}}> <> - First - Second + First + Second - First panel - Second panel + First panel + Second panel ); const { rerender } = render(renderTabs(0)); @@ -642,18 +871,18 @@ describe('', () => { }); test('should preserve outside focus when controlled tabs are inside a fragment', () => { - const renderTabs = (selectedIndex) => ( + const renderTabs = (selectedKey) => ( <> - {}}> + {}}> <> - First - Second + First + Second - First panel - Second panel + First panel + Second panel ); @@ -709,16 +938,24 @@ describe('', () => { }); test('should render first tab once tabs are available', () => { - const { rerender } = render(); + const { rerender } = render(); rerender( - + - Tab1 - Tab2 + + Tab1 + + + Tab2 + - Hello Tab1 - Hello Tab2 + + Hello Tab1 + + + Hello Tab2 + , ); diff --git a/src/components/__tests__/__snapshots__/Tab-test.jsx.snap b/src/components/__tests__/__snapshots__/Tab-test.jsx.snap index 56ffb188b2..0e5e088801 100644 --- a/src/components/__tests__/__snapshots__/Tab-test.jsx.snap +++ b/src/components/__tests__/__snapshots__/Tab-test.jsx.snap @@ -2,12 +2,10 @@ exports[` > override the tabIndex if it was provided 1`] = `