An open source design system that's fully customizable and agent ready
TypeScript
feat(CodeBlock): endContent places caller controls beside Copy (#8285)
Cindy Zhang01e47f5d0270
diff --git a/.changeset/codeblock-end-content.md b/.changeset/codeblock-end-content.mdnew file mode 100644index 0000000000..469884271b--- /dev/null+++ b/.changeset/codeblock-end-content.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `CodeBlock` takes `endContent`, a slot for your own controls, such as a "Run in terminal" button. They appear just before Copy: in the header when the block has one, otherwise beside the code in the top inline-end corner, never over it. The slot never creates a header, and clicking or pressing keys in it never collapses the block. For single-line mode, leave out the title and pass `hasLanguageLabel={false}`: a one-line command then reads as one row with its controls beside it.++@cixzhangdiff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex 80230ac139..63e574f37e 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -415,6 +415,24 @@"next": ".astryx-code-block-copy-button"}},+ {+ "component": "CodeBlock",+ "storyId": "core-codeblock--end-content",+ "dims": ["D2"],+ "selectors": {+ "prev": "[aria-label=\"Run in terminal\"]",+ "next": ".astryx-code-block-copy-button"+ }+ },+ {+ "component": "CodeBlock",+ "storyId": "core-codeblock--end-content-headerless",+ "dims": ["D2"],+ "selectors": {+ "prev": "[aria-label=\"Run in terminal\"]",+ "next": ".astryx-code-block-copy-button"+ }+ },{"component": "FileInput","storyId": "core-fileinput--with-error-status",diff --git a/apps/storybook/stories/CodeBlock.stories.tsx b/apps/storybook/stories/CodeBlock.stories.tsxindex 6a4613cd00..7b7afd0c89 100644--- a/apps/storybook/stories/CodeBlock.stories.tsx+++ b/apps/storybook/stories/CodeBlock.stories.tsx@@ -2,6 +2,7 @@import type {Meta, StoryObj} from '@storybook/react';import {CodeBlock} from '@astryxdesign/core/CodeBlock';+import {IconButton} from '@astryxdesign/core/IconButton';const meta: Meta<typeof CodeBlock> = {title: 'Core/CodeBlock',@@ -163,6 +164,68 @@ export const CopyClearance: Story = {},};+// A product action beside Copy, as a ghost sm IconButton like Copy. With a+// header it sits in the header; with no title and the label hidden it sits+// in the corner column beside the code.+const terminalIcon = (+ <svg+ viewBox="0 0 24 24"+ width={16}+ height={16}+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true">+ <path d="m7 11 2-2-2-2" />+ <path d="M11 13h4" />+ <rect x="3" y="3" width="18" height="18" rx="2" />+ </svg>+);+const runAction = (+ <IconButton+ variant="ghost"+ size="sm"+ label="Run in terminal"+ tooltip="Run in terminal"+ icon={terminalIcon}+ />+);++export const EndContent: Story = {+ args: {+ code: 'npm install @astryxdesign/core',+ language: 'bash',+ endContent: runAction,+ width: '360px',+ },+};++export const EndContentHeaderless: Story = {+ args: {+ code: 'pnpm --filter @astryxdesign/core exec vitest run src/CodeBlock --reporter=verbose --coverage\nexit 0',+ language: 'bash',+ hasLanguageLabel: false,+ endContent: runAction,+ width: '360px',+ },+};++// A taller caller control (the default IconButton size) still sits centred on+// the first line of a headerless one-line block.+export const EndContentTall: Story = {+ args: {+ code: 'npm install @astryxdesign/core',+ language: 'bash',+ hasLanguageLabel: false,+ endContent: (+ <IconButton label="Run in terminal" variant="ghost" icon={terminalIcon} />+ ),+ width: '360px',+ },+};+export const JSON: Story = {args: {code: `{diff --git a/packages/core/src/CodeBlock/CodeBlock.doc.mjs b/packages/core/src/CodeBlock/CodeBlock.doc.mjsindex 72194bca3b..fd17c2990f 100644--- a/packages/core/src/CodeBlock/CodeBlock.doc.mjs+++ b/packages/core/src/CodeBlock/CodeBlock.doc.mjs@@ -74,6 +74,22 @@ export const docs = {type: '() => void',description: 'Callback after the code is copied.',},+ {+ name: 'endContent',+ type: 'ReactNode',+ description:+ '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 over it. It never creates a header and never collapses the block. Use ghost sm IconButtons to match Copy.',+ slotElements: [+ {+ __element: 'IconButton',+ props: {+ variant: 'ghost',+ size: 'sm',+ label: 'Run in terminal',+ },+ },+ ],+ },{name: 'isWrapped',type: 'boolean',@@ -230,7 +246,7 @@ export const docs = {name: 'Header Bar',required: false,description:- 'Shows the title, visible language label, and copy button when a header is present. A title or visible language label creates the header; in a headerless block the copy button sits in its own column beside the code, centred on the first line, and never covers it.',+ 'Shows the title, visible language label, endContent, and copy button when a header is present. A title or visible language label creates the header at every line count. With no title and hasLanguageLabel={false}, endContent and the copy button sit in their own column beside the code, centred on the first line, and never cover it; a one-line block then reads as a single row.',},{name: 'Header Title',diff --git a/packages/core/src/CodeBlock/CodeBlock.test.tsx b/packages/core/src/CodeBlock/CodeBlock.test.tsxindex 32022f2af5..2e944236fd 100644--- a/packages/core/src/CodeBlock/CodeBlock.test.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.test.tsx@@ -314,6 +314,99 @@ describe('CodeBlock', () => {expect(navigator.clipboard.writeText).toHaveBeenCalled();});+ describe('endContent', () => {+ const run = () => (+ <button type="button" onClick={onRun}>+ Run in terminal+ </button>+ );+ let onRun: ReturnType<typeof vi.fn<() => void>>;+ beforeEach(() => {+ onRun = vi.fn<() => void>();+ });++ it('renders caller controls before Copy in the header', () => {+ render(<CodeBlock code="npm test" language="bash" endContent={run()} />);+ const action = screen.getByRole('button', {name: 'Run in terminal'});+ const copy = screen.getByRole('button', {name: 'Copy code'});+ expect(action.parentElement).toBe(copy.parentElement);+ expect(+ action.compareDocumentPosition(copy) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(screen.getByText('bash')).toBeInTheDocument();+ });++ it('never creates a header: with no title or label the controls sit in the corner', () => {+ const {container} = render(+ <CodeBlock+ code="npm test"+ language="bash"+ hasLanguageLabel={false}+ endContent={run()}+ />,+ );+ expect(container.querySelector('.astryx-code-block-header')).toBeNull();+ const action = screen.getByRole('button', {name: 'Run in terminal'});+ const copy = screen.getByRole('button', {name: 'Copy code'});+ const cluster = action.parentElement;+ expect(cluster).toBe(copy.parentElement);+ expect(cluster?.parentElement).toBe(container.querySelector('pre'));+ expect(+ action.compareDocumentPosition(copy) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });++ it('keeps its place when Copy is hidden', () => {+ const {container} = render(+ <CodeBlock code="npm test" hasCopyButton={false} endContent={run()} />,+ );+ expect(screen.queryByRole('button', {name: 'Copy code'})).toBeNull();+ const action = screen.getByRole('button', {name: 'Run in terminal'});+ expect(action.parentElement?.parentElement).toBe(+ container.querySelector('pre'),+ );+ });++ it('sits outside the disclosure and never toggles it, by pointer or keyboard', () => {+ render(+ <CodeBlock+ code={LONG_CODE}+ language="javascript"+ title="example"+ isCollapsible+ endContent={run()}+ />,+ );+ const header = screen+ .getAllByRole('button')+ .find(el => el.hasAttribute('aria-expanded'));+ const action = screen.getByRole('button', {name: 'Run in terminal'});+ expect(header!.contains(action)).toBe(false);+ fireEvent.click(action);+ fireEvent.keyDown(action, {key: 'Enter'});+ fireEvent.keyDown(action, {key: ' '});+ expect(onRun).toHaveBeenCalledTimes(1);+ expect(header).toHaveAttribute('aria-expanded', 'true');+ });++ it('treats a falsy endContent as absent: no corner column without Copy', () => {+ const {container} = render(+ <CodeBlock code="npm test" hasCopyButton={false} endContent={false} />,+ );+ const root = container.querySelector('pre');+ // Only the code viewport: no empty cluster beside it.+ expect(root?.children).toHaveLength(1);+ expect(screen.queryAllByRole('button')).toHaveLength(0);+ });++ it('leaves caller controls unnamed and unstyled by CodeBlock', () => {+ render(<CodeBlock code="npm test" language="bash" endContent={run()} />);+ const action = screen.getByRole('button', {name: 'Run in terminal'});+ expect(action.getAttribute('class')).toBeNull();+ expect(action).not.toHaveAttribute('aria-label');+ });+ });+it('does not nest the copy button inside the collapsible header role="button"', () => {render(<CodeBlock@@ -561,7 +654,10 @@ describe('CodeBlock', () => {expect(screen.getByRole('group')).toHaveAttribute('aria-label', 'Code');const copyButton = screen.getByRole('button', {name: 'Copy code'});- expect(copyButton.parentElement).toBe(container.querySelector('pre'));+ // Headerless: Copy sits in the corner cluster, a direct child of the root.+ expect(copyButton.parentElement?.parentElement).toBe(+ container.querySelector('pre'),+ );await act(async () => {fireEvent.click(copyButton);});diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsxindex 6d346b5e00..95ef4d32a1 100644--- a/packages/core/src/CodeBlock/CodeBlock.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.tsx@@ -31,9 +31,8 @@ import {borderVars,durationVars,easeVars,- sizeVars,} from '../theme/tokens.stylex';-import {mergeProps} from '../utils';+import {isRenderable, mergeProps} from '../utils';import {useClipboard} from '../hooks/useClipboard';import {useScrollableArea} from '../hooks/useScrollableArea';import {Icon} from '../Icon';@@ -402,19 +401,32 @@ const styles = stylex.create({// reaches it via the `code-block-copy-button` target on the Button.color: 'var(--color-syntax-comment)',},- // Centred on the first line of code: a one-line block reads as one row with- // even space above and below, and a block that grows keeps the button where- // it was. The first line's centre is the code's block padding plus half its- // line box (font size × leading for the block's size).- copyButtonCorner: {+ // The controls of a headerless block: caller controls, then Copy, in the+ // second column (cornerClusterMd/Sm give its height).+ cornerCluster: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],alignSelf: 'start',marginInline: spacingVars['--spacing-2'],},- copyButtonCornerMd: {- marginBlockStart: `calc(${spacingVars['--spacing-3']} + ${typeScaleVars['--text-code-size']} * ${typeScaleVars['--text-code-leading']} / 2 - ${sizeVars['--size-element-sm']} / 2)`,+ // The header's controls: caller controls, then Copy.+ headerControls: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ flexShrink: 0,+ },+ // The cluster is exactly as tall as the first line's row (its block padding+ // on both sides plus its line box), and centres its controls in it, so any+ // control height sits on the first line: a one-line block reads as one row+ // with even space above and below, and a block that grows keeps its+ // controls where they were.+ cornerClusterMd: {+ blockSize: `calc(2 * ${spacingVars['--spacing-3']} + ${typeScaleVars['--text-code-size']} * ${typeScaleVars['--text-code-leading']})`,},- copyButtonCornerSm: {- marginBlockStart: `calc(${spacingVars['--spacing-3']} + ${typeScaleVars['--text-supporting-size']} * ${typeScaleVars['--text-code-leading']} / 2 - ${sizeVars['--size-element-sm']} / 2)`,+ cornerClusterSm: {+ blockSize: `calc(2 * ${spacingVars['--spacing-3']} + ${typeScaleVars['--text-supporting-size']} * ${typeScaleVars['--text-code-leading']})`,},});@@ -545,6 +557,14 @@ export interface CodeBlockProps extends BaseProps<HTMLPreElement> {isDiff?: boolean;hasCopyButton?: boolean;onCopy?: () => 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+ * over it. It never creates a header, and activating it never collapses the+ * block. You own each control's label, state, and action; ghost `sm`+ * IconButtons match Copy.+ */+ endContent?: React.ReactNode;isWrapped?: boolean;maxHeight?: number | string;isCollapsible?: boolean;@@ -898,6 +918,7 @@ export function CodeBlock({isDiff = false,hasCopyButton = true,onCopy,+ endContent,isWrapped = false,maxHeight,isCollapsible = false,@@ -1020,6 +1041,10 @@ export function CodeBlock({}: undefined;+ // Caller controls render before Copy; together they are the block's controls,+ // in the header when there is one and in the corner cluster otherwise.+ const hasEndContent = isRenderable(endContent);+ const hasControls = hasCopyButton || hasEndContent;const copyButtonEl = hasCopyButton ? (<IconButtonvariant="ghost"@@ -1038,14 +1063,7 @@ export function CodeBlock({e.stopPropagation();void handleCopy();}}- xstyle={[- styles.copyButton,- !showHeader && styles.copyButtonCorner,- !showHeader &&- (size === 'sm'- ? styles.copyButtonCornerSm- : styles.copyButtonCornerMd),- ]}+ xstyle={styles.copyButton}{...themeProps('code-block-copy-button')}/>) : null;@@ -1107,7 +1125,12 @@ export function CodeBlock({{languageLabel}</span></div>- {copyButtonEl}+ {hasControls ? (+ <div {...stylex.props(styles.headerControls)}>+ {hasEndContent ? endContent : null}+ {copyButtonEl}+ </div>+ ) : null}</div>) : null;@@ -1159,7 +1182,7 @@ export function CodeBlock({themeProps('code-block', {size, language, container}),stylex.props(styles.root,- hasCopyButton && !showHeader && styles.rootCorner,+ hasControls && !showHeader && styles.rootCorner,dynamicStyles.width(widthProp),containerStyles[container],xstyle,@@ -1187,7 +1210,16 @@ export function CodeBlock({) : (codeBody)}- {!showHeader && copyButtonEl}+ {hasControls && !showHeader ? (+ <div+ {...stylex.props(+ styles.cornerCluster,+ size === 'sm' ? styles.cornerClusterSm : styles.cornerClusterMd,+ )}>+ {hasEndContent ? endContent : null}+ {copyButtonEl}+ </div>+ ) : null}</pre>);diff --git a/packages/core/src/CodeBlock/__tests__/CodeBlockCopyClearance.a11y.chromium.spec.ts b/packages/core/src/CodeBlock/__tests__/CodeBlockCopyClearance.a11y.chromium.spec.tsindex 985a2435e9..8e5249adc5 100644--- a/packages/core/src/CodeBlock/__tests__/CodeBlockCopyClearance.a11y.chromium.spec.ts+++ b/packages/core/src/CodeBlock/__tests__/CodeBlockCopyClearance.a11y.chromium.spec.ts@@ -212,3 +212,78 @@ test('the small size centres Copy on its own first line', async ({page}) => {const one = await centres(page);expect(Math.abs(one.button - one.line)).toBeLessThanOrEqual(1);});++test('caller controls join Copy in the corner and never cover code', async ({+ page,+}) => {+ await page.setViewportSize({width: 600, height: 400});+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-codeblock--end-content-headerless&viewMode=story`,+ );+ const action = page.getByRole('button', {name: 'Run in terminal'});+ await expect(action).toBeVisible();+ const viewport = await box(page.getByRole('group', {name: 'Code'}));+ const run = await box(action);+ const copy = await box(copyButton(page));+ for (const control of [run, copy]) {+ const inline =+ Math.min(control.x + control.width, viewport.x + viewport.width) -+ Math.max(control.x, viewport.x);+ expect(inline).toBeLessThanOrEqual(0);+ }+ // Caller controls come first, then Copy, at the inline end.+ expect(run.x).toBeLessThan(copy.x);+ expect(Math.abs(run.y - copy.y)).toBeLessThanOrEqual(1);+});++test('with a header, caller controls sit before Copy in the header', async ({+ page,+}) => {+ await page.setViewportSize({width: 600, height: 400});+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-codeblock--end-content&viewMode=story`,+ );+ const header = page.locator('.astryx-code-block-header');+ await expect(header).toBeVisible();+ await expect(+ header.getByRole('button', {name: 'Run in terminal'}),+ ).toBeVisible();+ const run = await box(page.getByRole('button', {name: 'Run in terminal'}));+ const copy = await box(copyButton(page));+ expect(run.x).toBeLessThan(copy.x);+});++test('a taller caller control still centres on the first line of a one-line block', async ({+ page,+}) => {+ await page.setViewportSize({width: 600, height: 400});+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-codeblock--end-content-tall&viewMode=story`,+ );+ await expect(+ page.getByRole('button', {name: 'Run in terminal'}),+ ).toBeVisible();+ const geometry = await page.evaluate(() => {+ const rect = (selector: string) => {+ const node = document.querySelector(selector);+ if (!node) {+ throw new Error(`missing ${selector}`);+ }+ return node.getBoundingClientRect();+ };+ const action = rect('[aria-label="Run in terminal"]');+ const copy = rect('[aria-label="Copy code"]');+ const line = rect('pre.astryx-code-block [data-line="1"]');+ const root = rect('pre.astryx-code-block');+ return {+ action: action.top + action.height / 2,+ copy: copy.top + copy.height / 2,+ line: line.top + line.height / 2,+ above: line.top - root.top,+ below: root.bottom - line.bottom,+ };+ });+ expect(Math.abs(geometry.action - geometry.line)).toBeLessThanOrEqual(1);+ expect(Math.abs(geometry.copy - geometry.line)).toBeLessThanOrEqual(1);+ expect(Math.abs(geometry.above - geometry.below)).toBeLessThanOrEqual(1);+});diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.tsindex 38a3acfcdb..1e149afac8 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -907,8 +907,7 @@ for (const globals of [}// A fence that names no language keeps its corner copy button beside the// code, never over it: the text ends as far from the frame's inline end- // on both surfaces, so a long line wraps at the same place in read and- // edit mode.+ // on both surfaces.const textInset = (surface: string, key: string) =>page.evaluate(({selector}) => {