An open source design system that's fully customizable and agent ready
TypeScript
Add first-party Markdown soft breaks (#6459)
Cindy Zhanga00065f72ee0
diff --git a/.changeset/markdown-soft-breaks.md b/.changeset/markdown-soft-breaks.mdnew file mode 100644index 0000000000..d9d8abbd97--- /dev/null+++ b/.changeset/markdown-soft-breaks.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feat] Markdown: add the first-party soft-breaks plugin++Use `markdownSoftBreaksPlugin` from `@astryxdesign/core/Markdown/plugins` to render soft line endings as hard breaks without preprocessing source. The plugin matches the real `remark-breaks` package through Astryx's supported adapter path while keeping code and other opaque content unchanged.++@cixzhangdiff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.ts b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.tsindex d7b951fd51..3d36d234bb 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.ts@@ -1,7 +1,11 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, expect, it} from 'vitest';-import {generateMarkdownFixture, nextStreamOffset} from './benchmark';+import {+ formatBenchmarkChange,+ generateMarkdownFixture,+ nextStreamOffset,+} from './benchmark';describe('Markdown performance fixture', () => {it('generates the requested deterministic section count', () => {@@ -13,6 +17,15 @@ describe('Markdown performance fixture', () => {expect(first).toContain('const section3 = {id: 3, ready: true};');});+ it('formats missing, zero, positive, and negative baseline changes', () => {+ expect(formatBenchmarkChange(null, 10)).toBe('—');+ expect(formatBenchmarkChange(10, null)).toBe('—');+ expect(formatBenchmarkChange(0, 0)).toBe('0.0%');+ expect(formatBenchmarkChange(1, 0)).toBe('new');+ expect(formatBenchmarkChange(110, 100)).toBe('+10.0%');+ expect(formatBenchmarkChange(90, 100)).toBe('-10.0%');+ });+it('advances streaming offsets monotonically to the exact source length', () => {const offsets: number[] = [];let offset = 0;diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.ts b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.tsindex df55bc1d8e..3268d5d5d8 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.ts@@ -40,6 +40,20 @@ export function generateMarkdownFixture(sectionCount: number): string {].join('\n\n');}+export function formatBenchmarkChange(+ value: number | null,+ baseline: number | null,+): string {+ if (value == null || baseline == null) {+ return '—';+ }+ if (baseline === 0) {+ return value === 0 ? '0.0%' : 'new';+ }+ const percent = ((value - baseline) / baseline) * 100;+ return `${percent >= 0 ? '+' : ''}${percent.toFixed(1)}%`;+}+export function nextStreamOffset(sourceLength: number,currentOffset: number,diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.test.ts b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.test.tsnew file mode 100644index 0000000000..9350cc41d7--- /dev/null+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.test.ts@@ -0,0 +1,38 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {generateMarkdownFixture} from './benchmark';+import {+ getMarkdownBenchmarkPlugins,+ getMarkdownBenchmarkProfile,+ MARKDOWN_BENCHMARK_PROFILES,+} from './benchmarkProfiles';++describe('Markdown performance profiles', () => {+ const source = generateMarkdownFixture(20);+ const softBreaks = getMarkdownBenchmarkProfile('soft-breaks');++ it('uses the same prepared fixture for paired empty and plugin runs', () => {+ expect(softBreaks.plugins).toHaveLength(1);+ expect(softBreaks.prepareSource(source, 'none')).toBe(source);+ expect(getMarkdownBenchmarkPlugins(softBreaks, 'baseline')).toHaveLength(0);+ expect(getMarkdownBenchmarkPlugins(softBreaks, 'plugin')).toBe(+ softBreaks.plugins,+ );+ });++ it('provides deterministic sparse and dense soft-break fixtures', () => {+ expect(+ softBreaks.prepareSource(source, 'sparse').match(/\nand inline /g),+ ).toHaveLength(2);+ expect(+ softBreaks.prepareSource(source, 'dense').match(/\nand inline /g),+ ).toHaveLength(20);+ });++ it('keeps profile ids unique', () => {+ expect(+ new Set(MARKDOWN_BENCHMARK_PROFILES.map(profile => profile.id)).size,+ ).toBe(MARKDOWN_BENCHMARK_PROFILES.length);+ });+});diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.ts b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.tsnew file mode 100644index 0000000000..f65da0ba08--- /dev/null+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.ts@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file benchmarkProfiles.ts+ * @input A deterministic Markdown fixture, plugin profile, and claim density+ * @output Prepared benchmark source plus the public plugin list for that profile+ * @position Shared profile registry for the Markdown performance sandbox+ */++import {markdownSoftBreaksPlugin} from '@astryxdesign/core/Markdown/plugins';+import type {MarkdownPluginEntry} from '@astryxdesign/core/Markdown/plugins';++export type MarkdownBenchmarkClaimDensity = 'none' | 'sparse' | 'dense';+export type MarkdownBenchmarkPipeline = 'baseline' | 'plugin';+export type MarkdownBenchmarkProfileId = 'soft-breaks';++const EMPTY_PLUGINS: ReadonlyArray<MarkdownPluginEntry> = Object.freeze([]);++export interface MarkdownBenchmarkProfile {+ readonly id: MarkdownBenchmarkProfileId;+ readonly label: string;+ readonly plugins: ReadonlyArray<MarkdownPluginEntry>;+ prepareSource(source: string, density: MarkdownBenchmarkClaimDensity): string;+}++function addSoftBreakClaims(+ source: string,+ density: MarkdownBenchmarkClaimDensity,+): string {+ if (density === 'none') {+ return source;+ }+ return source+ .split('\n')+ .flatMap(line => {+ const match = /^Section (\d+) contains /.exec(line);+ if (match == null) {+ return [line];+ }+ const section = Number(match[1]);+ const claimed = density === 'dense' || section % 10 === 1;+ if (!claimed) {+ return [line];+ }+ const splitAt = line.indexOf(', and inline ');+ return splitAt < 0+ ? [line]+ : [line.slice(0, splitAt + 1), line.slice(splitAt + 2)];+ })+ .join('\n');+}++export const MARKDOWN_BENCHMARK_PROFILES: ReadonlyArray<MarkdownBenchmarkProfile> =+ [+ {+ id: 'soft-breaks',+ label: 'Soft breaks',+ plugins: [markdownSoftBreaksPlugin],+ prepareSource: addSoftBreakClaims,+ },+ ];++export function getMarkdownBenchmarkPlugins(+ profile: MarkdownBenchmarkProfile,+ pipeline: MarkdownBenchmarkPipeline,+): ReadonlyArray<MarkdownPluginEntry> {+ return pipeline === 'plugin' ? profile.plugins : EMPTY_PLUGINS;+}++export function getMarkdownBenchmarkProfile(+ id: MarkdownBenchmarkProfileId,+): MarkdownBenchmarkProfile {+ const profile = MARKDOWN_BENCHMARK_PROFILES.find(entry => entry.id === id);+ if (profile == null) {+ throw new RangeError(`Unknown Markdown benchmark profile: ${id}`);+ }+ return profile;+}diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsxindex ed723a6abc..f638fe9a54 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsx@@ -4,8 +4,8 @@/*** @file page.tsx- * @input Deterministic Markdown fixtures and configurable streamed bursts- * @output Interactive render/stream benchmark with paint and frame metrics+ * @input Deterministic Markdown fixtures, selectable plugin profiles, and streamed bursts+ * @output Interactive baseline comparison with paint, mutation, and frame metrics* @position Fullscreen sandbox tool for validating Markdown performance and animation*/@@ -23,24 +23,36 @@ import {} from '@astryxdesign/core/SegmentedControl';import {HStack, VStack} from '@astryxdesign/core/Stack';import {Heading, Text} from '@astryxdesign/core/Text';-import {generateMarkdownFixture, nextStreamOffset} from './benchmark';+import {+ formatBenchmarkChange,+ generateMarkdownFixture,+ nextStreamOffset,+} from './benchmark';+import {+ getMarkdownBenchmarkPlugins,+ getMarkdownBenchmarkProfile,+ MARKDOWN_BENCHMARK_PROFILES,+ type MarkdownBenchmarkClaimDensity,+ type MarkdownBenchmarkPipeline,+ type MarkdownBenchmarkProfileId,+} from './benchmarkProfiles';type BenchmarkMode = 'complete' | 'streaming';interface BenchmarkMetrics {firstPaintMs: number | null;completeMs: number | null;- mutationBatches: number;- frames: number;- droppedFrames: number;+ mutationBatches: number | null;+ frames: number | null;+ droppedFrames: number | null;}const EMPTY_METRICS: BenchmarkMetrics = {firstPaintMs: null,completeMs: null,- mutationBatches: 0,- frames: 0,- droppedFrames: 0,+ mutationBatches: null,+ frames: null,+ droppedFrames: null,};const SECTION_OPTIONS = ['10', '50', '200', '500'];@@ -52,8 +64,37 @@ function formatDuration(value: number | null): string {return value == null ? '—' : `${value.toFixed(1)} ms`;}+function formatCount(value: number | null): string {+ return value == null ? '—' : value.toLocaleString();+}++function formatFrameCounts(+ frames: number | null,+ droppedFrames: number | null,+): string {+ return frames == null || droppedFrames == null+ ? '—'+ : `${frames.toLocaleString()} / ${droppedFrames.toLocaleString()}`;+}++function comparisonKey(+ profileId: MarkdownBenchmarkProfileId,+ claimDensity: MarkdownBenchmarkClaimDensity,+ mode: BenchmarkMode,+ sectionCount: string,+ burstSize: string,+): string {+ return `${profileId}:${claimDensity}:${mode}:${sectionCount}:${mode === 'streaming' ? burstSize : 'all'}`;+}+export default function MarkdownPerfPage() {const [mode, setMode] = useState<BenchmarkMode>('streaming');+ const [pipeline, setPipeline] =+ useState<MarkdownBenchmarkPipeline>('baseline');+ const [profileId, setProfileId] =+ useState<MarkdownBenchmarkProfileId>('soft-breaks');+ const [claimDensity, setClaimDensity] =+ useState<MarkdownBenchmarkClaimDensity>('sparse');const [sectionCount, setSectionCount] = useState('50');const [burstSize, setBurstSize] = useState('256');const [renderedSource, setRenderedSource] = useState('');@@ -61,6 +102,9 @@ export default function MarkdownPerfPage() {const [isRunning, setIsRunning] = useState(false);const [runKey, setRunKey] = useState(0);const [metrics, setMetrics] = useState<BenchmarkMetrics>(EMPTY_METRICS);+ const [baselines, setBaselines] = useState<Record<string, BenchmarkMetrics>>(+ {},+ );const surfaceRef = useRef<HTMLDivElement>(null);const startTimeRef = useRef(0);@@ -72,11 +116,29 @@ export default function MarkdownPerfPage() {const feedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const resetFrameRef = useRef<number | null>(null);+ const activeRunRef = useRef<{+ readonly baselineKey: string;+ readonly pipeline: MarkdownBenchmarkPipeline;+ } | null>(null);- const fixture = useMemo(+ const profile = getMarkdownBenchmarkProfile(profileId);+ const plugins = getMarkdownBenchmarkPlugins(profile, pipeline);+ const baseFixture = useMemo(() => generateMarkdownFixture(Number(sectionCount)),[sectionCount],);+ const fixture = useMemo(+ () => profile.prepareSource(baseFixture, claimDensity),+ [baseFixture, claimDensity, profile],+ );+ const currentComparisonKey = comparisonKey(+ profileId,+ claimDensity,+ mode,+ sectionCount,+ burstSize,+ );+ const baseline = baselines[currentComparisonKey];const stopTimers = useCallback(() => {if (feedTimerRef.current != null) {@@ -101,13 +163,21 @@ export default function MarkdownPerfPage() {runningRef.current = false;setIsRunning(false);cancelAnimationFrame(frameRef.current.id);- setMetrics({+ const nextMetrics = {firstPaintMs: firstPaintRef.current,completeMs: performance.now() - startTimeRef.current,mutationBatches: mutationBatchesRef.current,frames: frameRef.current.frames,droppedFrames: frameRef.current.dropped,- });+ };+ setMetrics(nextMetrics);+ const activeRun = activeRunRef.current;+ if (activeRun?.pipeline === 'baseline') {+ setBaselines(current => ({+ ...current,+ [activeRun.baselineKey]: nextMetrics,+ }));+ }}, []);const scheduleFinish = useCallback(() => {@@ -148,6 +218,13 @@ export default function MarkdownPerfPage() {useEffect(() => stopTimers, [stopTimers]);+ useEffect(() => {+ if (!runningRef.current) {+ setRenderedSource('');+ setMetrics(EMPTY_METRICS);+ }+ }, [burstSize, claimDensity, mode, pipeline, profileId, sectionCount]);+const startFrameMeasurement = useCallback(() => {const frameState = frameRef.current;frameState.frames = 0;@@ -176,6 +253,10 @@ export default function MarkdownPerfPage() {setRenderedSource('');setRunKey(value => value + 1);setMetrics(EMPTY_METRICS);+ activeRunRef.current = {+ baselineKey: currentComparisonKey,+ pipeline,+ };resetFrameRef.current = requestAnimationFrame(() => {resetFrameRef.current = requestAnimationFrame(() => {@@ -212,8 +293,11 @@ export default function MarkdownPerfPage() {});}, [burstSize,+ currentComparisonKey,fixture,mode,+ pipeline,+ profileId,scheduleFinish,startFrameMeasurement,stopTimers,@@ -245,10 +329,54 @@ export default function MarkdownPerfPage() {<Section variant="muted" padding={3} dividers={['bottom']}><HStack gap={4} vAlign="center" wrap="wrap">+ <SegmentedControl+ label="Plugin profile"+ value={profileId}+ onChange={value =>+ setProfileId(value as MarkdownBenchmarkProfileId)+ }+ isDisabled={isRunning}+ disabledMessage="Stop the active run before changing profiles."+ size="sm">+ {MARKDOWN_BENCHMARK_PROFILES.map(entry => (+ <SegmentedControlItem+ key={entry.id}+ value={entry.id}+ label={entry.label}+ />+ ))}+ </SegmentedControl>+ <SegmentedControl+ label="Pipeline"+ value={pipeline}+ onChange={value =>+ setPipeline(value as MarkdownBenchmarkPipeline)+ }+ isDisabled={isRunning}+ disabledMessage="Stop the active run before changing pipelines."+ size="sm">+ <SegmentedControlItem value="baseline" label="Empty" />+ <SegmentedControlItem value="plugin" label="Plugin" />+ </SegmentedControl>+ <SegmentedControl+ label="Claim density"+ value={claimDensity}+ onChange={value =>+ setClaimDensity(value as MarkdownBenchmarkClaimDensity)+ }+ isDisabled={isRunning}+ disabledMessage="Stop the active run before changing claim density."+ size="sm">+ <SegmentedControlItem value="none" label="No claims" />+ <SegmentedControlItem value="sparse" label="Sparse" />+ <SegmentedControlItem value="dense" label="Dense" />+ </SegmentedControl><SegmentedControllabel="Render mode"value={mode}onChange={value => setMode(value as BenchmarkMode)}+ isDisabled={isRunning}+ disabledMessage="Stop the active run before changing render mode."size="sm"><SegmentedControlItem value="complete" label="Complete" /><SegmentedControlItem value="streaming" label="Streaming" />@@ -257,6 +385,8 @@ export default function MarkdownPerfPage() {label="Section count"value={sectionCount}onChange={setSectionCount}+ isDisabled={isRunning}+ disabledMessage="Stop the active run before changing section count."size="sm">{SECTION_OPTIONS.map(value => (<SegmentedControlItem key={value} value={value} label={value} />@@ -266,8 +396,12 @@ export default function MarkdownPerfPage() {label="Burst size"value={burstSize}onChange={setBurstSize}- isDisabled={mode !== 'streaming'}- disabledMessage="Burst size applies only to streaming runs."+ isDisabled={mode !== 'streaming' || isRunning}+ disabledMessage={+ isRunning+ ? 'Stop the active run before changing burst size.'+ : 'Burst size applies only to streaming runs.'+ }size="sm">{BURST_OPTIONS.map(value => (<SegmentedControlItem@@ -295,6 +429,9 @@ export default function MarkdownPerfPage() {<VStack gap={3}><Heading level={3}>Run metrics</Heading><HStack gap={2} wrap="wrap">+ <Badge label={profile.label} />+ <Badge label={pipeline === 'baseline' ? 'Empty' : 'Plugin'} />+ <Badge label={`${claimDensity} claims`} /><Badgelabel={mode === 'streaming' ? 'Streaming' : 'Complete'}/>@@ -310,36 +447,72 @@ export default function MarkdownPerfPage() {<VStack gap={0.5}><Text type="label">First paint</Text><Text type="code">- {formatDuration(metrics.firstPaintMs)}+ {formatDuration(metrics.firstPaintMs)} ·{' '}+ {formatBenchmarkChange(+ metrics.firstPaintMs,+ baseline?.firstPaintMs ?? null,+ )}</Text></VStack><VStack gap={0.5}><Text type="label">Complete</Text>- <Text type="code">{formatDuration(metrics.completeMs)}</Text>+ <Text type="code">+ {formatDuration(metrics.completeMs)} ·{' '}+ {formatBenchmarkChange(+ metrics.completeMs,+ baseline?.completeMs ?? null,+ )}+ </Text></VStack><VStack gap={0.5}><Text type="label">DOM mutation batches</Text>- <Text type="code">{metrics.mutationBatches}</Text>+ <Text type="code">+ {formatCount(metrics.mutationBatches)} ·{' '}+ {formatBenchmarkChange(+ metrics.mutationBatches,+ baseline?.mutationBatches ?? null,+ )}+ </Text></VStack><VStack gap={0.5}><Text type="label">Frames / drops</Text><Text type="code">- {metrics.frames} / {metrics.droppedFrames}+ {formatFrameCounts(metrics.frames, metrics.droppedFrames)} ·{' '}+ {formatBenchmarkChange(+ metrics.droppedFrames,+ baseline?.droppedFrames ?? null,+ )}</Text></VStack></Grid><Text type="body" color="secondary">- A dropped frame is a measured animation-frame gap over 20 ms.- Completion waits for the rendered subtree to stay unchanged for- 180 ms after the final source burst.+ Each metric includes its change from the latest matching+ baseline. For each workload and density, run the Empty pipeline+ before the Plugin pipeline. A dropped frame is a measured+ animation-frame gap over 20 ms. Completion waits for the+ rendered subtree to stay unchanged for 180 ms after the final+ source burst.</Text></VStack></Card><Card ref={surfaceRef} height={560} padding={4}>- <Markdown key={runKey} isStreaming={isStreaming} contentWidth={760}>- {renderedSource}- </Markdown>+ {plugins.length === 0 ? (+ <Markdown+ key={runKey}+ isStreaming={isStreaming}+ contentWidth={760}>+ {renderedSource}+ </Markdown>+ ) : (+ <Markdown+ key={runKey}+ isStreaming={isStreaming}+ contentWidth={760}+ plugins={plugins}>+ {renderedSource}+ </Markdown>+ )}</Card></Grid></VStack>diff --git a/apps/storybook/.storybook/Markdown.remarkPlugins.test.ts b/apps/storybook/.storybook/Markdown.remarkPlugins.test.tsnew file mode 100644index 0000000000..c43df3a3e8--- /dev/null+++ b/apps/storybook/.storybook/Markdown.remarkPlugins.test.ts@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {parseMarkdownAst} from '@astryxdesign/core/Markdown/parser';+import {markdownSoftBreaksPlugin} from '@astryxdesign/core/Markdown/plugins';+import {remarkBreaksPlugin} from '../stories/Markdown.remarkPlugins';++describe('adapted remark-breaks story fixture', () => {+ it.each([+ ['no space', 'First\nSecond'],+ ['one space', 'First \nSecond'],+ ['one tab', 'First\t\nSecond'],+ ['multiline link', '[Linked\nlabel](/docs)'],+ ['phrasing', 'First *emphasized\nline*'],+ ])('matches the first-party tree for %s', (_name, source) => {+ expect(+ parseMarkdownAst(source, {plugins: [markdownSoftBreaksPlugin]}),+ ).toEqual(parseMarkdownAst(source, {plugins: [remarkBreaksPlugin]}));+ });++ it('preserves opaque fenced code in both paths', () => {+ const source = ['```text', 'fenced', 'code', '```'].join('\n');++ expect(+ parseMarkdownAst(source, {plugins: [markdownSoftBreaksPlugin]}),+ ).toEqual(parseMarkdownAst(source, {plugins: [remarkBreaksPlugin]}));+ });+});diff --git a/apps/storybook/package.json b/apps/storybook/package.jsonindex c469989241..fbabf5dfea 100644--- a/apps/storybook/package.json+++ b/apps/storybook/package.json@@ -42,6 +42,7 @@"@stylexjs/stylex": "catalog:","@stylexjs/unplugin": "^0.19.0","lexical": "^0.46.0",+ "remark-breaks": "^4.0.0","storybook": "^10.4.6"}}diff --git a/apps/storybook/stories/Markdown.remarkPlugins.tsx b/apps/storybook/stories/Markdown.remarkPlugins.tsxindex df327e1f2d..a470753ea3 100644--- a/apps/storybook/stories/Markdown.remarkPlugins.tsx+++ b/apps/storybook/stories/Markdown.remarkPlugins.tsx@@ -3,10 +3,11 @@/*** @file Markdown.remarkPlugins.tsx* @input Synchronous transform-only Remark plugins in Unified's attacher shape- * @output Storybook-only adapted plugins: one compatible, two outside the profile+ * @output Storybook-only adapted plugins: two compatible, two outside the profile* @position Documentation fixtures for the limited Remark compatibility profile*/+import remarkBreaks from 'remark-breaks';import {createMarkdownPlugin,createMarkdownTextTransform,@@ -121,6 +122,12 @@ export const specBadgePlugin = createMarkdownPlugin<},});+export const remarkBreaksPlugin = createMarkdownPlugin({+ name: 'demo-remark-breaks',+ apiVersion: 1,+ transform: createMarkdownRemarkTransform(remarkBreaks),+});+export const remarkSpecLinkPlugin = createMarkdownPlugin({name: 'demo-remark-spec-links',apiVersion: 1,diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsxindex 2a63f8eef8..06be80be1a 100644--- a/apps/storybook/stories/Markdown.stories.tsx+++ b/apps/storybook/stories/Markdown.stories.tsx@@ -4,6 +4,7 @@ import {useCallback, useEffect, useMemo, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {Markdown} from '@astryxdesign/core/Markdown';import type {MarkdownComponents} from '@astryxdesign/core/Markdown';+import {markdownSoftBreaksPlugin} from '@astryxdesign/core/Markdown/plugins';import {Button} from '@astryxdesign/core/Button';import {Link} from '@astryxdesign/core/Link';import {Text} from '@astryxdesign/core/Text';@@ -16,6 +17,7 @@ import {markdownSemanticFenceDemoPlugin,} from './Markdown.demoPlugins';import {+ remarkBreaksPlugin,remarkRawHtmlPlugin,remarkSpecLinkPlugin,remarkUnsafeLinkPlugin,@@ -498,6 +500,76 @@ export const CustomMath: Story = {),};+const softBreaksSource = [+ 'First line',+ 'Second **emphasized** line',+ '',+ '[Linked',+ 'label](/docs) stays one protected link.',+ '',+ '```text',+ 'fenced',+ 'code',+ '```',+].join('\n');++export const SoftBreaks: Story = {+ name: 'First-party soft breaks',+ parameters: {+ docs: {+ description: {+ story:+ 'The first-party native plugin matches adapted remark-breaks output for supported prose. Links and code remain protected in both paths.',+ },+ },+ },+ render: () => (+ <div style={{display: 'grid', gap: 24, maxWidth: 680}}>+ <section data-soft-breaks="native">+ <Text>Native first-party plugin</Text>+ <Markdown plugins={[markdownSoftBreaksPlugin]}>+ {softBreaksSource}+ </Markdown>+ </section>+ <section data-soft-breaks="remark">+ <Text>Adapted remark-breaks</Text>+ <Markdown plugins={[remarkBreaksPlugin]}>{softBreaksSource}</Markdown>+ </section>+ </div>+ ),+ play: async ({canvasElement}) => {+ const pane = (kind: string): HTMLElement => {+ const element = canvasElement.querySelector<HTMLElement>(+ `[data-soft-breaks="${kind}"]`,+ );+ if (element == null) {+ throw new Error(`missing soft-breaks pane: ${kind}`);+ }+ return element;+ };+ const nativePane = pane('native');+ const remarkPane = pane('remark');++ await expect(nativePane.querySelectorAll('br')).toHaveLength(2);+ await expect(remarkPane.querySelectorAll('br')).toHaveLength(2);+ await expect(nativePane.querySelector('p')?.innerHTML).toBe(+ remarkPane.querySelector('p')?.innerHTML,+ );+ await expect(+ within(nativePane).getByRole('link', {name: 'Linked label'}),+ ).toHaveAttribute('href', '/docs');+ await expect(+ within(remarkPane).getByRole('link', {name: 'Linked label'}),+ ).toHaveAttribute('href', '/docs');+ await expect(nativePane.querySelector('code')?.textContent).toBe(+ 'fenced\ncode',+ );+ await expect(remarkPane.querySelector('code')?.textContent).toBe(+ 'fenced\ncode',+ );+ },+};+export const SyntaxPlugins: Story = {name: 'Syntax Plugins',render: () => (diff --git a/docs/specs/AST-036/spec.md b/docs/specs/AST-036/spec.mdindex b249b3ca67..a8b571d430 100644--- a/docs/specs/AST-036/spec.md+++ b/docs/specs/AST-036/spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-15+approved_at: 2026-09-22phase: acceptedowners: [cixzhang]affects_architecture:@@ -215,7 +215,7 @@ Compatibility is explicit per plugin and tested version. “Remark-compatible”### Planned first-party scope-- **FR40 — First-party plugins use the public protocol.** Astryx ships a small first-party set — a mention plugin, an entity-link plugin, and a callout container — built only on the public protocol, each owning its semantics and evidence in its own module record and serving as canonical documentation examples. No first-party plugin receives a capability, validation exemption, ordering privilege, or type affordance unavailable to a third party; an internal fast path is permitted only where it is observationally identical, per FR23.+- **FR40 — First-party plugins use the public protocol.** Astryx ships a small first-party set — a soft-breaks plugin, a configurable entity-reference plugin, and a callout container — built only on the public protocol, each owning its semantics and evidence in its own module record and serving as canonical documentation examples. No first-party plugin receives a capability, validation exemption, ordering privilege, or type affordance unavailable to a third party; an internal fast path is permitted only where it is observationally identical, per FR23.- **FR41 — Footnotes, definitions, and references stay Core scope.** They are not a plugin surface: their identity is document-level ID allocation, collision handling, and back-reference navigation that Core owns under FR15 and FR16, and a plugin owning them would fork the identity system Markdown and Outline share. Until a separately approved contract adds them as Core syntax, they are unsupported, the adapter rejects them, and consumer documentation names the gap explicitly rather than implying a plugin workaround.## Performance evidence protocol@@ -264,7 +264,7 @@ The new decisions are additive and opt-in. `components` swaps supported built-in| FR29–FR30 | Diagnostic fixtures in development/production and admission parity across entrypoints | Every phase/code, advisories, rate suppression, no-handler default, malformed list, duplicate Core, version skew | Silent production failure, document content in diagnostics, module-scope throw, or entrypoint divergence fails. || FR31–FR35 | Inference fixtures without explicit type arguments, canonical/server imports, conformance-kit self-test, documentation checks | Syntax-only, transform-only, renderer-only, heterogeneous lists, server import, third-party kit run | Explicit-type workarounds, client references in server entry, or undocumented rejected categories fail. || FR36–FR39 | Streaming no-oscillation, theme reachability, prepared-reuse counts, stability-policy docs | Chunk boundaries, final-only effects, themed/unthemed output, equal new-identity lists, version skew | Oscillation, unreachable opted-in output, per-render re-preparation, or unpublished policy fails. |-| FR40–FR41 | First-party module records/evidence and unsupported-node fixtures | Mention, entity link, callout; footnote/definition/reference source through parser and adapter | First-party privilege or plugin-owned footnote/definition support fails. |+| FR40–FR41 | First-party module records/evidence and unsupported-node fixtures | Soft breaks, configurable entity references, callouts; footnote/definition/reference source through parser and adapter | First-party privilege or plugin-owned footnote/definition support fails. || Repository integrity | Knowledge validation, public-content checks, typecheck, formatting, and changed-file review | Specification and every implementation PR | Internal content, stale owner records, unrelated paths, or formatting/type failures block merge. |## Related owner prerequisites@@ -279,7 +279,7 @@ Before implementation acceptance, current owner clauses must cover:6. the diagnostic channel on the component and parser options;7. the opt-in extension theme target in Markdown's theming anatomy;8. server-safe parser and conformance-kit package entries;-9. first-party plugin module owners for mention, entity link, and callout.+9. first-party plugin module owners for soft breaks, configurable entity references, and callouts.## Decision log@@ -383,9 +383,9 @@ Rejected: first- or third-party footnote plugins; adapter translation into ordin### DEC-11 — First-party plugins are ordinary plugins**Reference:** `spec:AST-036/DEC-11`-**Direction owner:** `cixzhang`, `2026-09-16`+**Direction owner:** `cixzhang`, `2026-09-22`-Mention, entity-link, and callout examples use only the public protocol, own their semantics and evidence in module records, and receive no capability, exemption, ordering privilege, or type affordance unavailable to third parties. An internal fast path is allowed only when observationally identical.+Soft breaks, configurable entity references, and callout examples use only the public protocol, own their semantics and evidence in module records, and receive no capability, exemption, ordering privilege, or type affordance unavailable to third parties. An internal fast path is allowed only when observationally identical.Rejected: privileged first-party capabilities; demos that exercise private paths; a public protocol with no real first-party consumers.diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjsindex 47402e0ad5..92680abcd9 100644--- a/packages/core/src/Markdown/Markdown.doc.mjs+++ b/packages/core/src/Markdown/Markdown.doc.mjs@@ -252,6 +252,11 @@ export const docs = {description:'Use plugins created by createMarkdownPlugin for reusable syntax, immutable AST transforms, and typed extension rendering. Keep the ordered list stable while its syntax configuration is unchanged.',},+ {+ guidance: true,+ description:+ 'Add markdownSoftBreaksPlugin when single line endings are meaningful. It matches remark-breaks for supported Markdown, including multiline link labels, while code and other opaque content stay unchanged.',+ },{guidance: true,description:@@ -329,6 +334,17 @@ import {Text} from '@astryxdesign/core/Text';{'Visit https://example.com or email [email protected]. ' +'You can also bracket links: <https://docs.example.com>.'}</Markdown>;+`,+ },+ {+ label: 'First-party soft breaks',+ code: `+import {Markdown} from '@astryxdesign/core/Markdown';+import {markdownSoftBreaksPlugin} from '@astryxdesign/core/Markdown/plugins';++<Markdown plugins={[markdownSoftBreaksPlugin]}>+ {'First line\\nSecond line'}+</Markdown>;`,},{@@ -712,6 +728,11 @@ export const docsZh = {description:'Use plugins created by createMarkdownPlugin for reusable syntax, immutable AST transforms, and typed extension rendering. Keep the ordered list stable while its syntax configuration is unchanged.',},+ {+ guidance: true,+ description:+ 'Add markdownSoftBreaksPlugin when single line endings are meaningful. It matches remark-breaks for supported Markdown, including multiline link labels, while code and other opaque content stay unchanged.',+ },{guidance: true,description:@@ -794,6 +815,11 @@ export const docsDense = {description:'Use plugins created by createMarkdownPlugin for reusable syntax, immutable AST transforms, and typed extension rendering. Keep the ordered list stable while its syntax configuration is unchanged.',},+ {+ guidance: true,+ description:+ 'Add markdownSoftBreaksPlugin when single line endings are meaningful. It matches remark-breaks for supported Markdown, including multiline link labels, while code and other opaque content stay unchanged.',+ },{guidance: true,description:diff --git a/packages/core/src/Markdown/Markdown.public.test.ts b/packages/core/src/Markdown/Markdown.public.test.tsindex 2acb90962b..adb91a5244 100644--- a/packages/core/src/Markdown/Markdown.public.test.ts+++ b/packages/core/src/Markdown/Markdown.public.test.ts@@ -20,6 +20,7 @@ import {createMarkdownPlugin,createMarkdownTextTransform,isMarkdownExtensionNode,+ markdownSoftBreaksPlugin,} from './plugins';import type {MarkdownExtensionNode,@@ -202,6 +203,9 @@ describe('Markdown public parser types', () => {expectTypeOf(nodes).toEqualTypeOf<InlineNode<PublicNode>[]>();expectTypeOf(visitMarkdownNodes).toBeFunction();expectTypeOf(createMarkdownTextTransform).toBeFunction();+ expectTypeOf(markdownSoftBreaksPlugin).toEqualTypeOf<+ MarkdownPluginEntry<never>+ >();expectTypeOf(isMarkdownExtensionNode).toBeFunction();function compileOnlyPluginGuards() {diff --git a/packages/core/src/Markdown/Markdown.spec.md b/packages/core/src/Markdown/Markdown.spec.mdindex 3a83747366..15007db10c 100644--- a/packages/core/src/Markdown/Markdown.spec.md+++ b/packages/core/src/Markdown/Markdown.spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-19+approved_at: 2026-09-22owners: [cixzhang]review_triggers: [api, theming]verified_by:@@ -18,11 +18,12 @@ verified_by:packages/core/src/Markdown/parser.test.ts,packages/core/src/Markdown/incremental.test.ts,packages/core/src/Markdown/remark.test.tsx,+ packages/core/src/Markdown/plugins/softBreaks.test.tsx,packages/core/src/Outline/parseOutlineFromMarkdown.test.ts,packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,]-modules: [module:Markdown/remark]+modules: [module:Markdown/remark, module:Markdown/softBreaks]families: [family:navigation-destinations]design_specs: []architecture:diff --git a/packages/core/src/Markdown/modules/softBreaks.spec.md b/packages/core/src/Markdown/modules/softBreaks.spec.mdnew file mode 100644index 0000000000..20ccce4e82--- /dev/null+++ b/packages/core/src/Markdown/modules/softBreaks.spec.md@@ -0,0 +1,137 @@+---+schema_version: 3+template_version: 2+kind: module+id: module:Markdown/softBreaks+authority: current+archive_reason: null+superseded_by: null+approved_by: cixzhang+approved_at: 2026-09-22+owners: [cixzhang]+review_triggers: [public-api, behavior]+verified_by:+ [+ packages/core/src/Markdown/plugins/softBreaks.test.tsx,+ apps/storybook/.storybook/Markdown.remarkPlugins.test.ts,+ apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmarkProfiles.test.ts,+ ]+parent_component: component:Markdown+references: [spec:AST-036/DEC-1, spec:AST-036/DEC-11]+---++# Markdown soft-breaks module contract++## Contract at a glance++| Area | Contract |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `markdownSoftBreaksPlugin` is one durable first-party plugin value exported from `@astryxdesign/core/Markdown/plugins`. |+| Behavior | Each soft LF, CRLF, or lone CR line ending in eligible phrasing becomes a canonical Markdown `break` node, matching the real plugin through Astryx's adapter. |+| End-user impact | Readers see author-intended line wrapping without requiring two trailing spaces, while protected content remains literal and copyable. |+| Builder impact | Builders opt in by adding one value to `plugins`; there are no settings or renderer slots. |+| Compatibility | Additive and opt-in; omitted and empty plugin lists preserve the released parser, DOM, accessibility, and streaming behavior. |+| Review checks | Reject missing link-label parity with `remark-breaks`, matching inside code, images, citations, math, or extension nodes; source preprocessing; a custom renderer; or behavior that diverges between complete and streaming input. |+| Governing rules | [`spec:AST-036` FR1–FR17, FR21–FR24, FR36, FR38, FR40](../../../../../docs/specs/AST-036/spec.md); [`component:Markdown` FR12–FR16, FR21](../Markdown.spec.md). |++This table is a review projection; the body below is authoritative.++## Intent++Builders who receive prose with meaningful single line endings should be able to+render those endings as breaks without rewriting source or changing Markdown's+parser. The plugin is deliberately fixed: one stable behavior makes it easy to+recognize, benchmark, and replace with an adapted `remark-breaks` transform.++## Compatibility and migration++- Released default preserved: `yes`+- Compatibility class: additive and opt-in+- Migration decision: `spec:AST-036/DEC-11`++## Ownership boundary++**Owns**++- The exported plugin value and its stable plugin name.+- Converting eligible soft line endings to built-in `break` nodes.+- Complete, streaming, SSR, Storybook parity, and browser-performance evidence.++**Does not own / non-goals**++- Parsing or rendering a new extension node.+- Opaque line endings inside inline/fenced code, images, citations, math, or extension nodes.+- CSS white-space behavior or source preprocessing.+- Hard breaks already authored with Markdown's two-space or backslash syntax.++## Public API and concepts++| Concept | Closed values or states | Meaning | Default | Owner | Stability |+| -------------------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------- | ---------------------------- | --------- |+| `markdownSoftBreaksPlugin` | one `MarkdownPluginEntry<never>` | Converts eligible soft endings through the public transform protocol. | absent | `module:Markdown/softBreaks` | stable |+| Eligible ending | LF, CRLF, or lone CR inside phrasing text, including link labels | Replaced by one built-in `break` node. | literal soft ending | `module:Markdown/softBreaks` | stable |+| Opaque context | code, image, citation, math, or extension content | Remains byte-for-byte content rather than becoming a break. | protected | `component:Markdown` | stable |++## Behavioral contract++| ID | Invariant | Basis |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |+| FR1 | Every eligible LF, CRLF, or lone CR ending becomes exactly one canonical `break` node. | `spec:AST-036` FR1, FR9 |+| FR2 | The plugin uses only `createMarkdownPlugin()` and the public immutable transform contract and introduces no extension node or renderer. | `spec:AST-036` FR1, FR40 |+| FR3 | Link-label prose transforms for `remark-breaks` parity; inline and fenced code, images, citations, math, and extension nodes remain opaque. | `spec:AST-036` FR7, FR15 |+| FR4 | Omitted or empty plugin lists preserve the released soft-ending behavior. | `spec:AST-036` FR2, FR3 |+| FR5 | Every streamed prefix is deterministic and the final streamed tree equals complete parsing of the same source. | `spec:AST-036` FR13, FR36 |+| FR6 | Source with no newline returns the original tree without allocating replacement nodes. | `spec:AST-036` FR21, FR23 |+| FR7 | Native output matches an adapted `remark-breaks` transform for the supported Astryx subset. | `spec:AST-036` FR20, FR40 |++## Accessibility contract++- **AR1 — reading order stays source order.** A break adds no focus target and+ does not move text between semantic containers.+- **AR2 — link meaning stays intact.** Link destinations and accessible names+ retain their source text while visual line breaks match `remark-breaks`.++## Design relationships++Soft breaks add no anatomy or styling. Existing Markdown paragraph and break+rendering remains authoritative.++## Parent and system relationships++- `component:Markdown` owns parsing, protected contexts, rendering, and fallback.+- `spec:AST-036` owns the plugin protocol and first-party parity requirement.+- `module:Markdown/remark` owns the adapted `remark-breaks` comparison path.++## Content boundary++This module recognizes only LF, CRLF, and lone CR characters already present in+eligible canonical phrasing text. It does not inspect or persist document content+outside the transform invocation.++## Verification map++| Contract | Verification | Representative states | Failure expectation |+| ----------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |+| FR1–FR4 | `softBreaks.test.tsx` AST and SSR fixtures | LF, CRLF, lone CR, prose, emphasis, multiline link, inline code, fence, authored hard break, no plugin | Extra, missing, opaque-context, doubled-hard-break, or default-path break fails. |+| FR5 | `softBreaks.test.tsx` prefix sequence | before, at, and after a streamed line ending | Oscillation or final mismatch fails. |+| FR6 | `softBreaks.test.tsx` identity coverage and Markdown Perf no-claim profile | no newline | Allocating a changed tree for absent source fails. |+| FR7 | Storybook native/adapted parity story | prose, emphasis, multiline link, protected code | DOM divergence fails. |+| Performance | Markdown Performance paired empty/plugin runs for the soft-break workload | no, sparse, and dense claims; complete and streaming modes | Different source between a pair, missing baseline delta, or missing density control blocks acceptance. |++## Decision log++### DEC-1 — Ship one fixed plugin value++**Reference:** `module:Markdown/softBreaks/DEC-1`+**Decider:** `cixzhang`, `2026-09-22`++Soft breaks have one established meaning and need no product-specific data or+presentation. A fixed value keeps the API smaller than a factory whose options+would not change behavior.++Rejected: source preprocessing; a boolean on Markdown; a renderer callback; a+factory with no meaningful configuration.++## Open questions++None.diff --git a/packages/core/src/Markdown/plugins/index.ts b/packages/core/src/Markdown/plugins/index.tsindex 44e9c91351..687ba62772 100644--- a/packages/core/src/Markdown/plugins/index.ts+++ b/packages/core/src/Markdown/plugins/index.ts@@ -28,6 +28,7 @@ export type {MarkdownSourceDecorationRange,} from './sourceDecoration';export {createMarkdownFrontmatter} from './frontmatter';+export {markdownSoftBreaksPlugin} from './softBreaks';export type {MarkdownFrontmatter,MarkdownFrontmatterOptions,diff --git a/packages/core/src/Markdown/plugins/softBreaks.test.tsx b/packages/core/src/Markdown/plugins/softBreaks.test.tsxnew file mode 100644index 0000000000..838822de09--- /dev/null+++ b/packages/core/src/Markdown/plugins/softBreaks.test.tsx@@ -0,0 +1,172 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file softBreaks.test.tsx+ * @input Complete and streaming Markdown with soft line endings+ * @output AST, rendering, protection, typing, and convergence evidence+ * @position Acceptance tests for the first-party Markdown soft-breaks plugin+ */++import {renderToString} from 'react-dom/server';+import {describe, expect, expectTypeOf, it} from 'vitest';+import {Markdown} from '../Markdown';+import {parseMarkdownAst, parseMarkdownAstInternal} from '../parser';+import type {MarkdownPluginEntry} from './protocol';+import {markdownSoftBreaksPlugin} from './softBreaks';++const SOURCE = [+ 'First line',+ 'Second **emphasized** line',+ '',+ '[Linked',+ 'label](/docs) and `inline code`.',+ '',+ '```text',+ 'fenced',+ 'code',+ '```',+].join('\n');++describe('markdownSoftBreaksPlugin', () => {+ it('turns eligible LF, CRLF, and lone CR endings into break nodes', () => {+ expect(+ parseMarkdownAst('Alpha\nBeta', {+ plugins: [markdownSoftBreaksPlugin],+ }).children[0],+ ).toMatchObject({+ type: 'paragraph',+ children: [+ {type: 'text', value: 'Alpha'},+ {type: 'break'},+ {type: 'text', value: 'Beta'},+ ],+ });+ expect(+ parseMarkdownAst('Alpha\r\nBeta', {+ plugins: [markdownSoftBreaksPlugin],+ }).children[0],+ ).toMatchObject({+ type: 'paragraph',+ children: [+ {type: 'text', value: 'Alpha'},+ {type: 'break'},+ {type: 'text', value: 'Beta'},+ ],+ });+ expect(+ parseMarkdownAst('Alpha\rBeta', {+ plugins: [markdownSoftBreaksPlugin],+ }).children[0],+ ).toMatchObject({+ type: 'paragraph',+ children: [+ {type: 'text', value: 'Alpha'},+ {type: 'break'},+ {type: 'text', value: 'Beta'},+ ],+ });+ for (const source of ['Alpha \nBeta', 'Alpha\t\nBeta']) {+ expect(+ parseMarkdownAst(source, {+ plugins: [markdownSoftBreaksPlugin],+ }).children[0],+ ).toMatchObject({+ type: 'paragraph',+ children: [+ {+ type: 'text',+ value: source.startsWith('Alpha\t') ? 'Alpha\t' : 'Alpha ',+ },+ {type: 'break'},+ {type: 'text', value: 'Beta'},+ ],+ });+ }+ expect(+ parseMarkdownAst('Alpha \nBeta', {+ plugins: [markdownSoftBreaksPlugin],+ }).children[0],+ ).toMatchObject({+ type: 'paragraph',+ children: [+ {type: 'text', value: 'Alpha'},+ {type: 'break'},+ {type: 'text', value: 'Beta'},+ ],+ });+ });++ it('preserves the no-plugin path and opaque contexts', () => {+ expect(+ parseMarkdownAst('No line ending', {+ plugins: [markdownSoftBreaksPlugin],+ }),+ ).toEqual(parseMarkdownAst('No line ending'));++ const baseline = parseMarkdownAst(SOURCE);+ const transformed = parseMarkdownAst(SOURCE, {+ plugins: [markdownSoftBreaksPlugin],+ });++ expect(JSON.stringify(baseline)).not.toContain('"type":"break"');+ expect(JSON.stringify(transformed)).toContain('"type":"break"');+ expect(transformed.children).toMatchObject([+ {type: 'paragraph'},+ {+ type: 'paragraph',+ children: [+ {+ type: 'link',+ url: '/docs',+ children: [+ {type: 'text', value: 'Linked'},+ {type: 'break'},+ {type: 'text', value: 'label'},+ ],+ },+ {type: 'text', value: ' and '},+ {type: 'inlineCode', value: 'inline code'},+ {type: 'text', value: '.'},+ ],+ },+ {type: 'code', value: 'fenced\ncode'},+ ]);+ });++ it('renders hard breaks during server rendering', () => {+ const html = renderToString(+ <Markdown plugins={[markdownSoftBreaksPlugin]}>{'Alpha\nBeta'}</Markdown>,+ );++ expect(html).toContain('Alpha<br/>Beta');+ expectTypeOf(markdownSoftBreaksPlugin).toMatchTypeOf<+ MarkdownPluginEntry<never>+ >();+ });++ it('is deterministic and converges across streaming prefixes', () => {+ const prefixes = ['Alpha', 'Alpha\n', 'Alpha\nBeta'];+ const snapshots = prefixes.map(source =>+ parseMarkdownAstInternal(+ source,+ {plugins: [markdownSoftBreaksPlugin]},+ false,+ ),+ );++ expect(snapshots[0]).toEqual(+ parseMarkdownAstInternal(+ prefixes[0],+ {plugins: [markdownSoftBreaksPlugin]},+ false,+ ),+ );+ expect(snapshots[1].children[0]).toMatchObject({+ type: 'paragraph',+ children: [{type: 'text', value: 'Alpha'}],+ });+ expect(snapshots[2]).toEqual(+ parseMarkdownAst(prefixes[2], {plugins: [markdownSoftBreaksPlugin]}),+ );+ });+});diff --git a/packages/core/src/Markdown/plugins/softBreaks.ts b/packages/core/src/Markdown/plugins/softBreaks.tsnew file mode 100644index 0000000000..4293eca649--- /dev/null+++ b/packages/core/src/Markdown/plugins/softBreaks.ts@@ -0,0 +1,169 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file softBreaks.ts+ * @input Soft line endings in Markdown phrasing content+ * @output A first-party plugin that renders each soft line ending as a hard break+ * @position Optional Markdown transform built only on the public plugin protocol+ */++import type {+ MarkdownAstBlockContent,+ MarkdownAstExtensionNode,+ MarkdownAstListItem,+ MarkdownAstPhrasingContent,+ MarkdownAstTableCell,+ MarkdownAstTableRow,+} from '../ast';+import {createMarkdownPlugin, type MarkdownTransform} from './protocol';++type Extension = MarkdownAstExtensionNode;+type Phrasing = MarkdownAstPhrasingContent<Extension>;+type Block = MarkdownAstBlockContent<Extension>;++function replaceLineEndings(value: string): ReadonlyArray<Phrasing> | null {+ const pattern = /\r?\n|\r/g;+ let match = pattern.exec(value);+ if (match == null) {+ return null;+ }+ const output: Phrasing[] = [];+ let cursor = 0;+ do {+ if (match.index > cursor) {+ output.push({type: 'text', value: value.slice(cursor, match.index)});+ }+ output.push({type: 'break'});+ cursor = match.index + match[0].length;+ match = pattern.exec(value);+ } while (match != null);+ if (cursor < value.length) {+ output.push({type: 'text', value: value.slice(cursor)});+ }+ return output;+}++function transformPhrasing(+ children: ReadonlyArray<Phrasing>,+): ReadonlyArray<Phrasing> {+ let next: Phrasing[] | undefined;+ for (let index = 0; index < children.length; index++) {+ const node = children[index];+ if (node.type === 'text') {+ const replacement = replaceLineEndings(node.value);+ if (replacement == null) {+ next?.push(node);+ } else {+ next ??= children.slice(0, index);+ next.push(...replacement);+ }+ continue;+ }+ if (+ node.type === 'strong' ||+ node.type === 'emphasis' ||+ node.type === 'delete' ||+ node.type === 'link'+ ) {+ const nested = transformPhrasing(node.children);+ if (nested !== node.children) {+ next ??= children.slice(0, index);+ next.push({...node, children: nested});+ } else {+ next?.push(node);+ }+ continue;+ }+ next?.push(node);+ }+ return next ?? children;+}++function transformTableCell(cell: MarkdownAstTableCell<Extension>) {+ const children = transformPhrasing(cell.children);+ return children === cell.children ? cell : {...cell, children};+}++function transformTableRow(row: MarkdownAstTableRow<Extension>) {+ const children = row.children.map(transformTableCell);+ return children.every((child, index) => child === row.children[index])+ ? row+ : {...row, children};+}++function transformListItem(item: MarkdownAstListItem<Extension>) {+ const children = transformBlocks(item.children);+ return children === item.children ? item : {...item, children};+}++function transformBlocks(children: ReadonlyArray<Block>): ReadonlyArray<Block> {+ let next: Block[] | undefined;+ for (let index = 0; index < children.length; index++) {+ const node = children[index];+ let transformed: Block = node;+ switch (node.type) {+ case 'heading':+ case 'paragraph': {+ const nested = transformPhrasing(node.children);+ if (nested !== node.children) {+ transformed = {...node, children: nested};+ }+ break;+ }+ case 'blockquote': {+ const nested = transformBlocks(node.children);+ if (nested !== node.children) {+ transformed = {...node, children: nested};+ }+ break;+ }+ case 'list': {+ const nested = node.children.map(transformListItem);+ if (+ nested.some(+ (child, childIndex) => child !== node.children[childIndex],+ )+ ) {+ transformed = {...node, children: nested};+ }+ break;+ }+ case 'table': {+ const nested = node.children.map(transformTableRow);+ if (+ nested.some(+ (child, childIndex) => child !== node.children[childIndex],+ )+ ) {+ transformed = {...node, children: nested};+ }+ break;+ }+ case 'code':+ case 'math':+ case 'thematicBreak':+ case 'image':+ case 'extension':+ break;+ default:+ node satisfies never;+ }+ if (transformed !== node) {+ next ??= children.slice(0, index);+ }+ next?.push(transformed);+ }+ return next ?? children;+}++const transformSoftBreaks: MarkdownTransform<never> = document => {+ const children = transformBlocks(document.children);+ return children === document.children ? document : {...document, children};+};++/** Converts soft line endings in Markdown phrasing content to hard breaks. */+export const markdownSoftBreaksPlugin = createMarkdownPlugin({+ name: 'soft-breaks',+ apiVersion: 1,+ transform: transformSoftBreaks,+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5d03fc0357..a6f8a0d608 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -494,6 +494,9 @@ importers:lexical:specifier: ^0.46.0version: 0.46.0([email protected])+ remark-breaks:+ specifier: ^4.0.0+ version: 4.0.0storybook:specifier: ^10.4.6version: 10.4.6(@testing-library/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3769,6 +3772,9 @@ packages:resolution: {integrity: sha512-s84fKOrzqqNCAPljhVyC5TjAo6BH4jKHw9NRNFNiRUY5QSgZCmVm5XILlWbisiKl+0OcS7eWihmKGS5akc2iQw==}deprecated: This is a stub types definition. lz-string provides its own type definitions, so you do not need this installed.+ '@types/[email protected]':+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}+'@types/[email protected]':resolution: {integrity: sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==}@@ -3792,6 +3798,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}+'@types/[email protected]':resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}@@ -4096,6 +4105,9 @@ packages:resolution: {integrity: sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==}engines: {node: '>=4'}+ resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}+resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}@@ -4540,6 +4552,9 @@ packages:resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}+ resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}+resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}engines: {node: '>=0.3.1'}@@ -4651,6 +4666,10 @@ packages:resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-oKalwDGcD+RX9mf3NEO4zOoUMeLvjSvcbbEOpquzmzqEEM2MQdp7/FY/Hx9NzmUwFzH1W9SKTz5fihfMldpEYw==}engines: {node: ^14.17.0 || ^16.0.0 || >= 18.0.0}@@ -4789,6 +4808,9 @@ packages:resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}engines: {node: '>= 18'}+ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}+resolution: {integrity: sha512-UOiS2in6/Q0FK0R0q6UY9vYpQ21mr/Qn1KOnte7vsACuNJf514WvCCUHSRCPcgjPT2bAhNIJdlE6bVap1GKmeg==}@@ -5526,6 +5548,12 @@ packages:next:optional: true+ resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}++ resolution: {integrity: sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==}+resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}@@ -6093,6 +6121,9 @@ packages:resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==}+ resolution: {integrity: sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==}+resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}engines: {node: '>=0.10.0'}@@ -6491,6 +6522,9 @@ packages:resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}hasBin: true+ resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}+resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==}engines: {node: '>=18.12'}@@ -6575,6 +6609,18 @@ packages:resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}++ resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}++ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}++ resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==}+resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}engines: {node: '>= 4.0.0'}@@ -6769,6 +6815,12 @@ packages:resolution: {integrity: sha512-BIwalIcEGysJdQDjeVUmMWB3e50jPDNAMfLJscjEvpunU9bSt7X1OYnQxkg3uBwuRRI4nWfFZO9uIW910nLeGw==}+ resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}++ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}+resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==}@@ -9540,6 +9592,10 @@ snapshots:dependencies:lz-string: 1.5.0+ '@types/[email protected]':+ dependencies:+ '@types/unist': 3.0.3+'@types/[email protected]': {}'@types/[email protected]': {}@@ -9560,6 +9616,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -9862,6 +9920,8 @@ snapshots:+ [email protected]: {}+@@ -10258,6 +10318,10 @@ snapshots:+ dependencies:+ dequal: 2.0.3+@@ -10367,6 +10431,8 @@ snapshots:+ [email protected]: {}+dependencies:'@babel/core': 7.29.7@@ -10624,6 +10690,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+@@ -11303,6 +11371,18 @@ snapshots:optionalDependencies:next: 16.3.0-preview.5(@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ dependencies:+ '@types/mdast': 4.0.4+ escape-string-regexp: 5.0.0+ unist-util-is: 6.0.1+ unist-util-visit-parents: 6.0.2++ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-find-and-replace: 3.0.2+@@ -11883,6 +11963,12 @@ snapshots:+ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-newline-to-break: 2.0.0+ unified: 11.0.5+@@ -12351,6 +12437,8 @@ snapshots:+ [email protected]: {}+dependencies:typescript: 6.0.3@@ -12439,6 +12527,29 @@ snapshots:+ dependencies:+ '@types/unist': 3.0.3+ bail: 2.0.2+ devlop: 1.1.0+ extend: 3.0.2+ is-plain-obj: 4.1.0+ trough: 2.2.0+ vfile: 6.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.1+@@ -12738,6 +12849,16 @@ snapshots:vega-voronoi: 5.1.0vega-wordcloud: 5.1.0+ dependencies:+ '@types/unist': 3.0.3+ unist-util-stringify-position: 4.0.0++ dependencies:+ '@types/unist': 3.0.3+ vfile-message: 4.0.3+dependencies:'@types/d3-array': 3.2.2