Skip to content

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

TypeScript

fix(core): render keyboard hints with Kbd (#3504)

Cindy Zhang3f91ba5bfb27
diff --git a/.changeset/keyboard-hint-kbd.md b/.changeset/keyboard-hint-kbd.md
new file mode 100644
index 0000000000..d0d06756be
--- /dev/null
+++ b/.changeset/keyboard-hint-kbd.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Use Kbd for arrow-key navigation hints and space the hint farther from focused controls so outlines stay visible.
+@cixzhang
diff --git a/packages/core/src/hooks/useKeyboardHint.doc.mjs b/packages/core/src/hooks/useKeyboardHint.doc.mjs
index ff758a7f1c..0c5952da0c 100644
--- a/packages/core/src/hooks/useKeyboardHint.doc.mjs
+++ b/packages/core/src/hooks/useKeyboardHint.doc.mjs
@@ -38,7 +38,7 @@ export const docs = {
{
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.',
+ description: 'The popover hint element to render inside the composite container (as the last child). Portals to the top layer via popover="manual", renders arrow keys with Kbd, and manages its own visibility — render it unconditionally.',
},
{
name: 'onFocus',
@@ -58,7 +58,7 @@ export const docs = {
],
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.',
+ '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 arrow keys with Kbd 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.' },
@@ -75,7 +75,7 @@ export const docs = {
/** @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.',
+ '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. Kbd-rendered arrows in a 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.",
@@ -83,7 +83,7 @@ export const docsDense = {
'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.',
+ hintElement: 'popover hint to render as last child of the container. Kbd-rendered arrows, 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.',
diff --git a/packages/core/src/hooks/useKeyboardHint.test.tsx b/packages/core/src/hooks/useKeyboardHint.test.tsx
new file mode 100644
index 0000000000..762647efe5
--- /dev/null
+++ b/packages/core/src/hooks/useKeyboardHint.test.tsx
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useKeyboardHint.test.tsx
+ * @input Uses React Testing Library, useKeyboardHint
+ * @output Unit tests for keyboard hint rendering
+ */
+
+import {render} from '@testing-library/react';
+import {describe, expect, it} from 'vitest';
+import {useKeyboardHint, type KeyboardHintOrientation} from './useKeyboardHint';
+
+function TestHint({orientation}: {orientation?: KeyboardHintOrientation}) {
+ const {hintElement} = useKeyboardHint({orientation});
+ return <div>{hintElement}</div>;
+}
+
+function getKeyLabels(container: HTMLElement): (string | null)[] {
+ return Array.from(container.querySelectorAll('.astryx-kbd')).map(key =>
+ key.getAttribute('aria-label'),
+ );
+}
+
+function getKeyText(container: HTMLElement): string[] {
+ return Array.from(container.querySelectorAll('kbd')).map(
+ key => key.textContent ?? '',
+ );
+}
+
+describe('useKeyboardHint', () => {
+ it('renders horizontal arrow keys with Kbd', () => {
+ const {container} = render(<TestHint orientation="horizontal" />);
+
+ expect(getKeyLabels(container)).toEqual(['Left arrow', 'Right arrow']);
+ expect(getKeyText(container)).toEqual(['←', '→']);
+ });
+
+ it('renders vertical arrow keys with Kbd', () => {
+ const {container} = render(<TestHint orientation="vertical" />);
+
+ expect(getKeyLabels(container)).toEqual(['Up arrow', 'Down arrow']);
+ expect(getKeyText(container)).toEqual(['↑', '↓']);
+ });
+
+ it('renders all arrow keys for both-axis navigation', () => {
+ const {container} = render(<TestHint orientation="both" />);
+
+ expect(getKeyLabels(container)).toEqual([
+ 'Left arrow',
+ 'Right arrow',
+ 'Up arrow',
+ 'Down arrow',
+ ]);
+ expect(getKeyText(container)).toEqual(['←', '→', '↑', '↓']);
+ });
+
+ it('positions the hint farther from the anchor', () => {
+ const {container} = render(<TestHint />);
+ const hint = container.querySelector('[popover="manual"]') as HTMLElement;
+
+ expect(hint.style.marginBlockStart).toBe('var(--spacing-2)');
+ });
+
+ it('keeps the hint surface padding after useLayer reset styles', () => {
+ const {container} = render(<TestHint />);
+ const hint = container.querySelector('[popover="manual"]') as HTMLElement;
+
+ expect(hint.className).toContain('useKeyboardHint__styles.hint');
+ });
+});
diff --git a/packages/core/src/hooks/useKeyboardHint.tsx b/packages/core/src/hooks/useKeyboardHint.tsx
index 0eaef12b37..89cb85364c 100644
--- a/packages/core/src/hooks/useKeyboardHint.tsx
+++ b/packages/core/src/hooks/useKeyboardHint.tsx
@@ -4,7 +4,7 @@
/**
* @file useKeyboardHint.tsx
- * @input Uses React, StyleX, CSS anchor positioning, Popover API (top layer)
+ * @input Uses React, StyleX, Kbd, useLayer
* @output Exports useKeyboardHint hook — ephemeral arrow-key navigation hint
* @position Core hook; shows sighted keyboard users how to navigate composite
* widgets that use roving tabindex (single Tab stop, arrows inside)
@@ -16,25 +16,17 @@
* - /packages/cli/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
*/
-import React, {
- useCallback,
- useEffect,
- useId,
- useRef,
- useState,
- type ReactNode,
-} from 'react';
+import React, {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
radiusVars,
shadowVars,
spacingVars,
- textSizeVars,
typeScaleVars,
} from '../theme/tokens.stylex';
-import {addAnchorName, removeAnchorName} from '../Layer/anchorName';
-import {mergeProps} from '../utils';
+import {Kbd} from '../Kbd';
+import {useLayer} from '../Layer/useLayer';
// ---------------------------------------------------------------------------
// Types
@@ -101,6 +93,15 @@ export interface UseKeyboardHintReturn {
const ARROW_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);
+const ARROW_HINT_KEYS: Record<
+ KeyboardHintOrientation,
+ ReadonlyArray<string>
+> = {
+ horizontal: ['left', 'right'],
+ vertical: ['up', 'down'],
+ both: ['left', 'right', 'up', 'down'],
+};
+
const styles = stylex.create({
hint: {
// Top layer + anchor positioned
@@ -113,7 +114,10 @@ const styles = stylex.create({
backgroundColor: colorVars['--color-background-popover'],
borderRadius: radiusVars['--radius-element'],
boxShadow: shadowVars['--shadow-low'],
- padding: `${spacingVars['--spacing-1']} ${spacingVars['--spacing-2']}`,
+ paddingBlockStart: spacingVars['--spacing-1'],
+ paddingBlockEnd: spacingVars['--spacing-1'],
+ paddingInlineStart: spacingVars['--spacing-2'],
+ paddingInlineEnd: spacingVars['--spacing-2'],
// Typography
fontSize: typeScaleVars['--text-supporting-size'],
@@ -138,18 +142,8 @@ const styles = stylex.create({
alignItems: 'center',
gap: spacingVars['--spacing-1'],
},
- kbd: {
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- minWidth: '18px',
- height: '18px',
- padding: `0 ${spacingVars['--spacing-0-5']}`,
- borderRadius: radiusVars['--radius-element'],
- backgroundColor: colorVars['--color-background-muted'],
- fontSize: textSizeVars['--font-size-xs'],
- fontFamily: 'inherit',
- lineHeight: typeScaleVars['--text-supporting-leading'],
+ label: {
+ marginInlineStart: spacingVars['--spacing-1'],
},
});
@@ -185,81 +179,69 @@ export function useKeyboardHint(
isEnabled = true,
} = options;
- const id = useId();
- const anchorId = `--astryx-hint-${id.replace(/:/g, '')}`;
- const popoverRef = useRef<HTMLDivElement>(null);
- const dismissedRef = useRef(false);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const anchoredElRef = useRef<HTMLElement | null>(null);
- const [isVisible, setIsVisible] = useState(false);
+ const dismissedRef = useRef(false);
+ const isVisibleRef = useRef(false);
+ const layerAnchorRef = useRef<(el: HTMLElement | null) => void>(() => {});
- // Hide + mark dismissed (won't re-show for this instance)
- const dismiss = useCallback(() => {
- dismissedRef.current = true;
- setIsVisible(false);
+ const clearDismissTimeout = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
- const el = popoverRef.current;
- if (el && typeof el.hidePopover === 'function') {
- try {
- el.hidePopover();
- } catch {
- // already hidden or unsupported
- }
- }
- if (anchoredElRef.current) {
- removeAnchorName(anchoredElRef.current, anchorId);
- anchoredElRef.current = null;
- }
- }, [anchorId]);
+ }, []);
+
+ const handleLayerShow = useCallback(() => {
+ isVisibleRef.current = true;
+ }, []);
+
+ const handleLayerHide = useCallback(() => {
+ isVisibleRef.current = false;
+ clearDismissTimeout();
+ layerAnchorRef.current(null);
+ }, [clearDismissTimeout]);
- // Show the popover (top layer)
+ const layer = useLayer({
+ mode: 'context',
+ onShow: handleLayerShow,
+ onHide: handleLayerHide,
+ });
+ layerAnchorRef.current = layer.ref;
+
+ // Hide + mark dismissed (won't re-show for this instance)
+ const dismiss = useCallback(() => {
+ dismissedRef.current = true;
+ clearDismissTimeout();
+ layer.hide();
+ isVisibleRef.current = false;
+ layerAnchorRef.current(null);
+ }, [clearDismissTimeout, layer]);
+
+ // Show the layer anchored to the focused element
const show = useCallback(
(anchor: HTMLElement) => {
if (dismissedRef.current || !isEnabled) {
return;
}
- // Anchor to the focused element
- if (anchoredElRef.current && anchoredElRef.current !== anchor) {
- removeAnchorName(anchoredElRef.current, anchorId);
- }
- addAnchorName(anchor, anchorId);
- anchoredElRef.current = anchor;
-
- setIsVisible(true);
- const el = popoverRef.current;
- if (el && typeof el.showPopover === 'function') {
- try {
- el.showPopover();
- } catch {
- // already showing or unsupported
- }
- }
- // Auto-dismiss timeout
- if (timeoutRef.current) {
- clearTimeout(timeoutRef.current);
- }
+ layerAnchorRef.current(anchor);
+ layer.show();
+
+ clearDismissTimeout();
timeoutRef.current = setTimeout(() => {
dismiss();
}, dismissAfterMs);
},
- [anchorId, dismiss, dismissAfterMs, isEnabled],
+ [clearDismissTimeout, dismiss, dismissAfterMs, isEnabled, layer],
);
// Cleanup on unmount
useEffect(
() => () => {
- if (timeoutRef.current) {
- clearTimeout(timeoutRef.current);
- }
- if (anchoredElRef.current) {
- removeAnchorName(anchoredElRef.current, anchorId);
- }
+ clearDismissTimeout();
+ layerAnchorRef.current(null);
},
- [anchorId],
+ [clearDismissTimeout],
);
// --- Handlers ---
@@ -289,7 +271,7 @@ export function useKeyboardHint(
const onBlur = useCallback(
(e: React.FocusEvent) => {
- if (!isVisible) {
+ if (!isVisibleRef.current) {
return;
}
const container = e.currentTarget as HTMLElement;
@@ -300,76 +282,50 @@ export function useKeyboardHint(
) {
// Focus moved within — re-anchor to the new target
if (!dismissedRef.current && e.relatedTarget instanceof HTMLElement) {
- if (anchoredElRef.current) {
- removeAnchorName(anchoredElRef.current, anchorId);
- }
- addAnchorName(e.relatedTarget, anchorId);
- anchoredElRef.current = e.relatedTarget;
+ layerAnchorRef.current(e.relatedTarget);
}
return;
}
dismiss();
},
- [isVisible, dismiss, anchorId],
+ [dismiss],
);
const onKeyDown = useCallback(
(e: React.KeyboardEvent) => {
- if (!isVisible) {
+ if (!isVisibleRef.current) {
return;
}
if (ARROW_KEYS.has(e.key)) {
dismiss();
}
},
- [isVisible, dismiss],
+ [dismiss],
);
// --- Render the hint element ---
- const arrowContent =
- orientation === 'vertical' ? (
- <span {...stylex.props(styles.keys)}>
- <kbd {...stylex.props(styles.kbd)}>↑</kbd>
- <kbd {...stylex.props(styles.kbd)}>↓</kbd>
- </span>
- ) : orientation === 'both' ? (
- <span {...stylex.props(styles.keys)}>
- <kbd {...stylex.props(styles.kbd)}>←</kbd>
- <kbd {...stylex.props(styles.kbd)}>→</kbd>
- <kbd {...stylex.props(styles.kbd)}>↑</kbd>
- <kbd {...stylex.props(styles.kbd)}>↓</kbd>
- </span>
- ) : (
- <span {...stylex.props(styles.keys)}>
- <kbd {...stylex.props(styles.kbd)}>←</kbd>
- <kbd {...stylex.props(styles.kbd)}>→</kbd>
- </span>
- );
-
- const hintElement = (
- <div
- ref={popoverRef}
- // Top layer, no light-dismiss (we manage visibility ourselves)
- popover="manual"
- aria-hidden="true"
- {...mergeProps(
- stylex.props(styles.hint),
- undefined,
- // Anchor positioned to the currently-focused item
- {
- positionAnchor: anchorId,
- positionArea: 'block-end span-inline-end',
- positionTryFallbacks:
- 'flip-block, flip-inline, flip-block flip-inline',
- marginBlockStart: spacingVars['--spacing-1'],
- },
- )}>
+ const arrowContent = (
+ <span {...stylex.props(styles.keys)}>
+ {ARROW_HINT_KEYS[orientation].map(key => (
+ <Kbd key={key} keys={key} />
+ ))}
+ </span>
+ );
+
+ const hintElement = layer.render(
+ <span aria-hidden="true">
{arrowContent}
- <span style={{marginInlineStart: spacingVars['--spacing-1']}}>
- to navigate
- </span>
- </div>
+ <span {...stylex.props(styles.label)}>to navigate</span>
+ </span>,
+ {
+ placement: 'below',
+ alignment: 'start',
+ xstyle: styles.hint,
+ style: {
+ marginBlockStart: spacingVars['--spacing-2'],
+ },
+ },
);
return {hintElement, onFocus, onBlur, onKeyDown};