An open source design system that's fully customizable and agent ready
TypeScript
feat(codeblock): themeable copy button with default tooltip, backed by a shared useClipboard hook (#4867)
freddymeta9b5eaa052813
diff --git a/.changeset/codeblock-copy-button-themeable.md b/.changeset/codeblock-copy-button-themeable.mdnew file mode 100644index 0000000000..b3c11a04de--- /dev/null+++ b/.changeset/codeblock-copy-button-themeable.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feat] CodeBlock: the built-in copy button is now a themeable ghost `IconButton` with a default "Copy code" tooltip, reachable via the stable `astryx-codeblock-copy-button` class (theme it through the `codeblock-copy-button` component key). Restyle or keep the copy control without turning it off and re-implementing it. The tooltip stays "Copy code" after copying — the copy→check icon flip is the confirmation.++[feat] New `useClipboard` hook (`@astryxdesign/core/hooks`): the shared copy-to-clipboard behavior — clipboard write, a transient `isCopied` flag with its reset timer, and an optional polite screen-reader announcement. CodeBlock and Timestamp now build their copy buttons on it; reach for it directly for copy affordances that are not a plain icon button.++@freddymetadiff --git a/apps/storybook/stories/useClipboard.stories.tsx b/apps/storybook/stories/useClipboard.stories.tsxnew file mode 100644index 0000000000..4e00ef2a99--- /dev/null+++ b/apps/storybook/stories/useClipboard.stories.tsx@@ -0,0 +1,90 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useClipboard} from '@astryxdesign/core/hooks';+import {IconButton} from '@astryxdesign/core/IconButton';+import {Button} from '@astryxdesign/core/Button';+import {Icon} from '@astryxdesign/core/Icon';+import {Text} from '@astryxdesign/core/Text';+import {VStack} from '@astryxdesign/core/Layout';++interface ClipboardDemoProps {+ value: string;+ announce: string;+ resetAfterMs: number;+}++/**+ * The overwhelmingly common shape: a compact ghost `IconButton` over the hook.+ * The tooltip stays "Copy" — the copy → check icon flip is the confirmation —+ * and the announce message is spoken to a polite live region on success.+ */+function IconButtonDemo({value, announce, resetAfterMs}: ClipboardDemoProps) {+ const {copy, isCopied} = useClipboard({announce, resetAfterMs});+ return (+ <VStack gap={3}>+ <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>+ <IconButton+ variant="ghost"+ size="sm"+ tooltip="Copy"+ label={isCopied ? 'Copied' : 'Copy'}+ icon={<Icon icon={isCopied ? 'check' : 'copy'} size="sm" />}+ onClick={() => void copy(value)}+ />+ <Text type="supporting">{value}</Text>+ </div>+ <Text type="supporting">isCopied: {String(isCopied)}</Text>+ </VStack>+ );+}++/**+ * The hook is not tied to an icon button — the same behavior drives a labeled+ * text button whose label reflects `isCopied`.+ */+function TextButtonDemo({value, announce, resetAfterMs}: ClipboardDemoProps) {+ const {copy, isCopied} = useClipboard({announce, resetAfterMs});+ return (+ <Button+ variant="secondary"+ size="sm"+ icon={<Icon icon={isCopied ? 'check' : 'copy'} size="sm" />}+ label={isCopied ? 'Copied' : 'Copy link'}+ onClick={() => void copy(value)}+ />+ );+}++const meta: Meta<typeof IconButtonDemo> = {+ title: 'Hooks/useClipboard',+ component: IconButtonDemo,+ tags: ['autodocs'],+ argTypes: {+ value: {control: 'text'},+ announce: {control: 'text'},+ resetAfterMs: {control: {type: 'range', min: 500, max: 4000, step: 100}},+ },+ args: {+ value: 'npm install @astryxdesign/core',+ announce: 'Copied',+ resetAfterMs: 2000,+ },+};++export default meta;+type Story = StoryObj<typeof IconButtonDemo>;++export const CopyIconButton: Story = {+ name: 'Copy icon button (common case)',+};++export const CopyTextButton: Story = {+ name: 'Labeled copy button',+ render: args => <TextButtonDemo {...args} />,+};++export const NoAnnounce: Story = {+ name: 'Without announcement',+ args: {announce: ''},+};diff --git a/packages/core/src/CodeBlock/CodeBlock.doc.mjs b/packages/core/src/CodeBlock/CodeBlock.doc.mjsindex 3ad0960c53..08ddef425a 100644--- a/packages/core/src/CodeBlock/CodeBlock.doc.mjs+++ b/packages/core/src/CodeBlock/CodeBlock.doc.mjs@@ -142,6 +142,7 @@ export const docs = {targets: [{className: 'astryx-code', visualProps: ['color']},{className: 'astryx-codeblock', visualProps: ['size', 'language', 'container']},+ {className: 'astryx-codeblock-copy-button'},],},usage: {diff --git a/packages/core/src/CodeBlock/CodeBlock.test.tsx b/packages/core/src/CodeBlock/CodeBlock.test.tsxindex 0f8e0027d3..1e1e5ce045 100644--- a/packages/core/src/CodeBlock/CodeBlock.test.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.test.tsx@@ -64,6 +64,30 @@ describe('CodeBlock', () => {expect(navigator.clipboard.writeText).toHaveBeenCalledWith('const x = 1;');});+ it('renders the copy button as a themeable target with a "Copy code" tooltip', () => {+ render(<CodeBlock code="const x = 1;" language="javascript" />);+ const copyButton = screen.getByRole('button', {name: 'Copy code'});+ // Theme seam: a design system can restyle the copy control via this class+ // without turning the button off and re-implementing it.+ expect(copyButton).toHaveClass('astryx-codeblock-copy-button');+ // The button carries a visible "Copy code" hover/focus hint (tooltip),+ // wired through aria-describedby — a bare <button> could not.+ expect(copyButton).toHaveAttribute('aria-describedby');+ });++ it('keeps the copy button tooltip as "Copy code" after copying', async () => {+ render(<CodeBlock code="const x = 1;" language="javascript" />);+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));+ await act(async () => {});+ // The icon flip (copy → check) is the confirmation; the tooltip text does+ // not change. The accessible name still swaps to "Copied" for AT.+ const copyButton = screen.getByRole('button', {name: 'Copied'});+ const tooltipId = copyButton.getAttribute('aria-describedby');+ expect(tooltipId).toBeTruthy();+ const tooltip = document.getElementById(tooltipId as string);+ expect(tooltip).toHaveTextContent('Copy code');+ });+it('announces "Copied" to a polite live region after copying', async () => {render(<CodeBlock code="const x = 1;" language="javascript" />);const copyButton = screen.getByRole('button', {name: 'Copy code'});diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsxindex 5f482cd566..28e36fe861 100644--- a/packages/core/src/CodeBlock/CodeBlock.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.tsx@@ -33,8 +33,9 @@ import {easeVars,} from '../theme/tokens.stylex';import {mergeProps} from '../utils';-import {useAnnounce} from '../hooks/useAnnounce';+import {useClipboard} from '../hooks/useClipboard';import {Icon} from '../Icon';+import {IconButton} from '../IconButton';import {tokenize,tokenizeAsync,@@ -300,22 +301,11 @@ const styles = stylex.create({fontSize: typeScaleVars['--text-code-size'],},copyButton: {- display: 'inline-flex',- alignItems: 'center',- justifyContent: 'center',- padding: spacingVars['--spacing-1'],- marginInlineEnd: `calc(-1 * ${spacingVars['--spacing-2']})`,- border: 'none',- borderRadius: radiusVars['--radius-inner'],- backgroundColor: {- default: 'transparent',- '@media (hover: hover)': {- ':hover': colorVars['--color-overlay-hover'],- },- },+ // The copy control is a ghost IconButton (Button owns its own padding,+ // radius, and hover surface); this only tints the resting glyph to the+ // muted syntax-comment colour so it blends into the header/corner. A theme+ // reaches it via the `codeblock-copy-button` target on the Button.color: 'var(--color-syntax-comment)',- cursor: 'pointer',- lineHeight: 0,},copyButtonAbsolute: {position: 'absolute',@@ -744,18 +734,12 @@ export function CodeBlock({...props}: CodeBlockProps) {const t = useTranslator();- const [copied, setCopied] = useState(false);- const copyResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const announce = useAnnounce();-- // Clear a pending "copied" reset when the block unmounts.- useEffect(() => {- return () => {- if (copyResetTimerRef.current != null) {- clearTimeout(copyResetTimerRef.current);- }- };- }, []);+ // Owns the clipboard write, the transient copied flag, its reset timer, and+ // the polite copy announcement (a swapped aria-label alone is not reliably+ // announced) — shared with Timestamp via the same hook.+ const {copy, isCopied: copied} = useClipboard({+ announce: t('@astryx.codeBlock.copied'),+ });const useSpans =highlightMode === 'spans' ||@@ -778,26 +762,11 @@ export function CodeBlock({);const handleCopy = useCallback(async () => {- try {- await navigator.clipboard.writeText(code);- setCopied(true);- // Swapping the button's aria-label alone isn't reliably announced by- // screen readers, so confirm the copy via a polite live region.- announce(t('@astryx.codeBlock.copied'));+ const didCopy = await copy(code);+ if (didCopy) {onCopy?.();- // Restart the reset timer on every copy — otherwise a rapid re-copy- // is reverted early by the previous click's timer.- if (copyResetTimerRef.current != null) {- clearTimeout(copyResetTimerRef.current);- }- copyResetTimerRef.current = setTimeout(() => {- copyResetTimerRef.current = null;- setCopied(false);- }, 2000);- } catch {- // Clipboard failures leave the copied state unchanged.}- }, [code, onCopy, announce, t]);+ }, [code, copy, onCopy]);const sizeStyle = size === 'sm' ? styles.sizeSm : styles.sizeMd;// Digits in the largest line number — sizes the gutter column width.@@ -819,27 +788,27 @@ export function CodeBlock({? {maxHeight: typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight}: undefined;- const copyIcon = (- <Icon icon={copied ? 'check' : 'copy'} size="sm" color="inherit" />- );-const copyButtonEl = hasCopyButton ? (- <button- type="button"+ <IconButton+ variant="ghost"+ size="sm"+ icon={<Icon icon={copied ? 'check' : 'copy'} size="sm" color="inherit" />}+ // A visible "Copy" hover/focus hint via Button's built-in tooltip. It+ // stays "Copy" after copying — the copy → check icon flip is the+ // confirmation, not a tooltip change. The aria-label still swaps to the+ // localized "Copied" for assistive tech, backed by the announcement.+ tooltip={t('@astryx.codeBlock.copyCode')}+ label={+ copied ? t('@astryx.codeBlock.copied') : t('@astryx.codeBlock.copyCode')+ }onClick={e => {// Stop propagation so copying does not toggle the collapsible header.e.stopPropagation();void handleCopy();}}- aria-label={- copied ? t('@astryx.codeBlock.copied') : t('@astryx.codeBlock.copyCode')- }- {...stylex.props(- styles.copyButton,- !showHeader && styles.copyButtonAbsolute,- )}>- {copyIcon}- </button>+ xstyle={[styles.copyButton, !showHeader && styles.copyButtonAbsolute]}+ {...themeProps('codeblock-copy-button')}+ />) : null;const headerEl = showHeader ? (diff --git a/packages/core/src/Timestamp/TimestampHoverCard.tsx b/packages/core/src/Timestamp/TimestampHoverCard.tsxindex e387e83fc0..814f25f3ae 100644--- a/packages/core/src/Timestamp/TimestampHoverCard.tsx+++ b/packages/core/src/Timestamp/TimestampHoverCard.tsx@@ -24,12 +24,12 @@*/import type {ReactNode} from 'react';-import {useCallback, useEffect, useRef, useState} from 'react';+import {useCallback} from 'react';import * as stylex from '@stylexjs/stylex';import {HoverCard} from '../HoverCard';import {IconButton} from '../IconButton';import {Icon} from '../Icon';-import {useAnnounce} from '../hooks/useAnnounce';+import {useClipboard} from '../hooks/useClipboard';import {useTranslator} from '../i18n';import {themeProps} from '../utils/themeProps';import {@@ -108,7 +108,9 @@ const COPY_FEEDBACK_MS = 1500;* The per-row copy affordance: a compact ghost `IconButton` that writes the* row's value to the clipboard, flips `copy` → `check` for a moment, and* announces the copy to a polite live region (a swapped aria-label alone- * isn't reliably announced). A clipboard rejection is a silent no-op.+ * isn't reliably announced). A clipboard rejection is a silent no-op. The+ * clipboard write, copied flag, reset timer, and announcement are owned by+ * `useClipboard` — shared with CodeBlock's built-in copy button.** Kept as its own component so its state/timer/effect only exist for rows that* actually opt into copying — read-only rows render no button and carry none@@ -116,36 +118,14 @@ const COPY_FEEDBACK_MS = 1500;*/function CopyButton({value}: {value: string}) {const t = useTranslator();- const announce = useAnnounce();- const [copied, setCopied] = useState(false);- const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const {copy, isCopied: copied} = useClipboard({+ announce: t('@astryx.timestamp.copied'),+ resetAfterMs: COPY_FEEDBACK_MS,+ });- useEffect(() => {- return () => {- if (resetTimerRef.current != null) {- clearTimeout(resetTimerRef.current);- }- };- }, []);-- const handleCopy = useCallback(async () => {- try {- await navigator.clipboard.writeText(value);- setCopied(true);- announce(t('@astryx.timestamp.copied'));- // Restart the reset timer on every copy so a rapid re-copy isn't- // reverted early by the previous click's timer.- if (resetTimerRef.current != null) {- clearTimeout(resetTimerRef.current);- }- resetTimerRef.current = setTimeout(() => {- resetTimerRef.current = null;- setCopied(false);- }, COPY_FEEDBACK_MS);- } catch {- // Clipboard failures leave the copied state unchanged.- }- }, [value, announce, t]);+ const handleCopy = useCallback(() => {+ void copy(value);+ }, [copy, value]);return (<IconButton@@ -163,9 +143,7 @@ function CopyButton({value}: {value: string}) {? t('@astryx.timestamp.copied'): t('@astryx.timestamp.copyValue', {value})}- onClick={() => {- void handleCopy();- }}+ onClick={handleCopy}{...themeProps('timestamp-copy-button')}/>);diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 90fdda38de..dfb3d84581 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -17,6 +17,9 @@ export type {UseFocusTrapOptions, UseFocusTrapReturn} from './useFocusTrap';export {useAnnounce} from './useAnnounce';export type {AnnounceFn, AnnouncePoliteness} from './useAnnounce';+export {useClipboard} from './useClipboard';+export type {UseClipboardOptions, UseClipboardReturn} from './useClipboard';+export {useGridFocus} from './useGridFocus';export type {UseGridFocusOptions, UseGridFocusReturn} from './useGridFocus';diff --git a/packages/core/src/hooks/useClipboard.doc.mjs b/packages/core/src/hooks/useClipboard.doc.mjsnew file mode 100644index 0000000000..1bcae27328--- /dev/null+++ b/packages/core/src/hooks/useClipboard.doc.mjs@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'useClipboard',+ displayName: 'useClipboard',+ keywords: [+ 'clipboard', 'copy', 'copied', 'paste', 'writeText', 'copy-to-clipboard',+ 'copy button', 'announce', 'a11y',+ ],+ params: [+ {+ name: 'options',+ type: 'UseClipboardOptions',+ description: 'Configuration object.',+ required: false,+ },+ {+ name: 'options.announce',+ type: 'string',+ description:+ 'Message announced to a polite live region on a successful copy. A swapped aria-label alone is not reliably announced, so pass the localized confirmation (e.g. "Copied") to have it spoken. Omit to skip the announcement.',+ required: false,+ },+ {+ name: 'options.resetAfterMs',+ type: 'number',+ description:+ 'Milliseconds isCopied stays true after a successful copy before reverting.',+ default: '2000',+ required: false,+ },+ ],+ returns: [+ {+ name: 'copy',+ type: '(text: string) => Promise<boolean>',+ description:+ 'Writes text to the clipboard. On success flips isCopied to true, announces the configured message, restarts the reset timer, and resolves true. A clipboard rejection is a silent no-op that leaves the copied state unchanged and resolves false.',+ },+ {+ name: 'isCopied',+ type: 'boolean',+ description:+ 'True for resetAfterMs after the most recent successful copy, then reverts. Drive the copied confirmation (e.g. a copy → check icon flip) off this.',+ },+ ],+ usage: {+ description:+ 'Copy-to-clipboard behavior: the clipboard write, a transient isCopied flag with its own reset timer, and an optional polite screen-reader announcement. Extracted so every copy affordance is a thin control over one implementation instead of re-deriving the timer and announcement. Rapid re-copies restart the reset timer so the confirmation always lasts the full duration, and the timer is cleaned up on unmount. CodeBlock and Timestamp build their built-in copy buttons on it; reach for it directly when building a copy affordance that is not a plain icon button (a menu item, a labeled text button, a copy-on-click value chip).',+ bestPractices: [+ { guidance: true, description: 'Drive the copied confirmation (copy → check icon, label swap) off the returned isCopied flag rather than tracking your own state.' },+ { guidance: true, description: 'Pass a localized announce message so the copy is spoken by screen readers — swapping the button aria-label alone is not reliably announced.' },+ { guidance: true, description: 'For the common compact icon copy button, render a ghost IconButton with a "Copy" tooltip and wire onClick to copy(); the tooltip stays "Copy" and the icon flip is the confirmation.' },+ { guidance: false, description: 'Track a separate copied useState alongside the hook; isCopied already reflects the copied window and resets itself.' },+ ],+ },+ relatedComponents: ['CodeBlock', 'Timestamp', 'IconButton'],+ relatedHooks: ['useAnnounce'],+ importPath: '@astryxdesign/core/hooks',+ category: 'interaction',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ 'Copy-to-clipboard behavior: clipboard write + transient isCopied flag with reset timer + optional polite SR announcement. One implementation shared by copy affordances instead of re-deriving timer/announce. Rapid re-copies restart the timer; timer cleaned up on unmount. CodeBlock/Timestamp build their copy buttons on it.',+ paramDescriptions: {+ options: 'config object.',+ 'options.announce': 'polite live-region message on successful copy (e.g. "Copied"); aria-label swap alone is not reliably announced. Omit to skip.',+ 'options.resetAfterMs': 'ms isCopied stays true after a copy before reverting.',+ },+ returnDescriptions: {+ copy: '(text) => Promise<boolean>: writes text, flips isCopied, announces, restarts reset timer, resolves true; silent no-op resolving false on rejection.',+ isCopied: 'true for resetAfterMs after the last successful copy; drive the copy → check confirmation off it.',+ },+ usage: {+ description:+ 'Copy-to-clipboard behavior (write + isCopied flag with reset timer + optional polite SR announce). Thin controls over one implementation. Rapid re-copies restart the timer; cleaned up on unmount. Use directly for copy affordances that are not plain icon buttons (menu item, labeled text button, value chip).',+ bestPractices: [+ { guidance: true, description: 'Drive the copy → check confirmation off the returned isCopied, not your own state.' },+ { guidance: true, description: 'Pass a localized announce so the copy is spoken (aria-label swap alone is not reliably announced).' },+ { guidance: false, description: 'Track a separate copied useState alongside the hook.' },+ ],+ },+};diff --git a/packages/core/src/hooks/useClipboard.test.tsx b/packages/core/src/hooks/useClipboard.test.tsxnew file mode 100644index 0000000000..2af474814e--- /dev/null+++ b/packages/core/src/hooks/useClipboard.test.tsx@@ -0,0 +1,151 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useClipboard.test.tsx+ * @input Uses vitest, @testing-library/react, useClipboard hook+ * @output Unit tests for the useClipboard copy behavior+ * @position Testing; validates useClipboard.ts+ *+ * SYNC: When useClipboard.ts changes, update tests to match new behavior+ */++import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {act, renderHook, waitFor} from '@testing-library/react';+import {useClipboard} from './useClipboard';+import {__resetLiveRegionsForTest} from './useAnnounce';++function politeRegion(): HTMLElement | null {+ return document.querySelector('[data-astryx-live-region="polite"]');+}++describe('useClipboard', () => {+ beforeEach(() => {+ // jsdom does not implement the async Clipboard API.+ Object.assign(navigator, {+ clipboard: {writeText: vi.fn().mockResolvedValue(undefined)},+ });+ });++ afterEach(() => {+ __resetLiveRegionsForTest();+ vi.restoreAllMocks();+ });++ it('writes the given text to the clipboard and resolves true', async () => {+ const {result} = renderHook(() => useClipboard());+ let outcome: boolean | undefined;+ await act(async () => {+ outcome = await result.current.copy('hello world');+ });+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('hello world');+ expect(outcome).toBe(true);+ });++ it('flips isCopied to true after a successful copy', async () => {+ const {result} = renderHook(() => useClipboard());+ expect(result.current.isCopied).toBe(false);+ await act(async () => {+ await result.current.copy('x');+ });+ expect(result.current.isCopied).toBe(true);+ });++ it('reverts isCopied after resetAfterMs', async () => {+ vi.useFakeTimers();+ try {+ const {result} = renderHook(() => useClipboard({resetAfterMs: 1000}));+ await act(async () => {+ await result.current.copy('x');+ });+ expect(result.current.isCopied).toBe(true);+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(result.current.isCopied).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps isCopied true for the full window after a rapid re-copy', async () => {+ vi.useFakeTimers();+ try {+ const {result} = renderHook(() => useClipboard({resetAfterMs: 2000}));+ await act(async () => {+ await result.current.copy('x');+ });+ expect(result.current.isCopied).toBe(true);++ // Re-copy partway through the window.+ act(() => {+ vi.advanceTimersByTime(1500);+ });+ await act(async () => {+ await result.current.copy('x');+ });++ // 600ms after the second copy (2.1s after the first): the first copy's+ // timer must not have reverted it early.+ act(() => {+ vi.advanceTimersByTime(600);+ });+ expect(result.current.isCopied).toBe(true);++ // It resets 2s after the most recent copy.+ act(() => {+ vi.advanceTimersByTime(1400);+ });+ expect(result.current.isCopied).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('announces the configured message to a polite live region', async () => {+ const {result} = renderHook(() => useClipboard({announce: 'Copied'}));+ await act(async () => {+ await result.current.copy('x');+ });+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Copied');+ });+ });++ it('does not announce when no announce message is configured', async () => {+ const {result} = renderHook(() => useClipboard());+ await act(async () => {+ await result.current.copy('x');+ });+ // No announce option → no live region is ever created.+ expect(politeRegion()).toBeNull();+ });++ it('is a silent no-op that resolves false when the clipboard rejects', async () => {+ (+ navigator.clipboard.writeText as ReturnType<typeof vi.fn>+ ).mockRejectedValue(new Error('denied'));+ const {result} = renderHook(() => useClipboard({announce: 'Copied'}));+ let outcome: boolean | undefined;+ await act(async () => {+ outcome = await result.current.copy('x');+ });+ expect(outcome).toBe(false);+ expect(result.current.isCopied).toBe(false);+ expect(politeRegion()).toBeNull();+ });++ it('clears a pending reset timer on unmount', async () => {+ vi.useFakeTimers();+ const clearSpy = vi.spyOn(globalThis, 'clearTimeout');+ try {+ const {result, unmount} = renderHook(() => useClipboard());+ await act(async () => {+ await result.current.copy('x');+ });+ unmount();+ expect(clearSpy).toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/packages/core/src/hooks/useClipboard.ts b/packages/core/src/hooks/useClipboard.tsnew file mode 100644index 0000000000..a06534817d--- /dev/null+++ b/packages/core/src/hooks/useClipboard.ts@@ -0,0 +1,135 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useClipboard.ts+ * @input Uses React state/effect/callback; navigator.clipboard; useAnnounce+ * @output Exports useClipboard hook plus its options/return types+ * @position Core behavior hook; owns the copy-to-clipboard behavior shared by+ * CodeBlock and Timestamp — the clipboard write, the transient "copied"+ * flag with its reset timer, and the polite screen-reader announcement — so+ * each call site is a thin control over one implementation instead of+ * re-deriving the timer/announce details independently.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/hooks/index.ts+ * - /packages/core/src/hooks/useClipboard.doc.mjs+ * - /packages/core/src/hooks/useClipboard.test.tsx+ */++import {useCallback, useEffect, useRef, useState} from 'react';+import {useAnnounce} from './useAnnounce';++/**+ * How long `isCopied` stays true after a successful copy before reverting.+ * Long enough for the copied confirmation (e.g. a copy → check icon flip) to+ * register without lingering.+ */+const DEFAULT_RESET_AFTER_MS = 2000;++/**+ * Options for {@link useClipboard}.+ */+export interface UseClipboardOptions {+ /**+ * Message announced to a polite live region on a successful copy. Swapping a+ * control's `aria-label` alone is not reliably announced by screen readers,+ * so pass the localized confirmation (e.g. "Copied") to have it spoken.+ * Omit to skip the announcement.+ */+ announce?: string;+ /**+ * Milliseconds `isCopied` stays true after a successful copy before it+ * reverts to false.+ * @default 2000+ */+ resetAfterMs?: number;+}++/**+ * Return value of {@link useClipboard}.+ */+export interface UseClipboardReturn {+ /**+ * Write `text` to the clipboard. On success, flips `isCopied` to true,+ * announces the configured message, and (re)starts the reset timer;+ * resolves `true`. A clipboard rejection is a silent no-op that leaves the+ * copied state unchanged and resolves `false`.+ */+ copy: (text: string) => Promise<boolean>;+ /** True for `resetAfterMs` after the most recent successful copy. */+ isCopied: boolean;+}++/**+ * Copy-to-clipboard behavior: the clipboard write, a transient `isCopied`+ * flag with its own reset timer, and an optional polite screen-reader+ * announcement — the block otherwise re-derived at every copy affordance.+ *+ * Per [API Conventions → Behaviors: Hooks Over Wrappers], the behavior is a+ * hook and the control (an icon button, a menu item, a value chip) is a thin+ * shell over it. Rapid re-copies restart the reset timer so the confirmation+ * always lasts the full duration, and the timer is cleaned up on unmount.+ *+ * @example+ * ```+ * function CopyButton({text}: {text: string}) {+ * const {copy, isCopied} = useClipboard({announce: 'Copied'});+ * return (+ * <IconButton+ * label={isCopied ? 'Copied' : 'Copy'}+ * tooltip="Copy"+ * icon={<Icon icon={isCopied ? 'check' : 'copy'} />}+ * onClick={() => void copy(text)}+ * />+ * );+ * }+ * ```+ */+export function useClipboard(+ options: UseClipboardOptions = {},+): UseClipboardReturn {+ const {announce: announceMessage, resetAfterMs = DEFAULT_RESET_AFTER_MS} =+ options;+ const announce = useAnnounce();+ const [isCopied, setIsCopied] = useState(false);+ const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ // Clear a pending "copied" reset when the consumer unmounts.+ useEffect(() => {+ return () => {+ if (resetTimerRef.current != null) {+ clearTimeout(resetTimerRef.current);+ }+ };+ }, []);++ const copy = useCallback(+ async (text: string): Promise<boolean> => {+ try {+ await navigator.clipboard.writeText(text);+ setIsCopied(true);+ if (announceMessage) {+ announce(announceMessage);+ }+ // Restart the reset timer on every copy — otherwise a rapid re-copy+ // is reverted early by the previous copy's timer.+ if (resetTimerRef.current != null) {+ clearTimeout(resetTimerRef.current);+ }+ resetTimerRef.current = setTimeout(() => {+ resetTimerRef.current = null;+ setIsCopied(false);+ }, resetAfterMs);+ return true;+ } catch {+ // Clipboard failures leave the copied state unchanged.+ return false;+ }+ },+ [announce, announceMessage, resetAfterMs],+ );++ return {copy, isCopied};+}