From b3e5d6a428b7a503b0c88ceca36f24d2e76f2cf7 Mon Sep 17 00:00:00 2001 From: onmax Date: Sun, 25 Oct 2026 13:28:10 +0100 Subject: [PATCH 1/2] fix: preserve documents when rendering streaming carets --- docs/content/3.rendering/3.vue.md | 2 +- docs/content/3.rendering/5.react.md | 2 +- .../src/components/MarkdownDocument.tsx | 8 +- packages/comark-react/src/utils/caret.ts | 31 +++--- packages/comark-react/test/caret.test.tsx | 103 ++++++++++++++++++ .../src/components/MarkdownDocument.ts | 8 +- packages/comark-vue/src/utils/caret.ts | 31 +++--- packages/comark-vue/test/caret.test.ts | 80 ++++++++++++++ 8 files changed, 225 insertions(+), 40 deletions(-) create mode 100644 packages/comark-react/test/caret.test.tsx create mode 100644 packages/comark-vue/test/caret.test.ts diff --git a/docs/content/3.rendering/3.vue.md b/docs/content/3.rendering/3.vue.md index 6a91b3717..48beeac8f 100644 --- a/docs/content/3.rendering/3.vue.md +++ b/docs/content/3.rendering/3.vue.md @@ -783,7 +783,7 @@ async function askAI(prompt: string) { ### Caret -The `caret` prop appends a blinking cursor to the last text node while `streaming` is `true`: +The `caret` prop shows a blinking cursor after the last text node while `streaming` is `true`. It leaves the input document unchanged, so the same document can be rendered again or shared between components. ```vue [App.vue] diff --git a/docs/content/3.rendering/5.react.md b/docs/content/3.rendering/5.react.md index 6b6aeeaac..4740f7459 100644 --- a/docs/content/3.rendering/5.react.md +++ b/docs/content/3.rendering/5.react.md @@ -716,7 +716,7 @@ export default function AiChat() { ### Caret -The `caret` prop appends a blinking cursor to the last text node while `streaming` is `true`: +The `caret` prop shows a blinking cursor after the last text node while `streaming` is `true`. It leaves the input document unchanged, so the same document can be rendered again or shared between components. ```tsx [App.tsx] {/* Default caret */} diff --git a/packages/comark-react/src/components/MarkdownDocument.tsx b/packages/comark-react/src/components/MarkdownDocument.tsx index ca38cca2e..908f58023 100644 --- a/packages/comark-react/src/components/MarkdownDocument.tsx +++ b/packages/comark-react/src/components/MarkdownDocument.tsx @@ -15,7 +15,7 @@ import { resolveAttributes, toNativeAttributes, } from 'comark/utils' -import { findLastTextNodeAndAppendNode, getCaret } from '../utils/caret.ts' +import { appendCaretToLastTextNode, getCaret } from '../utils/caret.ts' /** * Helper to get tag from a Node @@ -399,8 +399,10 @@ export const MarkdownDocument: React.FC = ({ const nodes = [...(document.nodes || [])] if (streaming && caret && nodes.length > 0) { - const hasStreamCaret = findLastTextNodeAndAppendNode(nodes[nodes.length - 1] as ElementNode, caret) - if (!hasStreamCaret) { + const lastNode = appendCaretToLastTextNode(nodes[nodes.length - 1], caret) + if (lastNode) { + nodes[nodes.length - 1] = lastNode + } else { nodes.push(caret) } } diff --git a/packages/comark-react/src/utils/caret.ts b/packages/comark-react/src/utils/caret.ts index 0b6fc6cc2..b5f1041b9 100644 --- a/packages/comark-react/src/utils/caret.ts +++ b/packages/comark-react/src/utils/caret.ts @@ -1,4 +1,4 @@ -import type { ElementNode } from 'comark' +import type { ElementNode, Node } from 'comark' interface CaretOptions { class?: string @@ -28,25 +28,24 @@ export function getCaret(options: boolean | CaretOptions): ElementNode | null { return null } -export function findLastTextNodeAndAppendNode(parent: ElementNode, nodeToAppend: ElementNode): boolean { - // Traverse nodes backwards to find the last text node - for (let i = parent.length - 1; i >= 2; i--) { - const node = parent[i] - - if (typeof node === 'string' && parent[1]?.key !== 'stream-caret') { - // Found a text node - insert stream indicator after it - parent.push(nodeToAppend) +export function appendCaretToLastTextNode(parent: Node, caret: ElementNode): ElementNode | null { + if (!Array.isArray(parent) || parent[0] === null || parent[1]?.key === 'stream-caret') { + return null + } - return true + for (let i = parent.length - 1; i >= 2; i--) { + const node = parent[i] as Node + if (typeof node === 'string') { + return [...parent, caret] } - if (Array.isArray(node)) { - // This is an element node - recursively check its children - if (findLastTextNodeAndAppendNode(node as ElementNode, nodeToAppend)) { - return true - } + const child = appendCaretToLastTextNode(node, caret) + if (child) { + const copy: ElementNode = [...parent] + copy[i] = child + return copy } } - return false + return null } diff --git a/packages/comark-react/test/caret.test.tsx b/packages/comark-react/test/caret.test.tsx new file mode 100644 index 000000000..f7a506b30 --- /dev/null +++ b/packages/comark-react/test/caret.test.tsx @@ -0,0 +1,103 @@ +import { describe, expect, it } from 'vitest' +import { renderToString } from 'react-dom/server' +import { createMarkdownParser, parseMarkdown } from 'comark' +import { MarkdownDocument } from '../src/components/MarkdownDocument' + +function freeze(value: unknown): void { + if (value && typeof value === 'object') { + Object.values(value).forEach(freeze) + Object.freeze(value) + } +} + +describe('streaming caret', () => { + it.each(['Hello.', '> Hello **world**'])('preserves the input when rendering %s repeatedly', async (source) => { + const document = await parseMarkdown(source) + const original = structuredClone(document) + freeze(document) + + for (let i = 0; i < 3; i++) { + const html = renderToString( + + ) + expect(html.match(/class="test-caret"/g)).toHaveLength(1) + expect(document).toEqual(original) + } + expect( + renderToString( + + ) + ).not.toContain('test-caret') + }) + + it.each(['![image](/image.png)', 'plain text', ''])( + 'appends a caret after unwrapped content: %s', + async (source) => { + const document = await parseMarkdown(source, { unwrap: true }) + const original = structuredClone(document) + freeze(document) + const html = renderToString( + + ) + + expect(html.match(/class="test-caret"/g)).toHaveLength(1) + expect(document).toEqual(original) + } + ) + + it('leaves the caret out when streaming is disabled', async () => { + const document = await parseMarkdown('Hello.') + const original = structuredClone(document) + freeze(document) + const html = renderToString( + + ) + + expect(html).not.toContain('test-caret') + expect(document).toEqual(original) + }) + + it('does not add carets to documents reused by the streaming parser', async () => { + const parse = createMarkdownParser() + for (const source of ['First\n\nTail', 'First\n\nTail grows', 'First\n\nTail grows again']) { + const document = await parse(source, { streaming: true }) + const original = structuredClone(document) + const html = renderToString( + + ) + expect(html.match(/class="test-caret"/g)).toHaveLength(1) + expect(document).toEqual(original) + } + }) + + it('leaves an empty document empty', async () => { + const document = await parseMarkdown('') + expect( + renderToString( + + ) + ).not.toContain('test-caret') + }) +}) diff --git a/packages/comark-vue/src/components/MarkdownDocument.ts b/packages/comark-vue/src/components/MarkdownDocument.ts index ddaae93ec..235544078 100644 --- a/packages/comark-vue/src/components/MarkdownDocument.ts +++ b/packages/comark-vue/src/components/MarkdownDocument.ts @@ -21,7 +21,7 @@ import { shallowRef, toRaw, } from 'vue' -import { findLastTextNodeAndAppendNode, getCaret } from '../utils/caret.ts' +import { appendCaretToLastTextNode, getCaret } from '../utils/caret.ts' import { applyNodeTransforms, pascalCase, resolveAttributes, toNativeAttributes } from 'comark/utils' // Cache for dynamically resolved components @@ -471,8 +471,10 @@ export const MarkdownDocument: MarkdownDocumentComponent = defineComponent({ const nodes = [...(rawDocument.nodes || [])] if (props.streaming && caret.value && nodes.length > 0) { - const hasStreamCaret = findLastTextNodeAndAppendNode(nodes[nodes.length - 1] as ElementNode, caret.value) - if (!hasStreamCaret) { + const lastNode = appendCaretToLastTextNode(nodes[nodes.length - 1], caret.value) + if (lastNode) { + nodes[nodes.length - 1] = lastNode + } else { nodes.push(caret.value) } } diff --git a/packages/comark-vue/src/utils/caret.ts b/packages/comark-vue/src/utils/caret.ts index 0b6fc6cc2..b5f1041b9 100644 --- a/packages/comark-vue/src/utils/caret.ts +++ b/packages/comark-vue/src/utils/caret.ts @@ -1,4 +1,4 @@ -import type { ElementNode } from 'comark' +import type { ElementNode, Node } from 'comark' interface CaretOptions { class?: string @@ -28,25 +28,24 @@ export function getCaret(options: boolean | CaretOptions): ElementNode | null { return null } -export function findLastTextNodeAndAppendNode(parent: ElementNode, nodeToAppend: ElementNode): boolean { - // Traverse nodes backwards to find the last text node - for (let i = parent.length - 1; i >= 2; i--) { - const node = parent[i] - - if (typeof node === 'string' && parent[1]?.key !== 'stream-caret') { - // Found a text node - insert stream indicator after it - parent.push(nodeToAppend) +export function appendCaretToLastTextNode(parent: Node, caret: ElementNode): ElementNode | null { + if (!Array.isArray(parent) || parent[0] === null || parent[1]?.key === 'stream-caret') { + return null + } - return true + for (let i = parent.length - 1; i >= 2; i--) { + const node = parent[i] as Node + if (typeof node === 'string') { + return [...parent, caret] } - if (Array.isArray(node)) { - // This is an element node - recursively check its children - if (findLastTextNodeAndAppendNode(node as ElementNode, nodeToAppend)) { - return true - } + const child = appendCaretToLastTextNode(node, caret) + if (child) { + const copy: ElementNode = [...parent] + copy[i] = child + return copy } } - return false + return null } diff --git a/packages/comark-vue/test/caret.test.ts b/packages/comark-vue/test/caret.test.ts new file mode 100644 index 000000000..c0ba1ef37 --- /dev/null +++ b/packages/comark-vue/test/caret.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import { createSSRApp, h } from 'vue' +import { renderToString } from '@vue/server-renderer' +import { createMarkdownParser, parseMarkdown } from 'comark' +import { MarkdownDocument } from '../src/components/MarkdownDocument.ts' + +function freeze(value: unknown): void { + if (value && typeof value === 'object') { + Object.values(value).forEach(freeze) + Object.freeze(value) + } +} + +describe('streaming caret', () => { + it.each(['Hello.', '> Hello **world**'])('preserves the input when rendering %s repeatedly', async (source) => { + const document = await parseMarkdown(source) + const original = structuredClone(document) + freeze(document) + + for (let i = 0; i < 3; i++) { + const html = await renderToString( + createSSRApp(() => h(MarkdownDocument, { value: document, streaming: true, caret: { class: 'test-caret' } })) + ) + expect(html.match(/class="test-caret"/g)).toHaveLength(1) + expect(document).toEqual(original) + } + expect( + await renderToString(createSSRApp(() => h(MarkdownDocument, { value: document, caret: { class: 'test-caret' } }))) + ).not.toContain('test-caret') + }) + + it.each(['![image](/image.png)', 'plain text', ''])( + 'appends a caret after unwrapped content: %s', + async (source) => { + const document = await parseMarkdown(source, { unwrap: true }) + const original = structuredClone(document) + freeze(document) + const html = await renderToString( + createSSRApp(() => h(MarkdownDocument, { value: document, streaming: true, caret: { class: 'test-caret' } })) + ) + + expect(html.match(/class="test-caret"/g)).toHaveLength(1) + expect(document).toEqual(original) + } + ) + + it('leaves the caret out when streaming is disabled', async () => { + const document = await parseMarkdown('Hello.') + const original = structuredClone(document) + freeze(document) + const html = await renderToString( + createSSRApp(() => h(MarkdownDocument, { value: document, caret: { class: 'test-caret' } })) + ) + + expect(html).not.toContain('test-caret') + expect(document).toEqual(original) + }) + + it('does not add carets to documents reused by the streaming parser', async () => { + const parse = createMarkdownParser() + for (const source of ['First\n\nTail', 'First\n\nTail grows', 'First\n\nTail grows again']) { + const document = await parse(source, { streaming: true }) + const original = structuredClone(document) + const html = await renderToString( + createSSRApp(() => h(MarkdownDocument, { value: document, streaming: true, caret: { class: 'test-caret' } })) + ) + expect(html.match(/class="test-caret"/g)).toHaveLength(1) + expect(document).toEqual(original) + } + }) + + it('leaves an empty document empty', async () => { + const document = await parseMarkdown('') + expect( + await renderToString( + createSSRApp(() => h(MarkdownDocument, { value: document, streaming: true, caret: { class: 'test-caret' } })) + ) + ).not.toContain('test-caret') + }) +}) From 11d4a47c6529ef3a8934d362b52d3ae2548cba91 Mon Sep 17 00:00:00 2001 From: onmax Date: Thu, 5 Nov 2026 16:43:26 +0100 Subject: [PATCH 2/2] test: update caret renderer package sizes --- test/bundle.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 60b2c1f2b..22ee54e41 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -64,9 +64,9 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/ansi": "39.0k (105 files)", "@comark/html": "17.3k (65 files)", "@comark/nuxt": "13.5k (65 files)", - "@comark/react": "42.9k (83 files)", + "@comark/react": "43.0k (83 files)", "@comark/svelte": "50.3k (91 files)", - "@comark/vue": "60.2k (87 files)", + "@comark/vue": "60.4k (87 files)", "comark": "422k (167 files)", } `)