An open source design system that's fully customizable and agent ready
TypeScript
fix(Markdown): transforms keep working with source lines on nested blocks (#7345)
Cindy Zhangf77c6c385d34
diff --git a/.changeset/markdown-source-lines-transform.md b/.changeset/markdown-source-lines-transform.mdnew file mode 100644index 0000000000..4c18cdf5d0--- /dev/null+++ b/.changeset/markdown-source-lines-transform.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] With `markdownSourceLinesPlugin` installed, a transform plugin no longer falls back to its readable fallback on documents that contain a list or a quote. Blocks nested in a list item or a quote carry lines without offsets, and the transform check now accepts those Core-assigned lines while still refusing a transform that adds, shifts, or forges them.++@cixzhangdiff --git a/packages/core/src/Markdown/plugins/protocol.ts b/packages/core/src/Markdown/plugins/protocol.tsindex 0578b5a7e0..00c93a56cc 100644--- a/packages/core/src/Markdown/plugins/protocol.ts+++ b/packages/core/src/Markdown/plugins/protocol.ts@@ -708,10 +708,46 @@ export function freezeMarkdownPluginData<T extends MarkdownPluginData>(return value;}+/**+ * The identity of a source-backed node's position: its offsets, or, for a+ * block nested in a list item or quote, which carries lines and no offsets+ * while source lines are on (`module:Markdown/sourceLines`), its lines.+ */function positionKey(position: MarkdownAstPosition | undefined): string | null {const start = position?.start.offset;const end = position?.end.offset;- return start == null || end == null ? null : `${start}:${end}`;+ if (start != null && end != null) {+ return `${start}:${end}`;+ }+ const startLine = position?.start.line;+ const endLine = position?.end.line;+ return startLine == null || endLine == null+ ? null+ : `line ${startLine}:${endLine}`;+}++/** A position's two points measure the same thing and never run backwards. */+function isValidPosition(position: MarkdownAstPosition): boolean {+ const measures = [+ [position.start?.offset, position.end?.offset, 0],+ [position.start?.line, position.end?.line, 1],+ ] as const;+ let measured = false;+ for (const [start, end, minimum] of measures) {+ if (start === undefined && end === undefined) {+ continue;+ }+ if (+ !Number.isInteger(start) ||+ !Number.isInteger(end) ||+ (start as number) < minimum ||+ (end as number) < (start as number)+ ) {+ return false;+ }+ measured = true;+ }+ return measured;}interface CodeInternalProperties {@@ -825,6 +861,8 @@ function restoreCodeInternalProperties(interface SourceInvariant {readonly type: string;+ readonly startLine?: number;+ readonly endLine?: number;readonly depth?: unknown;readonly ordered?: unknown;readonly start?: unknown;@@ -844,6 +882,8 @@ function collectSourceInvariants(const record = node as unknown as Record<string, unknown>;const invariant = {type: node.type,+ startLine: node.position?.start.line,+ endLine: node.position?.end.line,depth: record.depth,ordered: record.ordered,start: record.start,@@ -1048,23 +1088,16 @@ function validateAst(const position = node.position as MarkdownAstPosition | undefined;const key = positionKey(position);- if (position != null) {- const start = position.start?.offset;- const end = position.end?.offset;- if (- !Number.isInteger(start) ||- !Number.isInteger(end) ||- (start as number) < 0 ||- (end as number) < (start as number)- ) {- return false;- }+ if (position != null && !isValidPosition(position)) {+ return false;}if (key != null) {const invariants = sourcePositions.get(key) ?? [];const invariantIndex = invariants.findIndex(invariant =>invariant.type === type &&+ invariant.startLine === position?.start?.line &&+ invariant.endLine === position?.end?.line &&invariant.depth === node.depth &&invariant.ordered === node.ordered &&invariant.start === node.start &&diff --git a/packages/core/src/Markdown/plugins/sourceLines.test.tsx b/packages/core/src/Markdown/plugins/sourceLines.test.tsxindex 6ef4823438..562ebfab86 100644--- a/packages/core/src/Markdown/plugins/sourceLines.test.tsx+++ b/packages/core/src/Markdown/plugins/sourceLines.test.tsx@@ -136,6 +136,16 @@ function hasAnyLine(value: unknown): boolean {return JSON.stringify(value).includes('"line"');}+/** A parsed node, walked generically by the transforms below. */+interface TreeNode {+ readonly type?: string;+ readonly position?: {+ readonly start: {readonly line?: number};+ readonly end: {readonly line?: number};+ };+ readonly children?: ReadonlyArray<TreeNode>;+}+describe('markdownSourceLinesPlugin', () => {beforeEach(() => {parseCalls.full = 0;@@ -466,6 +476,70 @@ describe('markdownSourceLinesPlugin', () => {expect(hasAnyLine(parseMarkdownAst(NESTED, {plugins: []}))).toBe(false);});+ it('composes with a transform that rebuilds nested blocks, which keep their lines', () => {+ const rebuild = (nodes: ReadonlyArray<TreeNode>): TreeNode[] =>+ nodes.map(node =>+ node.children == null+ ? {...node}+ : {...node, children: rebuild(node.children)},+ );+ const copy = createMarkdownPlugin({+ apiVersion: 1,+ name: 'test-rebuild',+ transform: document => ({+ ...document,+ children: rebuild(+ document.children as unknown as ReadonlyArray<TreeNode>,+ ) as unknown as typeof document.children,+ }),+ });+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const {container} = render(+ <Markdown plugins={[copy, markdownSourceLinesPlugin]}>{NESTED}</Markdown>,+ );+ expect(warning).not.toHaveBeenCalled();+ warning.mockRestore();+ expect(stamps(container, '[data-source-line]')).toEqual(+ stamps(renderDocument(NESTED, true), '[data-source-line]'),+ );+ });++ it('refuses a transform that shifts a nested block to other lines', () => {+ const shift = (nodes: ReadonlyArray<TreeNode>): TreeNode[] =>+ nodes.map(node => {+ if (node.type === 'paragraph' && node.position?.start.line === 12) {+ return {...node, position: {start: {line: 13}, end: {line: 13}}};+ }+ return node.children == null+ ? node+ : {...node, children: shift(node.children)};+ });+ const forge = createMarkdownPlugin({+ apiVersion: 1,+ name: 'test-shift-lines',+ transform: document => ({+ ...document,+ children: shift(+ document.children as unknown as ReadonlyArray<TreeNode>,+ ) as unknown as typeof document.children,+ }),+ });+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const {container} = render(+ <Markdown plugins={[forge, markdownSourceLinesPlugin]}>+ {NESTED}+ </Markdown>,+ );+ expect(warning).toHaveBeenCalledWith(+ expect.stringContaining('"test-shift-lines" failed in transform'),+ expect.anything(),+ );+ warning.mockRestore();+ expect(stamps(container, '[data-source-line]')).toEqual(+ stamps(renderDocument(NESTED, true), '[data-source-line]'),+ );+ });+it('keeps the released DOM and renderer props byte-identical without the plugin', () => {const plain = renderToStaticMarkup(<Markdown>{SOURCE}</Markdown>);expect(