Skip to content

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

TypeScript

chore(storybook): add a Markdown vs RichText parity sandbox (#6974)

Cindy Zhang50c209b0e98f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ef21c9aa02..ee9ed2ef49 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1158,6 +1158,63 @@ jobs:
--project chromium \
--output empty-state-announcement-output
+ # The RichTextEditor "Markdown parity" stories render one Markdown
+ # document with core Markdown and RichTextEditor and measure where each
+ # block lands; geometry, the read/edit switch and the scroll anchor only
+ # exist in a real engine. The spec proves the sandbox still works and
+ # banks screenshots plus a geometry manifest of today's differences. It
+ # asserts no parity. A pull request runs it only when it can change what
+ # the sandbox shows: Markdown or a RichText component is in the PR scope,
+ # the RichText package changed, or the sandbox's own stories or spec
+ # changed. Release-check always runs it. Its own --output directory, with
+ # the upload immediately after.
+ - name: Run Markdown/RichText parity sandbox evidence
+ id: markdown-parity
+ if: ${{ !cancelled() }}
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ run: |
+ should_run=true
+ if [ "${{ github.event_name }}" = 'pull_request' ]; then
+ should_run=false
+ COMPONENTS=$(node .github/scripts/a11y-pr-scope.mjs analysis.json)
+ case ",${COMPONENTS}," in
+ *,core/Markdown,* | *,richtext/*) should_run=true ;;
+ esac
+ if node -e "process.exit(require('./analysis.json').changedPackages?.includes('@astryxdesign/richtext') ? 0 : 1)"; then
+ should_run=true
+ fi
+ # The sandbox's stories belong to no package, so compare file names
+ # with the base. If the base cannot be fetched, run the evidence.
+ if git fetch --quiet --depth=1 origin "$BASE_SHA"; then
+ if git diff --name-only "$BASE_SHA" HEAD \
+ | grep -qE '^(apps/storybook/stories/RichTextEditor\.(markdownParity|stories)|packages/richtext/src/__tests__/MarkdownParitySandbox)'; then
+ should_run=true
+ fi
+ else
+ should_run=true
+ fi
+ fi
+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"
+ if [ "$should_run" != true ]; then
+ echo "Markdown, RichText, and the parity sandbox are not in PR scope; skipping parity evidence."
+ exit 0
+ fi
+ pnpm exec playwright test \
+ packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts \
+ --project chromium \
+ --output richtext-markdown-parity-output
+
+ - name: Upload Markdown/RichText parity sandbox evidence
+ if: ${{ !cancelled() && steps.markdown-parity.outputs.should_run == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: richtext-markdown-parity-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: test-results/richtext-markdown-parity/
+ retention-days: 30
+ if-no-files-found: warn
+
# Outline owns real DOM focus through roving tabindex. Computed paint,
# pointer modality, clipping, forced colors, and exact pixels require the
# same real Chromium artifact this blocking accessibility lane already owns.
diff --git a/apps/storybook/stories/RichTextEditor.markdownParity.tsx b/apps/storybook/stories/RichTextEditor.markdownParity.tsx
new file mode 100644
index 0000000000..8ab137eb4d
--- /dev/null
+++ b/apps/storybook/stories/RichTextEditor.markdownParity.tsx
@@ -0,0 +1,806 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RichTextEditor.markdownParity.tsx
+ * @input Core Markdown for the read surface; RichTextEditor with its toolbar and
+ * the Lexical plugins available today for the edit surface; the parity
+ * fixture; the Storybook demo Markdown plugins.
+ * @output `MarkdownParitySandbox`: one Markdown document rendered by both
+ * surfaces side by side, swapped in place, or overlaid, with diagnostic
+ * per-block geometry and the scroll anchor across a mode switch.
+ * @position Storybook-only diagnostic for RichTextEditor.stories.tsx. It shows
+ * current behavior and fixes nothing: every difference it reports is a
+ * finding, and none of its numbers is a target.
+ *
+ * Stable hooks for browser tests: `data-parity-sandbox` (the view),
+ * `data-parity-surface` (markdown | richtext | toggle) with
+ * `data-parity-mode` on the toggled surface, `data-parity-body` on the
+ * measured element inside each surface, `data-parity-block` and
+ * `data-parity-copy` on every paired block, `data-parity-row` on each
+ * measurement row, and `data-parity-anchor` on the scroll-anchor readout.
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Banner} from '@astryxdesign/core/Banner';
+import {Markdown} from '@astryxdesign/core/Markdown';
+import {Text} from '@astryxdesign/core/Text';
+import {ToggleButton} from '@astryxdesign/core/ToggleButton';
+import {colorVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {
+ RichTextEditor,
+ RichTextEditorAutoLinkPlugin,
+ RichTextEditorToolbar,
+ markdownToEditorStateJSON,
+} from '@astryxdesign/richtext';
+import {markdownDemoPlugins} from './Markdown.demoPlugins';
+import {
+ MARKDOWN_PARITY_BLOCKS,
+ MARKDOWN_PARITY_SOURCE,
+ type MarkdownParityBlock,
+} from './RichTextEditor.markdownParityFixture';
+
+/** Copies of the fixture in the long document. */
+export const LONG_DOCUMENT_COPIES = 12;
+
+/**
+ * Top-level elements the pairing may pass over while looking for a block before
+ * deciding the block produced no element of its own. Bounded so that a missing
+ * block cannot pair with its twin in a later copy of the document.
+ */
+const PAIRING_LOOKAHEAD = 4;
+
+export type ParityView = 'side-by-side' | 'toggle' | 'overlay';
+export type ParityHostWidth = 'fill' | '680px';
+
+export interface MarkdownParitySandboxProps {
+ /** Both surfaces side by side, one column swapped in place, or overlaid. */
+ view: ParityView;
+ /** Repeat the fixture so the document is long enough to scroll. */
+ isLongDocument: boolean;
+ /**
+ * Render each side with the extensions it has today: Markdown's GFM
+ * autolinks and the Storybook demo plugins on the read side, RichText's
+ * autolink plugin on the edit side.
+ */
+ hasPlugins: boolean;
+ /** Width of each column, the way a host page might constrain it. */
+ hostWidth: ParityHostWidth;
+}
+
+type Mode = 'read' | 'edit';
+
+interface Box {
+ readonly top: number;
+ readonly height: number;
+ readonly width: number;
+}
+
+interface Geometry {
+ readonly surface: Surface;
+ /** The whole surface. */
+ readonly box: Box;
+ /** Paired blocks by `<key>@<copy>`, relative to the surface's top edge. */
+ readonly blocks: ReadonlyMap<string, Box>;
+}
+
+interface ParityContent {
+ readonly source: string;
+ readonly copies: number;
+ readonly hasPlugins: boolean;
+ readonly editorState: string;
+}
+
+interface PendingAnchor {
+ readonly from: Surface;
+ readonly key: string;
+ readonly copy: number;
+ /** Viewport top of the anchored block before the switch. */
+ readonly top: number;
+ readonly scrollY: number;
+}
+
+interface AnchorShift {
+ readonly key: string;
+ readonly copy: number;
+ /** How far the anchored block moved; `null` when it has no pair. */
+ readonly delta: number | null;
+ readonly scrollBefore: number;
+ readonly scrollAfter: number;
+}
+
+const styles = stylex.create({
+ sandbox: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-4'],
+ },
+ columns: {
+ display: 'grid',
+ gap: spacingVars['--spacing-4'],
+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 320px), 1fr))',
+ alignItems: 'start',
+ },
+ stack: {
+ display: 'grid',
+ alignItems: 'start',
+ },
+ stackLayer: {
+ gridArea: '1 / 1',
+ },
+ differenceLayer: {
+ mixBlendMode: 'difference',
+ },
+ surface: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-2'],
+ minWidth: 0,
+ },
+ hostWidth: {
+ width: '100%',
+ maxWidth: 680,
+ },
+ controls: {
+ position: 'sticky',
+ top: 0,
+ // Paints over the document scrolling beneath it; local to this story.
+ zIndex: 2,
+ display: 'flex',
+ flexWrap: 'wrap',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-2'],
+ backgroundColor: colorVars['--color-background-surface'],
+ },
+ tableScroller: {
+ overflowX: 'auto',
+ maxWidth: '100%',
+ },
+ table: {
+ borderCollapse: 'collapse',
+ fontVariantNumeric: 'tabular-nums',
+ },
+ caption: {
+ textAlign: 'start',
+ paddingBlockEnd: spacingVars['--spacing-2'],
+ },
+ cell: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ borderBlockEndWidth: 1,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: colorVars['--color-border'],
+ textAlign: 'end',
+ whiteSpace: 'nowrap',
+ },
+ labelCell: {
+ textAlign: 'start',
+ },
+});
+
+const round = (value: number): number => Math.round(value * 10) / 10;
+
+const boxOf = (rect: DOMRect, origin: DOMRect): Box => ({
+ top: round(rect.top - origin.top),
+ height: round(rect.height),
+ width: round(rect.width),
+});
+
+const blockId = (key: string, copy: number | string): string =>
+ `${key}@${copy}`;
+
+function normalizedText(element: Element): string {
+ return (element.textContent ?? '').replace(/\s+/g, ' ').trim();
+}
+
+function rendersBlock(element: Element, block: MarkdownParityBlock): boolean {
+ if (block.probe != null) {
+ return normalizedText(element).includes(block.probe);
+ }
+ return (
+ element.matches('hr') ||
+ element.querySelector('hr') != null ||
+ normalizedText(element) === block.markdown.trim()
+ );
+}
+
+/**
+ * Marks the top-level element each fixture block rendered as. Pairing walks
+ * the content root's children in document order and matches by text, so it
+ * does not depend on either renderer's markup; a block that produced no
+ * element of its own is left unmarked and reported as unpaired.
+ */
+function pairBlocks(root: Element, copies: number): void {
+ const children = Array.from(root.children);
+ for (const child of children) {
+ child.removeAttribute('data-parity-block');
+ child.removeAttribute('data-parity-copy');
+ }
+ let next = 0;
+ for (let copy = 1; copy <= copies; copy += 1) {
+ for (const block of MARKDOWN_PARITY_BLOCKS) {
+ const end = Math.min(children.length, next + PAIRING_LOOKAHEAD);
+ for (let index = next; index < end; index += 1) {
+ if (rendersBlock(children[index], block)) {
+ children[index].setAttribute('data-parity-block', block.key);
+ children[index].setAttribute('data-parity-copy', String(copy));
+ next = index + 1;
+ break;
+ }
+ }
+ }
+ }
+}
+
+function measure(body: HTMLElement, surface: Surface): Geometry {
+ const origin = body.getBoundingClientRect();
+ const blocks = new Map<string, Box>();
+ for (const element of body.querySelectorAll<HTMLElement>(
+ '[data-parity-block]',
+ )) {
+ blocks.set(
+ blockId(
+ element.dataset.parityBlock ?? '',
+ element.dataset.parityCopy ?? '',
+ ),
+ boxOf(element.getBoundingClientRect(), origin),
+ );
+ }
+ return {surface, box: boxOf(origin, origin), blocks};
+}
+
+const geometryKey = (geometry: Geometry): string =>
+ JSON.stringify([geometry.surface, geometry.box, [...geometry.blocks]]);
+
+/**
+ * Keeps one surface's blocks paired and measured. Lexical fills its editable
+ * after mount and rewrites blocks as someone types, so pairing reruns on every
+ * DOM or size change rather than once.
+ */
+function useMeasuredSurface(
+ surface: Surface,
+ copies: number,
+ onMeasure: (geometry: Geometry) => void,
+): (element: HTMLElement | null) => void {
+ const [body, setBody] = useState<HTMLElement | null>(null);
+ useEffect(() => {
+ if (body == null) {
+ return undefined;
+ }
+ let frame = 0;
+ let last = '';
+ const schedule = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ const root = SURFACES[surface].contentRoot(body);
+ if (root == null) {
+ return;
+ }
+ pairBlocks(root, copies);
+ const geometry = measure(body, surface);
+ const key = geometryKey(geometry);
+ if (key !== last) {
+ last = key;
+ onMeasure(geometry);
+ }
+ });
+ };
+ const resizeObserver = new ResizeObserver(schedule);
+ resizeObserver.observe(body);
+ // Attributes are deliberately not observed: pairing writes them.
+ const mutationObserver = new MutationObserver(schedule);
+ mutationObserver.observe(body, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ });
+ schedule();
+ return () => {
+ cancelAnimationFrame(frame);
+ resizeObserver.disconnect();
+ mutationObserver.disconnect();
+ };
+ }, [body, surface, copies, onMeasure]);
+ return setBody;
+}
+
+/** The first paired block still visible below the sticky controls. */
+function captureAnchor(
+ body: HTMLElement | null,
+ controls: HTMLElement | null,
+ from: Surface,
+): PendingAnchor | null {
+ if (body == null) {
+ return null;
+ }
+ const viewTop = controls?.getBoundingClientRect().bottom ?? 0;
+ for (const element of body.querySelectorAll<HTMLElement>(
+ '[data-parity-block]',
+ )) {
+ const rect = element.getBoundingClientRect();
+ if (rect.bottom > viewTop) {
+ return {
+ from,
+ key: element.dataset.parityBlock ?? '',
+ copy: Number(element.dataset.parityCopy),
+ top: rect.top,
+ scrollY: window.scrollY,
+ };
+ }
+ }
+ return null;
+}
+
+function resolveAnchor(anchor: PendingAnchor, body: HTMLElement): AnchorShift {
+ const element = body.querySelector(
+ `[data-parity-block="${anchor.key}"][data-parity-copy="${anchor.copy}"]`,
+ );
+ return {
+ key: anchor.key,
+ copy: anchor.copy,
+ delta:
+ element == null
+ ? null
+ : round(element.getBoundingClientRect().top - anchor.top),
+ scrollBefore: round(anchor.scrollY),
+ scrollAfter: round(window.scrollY),
+ };
+}
+
+const formatPx = (value: number): string =>
+ Number.isInteger(value) ? String(value) : value.toFixed(1);
+
+const formatDelta = (value: number): string =>
+ `${value > 0 ? '+' : ''}${formatPx(value)}`;
+
+const labelOf = (key: string): string =>
+ MARKDOWN_PARITY_BLOCKS.find(block => block.key === key)?.label ?? key;
+
+function MarkdownRead({content}: {content: ParityContent}) {
+ return (
+ <Markdown
+ autolink={content.hasPlugins ? 'gfm' : undefined}
+ plugins={content.hasPlugins ? markdownDemoPlugins : undefined}>
+ {content.source}
+ </Markdown>
+ );
+}
+
+function RichTextEdit({content}: {content: ParityContent}) {
+ return (
+ <RichTextEditor
+ label="Document"
+ isLabelHidden
+ defaultValue={content.editorState}
+ toolbar={<RichTextEditorToolbar />}
+ plugins={
+ content.hasPlugins ? <RichTextEditorAutoLinkPlugin /> : undefined
+ }
+ />
+ );
+}
+
+interface SurfaceDefinition {
+ /** Accessible name and caption of the surface. */
+ readonly label: string;
+ /** The element whose children are the document's top-level blocks. */
+ readonly contentRoot: (body: HTMLElement) => Element | null;
+ readonly render: (content: ParityContent) => ReactNode;
+}
+
+/**
+ * Every renderer the sandbox can measure. Pairing and measurement only need
+ * `contentRoot`, so another surface (a second editor, a compatibility spike)
+ * is one more entry here.
+ */
+const SURFACES = {
+ markdown: {
+ label: 'Markdown, read mode',
+ contentRoot: body => body.firstElementChild,
+ render: content => <MarkdownRead content={content} />,
+ },
+ richtext: {
+ label: 'RichText, edit mode',
+ contentRoot: body => body.querySelector('[contenteditable]'),
+ render: content => <RichTextEdit content={content} />,
+ },
+} satisfies Record<string, SurfaceDefinition>;
+
+type Surface = keyof typeof SURFACES;
+
+/** The in-place toggle swaps the read renderer for the edit renderer. */
+const TOGGLE_SURFACES: Readonly<Record<Mode, Surface>> = {
+ read: 'markdown',
+ edit: 'richtext',
+};
+
+interface SurfaceSectionProps {
+ surface: Surface | 'toggle';
+ label: string;
+ mode?: Mode;
+ bodyRef: (element: HTMLElement | null) => void;
+ isHosted: boolean;
+ /** Set when the surface is one layer of the overlay. */
+ layer?: 'base' | 'difference';
+ children: ReactNode;
+}
+
+function SurfaceSection({
+ surface,
+ label,
+ mode,
+ bodyRef,
+ isHosted,
+ layer,
+ children,
+}: SurfaceSectionProps) {
+ return (
+ <section
+ aria-label={label}
+ data-parity-surface={surface}
+ data-parity-mode={mode}
+ // The difference layer is a picture of the editor, not a second copy of
+ // it: keep it out of the tab order and the accessibility tree.
+ inert={layer === 'difference' ? true : undefined}
+ {...stylex.props(
+ styles.surface,
+ isHosted && styles.hostWidth,
+ layer != null && styles.stackLayer,
+ layer === 'difference' && styles.differenceLayer,
+ )}>
+ {layer == null ? (
+ <Text as="p" type="label">
+ {label}
+ </Text>
+ ) : null}
+ <div ref={bodyRef} data-parity-body="">
+ {children}
+ </div>
+ </section>
+ );
+}
+
+interface MeasurementColumn {
+ readonly label: string;
+ readonly geometry: Geometry | null;
+}
+
+function cellText(geometry: Geometry | null, box: Box | undefined): string {
+ if (geometry == null) {
+ return 'not measured';
+ }
+ return box == null
+ ? 'not paired'
+ : `${formatPx(box.top)} / ${formatPx(box.height)}`;
+}
+
+function Measurements({
+ left,
+ right,
+}: {
+ left: MeasurementColumn;
+ right: MeasurementColumn;
+}) {
+ const rows = [
+ {
+ key: 'surface',
+ label: 'Whole surface',
+ a: left.geometry?.box,
+ b: right.geometry?.box,
+ },
+ ...MARKDOWN_PARITY_BLOCKS.map(block => ({
+ key: block.key,
+ label: block.label,
+ a: left.geometry?.blocks.get(blockId(block.key, 1)),
+ b: right.geometry?.blocks.get(blockId(block.key, 1)),
+ })),
+ ];
+ const cell = stylex.props(styles.cell);
+ const labelCell = stylex.props(styles.cell, styles.labelCell);
+ return (
+ <Text as="div" type="supporting">
+ <div
+ role="region"
+ aria-label="Diagnostic measurements"
+ // Keyboard users must be able to scroll a table wider than the view.
+ tabIndex={0}
+ {...stylex.props(styles.tableScroller)}>
+ <table data-parity-measurements="" {...stylex.props(styles.table)}>
+ <caption {...stylex.props(styles.caption)}>
+ Diagnostic measurements, not targets. Border-box top / height in px
+ from each surface&apos;s top edge, first copy of the document. Δ is{' '}
+ {right.label} minus {left.label}.
+ </caption>
+ <thead>
+ <tr>
+ <th scope="col" {...labelCell}>
+ Block
+ </th>
+ <th scope="col" {...cell}>
+ {left.label}
+ </th>
+ <th scope="col" {...cell}>
+ {right.label}
+ </th>
+ <th scope="col" {...cell}>
+ Δ top
+ </th>
+ <th scope="col" {...cell}>
+ Δ height
+ </th>
+ <th scope="col" {...cell}>
+ Δ width
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map(({key, label, a, b}) => {
+ const delta = (field: keyof Box) =>
+ a != null && b != null
+ ? formatDelta(round(b[field] - a[field]))
+ : '—';
+ return (
+ <tr
+ key={key}
+ data-parity-row={key}
+ data-parity-left={
+ a == null ? undefined : `${a.top} ${a.height} ${a.width}`
+ }
+ data-parity-right={
+ b == null ? undefined : `${b.top} ${b.height} ${b.width}`
+ }>
+ <th scope="row" {...labelCell}>
+ {label}
+ </th>
+ <td {...cell}>{cellText(left.geometry, a)}</td>
+ <td {...cell}>{cellText(right.geometry, b)}</td>
+ <td {...cell}>{delta('top')}</td>
+ <td {...cell}>{delta('height')}</td>
+ <td {...cell}>{delta('width')}</td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </Text>
+ );
+}
+
+function PairView({
+ content,
+ hostWidth,
+ isOverlay,
+}: {
+ content: ParityContent;
+ hostWidth: ParityHostWidth;
+ isOverlay: boolean;
+}) {
+ const [markdown, setMarkdown] = useState<Geometry | null>(null);
+ const [richText, setRichText] = useState<Geometry | null>(null);
+ const markdownBody = useMeasuredSurface(
+ 'markdown',
+ content.copies,
+ setMarkdown,
+ );
+ const richTextBody = useMeasuredSurface(
+ 'richtext',
+ content.copies,
+ setRichText,
+ );
+ const isHosted = hostWidth === '680px';
+ return (
+ <>
+ {isOverlay ? (
+ <Text as="p" type="supporting">
+ RichText (edit) is drawn over Markdown (read) with a difference blend,
+ so pixels that match cancel to black. The overlay is a picture only:
+ the editor is not interactive in this view.
+ </Text>
+ ) : null}
+ <div
+ {...stylex.props(
+ isOverlay ? styles.stack : styles.columns,
+ isOverlay && isHosted && styles.hostWidth,
+ )}>
+ <SurfaceSection
+ surface="markdown"
+ label={SURFACES.markdown.label}
+ bodyRef={markdownBody}
+ isHosted={isHosted && !isOverlay}
+ layer={isOverlay ? 'base' : undefined}>
+ {SURFACES.markdown.render(content)}
+ </SurfaceSection>
+ <SurfaceSection
+ surface="richtext"
+ label={SURFACES.richtext.label}
+ bodyRef={richTextBody}
+ isHosted={isHosted && !isOverlay}
+ layer={isOverlay ? 'difference' : undefined}>
+ {SURFACES.richtext.render(content)}
+ </SurfaceSection>
+ </div>
+ <Measurements
+ left={{label: 'Markdown (read)', geometry: markdown}}
+ right={{label: 'RichText (edit)', geometry: richText}}
+ />
+ </>
+ );
+}
+
+function AnchorReadout({shift}: {shift: AnchorShift | null}) {
+ if (shift == null) {
+ return (
+ <span data-parity-anchor="">
+ <Text type="supporting">
+ Scroll, then switch modes: this shows how far the block at the top of
+ the view moves.
+ </Text>
+ </span>
+ );
+ }
+ const where = `“${labelOf(shift.key)}” (copy ${shift.copy})`;
+ const scroll = `scrollY ${formatPx(shift.scrollBefore)} → ${formatPx(shift.scrollAfter)}`;
+ return (
+ <span
+ data-parity-anchor={shift.key}
+ data-parity-anchor-copy={shift.copy}
+ data-parity-anchor-delta={shift.delta ?? undefined}
+ data-parity-anchor-scroll={`${shift.scrollBefore} ${shift.scrollAfter}`}>
+ <Text type="supporting">
+ {shift.delta == null
+ ? `Anchor ${where} has no paired block in this mode; ${scroll}.`
+ : `Anchor ${where} moved ${formatDelta(shift.delta)} px; ${scroll}.`}
+ </Text>
+ </span>
+ );
+}
+
+function ToggleView({
+ content,
+ hostWidth,
+}: {
+ content: ParityContent;
+ hostWidth: ParityHostWidth;
+}) {
+ const [mode, setMode] = useState<Mode>('read');
+ const [read, setRead] = useState<Geometry | null>(null);
+ const [edit, setEdit] = useState<Geometry | null>(null);
+ const [shift, setShift] = useState<AnchorShift | null>(null);
+ const pendingAnchor = useRef<PendingAnchor | null>(null);
+ const bodyElement = useRef<HTMLElement | null>(null);
+ const controls = useRef<HTMLDivElement | null>(null);
+
+ const onMeasure = useCallback((geometry: Geometry) => {
+ if (geometry.surface === TOGGLE_SURFACES.read) {
+ setRead(geometry);
+ } else {
+ setEdit(geometry);
+ }
+ const anchor = pendingAnchor.current;
+ const body = bodyElement.current;
+ // Resolve once the new surface has painted its blocks, not on mount.
+ if (
+ anchor != null &&
+ body != null &&
+ geometry.surface !== anchor.from &&
+ geometry.blocks.size > 0
+ ) {
+ pendingAnchor.current = null;
+ setShift(resolveAnchor(anchor, body));
+ }
+ }, []);
+
+ const surface = TOGGLE_SURFACES[mode];
+ const measuredBody = useMeasuredSurface(surface, content.copies, onMeasure);
+ const bodyRef = useCallback(
+ (element: HTMLElement | null) => {
+ bodyElement.current = element;
+ measuredBody(element);
+ },
+ [measuredBody],
+ );
+
+ const onEditingChange = (isEditing: boolean) => {
+ const next: Mode = isEditing ? 'edit' : 'read';
+ if (next === mode) {
+ return;
+ }
+ pendingAnchor.current = captureAnchor(
+ bodyElement.current,
+ controls.current,
+ surface,
+ );
+ setShift(null);
+ setMode(next);
+ };
+
+ return (
+ <>
+ <div ref={controls} {...stylex.props(styles.controls)}>
+ <ToggleButton
+ label="Edit mode"
+ isPressed={mode === 'edit'}
+ onPressedChange={onEditingChange}
+ />
+ <AnchorReadout shift={shift} />
+ </div>
+ <Text as="p" type="supporting">
+ Edit mode swaps Markdown for a RichTextEditor imported from the same
+ source. Read mode always shows the source as authored, so edits are
+ discarded when you switch back.
+ </Text>
+ <SurfaceSection
+ surface="toggle"
+ mode={mode}
+ label={SURFACES[surface].label}
+ bodyRef={bodyRef}
+ isHosted={hostWidth === '680px'}>
+ {SURFACES[surface].render(content)}
+ </SurfaceSection>
+ <Measurements
+ left={{label: 'Read (last measured)', geometry: read}}
+ right={{label: 'Edit (last measured)', geometry: edit}}
+ />
+ </>
+ );
+}
+
+/**
+ * Renders one Markdown document with core Markdown (read) and RichTextEditor
+ * (edit), and reports where each block lands on both. It demonstrates current
+ * behavior; it does not promise parity.
+ */
+export function MarkdownParitySandbox({
+ view,
+ isLongDocument,
+ hasPlugins,
+ hostWidth,
+}: MarkdownParitySandboxProps) {
+ const copies = isLongDocument ? LONG_DOCUMENT_COPIES : 1;
+ const content = useMemo<ParityContent>(() => {
+ const source = Array.from(
+ {length: copies},
+ () => MARKDOWN_PARITY_SOURCE,
+ ).join('\n');
+ return {
+ source,
+ copies,
+ hasPlugins,
+ editorState: markdownToEditorStateJSON(source),
+ };
+ }, [copies, hasPlugins]);
+ // Remount on a content change: the editor reads its value once, on mount.
+ const contentKey = `${copies}:${String(hasPlugins)}`;
+
+ return (
+ <div
+ data-parity-sandbox={view}
+ data-parity-copies={copies}
+ {...stylex.props(styles.sandbox)}>
+ <Banner
+ status="info"
+ title="Diagnostic sandbox: current behavior, not a parity promise"
+ description="Core Markdown (read) and RichTextEditor (edit) render the same Markdown source. Differences shown here are findings about the components today, and the measurements are diagnostic, not targets."
+ />
+ {view === 'toggle' ? (
+ <ToggleView key={contentKey} content={content} hostWidth={hostWidth} />
+ ) : (
+ <PairView
+ key={contentKey}
+ content={content}
+ hostWidth={hostWidth}
+ isOverlay={view === 'overlay'}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts b/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts
new file mode 100644
index 0000000000..2a115eefb3
--- /dev/null
+++ b/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts
@@ -0,0 +1,183 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RichTextEditor.markdownParityFixture.ts
+ * @input None; plain data.
+ * @output The one Markdown document the Markdown/RichText parity sandbox
+ * renders on both surfaces, authored as an ordered list of blocks.
+ * @position Storybook-only fixture for RichTextEditor.markdownParity.tsx. It is
+ * an input, not an oracle: nothing here says how a block should look.
+ *
+ * Coverage: ATX headings 1-4; emphasis, strong, strikethrough, inline code,
+ * titled and bare links; soft and hard line breaks; a blockquote; nested
+ * unordered (2-space) and ordered (3-space) lists; a GFM task list; a fenced
+ * code block with an info string; a GFM table with column alignment; a
+ * thematic break; backslash escapes and character references; a right-to-left
+ * paragraph; and the Storybook demo plugins' mention, TODO, and callout syntax.
+ * There is no image: the repository has no offline image fixture, and Markdown
+ * refuses `data:` image sources by design.
+ */
+
+export interface MarkdownParityBlock {
+ /** Stable identity, written to `data-parity-block` on the rendered element. */
+ readonly key: string;
+ /** Label for the measurement table. */
+ readonly label: string;
+ /**
+ * Text that appears in this block's rendered text on both surfaces, so the
+ * sandbox can pair equivalent blocks without relying on either renderer's
+ * markup. `null` for a block with no text of its own (a thematic break): it
+ * pairs with an `<hr>`, or with a block whose text is its literal source.
+ */
+ readonly probe: string | null;
+ /** The block's Markdown source. */
+ readonly markdown: string;
+}
+
+const lines = (...rows: readonly string[]): string => rows.join('\n');
+
+export const MARKDOWN_PARITY_BLOCKS: readonly MarkdownParityBlock[] = [
+ {
+ key: 'heading-1',
+ label: 'Heading 1',
+ probe: 'Release notes',
+ markdown: '# Release notes',
+ },
+ {
+ key: 'paragraph-inline',
+ label: 'Paragraph: inline marks and line breaks',
+ probe: 'faster sync',
+ markdown: lines(
+ 'Version 2.4 brings **faster sync**, *clearer errors*, ***both at once***, ~~surprise reloads~~, `inline code`, a [titled link](https://example.com/changelog "Changelog"), and a bare URL https://example.com/status that may autolink.',
+ 'A soft break keeps this sentence in the same paragraph.',
+ 'A hard break ends this line with two trailing spaces ',
+ 'so this line starts below it.',
+ ),
+ },
+ {
+ key: 'heading-2',
+ label: 'Heading 2',
+ probe: 'What changed',
+ markdown: '## What changed',
+ },
+ {
+ key: 'heading-3',
+ label: 'Heading 3',
+ probe: 'Sync engine',
+ markdown: '### Sync engine',
+ },
+ {
+ key: 'heading-4',
+ label: 'Heading 4',
+ probe: 'Background retries',
+ markdown: '#### Background retries',
+ },
+ {
+ key: 'blockquote',
+ label: 'Blockquote',
+ probe: 'retry policy',
+ markdown: lines(
+ '> The new retry policy waits **longer** between attempts; see the [runbook](https://example.com/runbook).',
+ '> A second quote line continues the same blockquote.',
+ ),
+ },
+ {
+ key: 'list-unordered',
+ label: 'Unordered list, nested with 2 spaces',
+ probe: 'Unordered item one',
+ markdown: lines(
+ '- Unordered item one',
+ '- Unordered item two',
+ ' - Nested item',
+ ' - Second nested item',
+ ' - Deeply nested item',
+ '- Unordered item three',
+ ),
+ },
+ {
+ key: 'list-ordered',
+ label: 'Ordered list, nested with 3 spaces',
+ probe: 'Ordered step one',
+ markdown: lines(
+ '1. Ordered step one',
+ '2. Ordered step two',
+ ' 1. Nested ordered step',
+ '3. Ordered step three',
+ ),
+ },
+ {
+ key: 'list-task',
+ label: 'Task list',
+ probe: 'Open task',
+ markdown: lines('- [ ] Open task', '- [x] Completed task'),
+ },
+ {
+ key: 'code-fence',
+ label: 'Fenced code',
+ probe: 'retryDelay',
+ markdown: lines(
+ '```ts',
+ 'export function retryDelay(attempt: number): number {',
+ ' return Math.min(30_000, 2 ** attempt * 250);',
+ '}',
+ '```',
+ ),
+ },
+ {
+ key: 'table',
+ label: 'Table',
+ probe: 'Owner',
+ markdown: lines(
+ '| Area | Owner | Status |',
+ '| :--- | :---: | ---: |',
+ '| Sync | Platform | Shipped |',
+ '| Search **beta** | `search` | 80% |',
+ ),
+ },
+ {
+ key: 'thematic-break',
+ label: 'Thematic break',
+ probe: null,
+ markdown: '---',
+ },
+ {
+ key: 'paragraph-escapes',
+ label: 'Paragraph: escapes and character references',
+ probe: 'not italic',
+ markdown:
+ 'Escaped \\*not italic\\* and \\# not a heading; references &amp; &copy; &#169;.',
+ },
+ {
+ key: 'paragraph-rtl',
+ label: 'Paragraph: right-to-left script',
+ probe: 'כיוון',
+ markdown: 'פסקה בעברית לבדיקת כיוון הטקסט.',
+ },
+ {
+ key: 'paragraph-plugins',
+ label: 'Paragraph: mention and TODO plugin syntax',
+ probe: 'before launch',
+ markdown: 'Ask @{Ada} about the TODO before launch.',
+ },
+ {
+ key: 'callout',
+ label: 'Callout plugin block',
+ probe: 'Callouts',
+ markdown: lines(
+ ':::note',
+ 'Callouts come from a Markdown plugin and can hold **bold** text.',
+ ':::',
+ ),
+ },
+ {
+ key: 'paragraph-final',
+ label: 'Final paragraph',
+ probe: 'Final paragraph',
+ markdown: 'Final paragraph.',
+ },
+];
+
+/** The fixture as one Markdown string, one blank line between blocks. */
+export const MARKDOWN_PARITY_SOURCE = `${MARKDOWN_PARITY_BLOCKS.map(
+ block => block.markdown,
+).join('\n\n')}\n`;
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsx
index 50fa6adbc0..17eb9174f2 100644
--- a/apps/storybook/stories/RichTextEditor.stories.tsx
+++ b/apps/storybook/stories/RichTextEditor.stories.tsx
@@ -14,6 +14,11 @@ import {
import type {EditorState} from 'lexical';
import {BOLD_STAR, ITALIC_STAR, UNORDERED_LIST} from '@lexical/markdown';
import {$getRoot} from 'lexical';
+import {
+ LONG_DOCUMENT_COPIES,
+ MarkdownParitySandbox,
+ type MarkdownParitySandboxProps,
+} from './RichTextEditor.markdownParity';
const meta: Meta<typeof RichTextEditor> = {
title: 'Lab/RichTextEditor',
@@ -449,3 +454,94 @@ export const MarkdownSerializers = {
);
},
};
+
+/**
+ * Markdown parity sandbox: one Markdown document rendered by core Markdown
+ * (read) and RichTextEditor (edit). It is diagnostic: it shows current behavior
+ * and promises no parity. Theme, color mode, and direction come from the
+ * toolbar; the viewport menu offers 390px and 1440px.
+ */
+type MarkdownParityStory = StoryObj<MarkdownParitySandboxProps>;
+
+const markdownParity: MarkdownParityStory = {
+ render: args => <MarkdownParitySandbox {...args} />,
+ // Page-sized diagnostics, not usage examples: keep them off the docs page.
+ tags: ['!autodocs'],
+ argTypes: {
+ view: {
+ control: 'inline-radio',
+ options: ['side-by-side', 'toggle', 'overlay'],
+ },
+ isLongDocument: {
+ control: 'boolean',
+ description: `Repeat the fixture ${LONG_DOCUMENT_COPIES} times.`,
+ },
+ hasPlugins: {
+ control: 'boolean',
+ description:
+ "Read side: Markdown's GFM autolinks and the demo plugins. Edit side: RichText's autolink plugin.",
+ },
+ hostWidth: {control: 'inline-radio', options: ['fill', '680px']},
+ },
+ parameters: {
+ controls: {include: ['view', 'isLongDocument', 'hasPlugins', 'hostWidth']},
+ viewport: {
+ options: {
+ parityPhone: {
+ name: 'Phone (390px)',
+ styles: {width: '390px', height: '844px'},
+ type: 'mobile',
+ },
+ parityDesktop: {
+ name: 'Desktop (1440px)',
+ styles: {width: '1440px', height: '900px'},
+ type: 'desktop',
+ },
+ },
+ },
+ },
+};
+
+export const MarkdownParity: MarkdownParityStory = {
+ ...markdownParity,
+ name: 'Markdown parity: side by side',
+ args: {
+ view: 'side-by-side',
+ isLongDocument: false,
+ hasPlugins: true,
+ hostWidth: 'fill',
+ },
+};
+
+export const MarkdownParityToggle: MarkdownParityStory = {
+ ...markdownParity,
+ name: 'Markdown parity: read/edit toggle',
+ args: {
+ view: 'toggle',
+ isLongDocument: false,
+ hasPlugins: true,
+ hostWidth: '680px',
+ },
+};
+
+export const MarkdownParityOverlay: MarkdownParityStory = {
+ ...markdownParity,
+ name: 'Markdown parity: overlay',
+ args: {
+ view: 'overlay',
+ isLongDocument: false,
+ hasPlugins: true,
+ hostWidth: '680px',
+ },
+};
+
+export const MarkdownParityLongDocument: MarkdownParityStory = {
+ ...markdownParity,
+ name: 'Markdown parity: long document',
+ args: {
+ view: 'toggle',
+ isLongDocument: true,
+ hasPlugins: true,
+ hostWidth: '680px',
+ },
+};
diff --git a/packages/richtext/package.json b/packages/richtext/package.json
index a8dd86b159..4501e3de59 100644
--- a/packages/richtext/package.json
+++ b/packages/richtext/package.json
@@ -114,6 +114,7 @@
}
},
"devDependencies": {
+ "@astryxdesign/a11y-spec": "workspace:*",
"@astryxdesign/cli": "workspace:*",
"@babel/cli": "catalog:",
"@babel/core": "catalog:",
diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..c95ff52326
--- /dev/null
+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
@@ -0,0 +1,488 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MarkdownParitySandbox.a11y.chromium.spec.ts
+ * @input The RichTextEditor "Markdown parity" stories in a built Storybook
+ * @output Real-Chromium proof that the parity sandbox works, plus screenshots
+ * and a geometry manifest of today's Markdown/RichText differences under
+ * test-results/richtext-markdown-parity/
+ * @position Evidence for a Storybook diagnostic, not a parity contract. It
+ * asserts that the sandbox renders one fixture on both surfaces, keeps the
+ * source across a read/edit/read switch, follows direction and phone widths,
+ * fills in its measurements, logs no console errors, and has no axe
+ * violations. Every Markdown/RichText difference is recorded; none is
+ * asserted.
+ *
+ * Build the Storybook first:
+ *
+ * pnpm storybook:build
+ * pnpm exec playwright test MarkdownParitySandbox.a11y.chromium.spec.ts
+ */
+
+import * as crypto from 'node:crypto';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import AxeBuilder from '@axe-core/playwright';
+import {expect, test, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const OUTPUT = path.resolve('test-results/richtext-markdown-parity');
+
+const STORY = {
+ sideBySide: 'lab-richtexteditor--markdown-parity',
+ toggle: 'lab-richtexteditor--markdown-parity-toggle',
+ overlay: 'lab-richtexteditor--markdown-parity-overlay',
+ longDocument: 'lab-richtexteditor--markdown-parity-long-document',
+} as const;
+
+/** The exemptions the repository's Storybook axe audit already makes. */
+const AXE_DISABLED_RULES = [
+ 'html-has-lang',
+ 'document-title',
+ 'landmark-one-main',
+ 'page-has-heading-one',
+ 'region',
+];
+
+const DESKTOP = {width: 1440, height: 900} as const;
+const PHONE = {width: 390, height: 844} as const;
+
+type Viewport = typeof DESKTOP | typeof PHONE;
+
+interface BlockGeometry {
+ readonly key: string;
+ readonly copy: number;
+ readonly tag: string;
+ readonly direction: string;
+ readonly top: number;
+ readonly height: number;
+ readonly width: number;
+}
+
+interface SurfaceGeometry {
+ readonly height: number;
+ readonly width: number;
+ readonly direction: string;
+ readonly blocks: readonly BlockGeometry[];
+}
+
+const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
+
+let storybook: StaticServer;
+let browserVersion = '';
+
+test.beforeAll(async ({browser}) => {
+ // Not wiped: a worker restarted after a failure must keep earlier frames.
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ browserVersion = browser.version();
+ storybook = await serveStorybook(STORYBOOK_DIR);
+});
+
+test.afterAll(async () => {
+ const captures = fs
+ .readdirSync(OUTPUT)
+ .filter(name => name.endsWith('.json') && name !== 'manifest.json')
+ .sort()
+ .map(name => JSON.parse(fs.readFileSync(path.join(OUTPUT, name), 'utf8')));
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ version: 1,
+ headSha: process.env.ASTRYX_HEAD_SHA ?? null,
+ // CI stamps the commit a Storybook artifact was built from.
+ storybookSha: storybookStamp(),
+ browser: browserVersion,
+ captures,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ await storybook?.close();
+});
+
+function storybookStamp(): string | null {
+ const stamp = path.join(STORYBOOK_DIR, 'astryx-build-sha.txt');
+ return fs.existsSync(stamp) ? fs.readFileSync(stamp, 'utf8').trim() : null;
+}
+
+/** Opens a story and returns the console errors it logs from then on. */
+async function openStory(
+ page: Page,
+ story: string,
+ viewport: Viewport,
+ globals = 'colorMode:light;direction:ltr',
+): Promise<string[]> {
+ const errors: string[] = [];
+ page.on('console', message => {
+ const source = message.location().url;
+ // Chromium asks the static server for /favicon.ico on its own, and a built
+ // Storybook ships none; that 404 is not something the page did.
+ if (message.type() === 'error' && !source.endsWith('/favicon.ico')) {
+ errors.push(`${message.text()} (${source})`);
+ }
+ });
+ page.on('pageerror', error => errors.push(error.message));
+ page.on('response', response => {
+ if (response.status() >= 400) {
+ errors.push(`HTTP ${response.status()} ${response.url()}`);
+ }
+ });
+ await page.setViewportSize(viewport);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story&globals=astryxTheme:neutral;${globals}`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('[data-parity-sandbox]').waitFor();
+ await holdMotionStill(page);
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ });
+ return errors;
+}
+
+/** The toggle story's one control: pressed means the edit surface is up. */
+const editMode = (page: Page) => page.getByRole('button', {name: 'Edit mode'});
+
+async function settle(page: Page): Promise<void> {
+ await page.evaluate(
+ () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }),
+ );
+}
+
+/** The fixture's block keys, in order, from the sandbox's measurement rows. */
+async function fixtureKeys(page: Page): Promise<string[]> {
+ const keys = await page
+ .locator('[data-parity-row]')
+ .evaluateAll(rows =>
+ rows.map(row => row.getAttribute('data-parity-row') ?? ''),
+ );
+ return keys.filter(key => key !== 'surface');
+}
+
+/**
+ * Waits until a surface has painted the last block of the last copy: only a
+ * fully rendered document gets that far.
+ */
+async function waitForDocument(page: Page, surface: string): Promise<void> {
+ const keys = await fixtureKeys(page);
+ const copies = await page
+ .locator('[data-parity-sandbox]')
+ .getAttribute('data-parity-copies');
+ await page
+ .locator(
+ `${surface} [data-parity-block="${keys.at(-1)}"][data-parity-copy="${copies}"]`,
+ )
+ .waitFor();
+ await settle(page);
+}
+
+async function surfaceGeometry(
+ page: Page,
+ surface: string,
+): Promise<SurfaceGeometry> {
+ return page.locator(`${surface} > [data-parity-body]`).evaluate(body => {
+ const origin = body.getBoundingClientRect();
+ const blocks = Array.from(
+ body.querySelectorAll<HTMLElement>('[data-parity-block]'),
+ element => {
+ const rect = element.getBoundingClientRect();
+ return {
+ key: element.dataset.parityBlock ?? '',
+ copy: Number(element.dataset.parityCopy),
+ tag: element.tagName.toLowerCase(),
+ direction: getComputedStyle(element).direction,
+ top: rect.top - origin.top,
+ height: rect.height,
+ width: rect.width,
+ };
+ },
+ );
+ return {
+ height: origin.height,
+ width: origin.width,
+ direction: getComputedStyle(body).direction,
+ blocks,
+ };
+ });
+}
+
+const pairedKeys = (geometry: SurfaceGeometry): string[] =>
+ geometry.blocks.filter(block => block.copy === 1).map(block => block.key);
+
+async function axeViolations(page: Page): Promise<string[]> {
+ const results = await new AxeBuilder({page})
+ .include('#storybook-root')
+ .disableRules(AXE_DISABLED_RULES)
+ .analyze();
+ return results.violations.map(
+ violation =>
+ `${violation.id}: ${violation.nodes
+ .map(node => node.target.join(' '))
+ .join(', ')}`,
+ );
+}
+
+/** Banks a screenshot with its receipt; receipts are merged in afterAll. */
+async function capture(
+ page: Page,
+ name: string,
+ details: Record<string, unknown>,
+ {fullPage = true}: {fullPage?: boolean} = {},
+): Promise<void> {
+ const file = `${name}.png`;
+ const png = await page.screenshot({path: path.join(OUTPUT, file), fullPage});
+ fs.writeFileSync(
+ path.join(OUTPUT, `${name}.json`),
+ `${JSON.stringify(
+ {
+ file,
+ sha256: crypto.createHash('sha256').update(png).digest('hex'),
+ ...details,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+}
+
+const MARKDOWN = '[data-parity-surface="markdown"]';
+const RICH_TEXT = '[data-parity-surface="richtext"]';
+const TOGGLE = '[data-parity-surface="toggle"]';
+
+test('side by side: one fixture renders on both surfaces', async ({page}) => {
+ const errors = await openStory(page, STORY.sideBySide, DESKTOP);
+ await waitForDocument(page, MARKDOWN);
+ await waitForDocument(page, RICH_TEXT);
+ const keys = await fixtureKeys(page);
+ const markdown = await surfaceGeometry(page, MARKDOWN);
+ const richText = await surfaceGeometry(page, RICH_TEXT);
+
+ // Markdown is the reference renderer: every fixture block pairs, in order.
+ expect(pairedKeys(markdown)).toEqual(keys);
+ // The editor loaded the whole document: its first and last blocks pair.
+ const richTextKeys = pairedKeys(richText);
+ expect(richTextKeys[0]).toBe(keys[0]);
+ expect(richTextKeys.at(-1)).toBe(keys.at(-1));
+ // The edit surface is a real editor with an accessible name.
+ await expect(page.getByRole('textbox', {name: 'Document'})).toHaveCount(1);
+ // The diagnostic table measured both surfaces.
+ const surfaceRow = page.locator('[data-parity-row="surface"]');
+ await expect(surfaceRow).toHaveAttribute('data-parity-left', /\d/);
+ await expect(surfaceRow).toHaveAttribute('data-parity-right', /\d/);
+
+ expect(await axeViolations(page)).toEqual([]);
+ await capture(page, 'side-by-side--1440--light-ltr', {
+ story: STORY.sideBySide,
+ viewport: DESKTOP,
+ globals: 'neutral light ltr',
+ unpairedInRichText: keys.filter(key => !richTextKeys.includes(key)),
+ markdown,
+ richText,
+ });
+ expect(errors).toEqual([]);
+});
+
+for (const viewport of [DESKTOP, PHONE]) {
+ for (const colorMode of ['light', 'dark'] as const) {
+ test(`toggle keeps the source across read, edit, read (${viewport.width}px, ${colorMode})`, async ({
+ page,
+ }) => {
+ const errors = await openStory(
+ page,
+ STORY.toggle,
+ viewport,
+ `colorMode:${colorMode};direction:ltr`,
+ );
+ const read = `${TOGGLE}[data-parity-mode="read"]`;
+ const edit = `${TOGGLE}[data-parity-mode="edit"]`;
+ const name = `toggle--${viewport.width}--${colorMode}`;
+
+ await waitForDocument(page, read);
+ const readText = await page
+ .locator(`${read} > [data-parity-body]`)
+ .innerText();
+ const readGeometry = await surfaceGeometry(page, read);
+ await capture(page, `${name}--read`, {
+ story: STORY.toggle,
+ viewport,
+ globals: `neutral ${colorMode} ltr`,
+ mode: 'read',
+ geometry: readGeometry,
+ });
+
+ await editMode(page).click();
+ await waitForDocument(page, edit);
+ await expect(editMode(page)).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByRole('textbox', {name: 'Document'})).toHaveCount(
+ 1,
+ );
+ await expect(page.locator('[data-parity-row="surface"]')).toHaveAttribute(
+ 'data-parity-right',
+ /\d/,
+ );
+ const anchor = await page
+ .locator('[data-parity-anchor]')
+ .evaluate(element => ({...(element as HTMLElement).dataset}));
+ expect(await axeViolations(page)).toEqual([]);
+ await capture(page, `${name}--edit`, {
+ story: STORY.toggle,
+ viewport,
+ globals: `neutral ${colorMode} ltr`,
+ mode: 'edit',
+ anchor,
+ geometry: await surfaceGeometry(page, edit),
+ });
+
+ // Back to read with the keyboard: the control is reachable without a pointer.
+ await editMode(page).focus();
+ await page.keyboard.press('Enter');
+ await waitForDocument(page, read);
+ await expect(editMode(page)).toHaveAttribute('aria-pressed', 'false');
+ // Read mode re-renders the source as authored: same text, same layout.
+ expect(
+ await page.locator(`${read} > [data-parity-body]`).innerText(),
+ ).toBe(readText);
+ expect((await surfaceGeometry(page, read)).height).toBe(
+ readGeometry.height,
+ );
+ expect(errors).toEqual([]);
+ });
+ }
+}
+
+for (const [viewport, colorMode] of [
+ [PHONE, 'dark'],
+ [DESKTOP, 'light'],
+] as const) {
+ test(`right-to-left reaches both surfaces (${viewport.width}px, ${colorMode})`, async ({
+ page,
+ }) => {
+ const errors = await openStory(
+ page,
+ STORY.sideBySide,
+ viewport,
+ `colorMode:${colorMode};direction:rtl`,
+ );
+ await waitForDocument(page, MARKDOWN);
+ await waitForDocument(page, RICH_TEXT);
+ const markdown = await surfaceGeometry(page, MARKDOWN);
+ const richText = await surfaceGeometry(page, RICH_TEXT);
+ expect(markdown.direction).toBe('rtl');
+ expect(richText.direction).toBe('rtl');
+ if (viewport === PHONE) {
+ // At a phone width the surfaces stack instead of squeezing side by side.
+ const markdownBox = await page.locator(MARKDOWN).boundingBox();
+ const richTextBox = await page.locator(RICH_TEXT).boundingBox();
+ expect(richTextBox?.y ?? 0).toBeGreaterThanOrEqual(
+ (markdownBox?.y ?? 0) + (markdownBox?.height ?? 0),
+ );
+ }
+
+ expect(await axeViolations(page)).toEqual([]);
+ await capture(page, `side-by-side--${viewport.width}--${colorMode}-rtl`, {
+ story: STORY.sideBySide,
+ viewport,
+ globals: `neutral ${colorMode} rtl`,
+ pageOverflowX: await page.evaluate(
+ () =>
+ document.documentElement.scrollWidth -
+ document.documentElement.clientWidth,
+ ),
+ leftToRightBlocks: {
+ markdown: markdown.blocks
+ .filter(block => block.direction === 'ltr')
+ .map(block => block.key),
+ richText: richText.blocks
+ .filter(block => block.direction === 'ltr')
+ .map(block => block.key),
+ },
+ markdown,
+ richText,
+ });
+ expect(errors).toEqual([]);
+ });
+}
+
+test('overlay: both layers start together and the drawn editor is inert', async ({
+ page,
+}) => {
+ const errors = await openStory(page, STORY.overlay, DESKTOP);
+ await waitForDocument(page, MARKDOWN);
+ await waitForDocument(page, RICH_TEXT);
+ const base = await page
+ .locator(`${MARKDOWN} > [data-parity-body]`)
+ .boundingBox();
+ const layer = await page
+ .locator(`${RICH_TEXT} > [data-parity-body]`)
+ .boundingBox();
+ expect(layer?.x).toBe(base?.x);
+ expect(layer?.y).toBe(base?.y);
+ await expect(page.locator(RICH_TEXT)).toHaveAttribute('inert', '');
+ // An inert editor refuses focus, so neither keyboard nor pointer reach it.
+ const focusable = await page
+ .locator(`${RICH_TEXT} [contenteditable]`)
+ .evaluate(editor => {
+ (editor as HTMLElement).focus();
+ return document.activeElement === editor;
+ });
+ expect(focusable).toBe(false);
+
+ expect(await axeViolations(page)).toEqual([]);
+ await capture(page, 'overlay--1440--light-ltr', {
+ story: STORY.overlay,
+ viewport: DESKTOP,
+ globals: 'neutral light ltr',
+ });
+ expect(errors).toEqual([]);
+});
+
+test('long document: the block at the top of the view is followed across a switch', async ({
+ page,
+}) => {
+ const errors = await openStory(page, STORY.longDocument, DESKTOP);
+ await waitForDocument(page, `${TOGGLE}[data-parity-mode="read"]`);
+ const keys = await fixtureKeys(page);
+ await page.evaluate(() =>
+ window.scrollTo(
+ 0,
+ (document.documentElement.scrollHeight - window.innerHeight) / 2,
+ ),
+ );
+ await settle(page);
+ await capture(
+ page,
+ 'long-document--1440--read-scrolled',
+ {story: STORY.longDocument, viewport: DESKTOP, mode: 'read'},
+ {fullPage: false},
+ );
+
+ await editMode(page).click();
+ await waitForDocument(page, `${TOGGLE}[data-parity-mode="edit"]`);
+ const readout = page.locator(
+ '[data-parity-anchor]:not([data-parity-anchor=""])',
+ );
+ await readout.waitFor();
+ const anchor = await readout.evaluate(element => ({
+ ...(element as HTMLElement).dataset,
+ }));
+ expect(keys).toContain(anchor.parityAnchor);
+ // Halfway down a twelve-copy document, the anchor is past the first copy.
+ expect(Number(anchor.parityAnchorCopy)).toBeGreaterThan(1);
+ await capture(
+ page,
+ 'long-document--1440--edit-after-switch',
+ {story: STORY.longDocument, viewport: DESKTOP, mode: 'edit', anchor},
+ {fullPage: false},
+ );
+ expect(errors).toEqual([]);
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b8136b680e..dc71f20082 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -962,6 +962,9 @@ importers:
specifier: '>=19.0.0'
version: 19.2.7([email protected])
devDependencies:
+ '@astryxdesign/a11y-spec':
+ specifier: workspace:*
+ version: link:../../internal/a11y-spec
'@astryxdesign/cli':
specifier: workspace:*
version: link:../cli