Skip to content

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

TypeScript

docs(useOverflow): add an editor toolbar example block (#9689)

Mahesh Rijald5a3d00d0bde
diff --git a/.changeset/use-overflow-editor-toolbar-example.md b/.changeset/use-overflow-editor-toolbar-example.md
new file mode 100644
index 0000000000..92dd6e6a07
--- /dev/null
+++ b/.changeset/use-overflow-editor-toolbar-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useOverflow — Editor Toolbar` example block shows the hook on its own: eight toolbar actions sit in a card you can resize, a hidden copy of the row holds every action plus the `More` menu marked `data-overflow-indicator`, and the actions that do not fit move into the `More` menu with no flicker. Copy it with `astryx template useOverflowHookUsage <path>`.
+
+@maheshrijal
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 6716cbcda9..364a0ca267 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -785,6 +785,7 @@
"/templates/useContainerRevealHookUsage/",
"/templates/useKeyboardHintHookUsage/",
"/templates/useListFocusHookUsage/",
+ "/templates/useOverflowHookUsage/",
"/templates/usePressFeedbackHookUsage/",
"/templates/useStreamingTextHookUsage/",
"/templates/useThemeHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 0612525a49..75187ca89a 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3681,6 +3681,11 @@
"path": "examples/use-list-focus/recent-files",
"aliases": []
},
+ {
+ "name": "example-use-overflow-editor-toolbar",
+ "path": "examples/use-overflow/editor-toolbar",
+ "aliases": []
+ },
{
"name": "example-use-popover-quick-actions",
"path": "examples/use-popover/quick-actions",
diff --git a/packages/cli/api/template/use-overflow-hook-usage.test.tsx b/packages/cli/api/template/use-overflow-hook-usage.test.tsx
new file mode 100644
index 0000000000..7ffee50f11
--- /dev/null
+++ b/packages/cli/api/template/use-overflow-hook-usage.test.tsx
@@ -0,0 +1,142 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useOverflow example shows only the toolbar actions that fit the row and
+ * a More menu for the rest. jsdom has no layout, so each test sets the widths
+ * the hook reads: every measured child is 100px wide.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
+import UseOverflowHookUsage from '../../assets/templates/blocks/components/Hooks/useOverflowHookUsage';
+
+// This project does not compile StyleX, and jsdom does no layout, so the
+// block's own styles are not what this checks.
+vi.mock('@stylexjs/stylex', () => ({
+ create: (styles: Record<string, unknown>) =>
+ Object.fromEntries(Object.keys(styles).map(key => [key, {}])),
+ props: () => ({}),
+}));
+
+const ITEM_WIDTH = 100;
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+let rowWidth = 0;
+let resize: ResizeObserverCallback = () => {};
+
+beforeAll(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ resize = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return this.getAttribute('role') === 'group' ? rowWidth : ITEM_WIDTH;
+ },
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+});
+
+function renderExample(width: number): HTMLElement {
+ rowWidth = width;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseOverflowHookUsage />);
+ });
+ const row = container.querySelector<HTMLElement>('[role="group"]');
+ if (row == null) {
+ throw new Error('no toolbar row rendered');
+ }
+ return row;
+}
+
+function labels(row: HTMLElement): string[] {
+ return Array.from(row.querySelectorAll('button'), button =>
+ (button.textContent ?? '').trim(),
+ );
+}
+
+describe('useOverflow example', () => {
+ it('shows every action and no More menu when the row is wide', () => {
+ const row = renderExample(1000);
+ expect(labels(row)).toEqual([
+ 'Bold',
+ 'Italic',
+ 'Underline',
+ 'Strikethrough',
+ 'Link',
+ 'Quote',
+ 'Code',
+ 'Clear formatting',
+ ]);
+ });
+
+ it('moves the actions that do not fit into More, and back on resize', () => {
+ // Three 100px actions, three 4px gaps and the 100px More button fit 450px.
+ const row = renderExample(450);
+ expect(labels(row)).toEqual(['Bold', 'Italic', 'Underline', 'More']);
+
+ rowWidth = 1000;
+ act(() => {
+ resize(
+ [{target: row} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+ expect(labels(row)).toHaveLength(8);
+ expect(labels(row)).not.toContain('More');
+ });
+
+ it('lists only the actions that do not fit in the More menu', () => {
+ const row = renderExample(450);
+ const more = Array.from(row.querySelectorAll('button')).at(-1);
+ act(() => {
+ more?.focus();
+ more?.dispatchEvent(
+ new KeyboardEvent('keydown', {key: 'Enter', bubbles: true}),
+ );
+ });
+ const menuItems = Array.from(
+ document.querySelectorAll('[role="menuitem"]'),
+ ).filter(item => item.closest('[aria-hidden="true"]') == null);
+ expect(menuItems.map(item => (item.textContent ?? '').trim())).toEqual([
+ 'Strikethrough',
+ 'Link',
+ 'Quote',
+ 'Code',
+ 'Clear formatting',
+ ]);
+ });
+
+ it('measures every action and the marked More menu in a hidden copy', () => {
+ renderExample(450);
+ const measure = container.querySelector<HTMLElement>(
+ '[aria-hidden="true"]',
+ );
+ expect(measure?.children).toHaveLength(9);
+ expect(
+ measure?.lastElementChild?.hasAttribute('data-overflow-indicator'),
+ ).toBe(true);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useOverflowHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useOverflowHookUsage.doc.mjs
new file mode 100644
index 0000000000..99299d582a
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useOverflowHookUsage.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useOverflow',
+ name: 'useOverflow — Editor Toolbar',
+ displayName: 'useOverflow — Editor Toolbar',
+ description:
+ 'Resize the card: useOverflow moves the toolbar actions that do not fit into a More menu, and shows them again when the card gets wider.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Card', 'Button', 'DropdownMenu'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useOverflowHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useOverflowHookUsage.tsx
new file mode 100644
index 0000000000..e22fa6f00e
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useOverflowHookUsage.tsx
@@ -0,0 +1,89 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import {useOverflow} from '@astryxdesign/core/hooks';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
+
+const actions = [
+ 'Bold',
+ 'Italic',
+ 'Underline',
+ 'Strikethrough',
+ 'Link',
+ 'Quote',
+ 'Code',
+ 'Clear formatting',
+];
+
+const GAP = 4;
+
+const styles = stylex.create({
+ box: {
+ resize: 'horizontal',
+ overflow: 'hidden',
+ width: 480,
+ minWidth: 120,
+ maxWidth: '100%',
+ },
+ row: {
+ display: 'flex',
+ gap: GAP,
+ },
+ // Takes no space and paints nothing, so the hook measures every item
+ // without a flicker. Do not use display: none, which stops measurement.
+ measure: {
+ position: 'absolute',
+ visibility: 'hidden',
+ height: 0,
+ overflow: 'hidden',
+ whiteSpace: 'nowrap',
+ pointerEvents: 'none',
+ },
+});
+
+function MoreMenu({items}: {items: string[]}) {
+ return (
+ <DropdownMenu
+ button={{label: 'More', variant: 'ghost', size: 'sm'}}
+ items={items.map(label => ({label}))}
+ />
+ );
+}
+
+export default function UseOverflowHookUsage() {
+ const {containerRef, measureRef, visibleCount, hasOverflow} = useOverflow(
+ actions.length,
+ {gap: GAP},
+ );
+
+ return (
+ <Card padding={2} xstyle={styles.box}>
+ <div
+ ref={measureRef}
+ aria-hidden="true"
+ inert
+ {...stylex.props(styles.row, styles.measure)}>
+ {actions.map(label => (
+ <Button key={label} label={label} variant="ghost" size="sm" />
+ ))}
+ <div data-overflow-indicator>
+ <MoreMenu items={actions} />
+ </div>
+ </div>
+ <div
+ ref={containerRef}
+ role="group"
+ aria-label="Text formatting"
+ {...stylex.props(styles.row)}>
+ {actions.slice(0, visibleCount).map(label => (
+ <Button key={label} label={label} variant="ghost" size="sm" />
+ ))}
+ {hasOverflow && <MoreMenu items={actions.slice(visibleCount)} />}
+ </div>
+ </Card>
+ );
+}