diff --git a/packages/ui-tabs/package.json b/packages/ui-tabs/package.json
index d6f7873787..6a40878a01 100644
--- a/packages/ui-tabs/package.json
+++ b/packages/ui-tabs/package.json
@@ -29,7 +29,6 @@
"@instructure/emotion": "workspace:*",
"@instructure/shared-types": "workspace:*",
"@instructure/ui-dom-utils": "workspace:*",
- "@instructure/ui-focusable": "workspace:*",
"@instructure/ui-i18n": "workspace:*",
"@instructure/ui-motion": "workspace:*",
"@instructure/ui-react-utils": "workspace:*",
diff --git a/packages/ui-tabs/src/Tabs/__tests__/Tab.test.tsx b/packages/ui-tabs/src/Tabs/__tests__/Tab.test.tsx
index 63d58778ca..4e7aaf684e 100644
--- a/packages/ui-tabs/src/Tabs/__tests__/Tab.test.tsx
+++ b/packages/ui-tabs/src/Tabs/__tests__/Tab.test.tsx
@@ -59,7 +59,7 @@ describe('', () => {
)
const tab = page.getByRole('tab').element()
- expect(tab).not.toHaveAttribute('aria-selected')
+ expect(tab).toHaveAttribute('aria-selected', 'false')
expect(tab).not.toHaveAttribute('aria-disabled')
})
@@ -96,7 +96,7 @@ describe('', () => {
expect(tab).toHaveAttribute('tabindex', '0')
})
- it('should not set the tabindex when not selected', async () => {
+ it('should set the tabindex to -1 when not selected', async () => {
await render(
Tab Label
@@ -104,7 +104,7 @@ describe('', () => {
)
const tab = page.getByRole('tab').element()
- expect(tab).not.toHaveAttribute('tabindex')
+ expect(tab).toHaveAttribute('tabindex', '-1')
})
it('should remove the tabindex attribute when disabled', async () => {
diff --git a/packages/ui-tabs/src/Tabs/__tests__/TabsKeyboard.test.tsx b/packages/ui-tabs/src/Tabs/__tests__/TabsKeyboard.test.tsx
new file mode 100644
index 0000000000..3fa94ba711
--- /dev/null
+++ b/packages/ui-tabs/src/Tabs/__tests__/TabsKeyboard.test.tsx
@@ -0,0 +1,220 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2015 - present Instructure, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+import { useState } from 'react'
+import { render } from 'vitest-browser-react'
+import { page, userEvent } from 'vitest/browser'
+import { describe, it, expect, vi } from 'vitest'
+
+import { Tabs as TabsLatest } from '@instructure/ui-tabs/latest'
+import { Tabs as TabsV1 } from '@instructure/ui-tabs/v11_6'
+
+type TabsComponent = typeof TabsLatest
+
+const tabEl = (name: string) => page.getByText(name).element() as HTMLElement
+
+// v1 and v2 differ only in theming, so both have to pass every assertion here.
+function describeKeyboard(name: string, Tabs: TabsComponent) {
+ const Example = (props: {
+ activationMode?: 'auto' | 'manual'
+ onChange?: (index: number) => void
+ }) => {
+ const [selectedIndex, setSelectedIndex] = useState(0)
+ return (
+ {
+ setSelectedIndex(index)
+ props.onChange?.(index)
+ }}
+ >
+
+ Tab 1 content
+
+
+ Tab 2 content
+
+
+ Tab 3 content
+
+
+ Tab 4 content
+
+
+ )
+ }
+
+ describe(` ${name} keyboard navigation`, () => {
+ it('moves focus onto the newly selected tab on each arrow press', async () => {
+ await render()
+
+ tabEl('First Tab').focus()
+
+ await userEvent.keyboard('{ArrowRight}')
+ await vi.waitFor(() => {
+ expect(document.activeElement).toBe(tabEl('Second Tab'))
+ })
+
+ // skips the disabled tab
+ await userEvent.keyboard('{ArrowRight}')
+ await vi.waitFor(() => {
+ expect(document.activeElement).toBe(tabEl('Fourth Tab'))
+ })
+
+ await userEvent.keyboard('{ArrowLeft}')
+ await vi.waitFor(() => {
+ expect(document.activeElement).toBe(tabEl('Second Tab'))
+ })
+ })
+
+ it('gives unselected tabs tabindex="-1" so they can take focus', async () => {
+ await render()
+
+ const second = tabEl('Second Tab')
+
+ expect(tabEl('First Tab')).toHaveAttribute('tabindex', '0')
+ expect(second).toHaveAttribute('tabindex', '-1')
+
+ second.focus()
+ expect(document.activeElement).toBe(second)
+ })
+
+ it('reports aria-selected="false" on unselected tabs', async () => {
+ await render()
+
+ expect(tabEl('First Tab')).toHaveAttribute('aria-selected', 'true')
+ expect(tabEl('Second Tab')).toHaveAttribute('aria-selected', 'false')
+ })
+
+ it('marks the tablist as horizontally oriented', async () => {
+ await render()
+
+ expect(page.getByRole('tablist').element()).toHaveAttribute(
+ 'aria-orientation',
+ 'horizontal'
+ )
+ })
+
+ it('selects the first and last enabled tab with Home and End', async () => {
+ const onChange = vi.fn()
+ await render()
+
+ tabEl('First Tab').focus()
+
+ await userEvent.keyboard('{End}')
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenLastCalledWith(3)
+ expect(document.activeElement).toBe(tabEl('Fourth Tab'))
+ })
+
+ await userEvent.keyboard('{Home}')
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenLastCalledWith(0)
+ expect(document.activeElement).toBe(tabEl('First Tab'))
+ })
+ })
+
+ it('does not warn about Focusable while navigating', async () => {
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ await render()
+
+ tabEl('First Tab').focus()
+ await userEvent.keyboard('{ArrowRight}')
+ await vi.waitFor(() => {
+ expect(document.activeElement).toBe(tabEl('Second Tab'))
+ })
+
+ const focusableWarnings = warnSpy.mock.calls.filter((args) =>
+ /\[Focusable\]/.test(String(args[0]))
+ )
+ warnSpy.mockRestore()
+
+ expect(focusableWarnings).toEqual([])
+ })
+ })
+
+ describe(` ${name} manual activation`, () => {
+ it('moves focus without selecting when arrowing', async () => {
+ const onChange = vi.fn()
+ await render()
+
+ tabEl('First Tab').focus()
+ await userEvent.keyboard('{ArrowRight}')
+
+ await vi.waitFor(() => {
+ expect(document.activeElement).toBe(tabEl('Second Tab'))
+ })
+ expect(onChange).not.toHaveBeenCalled()
+ expect(tabEl('First Tab')).toHaveAttribute('aria-selected', 'true')
+ expect(tabEl('Second Tab')).toHaveAttribute('aria-selected', 'false')
+ })
+
+ it('keeps the roving tabindex on the focused tab, not the selected one', async () => {
+ await render()
+
+ tabEl('First Tab').focus()
+ await userEvent.keyboard('{ArrowRight}')
+
+ await vi.waitFor(() => {
+ expect(tabEl('Second Tab')).toHaveAttribute('tabindex', '0')
+ expect(tabEl('First Tab')).toHaveAttribute('tabindex', '-1')
+ })
+ })
+
+ for (const key of ['{Enter}', '{ }'] as const) {
+ it(`selects the focused tab on ${key}`, async () => {
+ const onChange = vi.fn()
+ await render()
+
+ tabEl('First Tab').focus()
+ await userEvent.keyboard('{ArrowRight}')
+ await vi.waitFor(() => {
+ expect(document.activeElement).toBe(tabEl('Second Tab'))
+ })
+ expect(onChange).not.toHaveBeenCalled()
+
+ await userEvent.keyboard(key)
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith(1)
+ expect(tabEl('Second Tab')).toHaveAttribute('aria-selected', 'true')
+ })
+ })
+ }
+ })
+}
+
+describeKeyboard('v2 (latest)', TabsLatest)
+describeKeyboard('v1 (v11_6)', TabsV1 as unknown as TabsComponent)
diff --git a/packages/ui-tabs/src/Tabs/v1/README.md b/packages/ui-tabs/src/Tabs/v1/README.md
index b05f835a8a..c39c49c3e1 100644
--- a/packages/ui-tabs/src/Tabs/v1/README.md
+++ b/packages/ui-tabs/src/Tabs/v1/README.md
@@ -2,7 +2,7 @@
describes: Tabs
---
-`` is an accessible tabbed navigation component. Use the TAB key to focus the component and arrow keys to navigate between panels of content. To set a default panel that should be selected on initial render, set the `selected` prop on that ``.
+`` is an accessible tabbed navigation component. Use the TAB key to focus the component and arrow keys to navigate between panels of content. Home and End jump to the first and last tab. By default a tab is selected as soon as it is focused; see [Manual activation](#Tabs/#Manual-activation) to require a key press instead. To set a default panel that should be selected on initial render, set the `selected` prop on that ``.
```js
---
@@ -533,6 +533,47 @@ const Example = () => {
render()
```
+### Manual activation
+
+By default (`activationMode="auto"`) a tab is selected the moment an arrow key
+focuses it. Set `activationMode="manual"` to separate the two: arrow keys, Home,
+and End only move focus, and Enter or Space selects the focused tab.
+
+Use manual activation when a panel is slow to load, so a keyboard user can scan
+the tab strip without triggering every panel on the way. It also matters for
+VoiceOver, which keeps the arrow keys for its own cursor and so never delivers
+them to the page — Enter and Space are passed through.
+
+```js
+---
+type: example
+---
+const Example = () => {
+ const [selectedIndex, setSelectedIndex] = useState(0)
+
+ return (
+ setSelectedIndex(index)}
+ >
+
+ Arrow to another tab, then press Enter or Space to open it.
+
+
+ Second panel
+
+
+ Third panel
+
+
+ )
+}
+
+render()
+```
+
### Guidelines
```js
diff --git a/packages/ui-tabs/src/Tabs/v1/Tab/index.tsx b/packages/ui-tabs/src/Tabs/v1/Tab/index.tsx
index 7bcb4b5bd6..c2dfc18721 100644
--- a/packages/ui-tabs/src/Tabs/v1/Tab/index.tsx
+++ b/packages/ui-tabs/src/Tabs/v1/Tab/index.tsx
@@ -93,9 +93,11 @@ class Tab extends Component {
variant,
isSelected,
isDisabled,
+ isFocusable,
controls,
children,
styles,
+ elementRef,
...props
} = this.props
@@ -105,13 +107,14 @@ class Tab extends Component {
as="div"
role="tab"
id={id}
+ elementRef={elementRef}
onClick={this.handleClick}
onKeyDown={this.handleKeyDown}
css={styles?.tab}
- aria-selected={isSelected ? 'true' : undefined}
+ aria-selected={isSelected ? 'true' : 'false'}
aria-disabled={isDisabled ? 'true' : undefined}
aria-controls={controls}
- tabIndex={isSelected && !isDisabled ? 0 : undefined}
+ tabIndex={isDisabled ? undefined : isFocusable ?? isSelected ? 0 : -1}
position="relative"
focusPosition="inset"
>
diff --git a/packages/ui-tabs/src/Tabs/v1/Tab/props.ts b/packages/ui-tabs/src/Tabs/v1/Tab/props.ts
index 4a36510461..6d80933072 100644
--- a/packages/ui-tabs/src/Tabs/v1/Tab/props.ts
+++ b/packages/ui-tabs/src/Tabs/v1/Tab/props.ts
@@ -38,6 +38,11 @@ type TabsTabOwnProps = {
controls: string
isDisabled?: boolean
isSelected?: boolean
+ /**
+ * Whether this tab holds the tablist's roving tabindex. Exactly one tab in a
+ * tablist should have it. Defaults to `isSelected`.
+ */
+ isFocusable?: boolean
onClick?: (
event: React.MouseEvent,
tabData: { index: number; id: string }
@@ -51,6 +56,10 @@ type TabsTabOwnProps = {
* Whether tabOverflow prop in Tabs is set to 'scroll'.
*/
isOverflowScroll?: boolean
+ /**
+ * provides a reference to the underlying html root element
+ */
+ elementRef?: (element: Element | null) => void
}
type PropKeys = keyof TabsTabOwnProps
@@ -70,10 +79,12 @@ const allowedProps: AllowedPropKeys = [
'controls',
'isDisabled',
'isSelected',
+ 'isFocusable',
'onClick',
'onKeyDown',
'children',
- 'isOverflowScroll'
+ 'isOverflowScroll',
+ 'elementRef'
]
export type { TabsTabProps, TabsTabStyle }
diff --git a/packages/ui-tabs/src/Tabs/v1/index.tsx b/packages/ui-tabs/src/Tabs/v1/index.tsx
index a29076a81a..d62e058c59 100644
--- a/packages/ui-tabs/src/Tabs/v1/index.tsx
+++ b/packages/ui-tabs/src/Tabs/v1/index.tsx
@@ -41,7 +41,6 @@ import {
withDeterministicId
} from '@instructure/ui-react-utils'
import { logError as error } from '@instructure/console'
-import { Focusable } from '@instructure/ui-focusable'
import { getBoundingClientRect } from '@instructure/ui-dom-utils'
import type { RectType } from '@instructure/ui-dom-utils'
import { debounce } from '@instructure/debounce'
@@ -81,14 +80,15 @@ class Tabs extends Component {
static defaultProps = {
variant: 'default',
shouldFocusOnRender: false,
- tabOverflow: 'stack'
+ tabOverflow: 'stack',
+ activationMode: 'auto'
}
static Panel = Panel
static Tab = Tab
private _tabList: Element | null = null
- private _focusable: Focusable | null = null
+ private _tabNodes = new Map()
private _tabListPosition?: RectType
private _debounced?: Debounced
private _resizeListener?: ResizeObserver
@@ -255,29 +255,54 @@ class Tabs extends Component {
handleTabClick: TabsTabProps['onClick'] = (event, { index }) => {
const nextTab = this.getNextTab(index, 0)
+
+ if (this.props.activationMode === 'manual') {
+ this.setState({ focusedIndex: nextTab.index })
+ }
this.fireOnChange(event, nextTab)
}
handleTabKeyDown: TabsTabProps['onKeyDown'] = (event, { index }) => {
+ const isManual = this.props.activationMode === 'manual'
let nextTab
- if (
- event.keyCode === keycode.codes.up ||
- event.keyCode === keycode.codes.left
- ) {
- // Select next tab to the left
- nextTab = this.getNextTab(index, -1)
- } else if (
- event.keyCode === keycode.codes.down ||
- event.keyCode === keycode.codes.right
- ) {
- // Select next tab to the right
- nextTab = this.getNextTab(index, 1)
+ switch (event.keyCode) {
+ case keycode.codes.up:
+ case keycode.codes.left:
+ nextTab = this.getNextTab(index, -1)
+ break
+ case keycode.codes.down:
+ case keycode.codes.right:
+ nextTab = this.getNextTab(index, 1)
+ break
+ case keycode.codes.home:
+ nextTab = this.getEdgeTab(1)
+ break
+ case keycode.codes.end:
+ nextTab = this.getEdgeTab(-1)
+ break
+ case keycode.codes.enter:
+ case keycode.codes.space:
+ if (isManual) {
+ event.preventDefault()
+ this.fireOnChange(event, this.getNextTab(index, 0))
+ }
+ return
}
- if (nextTab) {
- event.preventDefault()
+
+ if (!nextTab) {
+ return
+ }
+
+ event.preventDefault()
+
+ if (isManual) {
+ this.setState({ focusedIndex: nextTab.index })
+ } else {
this.fireOnChange(event, nextTab)
}
+
+ this.focusTab(nextTab.index)
}
handleResize = () => {
@@ -289,6 +314,46 @@ class Tabs extends Component {
this._tabListPosition = getBoundingClientRect(this._tabList)
}
+ getPanels(): PanelChild[] {
+ return (Children.toArray(this.props.children) as PanelChild[]).filter(
+ (child) => matchComponentTypes(child, [Panel])
+ )
+ }
+
+ getSelectedIndex() {
+ const index = this.getPanels().findIndex(
+ (child) => child.props.isSelected && !child.props.isDisabled
+ )
+ return index >= 0 ? index : 0
+ }
+
+ // Not just the selected index: in manual mode focus sits on a tab that isn't selected.
+ getRovingIndex() {
+ const panels = this.getPanels()
+ const isEnabled = (index: number) =>
+ index >= 0 && index < panels.length && !panels[index].props.isDisabled
+
+ const { focusedIndex } = this.state
+ if (focusedIndex !== undefined && isEnabled(focusedIndex)) {
+ return focusedIndex
+ }
+
+ const selectedIndex = this.getSelectedIndex()
+ if (isEnabled(selectedIndex)) {
+ return selectedIndex
+ }
+
+ return panels.findIndex((panel) => !panel.props.isDisabled)
+ }
+
+ getEdgeTab(step: -1 | 1) {
+ const panels = this.getPanels()
+ const enabled = panels.filter((panel) => !panel.props.isDisabled)
+ const edge = step > 0 ? enabled[0] : enabled[enabled.length - 1]
+
+ return edge && { index: panels.indexOf(edge), id: edge.props.id }
+ }
+
getNextTab(
startIndex: number,
step: -1 | 0 | 1
@@ -343,7 +408,8 @@ class Tabs extends Component {
index: number,
generatedId: string,
selected: boolean,
- panel: PanelChild
+ panel: PanelChild,
+ isFocusable: boolean
): TabChild {
const id = panel.props.id || generatedId
@@ -356,6 +422,8 @@ class Tabs extends Component {
index={index}
isSelected={selected}
isDisabled={panel.props.isDisabled}
+ isFocusable={isFocusable}
+ elementRef={(el: Element | null) => this.handleTabRef(index, el)}
onClick={this.handleTabClick}
onKeyDown={this.handleTabKeyDown}
isOverflowScroll={this.props.tabOverflow === 'scroll'}
@@ -409,8 +477,12 @@ class Tabs extends Component {
}
}
- handleFocusableRef = (el: Focusable | null) => {
- this._focusable = el
+ handleTabRef = (index: number, el: Element | null) => {
+ if (el) {
+ this._tabNodes.set(index, el as HTMLElement)
+ } else {
+ this._tabNodes.delete(index)
+ }
}
handleTabListRef = (el: Element | null) => {
@@ -418,9 +490,11 @@ class Tabs extends Component {
}
focus() {
- this._focusable &&
- typeof this._focusable.focus === 'function' &&
- this._focusable.focus()
+ this.focusTab(this.getRovingIndex())
+ }
+
+ focusTab(index: number) {
+ this._tabNodes.get(index)?.focus()
}
handleScroll = (
@@ -468,11 +542,8 @@ class Tabs extends Component {
error(false, `[Tabs] Only one Panel can be marked as active.`)
}
- const selectedChildIndex = (Children.toArray(children) as PanelChild[])
- .filter((child) => matchComponentTypes(child, [Panel]))
- .findIndex((child) => child.props.isSelected && !child.props.isDisabled)
-
- const selectedIndex = selectedChildIndex >= 0 ? selectedChildIndex : 0
+ const selectedIndex = this.getSelectedIndex()
+ const rovingIndex = this.getRovingIndex()
Children.toArray(children).map((child, index) => {
if (matchComponentTypes(child, [Panel])) {
const selected =
@@ -480,7 +551,9 @@ class Tabs extends Component {
(child.props.isSelected || selectedIndex === index)
const id = this.props.deterministicId!(`Tabs_${index}`)
- tabs.push(this.createTab(index, id, selected, child))
+ tabs.push(
+ this.createTab(index, id, selected, child, index === rovingIndex)
+ )
if (activePanels.length === 1) {
panels.push(
this.clonePanel(index, id, selected, child, activePanels[0])
@@ -515,30 +588,27 @@ class Tabs extends Component {
css={styles?.container}
data-cid="Tabs"
>
-
- {() => (
-
-
- {tabs}
- {withScrollFade && startScrollOverlay}
- {withScrollFade && endScrollOverlay}
-
-
- )}
-
+
+
+ {tabs}
+ {withScrollFade && startScrollOverlay}
+ {withScrollFade && endScrollOverlay}
+
+
{panels}
diff --git a/packages/ui-tabs/src/Tabs/v1/props.ts b/packages/ui-tabs/src/Tabs/v1/props.ts
index 268b6f0357..c72e235918 100644
--- a/packages/ui-tabs/src/Tabs/v1/props.ts
+++ b/packages/ui-tabs/src/Tabs/v1/props.ts
@@ -78,6 +78,12 @@ type TabsOwnProps = {
*/
tabOverflow?: 'stack' | 'scroll'
shouldFocusOnRender?: boolean
+ /**
+ * With `auto`, arrow keys select a tab as soon as it is focused. With
+ * `manual`, arrow keys only move focus and Enter or Space selects. Screen
+ * readers that keep the arrow keys for their own cursor need `manual`.
+ */
+ activationMode?: 'auto' | 'manual'
}
type PropKeys = keyof TabsOwnProps
@@ -106,6 +112,7 @@ type TabsState = {
withTabListOverflow: boolean
showStartOverLay: boolean
showEndOverLay: boolean
+ focusedIndex?: number
}
const allowedProps: AllowedPropKeys = [
'children',
@@ -121,7 +128,8 @@ const allowedProps: AllowedPropKeys = [
'textAlign',
'elementRef',
'tabOverflow',
- 'shouldFocusOnRender'
+ 'shouldFocusOnRender',
+ 'activationMode'
]
export type { TabsProps, TabsState, TabsStyle }
diff --git a/packages/ui-tabs/src/Tabs/v2/README.md b/packages/ui-tabs/src/Tabs/v2/README.md
index f61197d61a..26b2f3b4be 100644
--- a/packages/ui-tabs/src/Tabs/v2/README.md
+++ b/packages/ui-tabs/src/Tabs/v2/README.md
@@ -2,7 +2,7 @@
describes: Tabs
---
-`` is an accessible tabbed navigation component. Use the TAB key to focus the component and arrow keys to navigate between panels of content. To set a default panel that should be selected on initial render, set the `selected` prop on that ``.
+`` is an accessible tabbed navigation component. Use the TAB key to focus the component and arrow keys to navigate between panels of content. Home and End jump to the first and last tab. By default a tab is selected as soon as it is focused; see [Manual activation](#Tabs/#Manual-activation) to require a key press instead. To set a default panel that should be selected on initial render, set the `selected` prop on that ``.
```js
---
@@ -533,6 +533,47 @@ const Example = () => {
render()
```
+### Manual activation
+
+By default (`activationMode="auto"`) a tab is selected the moment an arrow key
+focuses it. Set `activationMode="manual"` to separate the two: arrow keys, Home,
+and End only move focus, and Enter or Space selects the focused tab.
+
+Use manual activation when a panel is slow to load, so a keyboard user can scan
+the tab strip without triggering every panel on the way. It also matters for
+VoiceOver, which keeps the arrow keys for its own cursor and so never delivers
+them to the page — Enter and Space are passed through.
+
+```js
+---
+type: example
+---
+const Example = () => {
+ const [selectedIndex, setSelectedIndex] = useState(0)
+
+ return (
+ setSelectedIndex(index)}
+ >
+
+ Arrow to another tab, then press Enter or Space to open it.
+
+
+ Second panel
+
+
+ Third panel
+
+
+ )
+}
+
+render()
+```
+
### Guidelines
```js
diff --git a/packages/ui-tabs/src/Tabs/v2/Tab/index.tsx b/packages/ui-tabs/src/Tabs/v2/Tab/index.tsx
index a4086920f4..4b699cdb0b 100644
--- a/packages/ui-tabs/src/Tabs/v2/Tab/index.tsx
+++ b/packages/ui-tabs/src/Tabs/v2/Tab/index.tsx
@@ -92,9 +92,11 @@ class Tab extends Component {
variant,
isSelected,
isDisabled,
+ isFocusable,
controls,
children,
styles,
+ elementRef,
...props
} = this.props
@@ -104,13 +106,14 @@ class Tab extends Component {
as="div"
role="tab"
id={id}
+ elementRef={elementRef}
onClick={this.handleClick}
onKeyDown={this.handleKeyDown}
css={styles?.tab}
- aria-selected={isSelected ? 'true' : undefined}
+ aria-selected={isSelected ? 'true' : 'false'}
aria-disabled={isDisabled ? 'true' : undefined}
aria-controls={controls}
- tabIndex={isSelected && !isDisabled ? 0 : undefined}
+ tabIndex={isDisabled ? undefined : isFocusable ?? isSelected ? 0 : -1}
position="relative"
focusPosition="offset"
>
diff --git a/packages/ui-tabs/src/Tabs/v2/Tab/props.ts b/packages/ui-tabs/src/Tabs/v2/Tab/props.ts
index a3a7fbd780..1b9309d855 100644
--- a/packages/ui-tabs/src/Tabs/v2/Tab/props.ts
+++ b/packages/ui-tabs/src/Tabs/v2/Tab/props.ts
@@ -35,6 +35,11 @@ type TabsTabOwnProps = {
controls: string
isDisabled?: boolean
isSelected?: boolean
+ /**
+ * Whether this tab holds the tablist's roving tabindex. Exactly one tab in a
+ * tablist should have it. Defaults to `isSelected`.
+ */
+ isFocusable?: boolean
onClick?: (
event: React.MouseEvent,
tabData: { index: number; id: string }
@@ -48,6 +53,10 @@ type TabsTabOwnProps = {
* Whether tabOverflow prop in Tabs is set to 'scroll'.
*/
isOverflowScroll?: boolean
+ /**
+ * provides a reference to the underlying html root element
+ */
+ elementRef?: (element: Element | null) => void
}
type PropKeys = keyof TabsTabOwnProps
@@ -67,10 +76,12 @@ const allowedProps: AllowedPropKeys = [
'controls',
'isDisabled',
'isSelected',
+ 'isFocusable',
'onClick',
'onKeyDown',
'children',
- 'isOverflowScroll'
+ 'isOverflowScroll',
+ 'elementRef'
]
export type { TabsTabProps, TabsTabStyle }
diff --git a/packages/ui-tabs/src/Tabs/v2/index.tsx b/packages/ui-tabs/src/Tabs/v2/index.tsx
index ef21375e5c..b3756629b1 100644
--- a/packages/ui-tabs/src/Tabs/v2/index.tsx
+++ b/packages/ui-tabs/src/Tabs/v2/index.tsx
@@ -41,7 +41,6 @@ import {
withDeterministicId
} from '@instructure/ui-react-utils'
import { logError as error } from '@instructure/console'
-import { Focusable } from '@instructure/ui-focusable'
import { getBoundingClientRect } from '@instructure/ui-dom-utils'
import type { RectType } from '@instructure/ui-dom-utils'
import { debounce } from '@instructure/debounce'
@@ -80,14 +79,15 @@ class Tabs extends Component {
static defaultProps = {
variant: 'default',
shouldFocusOnRender: false,
- tabOverflow: 'stack'
+ tabOverflow: 'stack',
+ activationMode: 'auto'
}
static Panel = Panel
static Tab = Tab
private _tabList: Element | null = null
- private _focusable: Focusable | null = null
+ private _tabNodes = new Map()
private _tabListPosition?: RectType
private _debounced?: Debounced
private _resizeListener?: ResizeObserver
@@ -254,29 +254,54 @@ class Tabs extends Component {
handleTabClick: TabsTabProps['onClick'] = (event, { index }) => {
const nextTab = this.getNextTab(index, 0)
+
+ if (this.props.activationMode === 'manual') {
+ this.setState({ focusedIndex: nextTab.index })
+ }
this.fireOnChange(event, nextTab)
}
handleTabKeyDown: TabsTabProps['onKeyDown'] = (event, { index }) => {
+ const isManual = this.props.activationMode === 'manual'
let nextTab
- if (
- event.keyCode === keycode.codes.up ||
- event.keyCode === keycode.codes.left
- ) {
- // Select next tab to the left
- nextTab = this.getNextTab(index, -1)
- } else if (
- event.keyCode === keycode.codes.down ||
- event.keyCode === keycode.codes.right
- ) {
- // Select next tab to the right
- nextTab = this.getNextTab(index, 1)
+ switch (event.keyCode) {
+ case keycode.codes.up:
+ case keycode.codes.left:
+ nextTab = this.getNextTab(index, -1)
+ break
+ case keycode.codes.down:
+ case keycode.codes.right:
+ nextTab = this.getNextTab(index, 1)
+ break
+ case keycode.codes.home:
+ nextTab = this.getEdgeTab(1)
+ break
+ case keycode.codes.end:
+ nextTab = this.getEdgeTab(-1)
+ break
+ case keycode.codes.enter:
+ case keycode.codes.space:
+ if (isManual) {
+ event.preventDefault()
+ this.fireOnChange(event, this.getNextTab(index, 0))
+ }
+ return
}
- if (nextTab) {
- event.preventDefault()
+
+ if (!nextTab) {
+ return
+ }
+
+ event.preventDefault()
+
+ if (isManual) {
+ this.setState({ focusedIndex: nextTab.index })
+ } else {
this.fireOnChange(event, nextTab)
}
+
+ this.focusTab(nextTab.index)
}
handleResize = () => {
@@ -288,6 +313,46 @@ class Tabs extends Component {
this._tabListPosition = getBoundingClientRect(this._tabList)
}
+ getPanels(): PanelChild[] {
+ return (Children.toArray(this.props.children) as PanelChild[]).filter(
+ (child) => matchComponentTypes(child, [Panel])
+ )
+ }
+
+ getSelectedIndex() {
+ const index = this.getPanels().findIndex(
+ (child) => child.props.isSelected && !child.props.isDisabled
+ )
+ return index >= 0 ? index : 0
+ }
+
+ // Not just the selected index: in manual mode focus sits on a tab that isn't selected.
+ getRovingIndex() {
+ const panels = this.getPanels()
+ const isEnabled = (index: number) =>
+ index >= 0 && index < panels.length && !panels[index].props.isDisabled
+
+ const { focusedIndex } = this.state
+ if (focusedIndex !== undefined && isEnabled(focusedIndex)) {
+ return focusedIndex
+ }
+
+ const selectedIndex = this.getSelectedIndex()
+ if (isEnabled(selectedIndex)) {
+ return selectedIndex
+ }
+
+ return panels.findIndex((panel) => !panel.props.isDisabled)
+ }
+
+ getEdgeTab(step: -1 | 1) {
+ const panels = this.getPanels()
+ const enabled = panels.filter((panel) => !panel.props.isDisabled)
+ const edge = step > 0 ? enabled[0] : enabled[enabled.length - 1]
+
+ return edge && { index: panels.indexOf(edge), id: edge.props.id }
+ }
+
getNextTab(
startIndex: number,
step: -1 | 0 | 1
@@ -342,7 +407,8 @@ class Tabs extends Component {
index: number,
generatedId: string,
selected: boolean,
- panel: PanelChild
+ panel: PanelChild,
+ isFocusable: boolean
): TabChild {
const id = panel.props.id || generatedId
@@ -355,6 +421,8 @@ class Tabs extends Component {
index={index}
isSelected={selected}
isDisabled={panel.props.isDisabled}
+ isFocusable={isFocusable}
+ elementRef={(el: Element | null) => this.handleTabRef(index, el)}
onClick={this.handleTabClick}
onKeyDown={this.handleTabKeyDown}
isOverflowScroll={this.props.tabOverflow === 'scroll'}
@@ -408,8 +476,12 @@ class Tabs extends Component {
}
}
- handleFocusableRef = (el: Focusable | null) => {
- this._focusable = el
+ handleTabRef = (index: number, el: Element | null) => {
+ if (el) {
+ this._tabNodes.set(index, el as HTMLElement)
+ } else {
+ this._tabNodes.delete(index)
+ }
}
handleTabListRef = (el: Element | null) => {
@@ -417,9 +489,11 @@ class Tabs extends Component {
}
focus() {
- this._focusable &&
- typeof this._focusable.focus === 'function' &&
- this._focusable.focus()
+ this.focusTab(this.getRovingIndex())
+ }
+
+ focusTab(index: number) {
+ this._tabNodes.get(index)?.focus()
}
handleScroll = (
@@ -467,11 +541,8 @@ class Tabs extends Component {
error(false, `[Tabs] Only one Panel can be marked as active.`)
}
- const selectedChildIndex = (Children.toArray(children) as PanelChild[])
- .filter((child) => matchComponentTypes(child, [Panel]))
- .findIndex((child) => child.props.isSelected && !child.props.isDisabled)
-
- const selectedIndex = selectedChildIndex >= 0 ? selectedChildIndex : 0
+ const selectedIndex = this.getSelectedIndex()
+ const rovingIndex = this.getRovingIndex()
Children.toArray(children).map((child, index) => {
if (matchComponentTypes(child, [Panel])) {
const selected =
@@ -479,7 +550,9 @@ class Tabs extends Component {
(child.props.isSelected || selectedIndex === index)
const id = this.props.deterministicId!(`Tabs_${index}`)
- tabs.push(this.createTab(index, id, selected, child))
+ tabs.push(
+ this.createTab(index, id, selected, child, index === rovingIndex)
+ )
if (activePanels.length === 1) {
panels.push(
this.clonePanel(index, id, selected, child, activePanels[0])
@@ -514,30 +587,27 @@ class Tabs extends Component {
css={styles?.container}
data-cid="Tabs"
>
-
- {() => (
-
-
- {tabs}
- {withScrollFade && startScrollOverlay}
- {withScrollFade && endScrollOverlay}
-
-
- )}
-
+
+
+ {tabs}
+ {withScrollFade && startScrollOverlay}
+ {withScrollFade && endScrollOverlay}
+
+
{panels}
diff --git a/packages/ui-tabs/src/Tabs/v2/props.ts b/packages/ui-tabs/src/Tabs/v2/props.ts
index de3f651e08..ac93f00605 100644
--- a/packages/ui-tabs/src/Tabs/v2/props.ts
+++ b/packages/ui-tabs/src/Tabs/v2/props.ts
@@ -79,6 +79,12 @@ type TabsOwnProps = {
*/
tabOverflow?: 'stack' | 'scroll'
shouldFocusOnRender?: boolean
+ /**
+ * With `auto`, arrow keys select a tab as soon as it is focused. With
+ * `manual`, arrow keys only move focus and Enter or Space selects. Screen
+ * readers that keep the arrow keys for their own cursor need `manual`.
+ */
+ activationMode?: 'auto' | 'manual'
}
type PropKeys = keyof TabsOwnProps
@@ -107,6 +113,7 @@ type TabsState = {
withTabListOverflow: boolean
showStartOverLay: boolean
showEndOverLay: boolean
+ focusedIndex?: number
}
const allowedProps: AllowedPropKeys = [
'children',
@@ -122,7 +129,8 @@ const allowedProps: AllowedPropKeys = [
'textAlign',
'elementRef',
'tabOverflow',
- 'shouldFocusOnRender'
+ 'shouldFocusOnRender',
+ 'activationMode'
]
export type { TabsProps, TabsState, TabsStyle }
diff --git a/packages/ui-tabs/tsconfig.build.json b/packages/ui-tabs/tsconfig.build.json
index cfd027fa96..7abe4abef5 100644
--- a/packages/ui-tabs/tsconfig.build.json
+++ b/packages/ui-tabs/tsconfig.build.json
@@ -16,7 +16,6 @@
{ "path": "../shared-types/tsconfig.build.json" },
{ "path": "../ui-axe-check/tsconfig.build.json" },
{ "path": "../ui-dom-utils/tsconfig.build.json" },
- { "path": "../ui-focusable/tsconfig.build.json" },
{ "path": "../ui-i18n/tsconfig.build.json" },
{ "path": "../ui-motion/tsconfig.build.json" },
{ "path": "../ui-react-utils/tsconfig.build.json" },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f821ddec79..96bfda7fdc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4499,9 +4499,6 @@ importers:
'@instructure/ui-dom-utils':
specifier: workspace:*
version: link:../ui-dom-utils
- '@instructure/ui-focusable':
- specifier: workspace:*
- version: link:../ui-focusable
'@instructure/ui-i18n':
specifier: workspace:*
version: link:../ui-i18n
@@ -7066,7 +7063,7 @@ packages:
optional: true
'@instructure/instructure-design-tokens@https://codeload.github.com/instructure/instructure-design-tokens/tar.gz/ae8f600e8ad4cbadddbaad857f0b6477c4a1e1d6':
- resolution: {gitHosted: true, tarball: https://codeload.github.com/instructure/instructure-design-tokens/tar.gz/ae8f600e8ad4cbadddbaad857f0b6477c4a1e1d6}
+ resolution: {gitHosted: true, integrity: sha512-zGW8VeTKSmXwpBTg+cobqem926UB4YQMtEphYOwifvo/oVxj7UCZ/VbQ2ZHlqPIdYXrLoCzkrLKz4vj0ixflrA==, tarball: https://codeload.github.com/instructure/instructure-design-tokens/tar.gz/ae8f600e8ad4cbadddbaad857f0b6477c4a1e1d6}
version: 1.0.0
'@isaacs/cliui@8.0.2':