An open source design system that's fully customizable and agent ready
TypeScript
feat(richtext): draw fenced code in core CodeBlock's frame, with its language header and copy button (#7004)
Cindy Zhangd11d49ef8f95
diff --git a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts b/apps/storybook/stories/RichTextEditor.markdownParityFixture.tsindex 2a115eefb3..8aaffeb6c3 100644--- a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts+++ b/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts@@ -123,6 +123,45 @@ export const MARKDOWN_PARITY_BLOCKS: readonly MarkdownParityBlock[] = ['```',),},+ // Fences that show no language label, as core CodeBlock decides: no info+ // string, a blank one, and `plaintext`; and an unknown language, which+ // shows its name.+ {+ key: 'code-plain',+ label: 'Fenced code, no info string',+ probe: 'plainFence',+ markdown: lines('```', 'const plainFence = true;', '```'),+ },+ {+ key: 'code-blank',+ label: 'Fenced code, blank info string',+ probe: 'blankFence',+ markdown: lines('``` ', 'const blankFence = true;', '```'),+ },+ {+ key: 'code-plaintext',+ label: 'Fenced code, plaintext',+ probe: 'typedAsIs',+ markdown: lines('```plaintext', 'typedAsIs = 1', '```'),+ },+ {+ key: 'code-unknown',+ label: 'Fenced code, unknown language',+ probe: 'unknownFence',+ markdown: lines('```notalanguage', 'unknownFence()', '```'),+ },+ // A line longer than the prose measure: the frame grows to fit it, up to+ // the full width, and wraps beyond that.+ {+ key: 'code-long',+ label: 'Fenced code, long line',+ probe: 'longFenceLine',+ markdown: lines(+ '```sh',+ 'echo "longFenceLine: the quick brown fox jumps over the lazy dog, then runs back across the field to do it again"',+ '```',+ ),+ },{key: 'table',label: 'Table',diff --git a/packages/richtext/src/CodeBlockHeaderPlugin.test.tsx b/packages/richtext/src/CodeBlockHeaderPlugin.test.tsxnew file mode 100644index 0000000000..1c99ebd27a--- /dev/null+++ b/packages/richtext/src/CodeBlockHeaderPlugin.test.tsx@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, describe, it, expect, vi} from 'vitest';+import {fireEvent, render, screen, waitFor} from '@testing-library/react';+import {RichTextEditor} from './RichTextEditor';+import {RichTextView} from './RichTextView';+import {markdownToEditorStateJSON} from './markdownSerializers';++describe('code block headers (spec:AST-061 FR8)', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('labels a fenced block with its language and copies its code, outside the editable text', async () => {+ const writeText = vi.fn(async () => {});+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: {writeText},+ });+ const value = markdownToEditorStateJSON(+ 'Before\n\n```ts\nconst a = 1;\nconst b = 2;\n```\n',+ );+ const {container} = render(<RichTextView value={value} />);+ const header = await waitFor(() => {+ const element = container.querySelector('[data-richtext-code-header]');+ expect(element).not.toBeNull();+ return element as HTMLElement;+ });+ expect(header.textContent).toContain('ts');+ expect(header.closest('[contenteditable]')).toBeNull();+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));+ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith('const a = 1;\nconst b = 2;'),+ );+ });++ it('shows only the copy button when the block names no language', async () => {+ const {container} = render(+ <RichTextView value={markdownToEditorStateJSON('```\nplain\n```\n')} />,+ );+ const header = await waitFor(() => {+ const element = container.querySelector('[data-richtext-code-header]');+ expect(element).not.toBeNull();+ return element as HTMLElement;+ });+ // The button's accessible name is all the header holds.+ expect(header.textContent).toBe('Copy code');+ expect(screen.getByRole('button', {name: 'Copy code'})).toBeTruthy();+ });++ it('names no language for a plaintext fence, as core CodeBlock does', async () => {+ const {container} = render(+ <RichTextView+ value={markdownToEditorStateJSON(+ '```plaintext\nas typed\n```\n\n```Plaintext\ncased\n```\n',+ )}+ />,+ );+ await waitFor(() =>+ expect(+ container.querySelectorAll('[data-richtext-code-header]'),+ ).toHaveLength(2),+ );+ const headers = [+ ...container.querySelectorAll('[data-richtext-code-header]'),+ ];+ // Exactly `plaintext` names nothing; core compares it case-sensitively.+ expect(headers.map(header => header.textContent)).toEqual([+ 'Copy code',+ 'PlaintextCopy code',+ ]);+ });++ it('draws one header per code block in the editor, outside the editable text', async () => {+ const {container} = render(+ <RichTextEditor+ label="Notes"+ defaultValue={markdownToEditorStateJSON(+ '```ts\none\n```\n\nText\n\n```js\ntwo\n```\n',+ )}+ />,+ );+ await waitFor(() =>+ expect(+ container.querySelectorAll('[data-richtext-code-header]'),+ ).toHaveLength(2),+ );+ const headers = [+ ...container.querySelectorAll('[data-richtext-code-header]'),+ ];+ // Each header: its language label, then the copy button's name.+ expect(headers.map(header => header.textContent)).toEqual([+ 'tsCopy code',+ 'jsCopy code',+ ]);+ for (const header of headers) {+ expect(header.closest('[contenteditable]')).toBeNull();+ }+ });+});diff --git a/packages/richtext/src/CodeBlockHeaderPlugin.tsx b/packages/richtext/src/CodeBlockHeaderPlugin.tsxnew file mode 100644index 0000000000..78e7c2a8d7--- /dev/null+++ b/packages/richtext/src/CodeBlockHeaderPlugin.tsx@@ -0,0 +1,261 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CodeBlockHeaderPlugin.tsx+ * @input Uses @lexical/react (composer context), @lexical/code (CodeNode),+ * lexical, and core IconButton, Icon, useClipboard, and useTranslator.+ * @output Exports CodeBlockHeaderPlugin, which draws core CodeBlock's header+ * over every fenced code block: the language label and a copy button, or+ * just the copy button in the corner when the block names no language.+ * @position Rendered by RichTextEditor and RichTextView inside the positioned+ * element that holds the content editable. The headers are siblings of the+ * editable text, never inside it, so they are not part of the document and+ * cannot be edited (spec:AST-061 FR8, DEC-4). The code block's theme class+ * reserves the header's height, so the code sits where core Markdown's does.+ */++import * as stylex from '@stylexjs/stylex';+import {useEffect, useState, type JSX} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {$isCodeNode} from '@lexical/code';+import {$getNodeByKey, $getRoot} from 'lexical';+import {Icon} from '@astryxdesign/core/Icon';+import {IconButton} from '@astryxdesign/core/IconButton';+import {useClipboard} from '@astryxdesign/core/hooks';+import {useTranslator} from '@astryxdesign/core/i18n';+import {+ fontWeightVars,+ spacingVars,+ typeScaleVars,+ typographyVars,+} from '@astryxdesign/core/theme/tokens.stylex';++/** Where one code block's header goes, in the container's coordinates. */+interface HeaderPlacement {+ readonly key: string;+ readonly language: string | null;+ readonly top: number;+ readonly left: number;+ readonly width: number;+}++const styles = stylex.create({+ // Core CodeBlock's compact header row: 8px above and below a small control,+ // 16px at the sides.+ header: {+ position: 'absolute',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-4'],+ boxSizing: 'border-box',+ },+ // No language: the copy button alone, 8px from the top end corner.+ corner: {+ position: 'absolute',+ display: 'flex',+ justifyContent: 'flex-end',+ padding: spacingVars['--spacing-2'],+ boxSizing: 'border-box',+ pointerEvents: 'none',+ },+ cornerButton: {+ pointerEvents: 'auto',+ },+ title: {+ fontSize: typeScaleVars['--text-supporting-size'],+ fontFamily: typographyVars['--font-family-code'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ color: 'var(--color-syntax-comment)',+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ copyButton: {+ color: 'var(--color-syntax-comment)',+ },+ placement: (top: number, left: number, width: number) => ({+ top,+ left,+ width,+ }),+});++/**+ * The language a header names, as core CodeBlock decides it: none for a fence+ * without one, and none for exactly `plaintext`, which core Markdown gives a+ * fence with no info string.+ */+function displayLanguageOf(language: string | null | undefined): string | null {+ return language == null || language === '' || language === PLAIN_TEXT+ ? null+ : language;+}++const PLAIN_TEXT = 'plaintext';++function samePlacements(+ a: ReadonlyArray<HeaderPlacement>,+ b: ReadonlyArray<HeaderPlacement>,+): boolean {+ return (+ a.length === b.length &&+ a.every(+ (placement, index) =>+ placement.key === b[index].key &&+ placement.language === b[index].language &&+ placement.top === b[index].top &&+ placement.left === b[index].left &&+ placement.width === b[index].width,+ )+ );+}++function CodeBlockHeader({+ placement,+}: {+ readonly placement: HeaderPlacement;+}): JSX.Element {+ const [editor] = useLexicalComposerContext();+ const t = useTranslator();+ const {copy, isCopied} = useClipboard({+ announce: t('@astryx.codeBlock.copied'),+ });+ const copyButton = (+ <IconButton+ variant="ghost"+ size="sm"+ icon={+ <Icon icon={isCopied ? 'check' : 'copy'} size="sm" color="inherit" />+ }+ tooltip={t('@astryx.codeBlock.copyCode')}+ label={+ isCopied+ ? t('@astryx.codeBlock.copied')+ : t('@astryx.codeBlock.copyCode')+ }+ onClick={() => {+ const code = editor+ .getEditorState()+ .read(() => $getNodeByKey(placement.key)?.getTextContent() ?? '');+ void copy(code);+ }}+ xstyle={[+ styles.copyButton,+ placement.language == null && styles.cornerButton,+ ]}+ />+ );+ const position = styles.placement(+ placement.top,+ placement.left,+ placement.width,+ );+ if (placement.language == null) {+ return (+ <div+ data-richtext-code-header=""+ {...stylex.props(styles.corner, position)}>+ {copyButton}+ </div>+ );+ }+ return (+ <div+ data-richtext-code-header=""+ {...stylex.props(styles.header, position)}>+ <span {...stylex.props(styles.title)}>{placement.language}</span>+ {copyButton}+ </div>+ );+}++/**+ * Draws a header over each top-level code block and keeps it there as the+ * document, the editor's size, or the window changes.+ */+export function CodeBlockHeaderPlugin(): JSX.Element {+ const [editor] = useLexicalComposerContext();+ const [placements, setPlacements] = useState<ReadonlyArray<HeaderPlacement>>(+ [],+ );++ useEffect(() => {+ let frame = 0;+ const measure = () => {+ frame = 0;+ const root = editor.getRootElement();+ const container = root?.parentElement;+ if (root == null || container == null) {+ setPlacements(current => (current.length === 0 ? current : []));+ return;+ }+ const origin = container.getBoundingClientRect();+ const next = editor.getEditorState().read(() =>+ $getRoot()+ .getChildren()+ .filter($isCodeNode)+ .flatMap(node => {+ const element = editor.getElementByKey(node.getKey());+ if (element == null) {+ return [];+ }+ const box = element.getBoundingClientRect();+ // Inside the block's border, so the header lines up with the+ // padding the theme reserves for it.+ return [+ {+ key: node.getKey(),+ language: displayLanguageOf(node.getLanguage()),+ top: box.top - origin.top + element.clientTop,+ left: box.left - origin.left + element.clientLeft,+ width: element.clientWidth,+ },+ ];+ }),+ );+ setPlacements(current =>+ samePlacements(current, next) ? current : next,+ );+ };+ const schedule = () => {+ if (frame === 0) {+ frame = requestAnimationFrame(measure);+ }+ };+ const observer =+ typeof ResizeObserver === 'undefined'+ ? null+ : new ResizeObserver(schedule);+ const unregisterRoot = editor.registerRootListener(root => {+ observer?.disconnect();+ if (root != null) {+ observer?.observe(root);+ }+ schedule();+ });+ const unregisterUpdate = editor.registerUpdateListener(schedule);+ window.addEventListener('resize', schedule);+ schedule();+ return () => {+ cancelAnimationFrame(frame);+ observer?.disconnect();+ unregisterRoot();+ unregisterUpdate();+ window.removeEventListener('resize', schedule);+ };+ }, [editor]);++ return (+ <>+ {placements.map(placement => (+ <CodeBlockHeader key={placement.key} placement={placement} />+ ))}+ </>+ );+}diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex d38190fe25..3a7a6f4b76 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -74,6 +74,7 @@ import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';import {TablePlugin} from '@lexical/react/LexicalTablePlugin';import {HorizontalRuleExtension} from '@lexical/extension';import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';+import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';import {type Transformer} from '@lexical/markdown';export type {Transformer} from '@lexical/markdown';import {$generateHtmlFromNodes} from '@lexical/html';@@ -688,6 +689,7 @@ export const RichTextEditor = forwardRef<hasHorizontalScroll/><TableColumnFloorPlugin />+ <CodeBlockHeaderPlugin /><TabIndentationPlugin /><TabFocusEscapePlugin />{hasMarkdownShortcuts && (diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsxindex 607bc5bfa2..cca8773fa6 100644--- a/packages/richtext/src/RichTextView.tsx+++ b/packages/richtext/src/RichTextView.tsx@@ -32,6 +32,7 @@ import {LexicalErrorBoundary} from '@lexical/react/LexicalErrorBoundary';import {TablePlugin} from '@lexical/react/LexicalTablePlugin';import {TableScrollRegionPlugin} from './TableScrollRegionPlugin';import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';+import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';import type {AnyLexicalExtension,Klass,@@ -45,6 +46,8 @@ import {DEFAULT_NODES} from './editorNodes';const styles = stylex.create({root: {width: '100%',+ // Holds the code block headers drawn over the content.+ position: 'relative',},});@@ -285,6 +288,8 @@ export function RichTextView({placeholder={null}ErrorBoundary={LexicalErrorBoundary}/>+ {/* After the content, so the copy buttons follow it in tab order. */}+ <CodeBlockHeaderPlugin />{plugins}</LexicalExtensionComposer></div>diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.tsindex de6704a300..272ebf211d 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -52,7 +52,7 @@ const AXE_DISABLED_RULES = [const DESKTOP = {width: 1440, height: 900} as const;const PHONE = {width: 390, height: 844} as const;-type Viewport = typeof DESKTOP | typeof PHONE;+type Viewport = {readonly width: number; readonly height: number};interface BlockGeometry {readonly key: string;@@ -342,6 +342,265 @@ test('a rule at either edge of the document adds no outer margin', async ({]);});+// spec:AST-061 FR8: a fenced code block has the same frame and header on+// both surfaces, so the code sits at the same place; the header is not part+// of the editable text.+/**+ * Whether core Markdown scrolls a fence's lines sideways. RichText wraps them+ * instead (a scrolling region inside the editable text cannot take focus), so+ * a fence whose lines do not fit is taller in RichText by its wrapped lines.+ */+async function markdownFenceScrolls(page: Page, key: string): Promise<boolean> {+ return page.evaluate(+ ({surface, block}) =>+ [+ ...document.querySelectorAll<HTMLElement>(+ `${surface} [data-parity-block="${block}"] *`,+ ),+ ].some(element => element.scrollWidth > element.clientWidth + 1),+ {surface: MARKDOWN, block: key},+ );+}++for (const viewport of [PHONE, DESKTOP, {width: 2200, height: 900}] as const) {+ test(`side by side: a fenced code block has core Markdown's frame and header (${viewport.width}px)`, async ({+ page,+ }) => {+ const errors = await openStory(page, STORY.sideBySide, viewport);+ await waitForDocument(page, MARKDOWN);+ await waitForDocument(page, RICH_TEXT);+ const markdown = await surfaceGeometry(page, MARKDOWN);+ const richText = await surfaceGeometry(page, RICH_TEXT);+ const code = (geometry: SurfaceGeometry) =>+ geometry.blocks.find(block => block.key === 'code-fence');+ if (!(await markdownFenceScrolls(page, 'code-fence'))) {+ expect(+ Math.abs((code(richText)?.height ?? 0) - (code(markdown)?.height ?? 0)),+ ).toBeLessThanOrEqual(2);+ }+ // Each frame is sized like core Markdown's: as wide as its longest line,+ // at least the 680px measure (or the whole width when narrower), and no+ // wider than the surface. Each surface is measured against its own width.+ const frames = await page.evaluate(+ ({markdownSurface, richTextSurface, keys}) =>+ keys.map(key => {+ const markdownBlock = document.querySelector<HTMLElement>(+ `${markdownSurface} [data-parity-block="${key}"]`,+ );+ const markdownFrame = [+ markdownBlock,+ ...(markdownBlock?.querySelectorAll<HTMLElement>('*') ?? []),+ ].find(element => {+ const style = element == null ? null : getComputedStyle(element);+ return (+ style != null &&+ style.borderTopStyle !== 'none' &&+ parseFloat(style.borderTopWidth) > 0+ );+ });+ const richTextFrame = document.querySelector<HTMLElement>(+ `${richTextSurface} [data-parity-block="${key}"]`,+ );+ const editable = richTextFrame?.parentElement;+ const editableStyle =+ editable == null ? null : getComputedStyle(editable);+ return {+ key,+ markdown: markdownFrame?.getBoundingClientRect().width ?? 0,+ markdownRoom: markdownBlock?.getBoundingClientRect().width ?? 0,+ richText: richTextFrame?.getBoundingClientRect().width ?? 0,+ richTextRoom:+ editable == null || editableStyle == null+ ? 0+ : editable.clientWidth -+ parseFloat(editableStyle.paddingLeft) -+ parseFloat(editableStyle.paddingRight),+ };+ }),+ {+ markdownSurface: MARKDOWN,+ richTextSurface: RICH_TEXT,+ keys: ['code-fence', 'code-plain', 'code-unknown', 'code-long'],+ },+ );+ for (const frame of frames) {+ if (frame.key === 'code-long') {+ // A long line widens the frame past the measure, up to the room.+ const markdownWide = Math.min(frame.markdownRoom, frame.markdown);+ expect(frame.markdown, frame.key).toBeGreaterThan(+ Math.min(680, frame.markdownRoom) - 1,+ );+ expect(frame.richText, frame.key).toBeLessThanOrEqual(+ frame.richTextRoom + 1,+ );+ if (frame.markdown < frame.markdownRoom - 1) {+ // Room to spare on both surfaces: the same width as core's frame.+ expect(+ Math.abs(frame.richText - markdownWide),+ frame.key,+ ).toBeLessThanOrEqual(2);+ } else {+ // Both fill their surface and wrap.+ expect(+ Math.abs(frame.richText - frame.richTextRoom),+ frame.key,+ ).toBeLessThanOrEqual(1);+ }+ } else {+ // A short block is the measure wide, or the whole width if narrower.+ expect(+ Math.abs(frame.markdown - Math.min(680, frame.markdownRoom)),+ `${frame.key} markdown`,+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(frame.richText - Math.min(680, frame.richTextRoom)),+ `${frame.key} rich text`,+ ).toBeLessThanOrEqual(1);+ }+ }+ expect(+ await page.evaluate(+ () => document.documentElement.scrollWidth - window.innerWidth,+ ),+ ).toBeLessThanOrEqual(0);+ // One header per fenced block; the first is the `ts` block's.+ await expect(+ page.locator(`${RICH_TEXT} [data-richtext-code-header]`),+ ).toHaveCount(6);+ const header = page+ .locator(`${RICH_TEXT} [data-richtext-code-header]`)+ .first();+ await expect(header).toContainText('ts');+ await expect(header.getByRole('button', {name: 'Copy code'})).toBeVisible();+ expect(+ await header.evaluate(element => element.closest('[contenteditable]')),+ ).toBeNull();+ // The header spans the block, inside its border.+ const widths = await page.evaluate(selector => {+ const block = document.querySelector(`${selector} code[data-language]`);+ const head = document.querySelector(+ `${selector} [data-richtext-code-header]`,+ );+ return [+ (block as HTMLElement | null)?.clientWidth,+ head?.getBoundingClientRect().width,+ ];+ }, RICH_TEXT);+ expect(widths[1]).toBe(widths[0]);+ expect(errors).toEqual([]);+ });+}++// A long unbroken line wraps inside the code frame at phone width instead of+// widening the page, and the copy button copies the block from the keyboard,+// in the editor and the view.+test('code blocks wrap long lines at phone width and copy from the keyboard', async ({+ page,+ context,+}) => {+ await context.grantPermissions(['clipboard-read', 'clipboard-write']);+ await page.setViewportSize(PHONE);+ await page.goto(+ `${storybook.origin}/iframe.html?id=lab-richtexteditor--markdown-serializers&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,+ {waitUntil: 'load'},+ );+ const token = 'x'.repeat(160);+ await page+ .locator('textarea')+ .fill(`\`\`\`ts\nconst id = "${token}";\n\`\`\``);+ await expect(page.locator('[data-richtext-code-header]')).toHaveCount(2);+ const layout = await page.evaluate(() => ({+ pageOverflow: document.documentElement.scrollWidth - window.innerWidth,+ blocks: [...document.querySelectorAll('[data-lexical-editor] code')].map(+ code => code.scrollWidth - code.clientWidth,+ ),+ }));+ expect(layout.pageOverflow).toBeLessThanOrEqual(0);+ expect(layout.blocks).toEqual([0, 0]);+ const copy = page+ .locator('[data-richtext-code-header]')+ .last()+ .getByRole('button', {name: 'Copy code'});+ await copy.focus();+ await page.keyboard.press('Enter');+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(+ `const id = "${token}";`,+ );+});++// spec:AST-061 FR8: a fence names a language exactly when core CodeBlock+// does — not with no info string, a blank one, or `plaintext` — and only a+// named block reserves the header row, so every fence is as tall as core+// Markdown's on both surfaces, in both color modes and directions.+for (const globals of [+ 'colorMode:light;direction:ltr',+ 'colorMode:dark;direction:rtl',+]) {+ test(`side by side: fences without a language have no label row (${globals})`, async ({+ page,+ }) => {+ const errors = await openStory(page, STORY.sideBySide, DESKTOP, globals);+ await waitForDocument(page, MARKDOWN);+ await waitForDocument(page, RICH_TEXT);+ const fences = {+ 'code-fence': 'ts',+ 'code-plain': '',+ 'code-blank': '',+ 'code-plaintext': '',+ 'code-unknown': 'notalanguage',+ 'code-long': 'sh',+ } as const;+ const markdown = await surfaceGeometry(page, MARKDOWN);+ const richText = await surfaceGeometry(page, RICH_TEXT);+ for (const key of Object.keys(fences)) {+ if (await markdownFenceScrolls(page, key)) {+ continue;+ }+ const height = (geometry: SurfaceGeometry) =>+ geometry.blocks.find(block => block.key === key)?.height ?? 0;+ expect(+ Math.abs(height(richText) - height(markdown)),+ `${key} height`,+ ).toBeLessThanOrEqual(2);+ }+ // The label core Markdown shows for each fence.+ const markdownLabels = await page.evaluate(+ ({selector, names}) =>+ Object.keys(names).map(key => {+ const block = document.querySelector(+ `${selector} [data-parity-block="${key}"]`,+ );+ const label = [...(block?.querySelectorAll('*') ?? [])].find(+ element =>+ element.childElementCount === 0 &&+ ['ts', 'notalanguage', 'plaintext', 'sh'].includes(+ element.textContent?.trim() ?? '',+ ),+ );+ return label?.textContent?.trim() ?? '';+ }),+ {selector: MARKDOWN, names: fences},+ );+ expect(markdownLabels).toEqual(Object.values(fences));+ // RichText draws one header per fence, in order, each with a copy button+ // and the same label.+ const headers = page.locator(`${RICH_TEXT} [data-richtext-code-header]`);+ await expect(headers).toHaveCount(6);+ const richTextLabels = await headers.evaluateAll(elements =>+ elements.map(element =>+ (element.textContent ?? '').replace('Copy code', '').trim(),+ ),+ );+ expect(richTextLabels).toEqual(Object.values(fences));+ for (const index of [0, 1, 2, 3, 4, 5]) {+ await expect(+ headers.nth(index).getByRole('button', {name: 'Copy code'}),+ ).toBeVisible();+ }+ expect(errors).toEqual([]);+ });+}+for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {for (const globals of ['colorMode:light;direction:ltr',diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.tsindex e2c370b760..f482328553 100644--- a/packages/richtext/src/editorTheme.ts+++ b/packages/richtext/src/editorTheme.ts@@ -22,6 +22,7 @@ import {fontWeightVars,borderVars,focusVars,+ sizeVars,} from '@astryxdesign/core/theme/tokens.stylex';import type {EditorThemeClasses} from 'lexical';@@ -46,6 +47,10 @@ const LIST_ROW_GAP = `calc(${spacingVars['--spacing-0-5']})`;const LIST_ROW_FLUSH = `calc(${spacingVars['--spacing-0']})`;const NESTED_LIST_SPACE = `calc(${spacingVars['--spacing-2']})`;const RULE_SPACE = `calc(${spacingVars['--spacing-6']})`;+const CODE_SPACE = `calc(${spacingVars['--spacing-3']})`;+// Core CodeBlock's header (8px, a small control, 8px) overlaps the code's+// 12px top padding by 8px, so its code starts 8px + control + 12px down.+const CODE_HEADER_SPACE = `calc(${spacingVars['--spacing-2']} + ${sizeVars['--size-element-sm']} + ${spacingVars['--spacing-3']})`;const editorTheme = stylex.create({// Lexical marks every top-level block `dir="auto"`, which picks each@@ -352,13 +357,38 @@ const editorTheme = stylex.create({outlineColor: focusVars['--focus-outline-color'],outlineOffset: focusVars['--focus-outline-offset'],},+ // Fenced code in core CodeBlock's frame: syntax background, a border, the+ // code type size, and room at the top for the header that+ // CodeBlockHeaderPlugin draws over a block that names its language. Long+ // lines wrap rather than scroll: a scrolling region inside the editable+ // text cannot take keyboard focus of its own, so keyboard users could not+ // scroll it (axe scrollable-region-focusable).code: {display: 'block',fontFamily: typographyVars['--font-family-code'],- backgroundColor: colorVars['--color-background-muted'],- padding: spacingVars['--spacing-3'],- borderRadius: radiusVars['--radius-inner'],- fontSize: typeScaleVars['--text-supporting-size'],+ fontSize: typeScaleVars['--text-code-size'],+ lineHeight: typeScaleVars['--text-code-leading'],+ backgroundColor: 'var(--color-syntax-background)',+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderColor: colorVars['--color-border'],+ borderRadius: radiusVars['--radius-element'],+ paddingBlockStart: {+ default: CODE_SPACE,+ // Only a block whose header names a language; `plaintext` names none,+ // as in core CodeBlock (CodeBlockHeaderPlugin).+ ':is([data-language]:not([data-language="plaintext"]))':+ CODE_HEADER_SPACE,+ },+ paddingBlockEnd: spacingVars['--spacing-3'],+ paddingInline: spacingVars['--spacing-4'],+ // Sized like core Markdown's code frame: as wide as its longest line, at+ // least the prose measure (or the whole width when that is narrower), and+ // never wider than the editor, where long lines wrap.+ boxSizing: 'border-box',+ width: 'fit-content',+ minWidth: `min(${PROSE_MEASURE}, 100%)`,+ maxWidth: '100%',marginBlockStart: {default: WIDE_BLOCK_SPACE,':first-child': spacingVars['--spacing-0'],@@ -368,6 +398,8 @@ const editorTheme = stylex.create({':last-child': spacingVars['--spacing-0'],},whiteSpace: 'pre-wrap',+ // An unbroken token wider than the block (a long URL or hash) wraps too.+ overflowWrap: 'anywhere',},});