Skip to content

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

TypeScript

docs(core): add a usePressFeedback example on a pressable Card (#9431)

Cindy Zhang1667ea833c89
diff --git a/.changeset/use-press-feedback-card-example.md b/.changeset/use-press-feedback-card-example.md
new file mode 100644
index 0000000000..2185afd275
--- /dev/null
+++ b/.changeset/use-press-feedback-card-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `usePressFeedback — Pressable Card` example block shows the hook on an Astryx Card: the hook's marker and the `interactionOverlayStyles.backgroundImage` overlay go straight on the Card, so pressing the card darkens it the way every Astryx pressable does, under a finger or a mouse (Enter or Space flips it), and `focusOutlineStyles.focusVisible` gives keyboard users the shared Astryx focus ring on it. Copy it with `astryx template usePressFeedbackHookUsage <path>`; the docs-only playing card it shows becomes a `<Text>` placeholder for your own content.
+
+@cixzhang
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index f48084fd1b..244bdcc9f2 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -783,6 +783,7 @@
"/templates/useCollatorHookUsage/",
"/templates/useContainerRevealHookUsage/",
"/templates/useKeyboardHintHookUsage/",
+ "/templates/usePressFeedbackHookUsage/",
"/templates/useStreamingTextHookUsage/",
"/templates/useThemeHookUsage/",
"/templates/useToastHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index db72ccce2c..0dd007c6f3 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3674,6 +3674,11 @@
"path": "examples/use-popover/quick-actions",
"aliases": []
},
+ {
+ "name": "example-use-press-feedback-pressable-card",
+ "path": "examples/use-press-feedback/pressable-card",
+ "aliases": []
+ },
{
"name": "example-use-streaming-text-streaming-response",
"path": "examples/use-streaming-text/streaming-response",
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.doc.mjs
new file mode 100644
index 0000000000..bf390e3c9d
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.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: 'usePressFeedback',
+ name: 'usePressFeedback — Pressable Card',
+ displayName: 'usePressFeedback — Pressable Card',
+ description:
+ 'A Card made pressable with usePressFeedback: its marker and the interactionOverlayStyles backgroundImage overlay go straight on the Card, so a press darkens the card the way every Astryx pressable does; focusOutlineStyles.focusVisible gives it the shared Astryx focus ring for keyboard focus; and a click, Enter or Space flips it.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Card'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsx b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsx
new file mode 100644
index 0000000000..6fcea8819b
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsx
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The usePressFeedback example applies the hook's output to the Astryx Card
+ * itself, with no wrapper: the marker lands on the Card's root, the press
+ * controller paints that root, the shared focus ring marks keyboard focus on
+ * it, and a click, Enter or Space flips the card. This is also a
+ * compatibility check that Card passes through what the hook returns.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
+import {focusOutlineStyles} from '@astryxdesign/core/utils';
+import UsePressFeedbackHookUsage from './usePressFeedbackHookUsage';
+
+// The docs-only card is not what this checks; stand it in with a plain
+// element so the test needs no StyleX compilation.
+vi.mock('@astryx-docs/demo-content', () => ({
+ PlayingCardContents: ({faceDown}: {faceDown?: boolean}) => (
+ <span>{faceDown === true ? 'back' : 'face'}</span>
+ ),
+}));
+
+const PRESS_ONSET_MS = 150;
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+/** Render the example and return its Card root, found by its button role. */
+function renderCard(): HTMLElement {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UsePressFeedbackHookUsage />);
+ });
+ const card = container.querySelector<HTMLElement>(
+ '[role="button"][aria-label="Flip card"]',
+ );
+ if (card == null) {
+ throw new Error('no "Flip card" button rendered');
+ }
+ return card;
+}
+
+beforeAll(() => {
+ 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(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ vi.useRealTimers();
+});
+
+/** A touch pointer event the press controller reads. */
+function touch(element: Element, type: string): void {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.assign(event, {
+ button: 0,
+ clientX: 10,
+ clientY: 10,
+ pointerId: 1,
+ pointerType: 'touch',
+ });
+ element.dispatchEvent(event);
+}
+
+describe('usePressFeedback example', () => {
+ it('puts the pressable marker and the button semantics on the Card root', () => {
+ const card = renderCard();
+ expect(container.firstElementChild).toBe(card);
+ expect(card.className).toMatch(/astryx-card/u);
+ expect(card.hasAttribute('data-astryx-pressable')).toBe(true);
+ expect(card.getAttribute('tabindex')).toBe('0');
+ });
+
+ it('paints a believed touch press on the Card root', () => {
+ vi.useFakeTimers();
+ const card = renderCard();
+ act(() => {
+ touch(card, 'pointerdown');
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ });
+ expect(card.getAttribute('data-astryx-press')).toBe('on');
+ });
+
+ it('paints the shared focus ring on the Card root for keyboard focus', () => {
+ const card = renderCard();
+ const ringClasses = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className?.split(' ');
+ expect(ringClasses?.length).toBeGreaterThan(0);
+ const cardClasses = card.className.split(' ');
+ for (const ringClass of ringClasses ?? []) {
+ expect(cardClasses).toContain(ringClass);
+ }
+ act(() => card.focus());
+ expect(document.activeElement).toBe(card);
+ });
+
+ it('flips on a click, Enter and Space', () => {
+ const card = renderCard();
+ expect(card.getAttribute('aria-pressed')).toBe('false');
+ expect(card.textContent).toBe('face');
+ act(() => card.click());
+ expect(card.getAttribute('aria-pressed')).toBe('true');
+ expect(card.textContent).toBe('back');
+ act(() => {
+ card.dispatchEvent(
+ new KeyboardEvent('keydown', {key: 'Enter', bubbles: true}),
+ );
+ });
+ expect(card.textContent).toBe('face');
+ act(() => {
+ card.dispatchEvent(
+ new KeyboardEvent('keydown', {key: ' ', bubbles: true}),
+ );
+ });
+ expect(card.textContent).toBe('back');
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx
new file mode 100644
index 0000000000..e6e2f61757
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx
@@ -0,0 +1,41 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Card} from '@astryxdesign/core/Card';
+import {usePressFeedback} from '@astryxdesign/core/hooks';
+import {
+ focusOutlineStyles,
+ interactionOverlayStyles,
+} from '@astryxdesign/core/utils';
+import {PlayingCardContents} from '@astryx-docs/demo-content';
+
+export default function UsePressFeedbackHookUsage() {
+ const pressable = usePressFeedback();
+ const [isFaceUp, setIsFaceUp] = useState(true);
+ const flip = () => setIsFaceUp(faceUp => !faceUp);
+
+ return (
+ <Card
+ {...pressable}
+ xstyle={[
+ interactionOverlayStyles.backgroundImage,
+ focusOutlineStyles.focusVisible,
+ ]}
+ width={160}
+ role="button"
+ tabIndex={0}
+ aria-label="Flip card"
+ aria-pressed={!isFaceUp}
+ onClick={flip}
+ onKeyDown={event => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ flip();
+ }
+ }}>
+ <PlayingCardContents rank="Q" suit="hearts" faceDown={!isFaceUp} />
+ </Card>
+ );
+}
diff --git a/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs b/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs
index 08dd9c0e25..36056c53d3 100644
--- a/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs
+++ b/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs
@@ -283,6 +283,19 @@ describe('catalog blocks', () => {
expect(files.length).toBeGreaterThan(100);
});
+ it('copies the usePressFeedback block as one Text placeholder in its Card, with no branch on the face', () => {
+ const file = files.find(f => f.endsWith('/usePressFeedbackHookUsage.tsx'));
+ expect(file).toBeDefined();
+ const {source, demoContentReplaced} = replaceTemplateDemos(
+ fs.readFileSync(/** @type {string} */ (file), 'utf8'),
+ );
+ expect(demoContentReplaced).toBe(1);
+ expect(source).toContain(
+ ' }}>\n <Text>Card content</Text>\n </Card>',
+ );
+ expect(source).not.toMatch(/\?\s*\(/u);
+ });
+
it('leaves no demo-content reference in any block as a copy writes it', () => {
const remaining = files.filter(file => {
const {source} = replaceTemplateDemos(fs.readFileSync(file, 'utf8'));