Skip to content

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

TypeScript

docs(useKeyboardHint): call the hook directly in a star rating example (#9575)

홍규진09ea8afb28b0
diff --git a/.changeset/use-keyboard-hint-star-rating-example.md b/.changeset/use-keyboard-hint-star-rating-example.md
new file mode 100644
index 0000000000..965508de82
--- /dev/null
+++ b/.changeset/use-keyboard-hint-star-rating-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] The `useKeyboardHint — Arrow-key Hint` example block now calls `useKeyboardHint` itself instead of relying on Toolbar, which calls the hook internally. It is a five-star rating with one Tab stop, where Left and Right change the rating: tabbing into it shows the "← → to navigate" hint, the first arrow press dismisses it, and tabbing back in does not show it again. Copy it with `astryx template useKeyboardHintHookUsage <path>`.
+
+@kyu-rong
diff --git a/packages/cli/api/template/use-keyboard-hint-hook-usage.test.tsx b/packages/cli/api/template/use-keyboard-hint-hook-usage.test.tsx
new file mode 100644
index 0000000000..46f7f0862c
--- /dev/null
+++ b/packages/cli/api/template/use-keyboard-hint-hook-usage.test.tsx
@@ -0,0 +1,159 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useKeyboardHint example is a star rating that calls the hook itself:
+ * keyboard focus entering the stars shows the arrow-key hint once, the first
+ * arrow press dismisses it, and coming back does not show it again.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseKeyboardHintHookUsage from '../../assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+let outside: HTMLButtonElement;
+const showPopover = vi.fn();
+const hidePopover = vi.fn();
+const {showPopover: originalShow, hidePopover: originalHide} =
+ HTMLElement.prototype;
+
+function renderExample(): void {
+ outside = document.createElement('button');
+ document.body.appendChild(outside);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseKeyboardHintHookUsage />);
+ });
+}
+
+function stars(): HTMLButtonElement[] {
+ return Array.from(
+ container.querySelectorAll<HTMLButtonElement>('[role="radio"]'),
+ );
+}
+
+function focus(element: HTMLElement): void {
+ act(() => element.focus());
+}
+
+function pressKey(key: string, init: KeyboardEventInit = {}): boolean {
+ let isPrevented = false;
+ act(() => {
+ const event = new KeyboardEvent('keydown', {
+ key,
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ });
+ document.activeElement?.dispatchEvent(event);
+ isPrevented = event.defaultPrevented;
+ });
+ return isPrevented;
+}
+
+function checkedStar(): number {
+ return stars().findIndex(
+ star => star.getAttribute('aria-checked') === 'true',
+ );
+}
+
+beforeEach(() => {
+ // jsdom has no Popover API; treat every focus as keyboard focus and record
+ // the hint's show and hide.
+ const matches = HTMLElement.prototype.matches;
+ vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function (
+ this: HTMLElement,
+ selector: string,
+ ) {
+ return selector === ':focus-visible' ? true : matches.call(this, selector);
+ });
+ HTMLElement.prototype.showPopover = showPopover;
+ HTMLElement.prototype.hidePopover = hidePopover;
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ outside.remove();
+ vi.restoreAllMocks();
+ HTMLElement.prototype.showPopover = originalShow;
+ HTMLElement.prototype.hidePopover = originalHide;
+ showPopover.mockReset();
+ hidePopover.mockReset();
+});
+
+describe('useKeyboardHint example', () => {
+ it('shows the arrow-key hint when keyboard focus enters the stars', () => {
+ renderExample();
+ const hint = container.querySelector('[popover="manual"]');
+ expect(hint?.textContent).toContain('to navigate');
+
+ focus(stars()[0]);
+ expect(showPopover).toHaveBeenCalledTimes(1);
+ });
+
+ it('dismisses the hint on the first arrow press and does not show it again', () => {
+ renderExample();
+ focus(stars()[0]);
+ pressKey('ArrowRight');
+ expect(hidePopover).toHaveBeenCalledTimes(1);
+ expect(stars()[1]).toBe(document.activeElement);
+ expect(stars()[1].getAttribute('aria-checked')).toBe('true');
+
+ focus(outside);
+ focus(stars()[1]);
+ expect(showPopover).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops at both ends instead of wrapping, and the rating follows focus', () => {
+ renderExample();
+ focus(stars()[0]);
+ for (let i = 0; i < 6; i++) {
+ pressKey('ArrowRight');
+ }
+ expect(stars()[4]).toBe(document.activeElement);
+ expect(checkedStar()).toBe(4);
+
+ for (let i = 0; i < 6; i++) {
+ pressKey('ArrowLeft');
+ }
+ expect(stars()[0]).toBe(document.activeElement);
+ expect(checkedStar()).toBe(0);
+ });
+
+ it('keeps one Tab stop on the checked star', () => {
+ renderExample();
+ focus(stars()[0]);
+ pressKey('ArrowRight');
+ pressKey('ArrowRight');
+ expect(stars().map(star => star.tabIndex)).toEqual([-1, -1, 0, -1, -1]);
+ });
+
+ it('follows the arrows visually in right-to-left', () => {
+ renderExample();
+ container.querySelector<HTMLElement>(
+ '[role="radiogroup"]',
+ )!.style.direction = 'rtl';
+ focus(stars()[0]);
+ pressKey('ArrowLeft');
+ expect(stars()[1]).toBe(document.activeElement);
+ expect(checkedStar()).toBe(1);
+ });
+
+ it('leaves an arrow pressed with a modifier to the browser', () => {
+ renderExample();
+ focus(stars()[0]);
+ expect(pressKey('ArrowRight', {altKey: true})).toBe(false);
+ expect(stars()[0]).toBe(document.activeElement);
+ expect(checkedStar()).toBe(-1);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs
index 6117da3e4b..e5e013489c 100644
--- a/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs
@@ -7,17 +7,9 @@ export const doc = {
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.',
+ 'A custom five-star rating with one Tab stop calls useKeyboardHint directly: tabbing into it shows a "← → to navigate" hint, the first arrow press dismisses it, and tabbing back in does not show it again.',
isReady: true,
aspectRatio: 16 / 9,
- componentsUsed: [
- 'Toolbar',
- 'Button',
- 'Icon',
- 'Card',
- 'Section',
- 'Text',
- 'Layout',
- ],
- icons: {BoldIcon: 'bold', ItalicIcon: 'italic', UnderlineIcon: 'underline'},
+ componentsUsed: ['Button', 'Icon', 'Card', 'Layout'],
+ icons: {StarIcon: 'star'},
};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
index 684017f476..3f37bb8456 100644
--- a/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx
@@ -2,56 +2,71 @@
'use client';
-import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {useState, type KeyboardEvent} from 'react';
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';
+import {useKeyboardHint, useListFocus} from '@astryxdesign/core/hooks';
+import {Icon} from '@astryxdesign/core/Icon';
+import {HStack} from '@astryxdesign/core/Layout';
+import {StarIcon as StarOutline} from '@heroicons/react/24/outline';
+import {StarIcon as StarSolid} from '@heroicons/react/24/solid';
+
+const STARS = [1, 2, 3, 4, 5];
export default function UseKeyboardHintHookUsage() {
+ const [rating, setRating] = useState(0);
+ // Left and Right move the rating, so the hint shows ← →.
+ const hint = useKeyboardHint({orientation: 'horizontal'});
+ // Moves focus between the stars, right-to-left aware and stopping at the
+ // ends; the tab stop stays with the checked star below.
+ const list = useListFocus<HTMLElement>({
+ itemSelector: '[role="radio"]',
+ orientation: 'horizontal',
+ wrap: false,
+ hasHomeEnd: false,
+ });
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLElement>) => {
+ // Dismisses the hint on the first arrow press; never prevents the key.
+ hint.onKeyDown(e);
+ list.handleKeyDown(e);
+ // The hook prevents the arrows it handled, so the rating follows focus.
+ if (
+ (e.key === 'ArrowLeft' || e.key === 'ArrowRight') &&
+ e.defaultPrevented
+ ) {
+ setRating(
+ list.getItems().indexOf(document.activeElement as HTMLElement) + 1,
+ );
+ }
+ };
+
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 padding={4}>
+ <HStack
+ ref={list.listRef}
+ gap={1}
+ role="radiogroup"
+ aria-label="Rating"
+ onFocus={hint.onFocus}
+ onBlur={hint.onBlur}
+ onKeyDown={handleKeyDown}>
+ {STARS.map(star => (
+ <Button
+ key={star}
+ role="radio"
+ aria-checked={star === rating}
+ // One Tab stop: the checked star, or the first while unrated.
+ tabIndex={star === Math.max(rating, 1) ? 0 : -1}
+ label={star === 1 ? '1 star' : `${star} stars`}
+ variant="ghost"
+ isIconOnly
+ icon={<Icon icon={star <= rating ? StarSolid : StarOutline} />}
+ onClick={() => setRating(star)}
+ />
+ ))}
+ {hint.hintElement}
+ </HStack>
</Card>
);
}