Skip to content

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

TypeScript

docs(useToast): add a settings saved example block (#9512)

Parman Mohammadalizadehd34e843ea554
diff --git a/.changeset/use-toast-settings-saved-example.md b/.changeset/use-toast-settings-saved-example.md
new file mode 100644
index 0000000000..78bc3819b2
--- /dev/null
+++ b/.changeset/use-toast-settings-saved-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useToast — Settings Saved` example block calls the function from `useToast` on a settings form: Save shows a "Settings saved" toast with an Undo action, its `uniqueID` makes a second Save replace the toast instead of stacking another, and a failed save shows an error toast instead. Copy it with `astryx template useToastHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 465850db41..5bbe572fc5 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -785,6 +785,7 @@
"/templates/useKeyboardHintHookUsage/",
"/templates/useStreamingTextHookUsage/",
"/templates/useThemeHookUsage/",
+ "/templates/useToastHookUsage/",
"/templates/work-item-detail/",
"/themes/",
"/tools/"
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 975c464b79..986235a580 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3729,6 +3729,11 @@
"path": "examples/use-theme/token-values",
"aliases": []
},
+ {
+ "name": "example-use-toast-settings-saved",
+ "path": "examples/use-toast/settings-saved",
+ "aliases": []
+ },
{
"name": "example-v-stack-basic",
"path": "examples/v-stack/basic",
diff --git a/packages/cli/api/template/use-toast-hook-usage.test.tsx b/packages/cli/api/template/use-toast-hook-usage.test.tsx
new file mode 100644
index 0000000000..c92b5025fd
--- /dev/null
+++ b/packages/cli/api/template/use-toast-hook-usage.test.tsx
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useToast example shows its toasts through the hook: Save shows one
+ * "Settings saved" toast however often it is pressed, Undo restores the
+ * value from before the save, and a failed save shows an error toast instead.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
+import UseToastHookUsage from '../../assets/templates/blocks/components/Toast/useToastHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+async function renderExample(): Promise<void> {
+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(0);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ await act(async () => {
+ root = createRoot(container);
+ root.render(<UseToastHookUsage />);
+ });
+}
+
+function button(label: string): HTMLButtonElement {
+ const match = Array.from(
+ document.querySelectorAll<HTMLButtonElement>('button'),
+ ).find(candidate => candidate.textContent === label);
+ if (match == null) {
+ throw new Error(`no "${label}" button rendered`);
+ }
+ return match;
+}
+
+async function press(label: string): Promise<void> {
+ await act(async () => {
+ button(label).click();
+ });
+}
+
+/** How many shown toasts read `text`, leaving out live-region copies. */
+function count(text: string): number {
+ return Array.from(
+ document.querySelectorAll('[data-toast-id]'),
+ shown => shown.textContent ?? '',
+ ).filter(shown => shown.includes(text)).length;
+}
+
+beforeAll(() => {
+ // No LayerProvider here, so the hook warns once and uses its fallback.
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ window.matchMedia ??= ((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: () => undefined,
+ removeListener: () => undefined,
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ dispatchEvent: () => false,
+ })) as typeof window.matchMedia;
+});
+
+afterEach(async () => {
+ // Dismiss every toast, then end the collapse transition jsdom never runs,
+ // so the shared viewport is empty for the next test.
+ for (const dismiss of document.querySelectorAll<HTMLButtonElement>(
+ '[data-toast-id] button[aria-label="Dismiss notification"]',
+ )) {
+ await act(async () => dismiss.click());
+ }
+ for (const row of document.querySelectorAll('[data-toast-id]')) {
+ const collapsed = Object.assign(
+ new Event('transitionend', {bubbles: true}),
+ {propertyName: 'grid-template-rows'},
+ );
+ await act(async () => row.dispatchEvent(collapsed));
+ }
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+});
+
+describe('useToast example', () => {
+ it('shows one "Settings saved" toast however often Save is pressed', async () => {
+ await renderExample();
+ await press('Save');
+ await press('Save');
+ expect(count('Settings saved')).toBe(1);
+ });
+
+ it('restores the previous name from Undo, even after a repeated Save', async () => {
+ await renderExample();
+ const input = container.querySelector('input[type="text"]');
+ const setValue = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ 'value',
+ )?.set;
+ act(() => {
+ setValue?.call(input, 'Grace Hopper');
+ input?.dispatchEvent(new Event('input', {bubbles: true}));
+ });
+ await press('Save');
+ await press('Save');
+ await press('Undo');
+ expect((input as HTMLInputElement).value).toBe('Ada Lovelace');
+ });
+
+ it('shows an error toast when the save fails', async () => {
+ await renderExample();
+ const toggle = container.querySelector<HTMLInputElement>(
+ 'input[type="checkbox"]',
+ );
+ await act(async () => toggle?.click());
+ await press('Save');
+ expect(count('Could not save settings')).toBe(1);
+ expect(count('Settings saved')).toBe(0);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Toast/useToastHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Toast/useToastHookUsage.doc.mjs
new file mode 100644
index 0000000000..fed0422d0d
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Toast/useToastHookUsage.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: 'useToast',
+ name: 'useToast — Settings Saved',
+ displayName: 'useToast — Settings Saved',
+ description:
+ 'Shows a toast from the function useToast returns: a "Settings saved" confirmation with an Undo action, a uniqueID so pressing the button again replaces the toast instead of stacking another, and an error toast when the request fails.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Toast', 'Card', 'TextInput', 'Switch', 'Button', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Toast/useToastHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Toast/useToastHookUsage.tsx
new file mode 100644
index 0000000000..6dfce1ad64
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Toast/useToastHookUsage.tsx
@@ -0,0 +1,65 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Switch} from '@astryxdesign/core/Switch';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {useToast} from '@astryxdesign/core/Toast';
+
+export default function UseToastHookUsage() {
+ const toast = useToast();
+ const [name, setName] = useState('Ada Lovelace');
+ const [savedName, setSavedName] = useState('Ada Lovelace');
+ const [undoName, setUndoName] = useState('Ada Lovelace');
+ const [isSaveFailing, setIsSaveFailing] = useState(false);
+
+ const save = () => {
+ if (isSaveFailing) {
+ toast({
+ type: 'error',
+ body: 'Could not save settings',
+ uniqueID: 'settings-save',
+ });
+ return;
+ }
+ // Saving an unchanged name keeps the earlier undo target.
+ const nextUndoName = name === savedName ? undoName : savedName;
+ setUndoName(nextUndoName);
+ setSavedName(name);
+ const dismiss = toast({
+ body: 'Settings saved',
+ // A repeated Save replaces this toast instead of stacking another.
+ uniqueID: 'settings-save',
+ endContent: (
+ <Button
+ label="Undo"
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setName(nextUndoName);
+ setSavedName(nextUndoName);
+ dismiss();
+ }}
+ />
+ ),
+ });
+ };
+
+ return (
+ <Card width={360} padding={4}>
+ <VStack gap={3}>
+ <TextInput label="Display name" value={name} onChange={setName} />
+ <Switch
+ label="Simulate a failed save"
+ value={isSaveFailing}
+ onChange={setIsSaveFailing}
+ />
+ <Button label="Save" variant="primary" onClick={save} />
+ </VStack>
+ </Card>
+ );
+}