Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): wire useKeyboardHint into Toolbar/TabList/SegmentedControl + showcase (#3501)

Cindy Zhangdeb5aa0e9c1d
diff --git a/.changeset/keyboard-hint-integration.md b/.changeset/keyboard-hint-integration.md
new file mode 100644
index 0000000000..e23ed092ea
--- /dev/null
+++ b/.changeset/keyboard-hint-integration.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Toolbar, TabList, and SegmentedControl now show an ephemeral "← → to navigate" hint on first keyboard focus, teaching sighted users that arrow keys navigate within the group.
+
+Adds a showcase block and Storybook story for useKeyboardHint.
+@cixzhang
diff --git a/apps/storybook/stories/useKeyboardHint.stories.tsx b/apps/storybook/stories/useKeyboardHint.stories.tsx
new file mode 100644
index 0000000000..5c8a1fd8c7
--- /dev/null
+++ b/apps/storybook/stories/useKeyboardHint.stories.tsx
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useCallback, useRef} from 'react';
+import {useKeyboardHint} from '@astryxdesign/core/hooks';
+import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {Section} from '@astryxdesign/core/Section';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Layout';
+
+/**
+ * `useKeyboardHint` shows an ephemeral "← → to navigate" badge the first time a
+ * roving-tabindex composite receives keyboard focus, teaching sighted keyboard
+ * users that arrow keys move within the group.
+ *
+ * **Tab into the widget with the keyboard** to see the hint appear. It
+ * auto-dismisses on the first arrow press, on blur, or after a short timeout,
+ * and does not re-show for that instance. (A mouse click does not trigger it —
+ * the hint only appears on `:focus-visible` entry.)
+ */
+
+// ---------------------------------------------------------------------------
+// A minimal roving-tabindex toolbar built by hand, to show the raw hook wiring.
+// ---------------------------------------------------------------------------
+
+interface HintToolbarProps {
+ label: string;
+ orientation: 'horizontal' | 'vertical';
+ items: string[];
+}
+
+function HintToolbar({label, orientation, items}: HintToolbarProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const hint = useKeyboardHint({orientation});
+
+ const nextKey = orientation === 'vertical' ? 'ArrowDown' : 'ArrowRight';
+ const prevKey = orientation === 'vertical' ? 'ArrowUp' : 'ArrowLeft';
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ const container = containerRef.current;
+ if (!container) {
+ return;
+ }
+ const buttons = Array.from(
+ container.querySelectorAll<HTMLButtonElement>('button'),
+ );
+ const current = buttons.findIndex(b => b === document.activeElement);
+ if (current === -1) {
+ return;
+ }
+ let next: number;
+ if (e.key === nextKey) {
+ next = (current + 1) % buttons.length;
+ } else if (e.key === prevKey) {
+ next = (current - 1 + buttons.length) % buttons.length;
+ } else {
+ return;
+ }
+ e.preventDefault();
+ buttons[current].tabIndex = -1;
+ buttons[next].tabIndex = 0;
+ buttons[next].focus();
+ },
+ [nextKey, prevKey],
+ );
+
+ return (
+ <div
+ ref={containerRef}
+ role="toolbar"
+ aria-label={label}
+ aria-orientation={orientation}
+ onKeyDown={e => {
+ hint.onKeyDown(e);
+ handleKeyDown(e);
+ }}
+ onFocus={hint.onFocus}
+ onBlur={hint.onBlur}
+ style={{
+ display: 'inline-flex',
+ flexDirection: orientation === 'vertical' ? 'column' : 'row',
+ alignItems: orientation === 'vertical' ? 'stretch' : 'center',
+ gap: 4,
+ padding: 8,
+ borderRadius: 8,
+ background: 'var(--color-background-muted)',
+ }}>
+ {items.map((item, i) => (
+ <button
+ key={item}
+ type="button"
+ tabIndex={i === 0 ? 0 : -1}
+ style={{
+ appearance: 'none',
+ border: 'none',
+ borderRadius: 6,
+ padding: '6px 12px',
+ background: 'var(--color-background-popover)',
+ color: 'var(--color-text-primary)',
+ font: 'inherit',
+ textAlign: orientation === 'vertical' ? 'start' : 'center',
+ cursor: 'pointer',
+ }}>
+ {item}
+ </button>
+ ))}
+ {hint.hintElement}
+ </div>
+ );
+}
+
+const meta: Meta = {
+ title: 'Hooks/useKeyboardHint',
+ parameters: {
+ layout: 'centered',
+ },
+};
+
+export default meta;
+type Story = StoryObj;
+
+/**
+ * Tab into the toolbar to reveal the horizontal "← → to navigate" hint.
+ */
+export const Default: Story = {
+ render: () => (
+ <Card padding={4}>
+ <VStack gap={3}>
+ <Text type="body" weight="bold">
+ Formatting
+ </Text>
+ <Text type="supporting" color="secondary">
+ Tab into the toolbar with your keyboard — the hint appears once.
+ </Text>
+ <HintToolbar
+ label="Formatting"
+ orientation="horizontal"
+ items={['Bold', 'Italic', 'Underline']}
+ />
+ </VStack>
+ </Card>
+ ),
+};
+
+/**
+ * A vertical list (e.g. a sidebar nav) shows the "↑ ↓ to navigate" hint.
+ */
+export const Vertical: Story = {
+ render: () => (
+ <Card padding={4}>
+ <VStack gap={3}>
+ <Text type="body" weight="bold">
+ Navigation
+ </Text>
+ <Text type="supporting" color="secondary">
+ Tab into the list — the vertical hint teaches ↑ ↓ navigation.
+ </Text>
+ <HintToolbar
+ label="Sidebar navigation"
+ orientation="vertical"
+ items={['Overview', 'Reports', 'Settings']}
+ />
+ </VStack>
+ </Card>
+ ),
+};
+
+/**
+ * The real `<Toolbar>` component wires `useKeyboardHint` in automatically — no
+ * extra wiring required. Tab into it to see the integrated behavior.
+ */
+export const WithToolbar: Story = {
+ render: () => (
+ <Card style={{width: 420}}>
+ <Toolbar
+ label="Document actions"
+ startContent={
+ <>
+ <Button label="Cut" variant="ghost" />
+ <Button label="Copy" variant="ghost" />
+ <Button label="Paste" variant="ghost" />
+ </>
+ }
+ endContent={<Button label="Settings" variant="ghost" />}
+ />
+ <Section>
+ <Text type="supporting" color="secondary">
+ Tab into the toolbar above — the arrow-key hint appears on first
+ keyboard focus.
+ </Text>
+ </Section>
+ </Card>
+ ),
+};
diff --git a/packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs b/packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs
new file mode 100644
index 0000000000..84fd1b5680
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useKeyboardHint',
+ name: 'useKeyboardHint — Arrow-key Hint',
+ displayName: 'useKeyboardHint — Arrow-key Hint',
+ description:
+ 'Toolbar shows an ephemeral "← → to navigate" hint on first keyboard focus via useKeyboardHint, teaching sighted keyboard users that arrows move within the group.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Toolbar', 'Button', 'Icon', 'Card', 'Section', 'Text', 'Layout'],
+};
diff --git a/packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx b/packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
new file mode 100644
index 0000000000..684017f476
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
@@ -0,0 +1,57 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {Button} from '@astryxdesign/core/Button';
+import {Icon} from '@astryxdesign/core/Icon';
+import {Card} from '@astryxdesign/core/Card';
+import {Section} from '@astryxdesign/core/Section';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Layout';
+import {BoldIcon, ItalicIcon, UnderlineIcon} from '@heroicons/react/24/outline';
+
+export default function UseKeyboardHintHookUsage() {
+ return (
+ <Card style={{width: 420}}>
+ <Toolbar
+ label="Text formatting"
+ dividers={['bottom']}
+ startContent={
+ <>
+ <Button
+ label="Bold"
+ variant="ghost"
+ icon={<Icon icon={BoldIcon} />}
+ isIconOnly
+ />
+ <Button
+ label="Italic"
+ variant="ghost"
+ icon={<Icon icon={ItalicIcon} />}
+ isIconOnly
+ />
+ <Button
+ label="Underline"
+ variant="ghost"
+ icon={<Icon icon={UnderlineIcon} />}
+ isIconOnly
+ />
+ </>
+ }
+ />
+ <Section>
+ <VStack gap={1}>
+ <Text type="body" weight="bold">
+ Keyboard-friendly by default
+ </Text>
+ <Text type="supporting" color="secondary">
+ Tab into the toolbar with your keyboard and Toolbar shows an
+ ephemeral "← → to navigate" hint — powered by useKeyboardHint — so
+ sighted keyboard users learn that arrows move within the group.
+ </Text>
+ </VStack>
+ </Section>
+ </Card>
+ );
+}
diff --git a/packages/core/src/SegmentedControl/SegmentedControl.tsx b/packages/core/src/SegmentedControl/SegmentedControl.tsx
index 59291c0826..ba5044dba4 100644
--- a/packages/core/src/SegmentedControl/SegmentedControl.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControl.tsx
@@ -4,7 +4,7 @@
/**
* @file SegmentedControl.tsx
- * @input Uses React, StyleX, SegmentedControlContext, useListFocus
+ * @input Uses React, StyleX, SegmentedControlContext, useListFocus, useKeyboardHint
* @output Exports SegmentedControl component and SegmentedControlProps type
* @position Container wrapper; provides context to SegmentedControlItem children
*
@@ -20,6 +20,7 @@ import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, radiusVars} from '../theme/tokens.stylex';
import {SegmentedControlContext} from './SegmentedControlContext';
import {useListFocus} from '../hooks/useListFocus';
+import {useKeyboardHint} from '../hooks/useKeyboardHint';
import type {
SegmentedControlSize,
SegmentedControlLayout,
@@ -147,6 +148,19 @@ export function SegmentedControl({
orientation: 'horizontal',
});
+ const hint = useKeyboardHint({
+ orientation: 'horizontal',
+ isEnabled: !isDisabled,
+ });
+
+ const handleContainerKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
+ hint.onKeyDown(e);
+ handleKeyDown(e);
+ },
+ [hint, handleKeyDown],
+ );
+
// Selection-follows-focus (APG radiogroup): useListFocus only *moves* focus,
// so whenever it lands focus on a new radio (arrow/Home/End, or a click) we
// select that radio's value. Reading the focused element's data-value here
@@ -156,6 +170,7 @@ export function SegmentedControl({
// on the current segment) is a no-op, matching click behavior.
const handleContainerFocus = useCallback(
(e: React.FocusEvent) => {
+ hint.onFocus(e);
handleFocus(e);
if (isDisabled) {
return;
@@ -171,7 +186,7 @@ export function SegmentedControl({
onChange(nextValue);
}
},
- [handleFocus, isDisabled, onChange, value],
+ [hint, handleFocus, isDisabled, onChange, value],
);
const contextValue = useMemo(
@@ -186,8 +201,9 @@ export function SegmentedControl({
role="radiogroup"
aria-label={label}
aria-disabled={isDisabled || undefined}
- onKeyDown={handleKeyDown}
+ onKeyDown={handleContainerKeyDown}
onFocus={handleContainerFocus}
+ onBlur={hint.onBlur}
{...mergeProps(
themeProps('segmented-control', {size}),
stylex.props(
@@ -201,6 +217,7 @@ export function SegmentedControl({
style,
)}>
{children}
+ {hint.hintElement}
</div>
</SegmentedControlContext>
);
diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsx
index 5de621dce6..8baec1a68e 100644
--- a/packages/core/src/TabList/TabList.test.tsx
+++ b/packages/core/src/TabList/TabList.test.tsx
@@ -445,6 +445,47 @@ describe('TabList keyboard navigation (roving tabindex)', () => {
await user.keyboard('a');
expect(home).toHaveFocus();
});
+
+ it('composes consumer onKeyDown with internal arrow navigation', async () => {
+ const user = userEvent.setup();
+ const onKeyDown = vi.fn();
+
+ render(
+ <TabList value="home" onChange={() => {}} onKeyDown={onKeyDown}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ const settings = screen.getByRole('button', {name: 'Settings'});
+
+ home.focus();
+ await user.keyboard('{ArrowRight}');
+
+ expect(onKeyDown).toHaveBeenCalled();
+ expect(settings).toHaveFocus();
+ });
+
+ it('respects preventDefault from consumer onKeyDown', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <TabList
+ value="home"
+ onChange={() => {}}
+ onKeyDown={e => e.preventDefault()}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ home.focus();
+ await user.keyboard('{ArrowRight}');
+
+ expect(home).toHaveFocus();
+ });
});
describe('Tab polymorphic link', () => {
diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsx
index 32f1d07e12..a4117f12e3 100644
--- a/packages/core/src/TabList/TabList.tsx
+++ b/packages/core/src/TabList/TabList.tsx
@@ -4,7 +4,7 @@
/**
* @file TabList.tsx
- * @input Uses React, StyleX, TabListContext, useListFocus
+ * @input Uses React, StyleX, TabListContext, useListFocus, useKeyboardHint
* @output Exports TabList component and TabListProps type
* @position Nav wrapper; provides TabListContext to Tab and TabMenu children.
* Owns roving-tabindex keyboard navigation (Arrow/Home/End) across the tab
@@ -17,7 +17,7 @@
* - /packages/cli/templates/blocks/components/TabList/ (showcase blocks)
*/
-import React, {useMemo, type ReactNode} from 'react';
+import React, {useCallback, useMemo, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {borderVars, colorVars, spacingVars} from '../theme/tokens.stylex';
import type {BaseProps} from '../BaseProps';
@@ -26,6 +26,7 @@ import type {TabListOrientation, TabListSize} from './TabListContext';
import {useSize} from '../SizeContext/SizeContext';
import {mergeProps, mergeRefs} from '../utils';
import {useListFocus} from '../hooks/useListFocus';
+import {useKeyboardHint} from '../hooks/useKeyboardHint';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
@@ -125,6 +126,12 @@ export function TabList({
className,
style,
children,
+ onKeyDown: onKeyDownProp,
+ onFocus: onFocusProp,
+ onBlur: onBlurProp,
+ 'aria-label': ariaLabel = 'Tabs',
+ 'aria-orientation': _ariaOrientation,
+ [EDGE_COMP_ATTR]: _edgeCompAttr,
...restProps
}: TabListProps) {
const size = useSize(sizeProp, 'md');
@@ -148,21 +155,64 @@ export function TabList({
hasRovingTabIndex: true,
});
+ const {
+ hintElement,
+ onKeyDown: onHintKeyDown,
+ onFocus: onHintFocus,
+ onBlur: onHintBlur,
+ } = useKeyboardHint({orientation});
+
const contextValue = useMemo(
() => ({value, onChange, size, layout}),
[value, onChange, size, layout],
);
+ const handleRootKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLElement>) => {
+ onKeyDownProp?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ onHintKeyDown(e);
+ handleKeyDown(e);
+ },
+ [onKeyDownProp, onHintKeyDown, handleKeyDown],
+ );
+
+ const handleRootFocus = useCallback(
+ (e: React.FocusEvent<HTMLElement>) => {
+ onFocusProp?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ onHintFocus(e);
+ handleFocus(e);
+ },
+ [onFocusProp, onHintFocus, handleFocus],
+ );
+
+ const handleRootBlur = useCallback(
+ (e: React.FocusEvent<HTMLElement>) => {
+ onBlurProp?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ onHintBlur(e);
+ },
+ [onBlurProp, onHintBlur],
+ );
+
return (
<TabListContext value={contextValue}>
<nav
ref={mergeRefs(ref, listRef)}
- aria-label="Tabs"
+ {...restProps}
+ aria-label={ariaLabel}
aria-orientation={orientation}
- onKeyDown={handleKeyDown}
- onFocus={handleFocus}
+ onKeyDown={handleRootKeyDown}
+ onFocus={handleRootFocus}
+ onBlur={handleRootBlur}
{...{[EDGE_COMP_ATTR]: ''}}
- {...restProps}
{...mergeProps(
themeProps('tab-list', {size}),
stylex.props(
@@ -175,6 +225,7 @@ export function TabList({
style,
)}>
{children}
+ {hintElement}
</nav>
</TabListContext>
);
diff --git a/packages/core/src/Toolbar/Toolbar.test.tsx b/packages/core/src/Toolbar/Toolbar.test.tsx
index 29fff97bd9..da66bbb1a2 100644
--- a/packages/core/src/Toolbar/Toolbar.test.tsx
+++ b/packages/core/src/Toolbar/Toolbar.test.tsx
@@ -71,9 +71,12 @@ describe('Toolbar', () => {
expect(screen.getByTestId('center')).toBeInTheDocument();
expect(screen.getByTestId('end')).toBeInTheDocument();
- // Three-slot layout produces 3 child divs
+ // Three-slot layout produces 3 child divs (plus the aria-hidden
+ // keyboard-hint popover, which is excluded here as an implementation detail)
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.children).toHaveLength(3);
+ expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
+ 3,
+ );
});
it('renders two-slot layout without centerContent', () => {
@@ -87,9 +90,12 @@ describe('Toolbar', () => {
expect(screen.getByTestId('start')).toBeInTheDocument();
expect(screen.getByTestId('end')).toBeInTheDocument();
- // Two-slot layout produces 2 child divs
+ // Two-slot layout produces 2 child divs (plus the aria-hidden
+ // keyboard-hint popover, excluded here)
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.children).toHaveLength(2);
+ expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
+ 2,
+ );
});
it('renders start-only layout', () => {
@@ -101,7 +107,9 @@ describe('Toolbar', () => {
);
expect(screen.getByTestId('start')).toBeInTheDocument();
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.children).toHaveLength(1);
+ expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
+ 1,
+ );
});
it('renders end-only layout', () => {
@@ -113,7 +121,9 @@ describe('Toolbar', () => {
);
expect(screen.getByTestId('end')).toBeInTheDocument();
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.children).toHaveLength(1);
+ expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
+ 1,
+ );
});
it('sets aria-orientation to horizontal by default', () => {
@@ -301,4 +311,52 @@ describe('Toolbar', () => {
// Caret movement stays in the input; focus is not stolen by the toolbar.
expect(document.activeElement).toBe(inputEl);
});
+
+ it('composes consumer onKeyDown with internal arrow navigation', async () => {
+ const user = userEvent.setup();
+ const onKeyDown = vi.fn();
+
+ render(
+ <Toolbar
+ label="Actions"
+ onKeyDown={onKeyDown}
+ startContent={
+ <>
+ <button type="button">Cut</button>
+ <button type="button">Copy</button>
+ </>
+ }
+ />,
+ );
+
+ const buttons = screen.getAllByRole('button');
+ buttons[0].focus();
+ await user.keyboard('{ArrowRight}');
+
+ expect(onKeyDown).toHaveBeenCalled();
+ expect(buttons[1]).toHaveFocus();
+ });
+
+ it('respects preventDefault from consumer onKeyDown', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <Toolbar
+ label="Actions"
+ onKeyDown={e => e.preventDefault()}
+ startContent={
+ <>
+ <button type="button">Cut</button>
+ <button type="button">Copy</button>
+ </>
+ }
+ />,
+ );
+
+ const buttons = screen.getAllByRole('button');
+ buttons[0].focus();
+ await user.keyboard('{ArrowRight}');
+
+ expect(buttons[0]).toHaveFocus();
+ });
});
diff --git a/packages/core/src/Toolbar/Toolbar.tsx b/packages/core/src/Toolbar/Toolbar.tsx
index e0da92ee85..c62d2e82fd 100644
--- a/packages/core/src/Toolbar/Toolbar.tsx
+++ b/packages/core/src/Toolbar/Toolbar.tsx
@@ -4,7 +4,7 @@
/**
* @file Toolbar.tsx
- * @input Uses Section, SizeContext, useListFocus, StyleX, spacingVars, sizeVars
+ * @input Uses Section, SizeContext, useListFocus, useKeyboardHint, StyleX, spacingVars, sizeVars
* @output Exports Toolbar component and ToolbarProps
* @position Core implementation; consumed by index.ts
*
@@ -16,7 +16,7 @@
* - /packages/cli/templates/blocks/components/Toolbar/ (showcase blocks)
*/
-import type {ReactNode} from 'react';
+import {useCallback, type ReactNode} from 'react';
import type {BaseProps} from '../BaseProps';
import type {SectionVariant} from '../Section/Section';
import type {SpacingStep} from '../utils/types';
@@ -26,6 +26,7 @@ import {spacingVars, sizeVars} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
import {Section} from '../Section/Section';
import {useListFocus} from '../hooks/useListFocus';
+import {useKeyboardHint} from '../hooks/useKeyboardHint';
import {SizeProvider} from '../SizeContext/SizeContext';
import {edgeCompSlot} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
@@ -227,6 +228,12 @@ export function Toolbar({
className,
style,
ref,
+ onKeyDown: onKeyDownProp,
+ onFocus: onFocusProp,
+ onBlur: onBlurProp,
+ role: _role,
+ 'aria-label': _ariaLabel,
+ 'aria-orientation': _ariaOrientation,
...props
}: ToolbarProps) {
const hasCenterContent = centerContent != null;
@@ -242,6 +249,48 @@ export function Toolbar({
hasCaretGuard: true,
});
+ const {
+ hintElement,
+ onKeyDown: onHintKeyDown,
+ onFocus: onHintFocus,
+ onBlur: onHintBlur,
+ } = useKeyboardHint({orientation});
+
+ const handleToolbarKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
+ onKeyDownProp?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ onHintKeyDown(e);
+ handleKeyDown(e);
+ },
+ [onKeyDownProp, onHintKeyDown, handleKeyDown],
+ );
+
+ const handleToolbarFocus = useCallback(
+ (e: React.FocusEvent<HTMLDivElement>) => {
+ onFocusProp?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ onHintFocus(e);
+ handleFocus(e);
+ },
+ [onFocusProp, onHintFocus, handleFocus],
+ );
+
+ const handleToolbarBlur = useCallback(
+ (e: React.FocusEvent<HTMLDivElement>) => {
+ onBlurProp?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ onHintBlur(e);
+ },
+ [onBlurProp, onHintBlur],
+ );
+
return (
<SizeProvider value={size}>
<Section
@@ -257,8 +306,9 @@ export function Toolbar({
role="toolbar"
aria-label={label}
aria-orientation={orientation}
- onKeyDown={handleKeyDown}
- onFocus={handleFocus}
+ onKeyDown={handleToolbarKeyDown}
+ onFocus={handleToolbarFocus}
+ onBlur={handleToolbarBlur}
{...mergeProps(
themeProps('toolbar', {size}),
stylex.props(
@@ -323,6 +373,7 @@ export function Toolbar({
)}
</>
)}
+ {hintElement}
</div>
</Section>
</SizeProvider>
diff --git a/packages/core/src/hooks/useKeyboardHint.doc.mjs b/packages/core/src/hooks/useKeyboardHint.doc.mjs
new file mode 100644
index 0000000000..ff758a7f1c
--- /dev/null
+++ b/packages/core/src/hooks/useKeyboardHint.doc.mjs
@@ -0,0 +1,101 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').HookDoc} */
+export const docs = {
+ name: 'useKeyboardHint',
+ displayName: 'useKeyboardHint',
+ keywords: ['keyboard', 'hint', 'arrow', 'navigation', 'roving', 'tabindex', 'focus', 'discoverability', 'toolbar', 'tabs', 'segmented', 'affordance', 'a11y'],
+ params: [
+ {
+ name: 'options',
+ type: 'UseKeyboardHintOptions',
+ description: 'Configuration object for the keyboard hint.',
+ required: false,
+ },
+ {
+ name: 'options.orientation',
+ type: "'horizontal' | 'vertical' | 'both'",
+ description: 'Which arrow-key axis the composite navigates, controlling which arrow icons the hint shows (← → for horizontal, ↑ ↓ for vertical, all four for both).',
+ default: "'horizontal'",
+ required: false,
+ },
+ {
+ name: 'options.dismissAfterMs',
+ type: 'number',
+ description: 'Milliseconds before the hint auto-dismisses after appearing.',
+ default: '3000',
+ required: false,
+ },
+ {
+ name: 'options.isEnabled',
+ type: 'boolean',
+ description: 'Whether the hint is enabled. Set to false to suppress it for a specific instance (e.g. a disabled or read-only widget).',
+ default: 'true',
+ required: false,
+ },
+ ],
+ returns: [
+ {
+ name: 'hintElement',
+ type: 'ReactNode',
+ description: 'The popover hint element to render inside the composite container (as the last child). Portals to the top layer via popover="manual" and manages its own visibility — render it unconditionally.',
+ },
+ {
+ name: 'onFocus',
+ type: '(e: React.FocusEvent) => void',
+ description: 'Attach to the container onFocus. Shows the hint on the first keyboard-focus (:focus-visible) entry from outside the composite.',
+ },
+ {
+ name: 'onBlur',
+ type: '(e: React.FocusEvent) => void',
+ description: 'Attach to the container onBlur. Hides the hint when focus leaves the composite entirely, and re-anchors when focus moves within.',
+ },
+ {
+ name: 'onKeyDown',
+ type: '(e: React.KeyboardEvent) => void',
+ description: 'Attach to the container onKeyDown. Dismisses the hint on the first arrow press (the user has discovered the interaction). Never prevents default or stops propagation.',
+ },
+ ],
+ usage: {
+ description:
+ 'Shows an ephemeral "← → to navigate" hint anchored to the focused item the first time a roving-tabindex composite (Toolbar, TabList, SegmentedControl, etc.) receives keyboard focus. It teaches sighted keyboard users that arrow keys move within the group. The hint renders in the top layer (popover="manual") and is CSS-anchor-positioned to the focused element, so overflow containers never clip it. It auto-dismisses on the first arrow press, on timeout, or on blur, and does not re-show for that instance. Toolbar, TabList, and SegmentedControl wire this in automatically — reach for the hook directly only when building a custom roving-tabindex widget.',
+ bestPractices: [
+ { guidance: true, description: 'Compose the returned onFocus/onKeyDown with your existing focus handlers rather than replacing them — call onKeyDown first (it only dismisses, never prevents), then your navigation handler.' },
+ { guidance: true, description: 'Render hintElement as the last child of the composite container; it is position:fixed in the top layer and aria-hidden, so it never affects layout or the accessibility tree.' },
+ { guidance: true, description: 'Match orientation to the arrow keys your widget actually responds to so the hint shows the correct icons.' },
+ { guidance: false, description: 'Use for single controls or widgets without roving-tabindex navigation — the hint only makes sense where arrows move focus within a group.' },
+ ],
+ },
+ relatedComponents: ['Toolbar', 'TabList', 'SegmentedControl'],
+ relatedHooks: ['useListFocus', 'useGridFocus', 'useTreeFocus'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'focus',
+};
+
+/** @type {import('../docs-types').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Ephemeral "← → to navigate" hint anchored to the focused item on first keyboard focus of a roving-tabindex composite (Toolbar/TabList/SegmentedControl). Teaches sighted keyboard users that arrows move within the group. Top-layer popover="manual", CSS-anchor-positioned (never clipped by overflow), aria-hidden. Auto-dismisses on first arrow press, timeout, or blur; never re-shows for that instance.',
+ paramDescriptions: {
+ options: 'config for the keyboard hint.',
+ 'options.orientation': "arrow axis: 'horizontal' (← →), 'vertical' (↑ ↓), 'both' (all four). Controls shown icons.",
+ 'options.dismissAfterMs': 'ms before auto-dismiss after appearing.',
+ 'options.isEnabled': 'whether the hint is enabled; false suppresses it (e.g. disabled/read-only widget).',
+ },
+ returnDescriptions: {
+ hintElement: 'popover hint to render as last child of the container. Top-layer, self-managing — render unconditionally.',
+ onFocus: 'container onFocus: shows hint on first :focus-visible entry from outside.',
+ onBlur: 'container onBlur: hides on leaving the composite; re-anchors on internal moves.',
+ onKeyDown: 'container onKeyDown: dismisses on first arrow press. Never prevents default.',
+ },
+ usage: {
+ description:
+ 'Ephemeral "← → to navigate" hint on first keyboard focus of a roving-tabindex composite. Top-layer anchored popover, aria-hidden. Auto-dismisses on first arrow press, timeout, or blur; no re-show. Toolbar/TabList/SegmentedControl wire it in automatically.',
+ bestPractices: [
+ { guidance: true, description: 'Compose returned onFocus/onKeyDown with existing handlers (call onKeyDown first — it only dismisses).' },
+ { guidance: true, description: 'Render hintElement as last child; top-layer + aria-hidden, no layout/a11y impact.' },
+ { guidance: true, description: 'Match orientation to the arrows the widget responds to.' },
+ { guidance: false, description: 'Use for single controls / non-roving widgets.' },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useKeyboardHint.tsx b/packages/core/src/hooks/useKeyboardHint.tsx
index 7730107f02..0eaef12b37 100644
--- a/packages/core/src/hooks/useKeyboardHint.tsx
+++ b/packages/core/src/hooks/useKeyboardHint.tsx
@@ -11,6 +11,9 @@
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
+ * - /packages/core/src/hooks/useKeyboardHint.doc.mjs
+ * - /apps/storybook/stories/useKeyboardHint.stories.tsx
+ * - /packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
*/
import React, {