Skip to content

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

TypeScript

docs(useTreeFocus): add a keyboard file tree example block (#9617)

Parman Mohammadalizadeh8c2262460c86
diff --git a/.changeset/use-tree-focus-file-tree-example.md b/.changeset/use-tree-focus-file-tree-example.md
new file mode 100644
index 0000000000..bcde41e3ce
--- /dev/null
+++ b/.changeset/use-tree-focus-file-tree-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useTreeFocus — Keyboard File Tree` example block builds a small file tree from plain rows with tree roles and gives it the WAI-ARIA tree keyboard model with `useTreeFocus`: arrow keys move over the visible rows and open, enter, leave or close folders, Home and End jump to the ends, a typed letter jumps to a matching name, Enter opens a file, and one row is the tab stop. Copy it with `astryx template useTreeFocusHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 13dc6d44a8..31429a43af 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -802,6 +802,7 @@
"/templates/useThemeHookUsage/",
"/templates/useToastHookUsage/",
"/templates/useTranslatorHookUsage/",
+ "/templates/useTreeFocusHookUsage/",
"/templates/useTypeaheadHookUsage/",
"/templates/work-item-detail/",
"/themes/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index e846289e3d..de79a4c914 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3811,6 +3811,11 @@
"path": "examples/use-translator/load-more-footer",
"aliases": []
},
+ {
+ "name": "example-use-tree-focus-keyboard-file-tree",
+ "path": "examples/use-tree-focus/keyboard-file-tree",
+ "aliases": []
+ },
{
"name": "example-use-typeahead-type-to-focus-a-country",
"path": "examples/use-typeahead/type-to-focus-a-country",
diff --git a/packages/cli/api/template/use-tree-focus-hook-usage.test.tsx b/packages/cli/api/template/use-tree-focus-hook-usage.test.tsx
new file mode 100644
index 0000000000..0c5b81c354
--- /dev/null
+++ b/packages/cli/api/template/use-tree-focus-hook-usage.test.tsx
@@ -0,0 +1,120 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useTreeFocus example is a file tree with the WAI-ARIA tree keyboard
+ * model: arrows move over the visible rows and open or close folders, Home and
+ * End jump to the ends, a typed letter jumps to a name, Enter opens a file,
+ * and only one row is in the tab order.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseTreeFocusHookUsage from '../../assets/templates/blocks/components/Hooks/useTreeFocusHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+function rows(): HTMLElement[] {
+ return Array.from(container.querySelectorAll('[role="treeitem"]'));
+}
+
+function row(name: string): HTMLElement {
+ const match = rows().find(candidate => candidate.textContent === name);
+ if (match == null) {
+ throw new Error(`no "${name}" row rendered`);
+ }
+ return match;
+}
+
+function focused(): string | null | undefined {
+ return document.activeElement?.textContent;
+}
+
+function press(key: string): void {
+ act(() => {
+ document.activeElement?.dispatchEvent(
+ new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true}),
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseTreeFocusHookUsage />);
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe('useTreeFocus example', () => {
+ it('keeps one row in the tab order and moves it with focus', () => {
+ expect(rows().filter(item => item.tabIndex === 0)).toEqual([row('src')]);
+
+ act(() => row('src').focus());
+ press('ArrowDown');
+
+ expect(focused()).toBe('index.ts');
+ expect(rows().filter(item => item.tabIndex === 0)).toEqual([
+ row('index.ts'),
+ ]);
+ });
+
+ it('moves over the visible rows with ArrowUp, ArrowDown, Home and End', () => {
+ act(() => row('src').focus());
+ press('End');
+ expect(focused()).toBe('README.md');
+ press('ArrowUp');
+ expect(focused()).toBe('package.json');
+ press('ArrowUp');
+ expect(focused()).toBe('docs');
+ press('Home');
+ expect(focused()).toBe('src');
+ });
+
+ it('opens, enters, leaves and closes a folder with ArrowRight and ArrowLeft', () => {
+ act(() => row('docs').focus());
+ press('ArrowRight');
+ expect(row('docs').getAttribute('aria-expanded')).toBe('true');
+ expect(focused()).toBe('docs');
+
+ press('ArrowRight');
+ expect(focused()).toBe('intro.md');
+
+ press('ArrowLeft');
+ expect(focused()).toBe('docs');
+
+ press('ArrowLeft');
+ expect(row('docs').getAttribute('aria-expanded')).toBe('false');
+ expect(rows().map(item => item.textContent)).not.toContain('intro.md');
+ });
+
+ it('jumps to a name that starts with the typed letter', () => {
+ vi.useFakeTimers();
+ act(() => row('src').focus());
+ press('r');
+ expect(focused()).toBe('README.md');
+ act(() => vi.advanceTimersByTime(500));
+ press('t');
+ expect(focused()).toBe('theme.ts');
+ });
+
+ it('opens a file on Enter', () => {
+ act(() => row('src').focus());
+ press('p');
+ press('Enter');
+ expect(container.textContent).toContain('Open file: package.json');
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.doc.mjs
new file mode 100644
index 0000000000..ee9416e401
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.doc.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useTreeFocus',
+ name: 'useTreeFocus — Keyboard File Tree',
+ displayName: 'useTreeFocus — Keyboard File Tree',
+ description:
+ 'A custom file tree built from plain rows with tree roles. useTreeFocus gives it the WAI-ARIA tree keyboard model: ArrowUp and ArrowDown move over the visible rows, ArrowRight opens a folder or moves into it, ArrowLeft closes it or moves to its parent, Home and End jump to the ends, a typed letter jumps to a matching name, Enter opens a file, and only one row is in the tab order.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Icon', 'Text', 'Layout'],
+ icons: {ChevronDownIcon: 'chevronDown', ChevronRightIcon: 'chevronRight'},
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.tsx
new file mode 100644
index 0000000000..1b8f3440ec
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.tsx
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {useTreeFocus} from '@astryxdesign/core/hooks';
+import {Icon} from '@astryxdesign/core/Icon';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+import {rtlStyles} from '@astryxdesign/core/utils';
+import {ChevronDownIcon, ChevronRightIcon} from '@heroicons/react/24/outline';
+
+type FileNode = {name: string; children?: FileNode[]};
+
+const FILES: FileNode[] = [
+ {name: 'src', children: [{name: 'index.ts'}, {name: 'theme.ts'}]},
+ {name: 'docs', children: [{name: 'intro.md'}, {name: 'usage.md'}]},
+ {name: 'package.json'},
+ {name: 'README.md'},
+];
+
+const FOLDERS = new Set(
+ FILES.filter(node => node.children != null).map(node => node.name),
+);
+
+export default function UseTreeFocusHookUsage() {
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(
+ () => new Set(['src']),
+ );
+ const [openFile, setOpenFile] = useState<string | null>(null);
+ const toggle = (name: string) =>
+ setExpanded(current => {
+ const next = new Set(current);
+ if (!next.delete(name)) {
+ next.add(name);
+ }
+ return next;
+ });
+ const {treeRef, handleKeyDown, handleFocus} = useTreeFocus({
+ hasRovingTabIndex: true,
+ onToggleExpand: toggle,
+ onActivate: (_item, name) => {
+ if (name == null || FOLDERS.has(name)) {
+ return false;
+ }
+ setOpenFile(name);
+ return true;
+ },
+ });
+
+ const renderRow = (node: FileNode, level: 1 | 2) => {
+ const isFolder = node.children != null;
+ const isExpanded = expanded.has(node.name);
+ return (
+ <HStack
+ key={node.name}
+ role="treeitem"
+ aria-level={level}
+ aria-expanded={isFolder ? isExpanded : undefined}
+ aria-selected={isFolder ? undefined : openFile === node.name}
+ data-tree-id={node.name}
+ gap={1}
+ vAlign="center"
+ paddingInlineStart={isFolder ? 0 : level === 1 ? 5 : 10}
+ onClick={() => (isFolder ? toggle(node.name) : setOpenFile(node.name))}>
+ {isFolder &&
+ (isExpanded ? (
+ <Icon icon={ChevronDownIcon} />
+ ) : (
+ // The collapsed chevron points toward the inline end, where
+ // ArrowRight (ArrowLeft under RTL) opens the folder.
+ <Icon icon={ChevronRightIcon} xstyle={rtlStyles.mirror} />
+ ))}
+ <Text type="body">{node.name}</Text>
+ </HStack>
+ );
+ };
+
+ return (
+ <VStack gap={3} width={240}>
+ <VStack
+ ref={treeRef}
+ role="tree"
+ aria-label="Files"
+ gap={1}
+ onKeyDown={handleKeyDown}
+ onFocus={handleFocus}>
+ {FILES.flatMap(node => [
+ renderRow(node, 1),
+ ...(expanded.has(node.name)
+ ? (node.children ?? []).map(child => renderRow(child, 2))
+ : []),
+ ])}
+ </VStack>
+ <Text type="supporting">Open file: {openFile ?? 'none'}</Text>
+ </VStack>
+ );
+}
diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.json b/packages/cli/test/__golden__/no-icon-set/search-close.json
index dc1a01162b..89858dc0df 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-close.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-close.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "close",
- "matchCount": 47,
+ "matchCount": 48,
"results": [
{
"domain": "component",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.txt b/packages/cli/test/__golden__/no-icon-set/search-close.txt
index ec841a389e..8d1b1c3465 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-close.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-close.txt
@@ -1,4 +1,4 @@
-Results for "close" (20 of 47)
+Results for "close" (20 of 48)
name: AlertDialog
domain: component
package: @astryxdesign/core
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
index bef00279f1..187911e488 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon set",
- "matchCount": 377,
+ "matchCount": 378,
"results": [
{
"domain": "doc",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
index aaeb49cd9e..d6bd00f528 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
@@ -1,4 +1,4 @@
-Results for "icon set" (20 of 377)
+Results for "icon set" (20 of 378)
name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons
section: use-astryx-icon
domain: doc
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.json b/packages/cli/test/__golden__/no-icon-set/search-icon.json
index 04cc30f4c4..af5b9c62c2 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon",
- "matchCount": 225,
+ "matchCount": 226,
"results": [
{
"domain": "component",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.txt b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
index cdb866cdc6..5fe6568a56 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
@@ -1,4 +1,4 @@
-Results for "icon" (20 of 225)
+Results for "icon" (20 of 226)
name: Icon
domain: component
package: @astryxdesign/core