Skip to content

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

TypeScript

fix(core): CodeBlock says when a copy fails (#10272)

Cindy Zhang5a323635e339
diff --git a/.changeset/code-block-copy-failure.md b/.changeset/code-block-copy-failure.md
new file mode 100644
index 0000000000..5651fd742a
--- /dev/null
+++ b/.changeset/code-block-copy-failure.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `CodeBlock`'s copy button now says when copying fails. A rejected clipboard write used to look like nothing happened. Now the button shows a cross in place of the copy icon for 2 seconds, as a copy shows its check mark (a theme that maps the `code-block-copy` icon slot keeps its own rest glyph during the failure), and is named, tooltipped and announced as "Failed to copy value to clipboard." (a new localized key, `@astryx.codeBlock.copyFailed`). A new `onCopyError(error)` prop receives the rejection once per failed copy; the error itself is never shown.
+
+@cixzhang
diff --git a/docs/specs/components/CodeBlock/CodeBlock.spec.md b/docs/specs/components/CodeBlock/CodeBlock.spec.md
index dbd0044a08..dbed22b3d5 100644
--- a/docs/specs/components/CodeBlock/CodeBlock.spec.md
+++ b/docs/specs/components/CodeBlock/CodeBlock.spec.md
@@ -89,26 +89,27 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
-| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ----------- | ------------------- | --------- | -------------------------------------------------------------------------------------------------------------- |
-| code content | caller-supplied string | Supplies the exact read-only source that is displayed and copied. | Every render | required | product callsite | stable | rejected by the public type |
-| language | built-in identifier (FR12), language value (FR13: an Astryx module or a custom language), or plaintext/unknown | Selects tokenization and the optional visible/accessible language label. | Every render | `plaintext` | component:CodeBlock | stable | an identifier with no built-in grammar renders without tokens unless the deprecated custom tokenizer paints it |
-| line presentation | numbers off/on; highlights absent or one-indexed line set; wrapped/unwrapped | Adds navigation and emphasis without changing the copied source string. | Code body | off/absent | component:CodeBlock | stable | out-of-range highlights have no rendered line |
-| diff layer | off; on — each line classified by its first character: `+` added, `-` removed, header (`@@`; a `--- `/`+++ ` pair directly before an `@@`), else context | Tints added and removed rows and quiets header rows from the syntax theme while the rest of every line keeps the base language's syntax paint; the glyph stays in display and copy. | Code body, any `language` | off | product callsite | stable | rejected by the public type (boolean) |
-| header | absent; title; language label; title and language label | Gives the snippet context and houses the caller controls and copy when it exists. | Derived from title and label choices | derived | component:CodeBlock | stable | empty visible content still requires AT naming |
-| copy | hidden; available; transient copied feedback | Copies the exact code string, then invokes `onCopy` only after a successful clipboard write. | Every render when enabled | available | component:CodeBlock | stable | failed clipboard writes do not invoke `onCopy` |
-| caller controls (`endContent`) | absent; caller-rendered nodes | Places product actions beside Copy, before it in reading order, in the header or the corner cluster; never creates the header. | Every render | absent | product callsite | stable | any React node; CodeBlock does not inspect it |
-| corner cluster | absent; caller controls and copy, in that order | Holds the controls of a block with no header in their own inline-end column beside the code, centred on the first line. | Blocks with no header and any control | derived | component:CodeBlock | stable | an empty cluster takes no column |
-| syntax rendering | auto; CSS ranges; spans; deprecated custom tokenizer; optional per-instance syntax theme | Selects a supported paint path without changing the text or public code semantics. | Every render | `auto` | component:CodeBlock | stable | unsupported range capability falls back to spans |
-| collapse | unavailable; expanded; collapsed | Turns an eligible visible header into a disclosure when the line threshold is met. | Long blocks with a header and collapse enabled | unavailable | component:CodeBlock | stable | missing-header or below-threshold blocks remain expanded and ordinary |
-| container geometry | card/section; small/medium; fit-content/custom width; unbounded/bounded height | Selects presentation and overflow geometry while preserving the read-only code task. | Every render | card/md | component:CodeBlock | stable | values follow their documented CSS/type behavior |
+| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
+| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ----------- | ------------------- | --------- | -------------------------------------------------------------------------------------------------------------- |
+| code content | caller-supplied string | Supplies the exact read-only source that is displayed and copied. | Every render | required | product callsite | stable | rejected by the public type |
+| language | built-in identifier (FR12), language value (FR13: an Astryx module or a custom language), or plaintext/unknown | Selects tokenization and the optional visible/accessible language label. | Every render | `plaintext` | component:CodeBlock | stable | an identifier with no built-in grammar renders without tokens unless the deprecated custom tokenizer paints it |
+| line presentation | numbers off/on; highlights absent or one-indexed line set; wrapped/unwrapped | Adds navigation and emphasis without changing the copied source string. | Code body | off/absent | component:CodeBlock | stable | out-of-range highlights have no rendered line |
+| diff layer | off; on — each line classified by its first character: `+` added, `-` removed, header (`@@`; a `--- `/`+++ ` pair directly before an `@@`), else context | Tints added and removed rows and quiets header rows from the syntax theme while the rest of every line keeps the base language's syntax paint; the glyph stays in display and copy. | Code body, any `language` | off | product callsite | stable | rejected by the public type (boolean) |
+| header | absent; title; language label; title and language label | Gives the snippet context and houses the caller controls and copy when it exists. | Derived from title and label choices | derived | component:CodeBlock | stable | empty visible content still requires AT naming |
+| copy | hidden; available; transient copied feedback; transient failure feedback | Copies the exact code string, then invokes `onCopy` only after a successful clipboard write; a failed write shows the failure feedback instead (FR2). | Every render when enabled | available | component:CodeBlock | stable | failed clipboard writes do not invoke `onCopy` |
+| copy failure callback (`onCopyError`) | absent; `(error: unknown) => void` | Receives the clipboard rejection once per failed write, so the product can log or recover; the control shows and announces the failure itself (FR2). Owner decision, Nov 6 2026 (Cindy). | Every render when copy is enabled | absent | component:CodeBlock | stable | TypeScript rejects other values; a successful write never calls it |
+| caller controls (`endContent`) | absent; caller-rendered nodes | Places product actions beside Copy, before it in reading order, in the header or the corner cluster; never creates the header. | Every render | absent | product callsite | stable | any React node; CodeBlock does not inspect it |
+| corner cluster | absent; caller controls and copy, in that order | Holds the controls of a block with no header in their own inline-end column beside the code, centred on the first line. | Blocks with no header and any control | derived | component:CodeBlock | stable | an empty cluster takes no column |
+| syntax rendering | auto; CSS ranges; spans; deprecated custom tokenizer; optional per-instance syntax theme | Selects a supported paint path without changing the text or public code semantics. | Every render | `auto` | component:CodeBlock | stable | unsupported range capability falls back to spans |
+| collapse | unavailable; expanded; collapsed | Turns an eligible visible header into a disclosure when the line threshold is met. | Long blocks with a header and collapse enabled | unavailable | component:CodeBlock | stable | missing-header or below-threshold blocks remain expanded and ordinary |
+| container geometry | card/section; small/medium; fit-content/custom width; unbounded/bounded height | Selects presentation and overflow geometry while preserving the read-only code task. | Every render | card/md | component:CodeBlock | stable | values follow their documented CSS/type behavior |
## Behavioral and layout contract
| ID | Candidate invariant | Basis | Draft review state |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| FR1 | CodeBlock MUST display the caller's code string as read-only code. Built-in or custom tokenization MAY change syntax paint but MUST NOT change displayed or copied source text. | released types, source, tests, consumer docs; established public interface | verify |
-| FR2 | A successful copy MUST write the exact `code` string, invoke `onCopy` once, expose localized copied feedback, and preserve the copy control's discoverable purpose. A failed write MUST NOT report success. | shipped source/tests; `architecture:component-test-sufficiency/INV2–INV6`; WCAG name/status obligations | verify |
+| FR2 | A successful copy MUST write the exact `code` string, invoke `onCopy` once, expose localized copied feedback, and preserve the copy control's discoverable purpose. A failed write MUST NOT report success: it shows a cross icon in place of the copy icon and names and announces the control as the localized "Failed to copy value to clipboard." for as long as the copied feedback would show, and calls `onCopyError` once with the rejection; the error detail is not exposed (Owner decision, Nov 6 2026 (Cindy)). | shipped source/tests; `architecture:component-test-sufficiency/INV2–INV6`; WCAG name/status obligations | verify |
| FR3 | A title or visible non-plaintext language label MUST create the visible header, at every line count. Hiding the language label MUST NOT remove copy behavior. Headerless copy remains available when enabled. `endContent` never creates the header. | released types, source, tests, consumer docs; established public interface; proposal for `endContent` | verify |
| FR4 | Line numbers, highlighted lines, wrapping, width, container presentation, size, and maximum height MUST affect only their documented presentation axes. Numeric `maxHeight={0}` MUST remain a valid zero-pixel bound rather than being discarded. | released public type/docs; `architecture:public-component-api/INV3,INV9`; objective JavaScript nullish semantics | verified by focused regression |
| FR5 | Collapse MUST become available only when enabled, a visible header exists, and the line threshold is met. The control MUST expose expanded state and a resolvable controlled region; collapsed content remains mounted but inert, and losing the control expands the region before hiding the control. | shipped docs/source/tests; WAI-ARIA disclosure pattern and HTML `inert` semantics | verify |
@@ -121,7 +122,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR12 | Without the deprecated `tokenizer`, given a built-in identifier, CodeBlock MUST paint syntax for these built-in identifiers and their aliases: `typescript`/`ts`, `javascript`/`js`, `tsx`, `jsx`; `json`; `html`, `xml`, `svg`; `css`, `scss`, `less`; `python`/`py`; `bash`, `sh`, `zsh`, `shell`; `php`; `hack`; `yaml`/`yml`; `markdown`/`md`; `c`, `h`; `cpp`, `c++`, `cc`, `cxx`, `hpp`, `hh`; `sql`; `rust`/`rs`; `kotlin`, `kt`, `kts`; `swift`; `go`/`golang`. Each built-in paints the comment, string, number, and keyword tokens its language has from the syntax theme. Any other identifier renders as plain code with its label unless the deprecated `tokenizer` paints it; an identifier string never resolves to a language value. | proposal | verify |
| FR13 | Each less common language MUST be its own module, one per subpath, each exporting one language value: `graphql` (`graphql`, `gql`), `java` (`java`), `thrift` (`thrift`), `objectiveC` (`objective-c`, `objc`, `m`, `mm`), `toml` (`toml`), `powershell` (`powershell`, `ps1`, `pwsh`), `ruby` (`ruby`, `rb`), `lua` (`lua`), and `dockerfile` (`dockerfile`, `docker`), at `@astryxdesign/core/CodeBlock/languages/<path>`, where `<path>` is the export's name in kebab case (`languages/graphql` exports `graphql`, `languages/objective-c` exports `objectiveC`). A language value is a `CodeLanguage` carrying everything needed to render that language: read-only `name` (the identifier its label shows, such as `graphql`: code text shown verbatim like a built-in identifier, never translated prose, so it needs no catalog entry), `identifiers`, `fileExtensions`, and `fileNames` (for example `graphql`, or `Dockerfile`), all required, and its grammar, which stays internal. `language` MUST accept a language value as well as an identifier string: given one, CodeBlock paints the code with that language, labels it with its `name`, and reflects its first identifier wherever it reflects the language, such as `data-language` on its theme targets (FR6), in the same render as a built-in would; a string selects only a built-in grammar (FR12). There is no provider, registry, or grouped export: each module is imported and passed on its own, and only modules a bundle imports reach it. A custom language is the same kind of value: `createCodeLanguage({name, identifiers, fileExtensions, fileNames, tokenize})`, exported from `@astryxdesign/core/CodeBlock`, makes one from a caller's `tokenize(code, language)` function returning `{type, start, end}` tokens, which runs synchronously; `fileExtensions` and `fileNames` default to none. It is passed and listed exactly like an Astryx module, and Astryx modules keep their grammar internal. In a `codeLanguages` list, a listed value takes precedence over a built-in with the same identifier, and a later entry over an earlier one. The released `tokenizer` prop is deprecated and still works exactly as released, taking precedence over the language's grammar; it is removed only at a minor release, and a codemod rewrites a block whose `language` is a static string literal other than `plaintext` to a custom language passed as `language`, whose first identifier is that string, and reports every other use it cannot rewrite. The exported `tokenize`, `tokenizeAsync`, and `tokenizeStreaming` MUST accept a language value wherever they accept a language identifier. A surface that sees only a fence's language word takes modules through its own prop: `Markdown`'s `codeLanguages` (`component:Markdown` FR30) and RichText's (`spec:AST-061`). Lab's `DiffViewer` takes a language value as its `language` the same way; without one it infers a file's language from the file's extension or name among the built-ins and the values in its own `codeLanguages`, and an unmatched file stays plain. It tokenizes each hunk's old and new side as continuous text with whichever grammar applies, and its line-number gutters and change marks are unaffected. Modules are opaque values: CodeBlock exposes no grammar format. The module is the portable form of a language (`spec:AST-082/FR3`): a platform CodeBlock takes the same kind of value for its language. | proposal | verify |
| FR14 | Current state, not owner-reviewed. `startLineNumber` (default 1) MUST set the number of the first line in the source file. The gutter MUST show file coordinates (`startLineNumber + index`), so an excerpt reads with its real line numbers. A value below 1 MUST clamp to 1. `highlightLines` MUST use the same file coordinates, and an out-of-range entry MUST render no highlight. The offset MUST NOT change the displayed or copied source text (FR1). | released public type and JSDoc; shipped API | verify |
-| FR15 | The copy control's glyph MUST resolve through the `code-block-copy` component icon slot, passing `{copied}`, which is true while the copied feedback (FR2) shows. With no theme entry, the glyph is `copy`, and `check` while copied. When the slot resolves to no icon (a theme value of `null`, a slot function that returns `null`, or a request with `icon: null`), only the glyph is hidden: the control keeps its size, name, tooltip, and copy behavior, and shows no glyph at rest or while copied. A request `size` changes only the glyph, never the control. | proposal; `architecture:icon-resolution-and-component-slots/INV2,INV4–INV8` | verify |
+| FR15 | The copy control's glyph MUST resolve through the `code-block-copy` component icon slot, passing `{copied}`, which is true while the copied feedback (FR2) shows. With no theme entry, the glyph is `copy`, `check` while copied, and a cross while a failed write shows (FR2), when `{copied}` is false. When the slot resolves to no icon (a theme value of `null`, a slot function that returns `null`, or a request with `icon: null`), only the glyph is hidden: the control keeps its size, name, tooltip, and copy behavior, and shows no glyph at rest or while copied. A request `size` changes only the glyph, never the control. | proposal; `architecture:icon-resolution-and-component-slots/INV2,INV4–INV8` | verify |
### Allowed variation
@@ -201,7 +202,7 @@ Exact CodeBlock proportions and syntax colors are not contract requirements; the
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| FR1, PR1–PR3 | `tokenizer.test.ts`; `highlightRanges.test.ts`; CodeBlock focused tests and built Storybook | short/long, built-in/custom, ranges/spans, empty lines | Text changes, stale tokens paint, ranges leak, source order changes, or long work stops yielding/canceling. | `audit:CodeBlock/behavior` |
| FR12, FR13, PR4 | `tokenizer.test.ts` (one representative snippet per built-in family and alias, and per module: the comment, string, number, and keyword tokens each language has; an unknown identifier yields no tokens, and a module's identifier passed as a string yields none); CodeBlock, Markdown, RichText, and Lab `DiffViewer` tests (a module passed as `language`, or listed in `codeLanguages`, paints and labels; `DiffViewer` infers a listed module from a file's extension or name; the same identifier or file without it stays plain; a custom language from `createCodeLanguage` paints, labels, and infers like a module; a listed value beats a built-in with the same identifier; the deprecated `tokenizer` still wins over a built-in identifier and a language value and still works as released; a language value reflects its first identifier as `data-language`; the codemod rewrites static non-`plaintext` uses, keeps their `data-language` and label, and reports the rest; server rendering paints in the first render); a size check over the minified, gzipped tokenizer and each module, and a bundle check that an unimported module adds nothing | every FR12 identifier and alias, every FR13 module passed as `language` and in `codeLanguages`, a diffed file named by a module's extension or file name, a module identifier as a plain string, a custom language passed and listed, a custom language reusing a built-in identifier, the deprecated `tokenizer` alone, with a built-in identifier, and with a language value, an unknown identifier, an empty string | A listed identifier renders without tokens, an alias paints differently from its family, a string resolves to a module, a module fails to paint or label on any of the four surfaces, a diffed file infers a module that was not listed, a custom language behaves differently from a module, a listed value loses to a built-in, the deprecated `tokenizer` stops working or loses to a language value, a language value reflects anything but its first identifier, the codemod rewrites a use it cannot prove or drops one silently, source text changes, the tokenizer exceeds 4,608 bytes, a module adds more than 512 bytes, or an unimported module reaches the bundle. | `audit:CodeBlock/behavior` |
-| FR2, AR1, AR3 | `CodeBlock.test.tsx`; component-scoped accessibility audit | copy success, rapid repeat, localized feedback, empty title | Exact source is not copied, callback fires on failure, announcement is absent/duplicated, or a control is unnamed. | `audit:CodeBlock/a11y` |
+| FR2, AR1, AR3 | `CodeBlock.test.tsx`; component-scoped accessibility audit; the failed-write suite (a rejected `writeText`: cross icon, failure name, tooltip and announcement, `onCopyError` once with the rejection and no `onCopy`, the same 2 s reset, a later success clears it) | copy success, rapid repeat, localized feedback, empty title | Exact source is not copied, callback fires on failure, announcement is absent/duplicated, or a control is unnamed. | `audit:CodeBlock/a11y` |
| FR3–FR5, AR2 | `CodeBlock.test.tsx`; `CodeBlock.stories.tsx`; exact-head browser evidence | headerless, titled, zero max height, line options, collapse/control removal | Header/copy placement changes, zero is dropped, disclosure state/wiring/keyboard behavior breaks, or inert outlives its control. | `audit:CodeBlock/behavior` |
| FR6 | `themingTargets.test.ts`; consumer docs; source review | root, header, title, copy; current and deprecated names | A target leaves its painter, an axis stops reflecting, or a deprecated alias disappears before authorization. | `audit:CodeBlock/theming` |
| FR7 | focused root-prop/ref tests; strict lint/typecheck; consumer-doc validation | ref plus supported root/style/data/ARIA inputs | The ref misses the root, accepted props disappear, or styling inputs replace rather than compose. | `audit:CodeBlock/api` |
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 1fbf783309..afc8e6b520 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -641,6 +641,7 @@ component CodeBlock(props: CodeBlockProps)
prop language?: string | CodeLanguage = 'plaintext'
prop maxHeight?: number | string
prop onCopy?: () => void
+ prop onCopyError?: (error: unknown) => void
prop ref?: React.Ref<HTMLPreElement>
prop size?: 'sm' | 'md'
prop startLineNumber?: number = 1
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index ad9df0def4..b79518a646 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1423,6 +1423,10 @@
"defaultMessage": "Copy code",
"description": "\"Code\" = source code. Aria label AND tooltip on the CodeBlock copy button in its default state. Pairs with `codeBlock.copied` (post-click state)."
},
+ "@astryx.codeBlock.copyFailed": {
+ "defaultMessage": "Failed to copy value to clipboard.",
+ "description": "Aria label, tooltip and screen-reader announcement on the CodeBlock copy button for ~2s after the clipboard write fails. Pairs with `codeBlock.copyCode` and `codeBlock.copied`."
+ },
"@astryx.codeBlock.code": {
"defaultMessage": "Code",
"description": "Screen-reader-only fallback name for a code-snippet scroll container when the code's language is unknown. \"Code\" = source code, not secret code or code of conduct."
diff --git a/packages/core/src/CodeBlock/CodeBlock.doc.mjs b/packages/core/src/CodeBlock/CodeBlock.doc.mjs
index 20d6f1851a..ae51a9ef2a 100644
--- a/packages/core/src/CodeBlock/CodeBlock.doc.mjs
+++ b/packages/core/src/CodeBlock/CodeBlock.doc.mjs
@@ -82,6 +82,12 @@ export const docs = {
type: '() => void',
description: 'Callback after the code is copied.',
},
+ {
+ name: 'onCopyError',
+ type: '(error: unknown) => void',
+ description:
+ 'Called once with the rejection when the clipboard write fails. The copy button shows a cross and is named and announced as "Failed to copy value to clipboard."; the error is not shown.',
+ },
{
name: 'endContent',
type: 'ReactNode',
@@ -223,13 +229,14 @@ export const docs = {
{
slot: 'code-block-copy',
description: 'The copy button icon.',
- fallback: '`copy`; `check` while copied',
+ fallback:
+ '`copy`; `check` while copied; `close` while a failed copy shows',
state: [
{
name: 'copied',
type: 'boolean',
description:
- 'True while the copied feedback shows after a successful copy.',
+ 'True while the copied feedback shows after a successful copy. False while a failed copy shows, so a theme that maps the slot draws its rest glyph then; the button is still named and announced as the failure.',
},
],
whenNull:
diff --git a/packages/core/src/CodeBlock/CodeBlock.test.tsx b/packages/core/src/CodeBlock/CodeBlock.test.tsx
index e7168c6b96..06e6ad64c9 100644
--- a/packages/core/src/CodeBlock/CodeBlock.test.tsx
+++ b/packages/core/src/CodeBlock/CodeBlock.test.tsx
@@ -264,6 +264,104 @@ describe('CodeBlock', () => {
expect(screen.getByRole('button', {name: 'Copié'})).toBeInTheDocument();
});
+ describe('when the clipboard write fails', () => {
+ function rejectWrites() {
+ const error = new DOMException(
+ 'Write permission denied.',
+ 'NotAllowedError',
+ );
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {writeText: vi.fn().mockRejectedValue(error)},
+ });
+ return error;
+ }
+
+ it('shows a cross, names the control and announces the failure, without the error', async () => {
+ rejectWrites();
+ render(<CodeBlock code="const x = 1;" language="javascript" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));
+ const failed = await screen.findByRole('button', {
+ name: 'Failed to copy value to clipboard.',
+ });
+ // The tooltip says the same as the name, so Button does not repeat it
+ // as a description.
+ expect(failed).not.toHaveAttribute('aria-describedby');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent(
+ 'Failed to copy value to clipboard.',
+ );
+ });
+ expect(politeRegion()).not.toHaveTextContent('permission');
+ });
+
+ it('calls onCopyError once with the rejection and never onCopy', async () => {
+ const error = rejectWrites();
+ const onCopy = vi.fn();
+ const onCopyError = vi.fn();
+ render(
+ <CodeBlock
+ code="const x = 1;"
+ onCopy={onCopy}
+ onCopyError={onCopyError}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));
+ await screen.findByRole('button', {
+ name: 'Failed to copy value to clipboard.',
+ });
+ expect(onCopyError).toHaveBeenCalledTimes(1);
+ expect(onCopyError).toHaveBeenCalledWith(error);
+ expect(onCopy).not.toHaveBeenCalled();
+ });
+
+ it('returns to Copy code after the same 2s a copy shows its check', async () => {
+ rejectWrites();
+ vi.useFakeTimers();
+ try {
+ render(<CodeBlock code="const x = 1;" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));
+ await act(async () => {});
+ expect(
+ screen.getByRole('button', {
+ name: 'Failed to copy value to clipboard.',
+ }),
+ ).toBeInTheDocument();
+ act(() => {
+ vi.advanceTimersByTime(1999);
+ });
+ expect(
+ screen.getByRole('button', {
+ name: 'Failed to copy value to clipboard.',
+ }),
+ ).toBeInTheDocument();
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(
+ screen.getByRole('button', {name: 'Copy code'}),
+ ).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('clears the failure when a later copy succeeds', async () => {
+ rejectWrites();
+ render(<CodeBlock code="const x = 1;" />);
+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));
+ const failed = await screen.findByRole('button', {
+ name: 'Failed to copy value to clipboard.',
+ });
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {writeText: vi.fn().mockResolvedValue(undefined)},
+ });
+ fireEvent.click(failed);
+ await screen.findByRole('button', {name: 'Copied'});
+ });
+ });
+
it('keeps the copied indicator a full 2s after a rapid re-copy', async () => {
vi.useFakeTimers();
try {
@@ -796,6 +894,7 @@ describe('CodeBlock copy icon slot', () => {
check: <span data-icon="check" />,
clock: <span data-icon="clock" />,
checkDouble: <span data-icon="checkDouble" />,
+ close: <span data-icon="close" />,
};
beforeEach(() => {
@@ -839,6 +938,20 @@ describe('CodeBlock copy icon slot', () => {
expect(glyphOf('Copied')).toBe('check');
});
+ it('draws a cross while a failed write shows, when the theme maps nothing', async () => {
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {writeText: vi.fn().mockRejectedValue(new Error('denied'))},
+ });
+ renderInTheme(defineTheme({name: 'copy-slot-failure', icons}));
+
+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));
+ await screen.findByRole('button', {
+ name: 'Failed to copy value to clipboard.',
+ });
+ expect(glyphOf('Failed to copy value to clipboard.')).toBe('close');
+ });
+
it('passes `copied` to a slot function and draws the name it returns', async () => {
const slot = vi.fn(({copied}: {copied: boolean}) => ({
icon: copied ? ('checkDouble' as const) : ('clock' as const),
diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsx
index ad6651adae..bb5a50b42c 100644
--- a/packages/core/src/CodeBlock/CodeBlock.tsx
+++ b/packages/core/src/CodeBlock/CodeBlock.tsx
@@ -35,7 +35,7 @@ import {
focusVars,
} from '../theme/tokens.stylex';
import {isRenderable, mergeProps, rtlStyles} from '../utils';
-import {useClipboard} from '../hooks/useClipboard';
+import {useClipboardCopy} from '../hooks/useClipboard';
import {useScrollableArea} from '../hooks/useScrollableArea';
import {Icon} from '../Icon';
import {ComponentIcon} from '../Icon/ComponentIcon';
@@ -605,6 +605,12 @@ export interface CodeBlockProps extends BaseProps<HTMLPreElement> {
isDiff?: boolean;
hasCopyButton?: boolean;
onCopy?: () => void;
+ /**
+ * Called once with the rejection when the clipboard write fails. The copy
+ * control then shows a cross and is named and announced as the localized
+ * "Failed to copy value to clipboard."; the error itself is not shown.
+ */
+ onCopyError?: (error: unknown) => void;
/**
* Your own controls, shown just before Copy: in the header when the block
* has one, otherwise beside the code in the top inline-end corner, never
@@ -1005,6 +1011,7 @@ export function CodeBlock({
isDiff = false,
hasCopyButton = true,
onCopy,
+ onCopyError,
endContent,
isWrapped = false,
maxHeight,
@@ -1026,8 +1033,17 @@ export function CodeBlock({
// 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({
+ // A failed write shows a cross for as long as a copy shows the check, and
+ // is named and announced as the localized failure (Owner decision, Nov 6
+ // 2026). The error itself goes only to `onCopyError`.
+ const {
+ copy,
+ isCopied: copied,
+ isFailed: copyFailed,
+ } = useClipboardCopy({
announce: t('@astryx.codeBlock.copied'),
+ announceFailure: t('@astryx.codeBlock.copyFailed'),
+ onError: onCopyError,
});
const useSpans =
@@ -1151,18 +1167,30 @@ export function CodeBlock({
icon={
<ComponentIcon
slot="code-block-copy"
- state={{copied}}
- fallback={{icon: copied ? 'check' : 'copy', size: 'sm'}}
+ state={{copied: copied && !copyFailed}}
+ fallback={{
+ icon: copyFailed ? 'close' : 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')}
+ // confirmation — and says the failure while a failed copy shows. The
+ // aria-label swaps to the localized "Copied" or failure text, backed by
+ // the announcement.
+ tooltip={
+ copyFailed
+ ? t('@astryx.codeBlock.copyFailed')
+ : t('@astryx.codeBlock.copyCode')
+ }
label={
- copied ? t('@astryx.codeBlock.copied') : t('@astryx.codeBlock.copyCode')
+ copyFailed
+ ? t('@astryx.codeBlock.copyFailed')
+ : copied
+ ? t('@astryx.codeBlock.copied')
+ : t('@astryx.codeBlock.copyCode')
}
onClick={e => {
// Stop propagation so copying does not toggle the collapsible header.
diff --git a/packages/core/src/hooks/useClipboard.test.tsx b/packages/core/src/hooks/useClipboard.test.tsx
index 2af474814e..9a8b85157d 100644
--- a/packages/core/src/hooks/useClipboard.test.tsx
+++ b/packages/core/src/hooks/useClipboard.test.tsx
@@ -11,7 +11,7 @@
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {act, renderHook, waitFor} from '@testing-library/react';
-import {useClipboard} from './useClipboard';
+import {useClipboard, useClipboardCopy} from './useClipboard';
import {__resetLiveRegionsForTest} from './useAnnounce';
function politeRegion(): HTMLElement | null {
@@ -149,3 +149,58 @@ describe('useClipboard', () => {
}
});
});
+
+describe('useClipboardCopy (internal)', () => {
+ const error = new Error('denied');
+ beforeEach(() => {
+ Object.assign(navigator, {
+ clipboard: {writeText: vi.fn().mockRejectedValue(error)},
+ });
+ });
+ afterEach(() => {
+ __resetLiveRegionsForTest();
+ vi.useRealTimers();
+ });
+
+ it('reports a failed write once, for as long as a copy shows, and leaves isCopied alone', async () => {
+ vi.useFakeTimers();
+ const onError = vi.fn();
+ const {result} = renderHook(() =>
+ useClipboardCopy({announceFailure: 'Failed', onError}),
+ );
+ let ok: boolean | undefined;
+ await act(async () => {
+ ok = await result.current.copy('x');
+ });
+ expect(ok).toBe(false);
+ expect(result.current.isFailed).toBe(true);
+ expect(result.current.isCopied).toBe(false);
+ expect(onError).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledWith(error);
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ expect(result.current.isFailed).toBe(false);
+ });
+
+ it('clears the failure when a later write succeeds', async () => {
+ const {result} = renderHook(() => useClipboardCopy());
+ await act(async () => {
+ await result.current.copy('x');
+ });
+ expect(result.current.isFailed).toBe(true);
+ Object.assign(navigator, {
+ clipboard: {writeText: vi.fn().mockResolvedValue(undefined)},
+ });
+ await act(async () => {
+ await result.current.copy('x');
+ });
+ expect(result.current.isFailed).toBe(false);
+ expect(result.current.isCopied).toBe(true);
+ });
+
+ it('keeps the public hook to copy and isCopied', () => {
+ const {result} = renderHook(() => useClipboard());
+ expect(Object.keys(result.current).sort()).toEqual(['copy', 'isCopied']);
+ });
+});
diff --git a/packages/core/src/hooks/useClipboard.ts b/packages/core/src/hooks/useClipboard.ts
index a06534817d..336d7706d8 100644
--- a/packages/core/src/hooks/useClipboard.ts
+++ b/packages/core/src/hooks/useClipboard.ts
@@ -90,18 +90,62 @@ export interface UseClipboardReturn {
export function useClipboard(
options: UseClipboardOptions = {},
): UseClipboardReturn {
- const {announce: announceMessage, resetAfterMs = DEFAULT_RESET_AFTER_MS} =
- options;
+ const {copy, isCopied} = useClipboardCopy(options);
+ return {copy, isCopied};
+}
+
+/**
+ * Options of {@link useClipboardCopy}: the public options plus what a
+ * component needs to report a failed write.
+ */
+export interface UseClipboardCopyOptions extends UseClipboardOptions {
+ /** Message announced to the polite live region when a write fails. */
+ announceFailure?: string;
+ /**
+ * Called once with the rejection when a write fails. `copy` still resolves
+ * `false`, and `isCopied` is unchanged.
+ */
+ onError?: (error: unknown) => void;
+}
+
+/** Return value of {@link useClipboardCopy}. */
+export interface UseClipboardCopyReturn extends UseClipboardReturn {
+ /**
+ * True for `resetAfterMs` after the most recent write failed, until a write
+ * succeeds.
+ */
+ isFailed: boolean;
+}
+
+/**
+ * The body of {@link useClipboard}, plus the failed-write state a copy control
+ * shows (CodeBlock's cross and its `onCopyError`). Not exported from the
+ * package: the public hook's options and return type stay as they are.
+ */
+export function useClipboardCopy(
+ options: UseClipboardCopyOptions = {},
+): UseClipboardCopyReturn {
+ const {
+ announce: announceMessage,
+ announceFailure,
+ resetAfterMs = DEFAULT_RESET_AFTER_MS,
+ onError,
+ } = options;
const announce = useAnnounce();
const [isCopied, setIsCopied] = useState(false);
+ const [isFailed, setIsFailed] = useState(false);
const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const failedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // Clear a pending "copied" reset when the consumer unmounts.
+ // Clear pending resets when the consumer unmounts.
useEffect(() => {
return () => {
if (resetTimerRef.current != null) {
clearTimeout(resetTimerRef.current);
}
+ if (failedTimerRef.current != null) {
+ clearTimeout(failedTimerRef.current);
+ }
};
}, []);
@@ -109,27 +153,45 @@ export function useClipboard(
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);
+ } catch (error) {
+ // A failure leaves the copied state unchanged; it shows for as long
+ // as a copy would.
+ setIsFailed(true);
+ if (failedTimerRef.current != null) {
+ clearTimeout(failedTimerRef.current);
}
- resetTimerRef.current = setTimeout(() => {
- resetTimerRef.current = null;
- setIsCopied(false);
+ failedTimerRef.current = setTimeout(() => {
+ failedTimerRef.current = null;
+ setIsFailed(false);
}, resetAfterMs);
- return true;
- } catch {
- // Clipboard failures leave the copied state unchanged.
+ if (announceFailure) {
+ announce(announceFailure);
+ }
+ onError?.(error);
return false;
}
+ if (failedTimerRef.current != null) {
+ clearTimeout(failedTimerRef.current);
+ failedTimerRef.current = null;
+ }
+ setIsFailed(false);
+ 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;
},
- [announce, announceMessage, resetAfterMs],
+ [announce, announceMessage, announceFailure, resetAfterMs, onError],
);
- return {copy, isCopied};
+ return {copy, isCopied, isFailed};
}