An open source design system that's fully customizable and agent ready
TypeScript
docs(useClickableContainer): a pressable surface without Card chrome (#10880)
Cindy Zhangd53cec5c7c12
diff --git a/.changeset/pressable-surface-recipe.md b/.changeset/pressable-surface-recipe.mdnew file mode 100644index 0000000000..a8201b3a2e--- /dev/null+++ b/.changeset/pressable-surface-recipe.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[docs] useClickableContainer documents a pressable surface without Card chrome: the hook on the surface, `usePressFeedback` with `interactionOverlayStyles.backgroundColor` for the hover tint and touch press, a visually hidden `<button>` or `<a>` as the named control, and `focusOutlineStyles.focusWithin` for the shared focus ring that ClickableCard draws. ClickableCard's docs point chrome-free use to it.++@cixzhangdiff --git a/apps/storybook/stories/PressableSurfaceRecipe.stories.tsx b/apps/storybook/stories/PressableSurfaceRecipe.stories.tsxnew file mode 100644index 0000000000..3ae456eb04--- /dev/null+++ b/apps/storybook/stories/PressableSurfaceRecipe.stories.tsx@@ -0,0 +1,163 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useRef, useState, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {Meta, StoryObj} from '@storybook/react';+import {+ useClickableContainer,+ usePressFeedback,+} from '@astryxdesign/core/hooks';+import {+ focusOutlineStyles,+ interactionOverlayStyles,+} from '@astryxdesign/core/utils';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';+import {Text} from '@astryxdesign/core/Text';+import {VStack} from '@astryxdesign/core/Layout';+import {+ borderVars,+ colorVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';++/**+ * A pressable surface without Card chrome: the recipe for a surface that owns+ * its own box but presses like a ClickableCard.+ *+ * - `useClickableContainer` gives the surface its press rules: a press on the+ * words acts, a press on a nested link or a text drag does not.+ * - `usePressFeedback` plus `interactionOverlayStyles.backgroundColor` paint+ * the system's hover tint and the touch press on the surface.+ * - A visually hidden native `<button>` (or `<a>` for a destination) is the+ * named control: it carries the role, the name and the Tab stop.+ * - `focusOutlineStyles.focusWithin` draws the shared focus ring, the one+ * ClickableCard draws, on the surface while its control has keyboard focus.+ */+const meta: Meta = {+ title: 'Core/Hooks/useClickableContainer',+ parameters: {+ layout: 'padded',+ docs: {+ description: {+ component:+ 'A pressable surface without Card chrome: `useClickableContainer` for the press rules, `usePressFeedback` with `interactionOverlayStyles.backgroundColor` for the hover tint and touch press, a visually hidden `<button>` (or `<a>` for a destination) as the named control, and `focusOutlineStyles.focusWithin` for the shared focus ring, the one ClickableCard draws. Use it when a surface owns its own box; use ClickableCard when the surface is a card.',+ },+ },+ },+};++export default meta;+type Story = StoryObj;++const styles = stylex.create({+ surface: {+ display: 'block',+ cursor: 'pointer',+ borderRadius: radiusVars['--radius-element'],+ borderInlineStartColor: colorVars['--color-border-emphasized'],+ borderInlineStartStyle: 'solid',+ borderInlineStartWidth: borderVars['--border-width'],+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ },+});++interface PressableQuoteProps {+ /** The control's accessible name: what a press does. */+ label: string;+ /** A destination: the control is a link. */+ href?: string;+ /** An action: the control is a button. */+ onPress?: () => void;+ children: ReactNode;+}++/** The recipe: copy this component into your app. */+function PressableQuote({label, href, onPress, children}: PressableQuoteProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const controlRef = useRef<HTMLElement | null>(null);+ const pressable = usePressFeedback();+ const {onClick, onMouseUp, onPointerDown} = useClickableContainer({+ containerRef,+ interactiveRef: controlRef,+ href,+ onClick: onPress,+ });+ return (+ <div+ ref={containerRef}+ {...pressable}+ onClick={onClick}+ onMouseUp={onMouseUp}+ onPointerDown={onPointerDown}+ {...stylex.props(+ styles.surface,+ interactionOverlayStyles.backgroundColor,+ focusOutlineStyles.focusWithin,+ )}>+ <VisuallyHidden>+ {href != null ? (+ <a+ ref={node => {+ controlRef.current = node;+ }}+ href={href}>+ {label}+ </a>+ ) : (+ <button+ ref={node => {+ controlRef.current = node;+ }}+ type="button"+ onClick={onPress}>+ {label}+ </button>+ )}+ </VisuallyHidden>+ {children}+ </div>+ );+}++export const PressableSurface: Story = {+ name: 'Pressable surface without Card chrome',+ render: function PressableSurfaceStory() {+ const [jumps, setJumps] = useState(0);+ return (+ <VStack gap={3}>+ <PressableQuote+ label="Jump to the quoted message"+ onPress={() => setJumps(count => count + 1)}>+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ Replying to Alex+ </Text>+ <Text type="body">+ Can we move the review to Thursday? The{' '}+ <a href="#agenda">agenda</a> is in the doc.+ </Text>+ </VStack>+ </PressableQuote>+ <Text type="supporting" color="secondary">+ {jumps === 0 ? 'Not jumped yet' : `Jumped ${jumps}×`}+ </Text>+ </VStack>+ );+ },+};++export const PressableSurfaceLink: Story = {+ name: 'Pressable surface without Card chrome (link)',+ render: () => (+ <PressableQuote label="Open the quoted message" href="#message-42">+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ Replying to Alex+ </Text>+ <Text type="body">Can we move the review to Thursday?</Text>+ </VStack>+ </PressableQuote>+ ),+};diff --git a/packages/core/src/ClickableCard/ClickableCard.doc.mjs b/packages/core/src/ClickableCard/ClickableCard.doc.mjsindex 6a144cdf50..185ec2177c 100644--- a/packages/core/src/ClickableCard/ClickableCard.doc.mjs+++ b/packages/core/src/ClickableCard/ClickableCard.doc.mjs@@ -13,6 +13,7 @@ export const docs = {{guidance: true, description: 'Use for cards that navigate to a detail page or trigger a single action.'},{guidance: true, description: 'Nest buttons or links freely inside; they handle their own events.'},{guidance: false, description: 'Use for toggling selection; use SelectableCard for that.'},+ {guidance: false, description: 'Use with a transparent variant and no padding only to borrow the press model for a surface that owns its own box. Compose the chrome-free recipe in the useClickableContainer docs instead: it adds no Card styles to the page.'},],anatomy: [{name: 'Container', required: true, description: 'Interactive div with hover/focus/active states.'},@@ -67,6 +68,7 @@ export const docsDense = {{guidance: true, description: 'Use for cards navigating to detail page or triggering single action.'},{guidance: true, description: 'Nest buttons/links freely inside; they handle own events.'},{guidance: false, description: 'Use for toggling selection; use SelectableCard instead.'},+ {guidance: false, description: 'Use w/ transparent variant + no padding only to borrow press model for surface owning its own box; compose chrome-free recipe in useClickableContainer docs instead (no Card styles).'},],},propDescriptions: {diff --git a/packages/core/src/hooks/useClickableContainer.a11y.chromium.spec.ts b/packages/core/src/hooks/useClickableContainer.a11y.chromium.spec.tsnew file mode 100644index 0000000000..6cf15f8468--- /dev/null+++ b/packages/core/src/hooks/useClickableContainer.a11y.chromium.spec.ts@@ -0,0 +1,95 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^(packages/core/src/(hooks/(useClickableContainer|usePressFeedback)|utils/interactionOverlay|VisuallyHidden)|apps/storybook/stories/PressableSurfaceRecipe\.stories)++/**+ * @file useClickableContainer.a11y.chromium.spec.ts+ * @input The built "pressable surface without Card chrome" stories in real+ * Chromium+ * @output Evidence that the recipe's surface exposes one named button (or+ * link), that Tab reaches it, that the surface shows the focus ring from+ * the focus tokens while it has keyboard focus, and that a press on the+ * words acts while a press on a nested link does not+ * @position Real-engine check for the documented useClickableContainer recipe+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const BUTTON_STORY = 'core-hooks-useclickablecontainer--pressable-surface';+const LINK_STORY = 'core-hooks-useclickablecontainer--pressable-surface-link';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page, story: string): Promise<void> {+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);+ await page.getByText('Replying to Alex').waitFor();+}++/** The computed outline of the element that holds `text`'s surface. */+async function surfaceOutline(page: Page) {+ return page.getByText('Replying to Alex').evaluate(node => {+ const surface = node.closest('[data-astryx-pressable]');+ if (surface == null) {+ return null;+ }+ const style = getComputedStyle(surface);+ return {style: style.outlineStyle, width: parseFloat(style.outlineWidth)};+ });+}++test('the surface exposes one named button that Tab reaches, with the focus ring', async ({+ page,+}) => {+ await openStory(page, BUTTON_STORY);+ const control = page.getByRole('button', {+ name: 'Jump to the quoted message',+ });+ await expect(control).toHaveCount(1);++ const before = await surfaceOutline(page);+ expect(before?.width ?? 0).toBe(0);++ await page.keyboard.press('Tab');+ await expect(control).toBeFocused();+ const focused = await surfaceOutline(page);+ expect(focused?.style).toBe('solid');+ expect(focused?.width ?? 0).toBeGreaterThan(0);++ await page.keyboard.press('Enter');+ await expect(page.getByText('Jumped 1×')).toBeVisible();+});++test('a press on the words acts; a press on a nested link does not', async ({+ page,+}) => {+ await openStory(page, BUTTON_STORY);+ await page.getByText('Can we move the review').click();+ await expect(page.getByText('Jumped 1×')).toBeVisible();++ await page.getByRole('link', {name: 'agenda'}).click();+ await expect(page.getByText('Jumped 1×')).toBeVisible();+});++test('a destination surface exposes one named link that Tab reaches', async ({+ page,+}) => {+ await openStory(page, LINK_STORY);+ const control = page.getByRole('link', {name: 'Open the quoted message'});+ await expect(control).toHaveCount(1);+ await page.keyboard.press('Tab');+ await expect(control).toBeFocused();+ const focused = await surfaceOutline(page);+ expect(focused?.width ?? 0).toBeGreaterThan(0);+});diff --git a/packages/core/src/hooks/useClickableContainer.doc.mjs b/packages/core/src/hooks/useClickableContainer.doc.mjsindex 7b6b3b2cff..92abfabcbf 100644--- a/packages/core/src/hooks/useClickableContainer.doc.mjs+++ b/packages/core/src/hooks/useClickableContainer.doc.mjs@@ -73,6 +73,7 @@ export const docs = {bestPractices: [{ guidance: true, description: 'Attach onClick, onMouseUp and onPointerDown to the container element: full click handling including middle-click, and no touch pressed state for a press on a nested control.' },{ guidance: true, description: 'Use inside ClickableCard or SelectableCard for the standard card interaction pattern.' },+ { guidance: true, description: 'For a pressable surface without Card chrome, such as a quoted message that jumps on press, compose it yourself: this hook on the surface; `usePressFeedback()` and `interactionOverlayStyles.backgroundColor` (from `@astryxdesign/core/utils`) on the same element for the hover tint and touch press; a native `<button>` (or an `<a>` for a destination) inside `VisuallyHidden` as the named control and interactiveRef; and `focusOutlineStyles.focusWithin` (from `@astryxdesign/core/utils`) on the surface for the shared focus ring, the one ClickableCard draws. The `Core/Hooks/useClickableContainer` story has the full recipe.' },{ guidance: false, description: 'Use when the entire container is a single interactive element; just use a <button> or <a> directly.' },],},@@ -106,6 +107,7 @@ export const docsDense = {bestPractices: [{ guidance: true, description: 'Attach onClick + onMouseUp + onPointerDown to container element: full click handling incl. middle-click, no touch pressed state for press on nested control.' },{ guidance: true, description: 'Use inside ClickableCard / SelectableCard for standard card interaction pattern.' },+ { guidance: true, description: 'Pressable surface w/o Card chrome (e.g. quoted message jumping on press): this hook on surface; usePressFeedback() + interactionOverlayStyles.backgroundColor on same element; native <button> (or <a> for destination) inside VisuallyHidden as named control + interactiveRef; focusOutlineStyles.focusWithin on surface for shared focus ring (the one ClickableCard draws). Full recipe: Core/Hooks/useClickableContainer story.' },{ guidance: false, description: 'Use when entire container is single interactive element; just use <button> / <a> directly.' },],},