Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.
TypeScript adeagent-ideai-agentsautomationbotclaude-codecodexghosttygrok-bothermes-agentmobile-appmuseopenclawopencodeorchestrationpiruntimeterminalworktreesyc-backed
fix(mobile): preserve code, quotes and code blocks through rich Markdown edits (#35056)
OrcaWine988b5dd77f0
diff --git a/config/scripts/mobile-web-app/mobile-web-app-code-block-selection.mjs b/config/scripts/mobile-web-app/mobile-web-app-code-block-selection.mjsnew file mode 100644index 00000000000..db51faf8b06--- /dev/null+++ b/config/scripts/mobile-web-app/mobile-web-app-code-block-selection.mjs@@ -0,0 +1,196 @@+import { expect, it } from 'vitest'++// WebKit can report a Mac user agent while running on Linux.+const historyModifier = process.platform === 'darwin' ? 'Meta' : 'Control'++async function verifyCodeBlockSelections({+ browser,+ openPage,+ setContent,+ select,+ press,+ readSurface+}) {+ const cases = [+ { markdown: 'selected text', html: '<p>selected text</p>', literal: 'selected text' },+ { markdown: 'first\nsecond', html: '<p>first<br>second</p>', literal: 'first\nsecond' },+ {+ markdown: 'first\n\nsecond',+ html: '<p>first</p>\n<p>second</p>',+ literal: 'first\nsecond'+ },+ {+ markdown: '**bold** and *italic*',+ html: '<p><strong>bold</strong> and <em>italic</em></p>',+ literal: 'bold and italic'+ },+ {+ markdown: '```ts\nfirst\nsecond\n```',+ html: '<pre data-language="ts"><code>first\nsecond</code></pre>',+ literal: 'first\nsecond',+ language: 'ts'+ },+ {+ markdown: 'Prefix first\n\nMiddle text\n\nlast suffix',+ html: '<p>Prefix first</p>\n<p>Middle text</p>\n<p>last suffix</p>',+ literal: 'Prefix first\nMiddle text\nlast suffix',+ partial: true+ },+ {+ markdown: 'Before\n\nAfter',+ html: '<p>Before</p>\n<p>After</p>',+ literal: 'code',+ collapsed: true,+ saved: 'Before\n\n```\ncode\n```\n\nAfter'+ },+ {+ markdown: 'Before\n\nSelected text\n\n- after',+ html: '<p>Before</p>\n<p>Selected text</p>\n<ul><li><p>after</p></li></ul>',+ literal: 'Selected text',+ paragraph: true,+ saved: 'Before\n\n```\nSelected text\n```\n\n- after'+ }+ ]+ for (const sample of cases) {+ const { page, consoleErrors } = await openPage(browser)+ try {+ await setContent(page, sample.markdown, sample.html)+ await (sample.partial || sample.collapsed || sample.paragraph+ ? page.evaluate(+ ({ partial, paragraph }) => {+ const editor = document.querySelector('#first-surface #editor')+ const paragraphs = editor.querySelectorAll('p')+ editor.focus()+ const range = document.createRange()+ if (partial) {+ range.setStart(paragraphs[0].firstChild, 7)+ range.setEnd(paragraphs[2].firstChild, 4)+ } else if (paragraph) {+ range.selectNodeContents(paragraphs[1])+ } else {+ range.setStart(paragraphs[1].firstChild, 0)+ range.collapse(true)+ }+ window.getSelection().removeAllRanges()+ window.getSelection().addRange(range)+ },+ { partial: sample.partial === true, paragraph: sample.paragraph === true }+ )+ : select(page, 'all'))+ const selected = await page.evaluate(() => window.getSelection().toString())+ await press(page, 'Code block')+ const saved = sample.saved ?? `\`\`\`${sample.language ?? ''}\n${sample.literal}\n\`\`\``+ await expect+ .poll(() => page.evaluate(() => globalThis.__orcaEditor.changes.at(-1)))+ .toBe(saved)+ await page.keyboard.press(`${historyModifier}+z`)+ await expect.poll(() => readSurface(page)).toBe(sample.html)+ expect(await page.evaluate(() => window.getSelection().toString())).toBe(selected)+ await page.keyboard.press(`${historyModifier}+Shift+z`)+ await expect+ .poll(() => page.evaluate(() => globalThis.__orcaEditor.changes.at(-1)))+ .toBe(saved)+ await page.evaluate(+ (content) => globalThis.__orcaEditor.set({ content, generation: 1 }),+ saved+ )+ await expect+ .poll(() => page.locator('#first-surface #editor pre code').textContent())+ .toBe(sample.literal)+ expect(await page.evaluate(() => globalThis.__orcaCspViolations)).toEqual([])+ expect(consoleErrors).toEqual([])+ } finally {+ await page.close()+ }+ }+}++async function verifyStructuredSelections({+ browser,+ openPage,+ setContent,+ select,+ press,+ readSurface+}) {+ const samples = [+ { markdown: 'Before\n\n- first\n- second\n - nested\n\nAfter', selector: 'ul' },+ { markdown: '| one | two |\n| --- | --- |\n| a | b |', selector: 'table' },+ {+ markdown: 'left  right',+ html: '<p>left <img src="/inserted.png" alt="pixel"> right</p>'+ }+ ]+ for (const sample of samples) {+ const { page, consoleErrors } = await openPage(browser)+ try {+ if (sample.html) {+ await setContent(page, sample.markdown, sample.html)+ } else {+ await page.evaluate((content) => globalThis.__orcaEditor.set({ content }), sample.markdown)+ await page.waitForSelector(`#first-surface #editor ${sample.selector}`)+ }+ await select(page, 'all')+ const before = await readSurface(page)+ const selected = await page.evaluate(() => window.getSelection().toString())+ await page.evaluate(() => {+ globalThis.__orcaEditor.changes.length = 0+ })+ await press(page, 'Code block')+ expect(await readSurface(page)).toBe(before)+ expect(await page.evaluate(() => window.getSelection().toString())).toBe(selected)+ expect(await page.evaluate(() => globalThis.__orcaEditor.changes)).toEqual([])+ expect(await page.evaluate(() => globalThis.__orcaCspViolations)).toEqual([])+ expect(consoleErrors).toEqual([])+ } finally {+ await page.close()+ }+ }+}++export function codeBlockSelectionTest(+ getBrowser,+ openPage,+ setContent,+ select,+ press,+ readSurface+) {+ it(+ 'preserves selected text through code-block formatting, undo and reload',+ () =>+ verifyCodeBlockSelections({+ browser: getBrowser(),+ openPage,+ setContent,+ select,+ press,+ readSurface+ }),+ 600_000+ )+ structuredCodeBlockSelectionTest(getBrowser, openPage, setContent, select, press, readSurface)+}++function structuredCodeBlockSelectionTest(+ getBrowser,+ openPage,+ setContent,+ select,+ press,+ readSurface+) {+ it(+ 'leaves structured selections unchanged instead of formatting them as code',+ () =>+ verifyStructuredSelections({+ browser: getBrowser(),+ openPage,+ setContent,+ select,+ press,+ readSurface+ }),+ 600_000+ )+}diff --git a/config/scripts/mobile-web-app/mobile-web-app-rich-markdown-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-rich-markdown-render.test.mjsindex c34270e1f1d..867e60823f7 100644--- a/config/scripts/mobile-web-app/mobile-web-app-rich-markdown-render.test.mjs+++ b/config/scripts/mobile-web-app/mobile-web-app-rich-markdown-render.test.mjs@@ -1,6 +1,7 @@// Exercise real editor in Chromium/WebKit under shipped CSP: toolbar effects, private ready/change seam, listener/style cleanup, font floor and URL modal.// Native WebView postMessage/injectJavaScript are replaced by direct module calls; execCommand behavior requires real engines.import { Buffer } from 'node:buffer'+import { codeBlockSelectionTest } from './mobile-web-app-code-block-selection.mjs'import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'import { join } from 'node:path'import { fileURLToPath } from 'node:url'@@ -314,9 +315,7 @@ async function select(page, how) {}, how)}-async function press(page, label) {- await page.locator(`[aria-label="${label}"]`).click()-}+const press = (page, label) => page.locator(`[aria-label="${label}"]`).click()describeEditor('the rich Markdown editor on the page',@@ -554,6 +553,8 @@ describeEditor(}}, 600_000)+ codeBlockSelectionTest(() => browser, openPage, setContent, select, press, readSurface)+it('opens a link through the host rather than navigating the page', async () => {const { page } = await openPage(browser)try {diff --git a/mobile/src/components/rich-markdown/editor-commands.ts b/mobile/src/components/rich-markdown/editor-commands.tsindex 2c80b5a2008..bc5eacaab71 100644--- a/mobile/src/components/rich-markdown/editor-commands.ts+++ b/mobile/src/components/rich-markdown/editor-commands.ts@@ -31,6 +31,19 @@ function acceptsCommands(scope: RichMarkdownEditorScope, generation: number): bo)}+function canFormatCodeBlock(scope: RichMarkdownEditorScope): boolean {+ const selection = scope.getSelection()+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {+ return true+ }+ const range = selection.getRangeAt(0)+ return !Array.from(+ editorElement(scope).querySelectorAll(+ 'blockquote,ul,ol,table,img,input,hr,[contenteditable="false"]'+ )+ ).some((node) => range.intersectsNode(node.closest('p,h1,h2,h3,h4,h5,h6,pre') ?? node))+}+// Link/Image await page URL modal; while waiting host may replace/lock/stop document, so capture generation and revalidate after answer.// Save caret before modal takes focus and restore after; execCommand without selection inserts nothing. Reading generation here equals runCommand’s read because no yield intervenes.async function insertUrl(@@ -64,7 +77,13 @@ const COMMANDS: Record<taskList: (scope) => exec(scope, 'insertHTML', TASK_LIST_HTML),quote: (scope) => exec(scope, 'formatBlock', 'blockquote'),inlineCode: (scope) => wrapSelection(scope, 'code'),- codeBlock: (scope) => exec(scope, 'insertHTML', CODE_BLOCK_HTML),+ codeBlock: (scope) => {+ if (scope.getSelection()?.isCollapsed === false) {+ exec(scope, 'formatBlock', 'pre')+ } else {+ exec(scope, 'insertHTML', CODE_BLOCK_HTML)+ }+ },link: (scope) => insertUrl(scope, 'link', 'createLink'),image: (scope) => insertUrl(scope, 'image', 'insertImage')}@@ -79,6 +98,9 @@ export async function runCommand(return}restoreSelectionOrEnd(scope)+ if (command === 'codeBlock' && !canFormatCodeBlock(scope)) {+ return+ }const pending = COMMANDS[command]?.(scope)if (pending) {await pendingdiff --git a/mobile/src/components/rich-markdown/html-block-markdown.ts b/mobile/src/components/rich-markdown/html-block-markdown.tsindex a66e0b54857..d668e17f73e 100644--- a/mobile/src/components/rich-markdown/html-block-markdown.ts+++ b/mobile/src/components/rich-markdown/html-block-markdown.ts@@ -1,40 +1,144 @@import { codeFenceFor } from './markdown-code-fence'import { escapeTableCell } from './markdown-table-rows'-import { inlineChildren, inlineMarkdown, textContent } from './html-inline-markdown'+import {+ inlineChildren,+ inlineMarkdown,+ inlineNodesMarkdown,+ textContent+} from './html-inline-markdown'import { holdsUnownedList, listMarkdown } from './html-list-markdown'+function* paragraphCodeNodes(element: Element): Generator<Node | null> {+ const pending: (Node | null)[] = []+ const pushChildren = (parent: Node) => {+ for (let index = parent.childNodes.length - 1; index >= 0; index -= 1) {+ const child = parent.childNodes.item(index)+ if (child) {+ pending.push(child)+ }+ }+ }+ pushChildren(element)+ while (pending.length) {+ const node = pending.pop() ?? null+ if (node instanceof Element && /^(p|div)$/i.test(node.tagName)) {+ yield null+ pending.push(null)+ pushChildren(node)+ } else {+ yield node+ }+ }+}++function hasParagraphCodeBlock(element: Element): boolean {+ for (const node of paragraphCodeNodes(element)) {+ if (node instanceof Element && node.tagName.toLowerCase() === 'pre') {+ return true+ }+ }+ return false+}+// WebKit 26.4/Chromium 147 insertUnorderedList nests ul inside p; serialize surrounding inline runs and list as separate blocks or typed list markers vanish. Leave DOM unchanged.-function blocksAroundLists(element: Element): string {+function blocksAroundLists(element: Element, preserveCode = false): string {const blocks: string[] = []- let inline = ''+ let inline: Node[] = []const flushInline = () => {- if (inline.trim()) {- blocks.push(inline.trim())+ const markdown = inlineNodesMarkdown(inline).trim()+ if (markdown) {+ blocks.push(markdown)}- inline = ''+ inline = []}- for (const child of Array.from(element.childNodes)) {+ const containsLists = !preserveCode || holdsUnownedList(element)+ const nodes = preserveCode ? paragraphCodeNodes(element) : Array.from(element.childNodes)+ for (const child of nodes) {+ if (child === null) {+ flushInline()+ continue+ }if (!(child instanceof Element)) {- inline += inlineMarkdown(child)+ inline.push(child)continue}const tag = child.tagName.toLowerCase()+ if (preserveCode && tag === 'pre') {+ flushInline()+ blocks.push(blockMarkdown(child))+ continue+ }if (tag === 'ul' || tag === 'ol') {flushInline()blocks.push(listMarkdown(child, 0))continue}- if (holdsUnownedList(child)) {+ if (containsLists && holdsUnownedList(child)) {flushInline()blocks.push(blocksAroundLists(child))continue}- inline += inlineMarkdown(child)+ inline.push(child)}flushInline()return blocks.filter(Boolean).join('\n\n')}+function quoteMarkdown(element: Element): string {+ const blocks: string[] = []+ let inline: Node[] = []+ const flushInline = () => {+ const markdown = inlineNodesMarkdown(inline).trim()+ if (markdown) {+ blocks.push(markdown)+ }+ inline = []+ }+ for (const child of element.childNodes) {+ if (+ child instanceof Element &&+ /^(p|div|h[1-6]|blockquote|pre|ul|ol|table|hr)$/.test(child.tagName.toLowerCase())+ ) {+ flushInline()+ const markdown = blockMarkdown(child)+ if (markdown.trim()) {+ blocks.push(markdown)+ }+ } else {+ inline.push(child)+ }+ }+ flushInline()+ return blocks+ .join('\n\n')+ .split('\n')+ .map((line) => `> ${line}`)+ .join('\n')+}++function headingCodeMarkdown(element: Element): string {+ const prefix = '#'.repeat(Number(element.tagName.slice(1)))+ const blocks: string[] = []+ let inline: Node[] = []+ const flushInline = () => {+ const markdown = inlineNodesMarkdown(inline).trim()+ if (markdown) {+ blocks.push(`${prefix} ${markdown}`)+ }+ inline = []+ }+ for (const child of Array.from(element.childNodes)) {+ if (child instanceof Element && child.tagName.toLowerCase() === 'pre') {+ flushInline()+ blocks.push(blockMarkdown(child))+ } else {+ inline.push(child)+ }+ }+ flushInline()+ return blocks.join('\n\n')+}+// Unknown block elements serialize inline content so browser-created tags cannot lose user text.export function blockMarkdown(node: Node): string {if (node.nodeType === Node.TEXT_NODE) {@@ -45,21 +149,24 @@ export function blockMarkdown(node: Node): string {}const tag = node.tagName.toLowerCase()if (/^h[1-6]$/.test(tag)) {+ if (Array.from(node.children).some((child) => child.tagName.toLowerCase() === 'pre')) {+ return headingCodeMarkdown(node)+ }return `${'#'.repeat(Number(tag.slice(1)))} ${inlineChildren(node).trim()}`}if (tag === 'p' || tag === 'div') {+ if (node.querySelector('pre') && hasParagraphCodeBlock(node)) {+ return blocksAroundLists(node, true)+ }return holdsUnownedList(node) ? blocksAroundLists(node) : inlineChildren(node).trim()}if (tag === 'blockquote') {- return inlineChildren(node)- .trim()- .split('\n')- .map((line) => `> ${line}`)- .join('\n')+ return quoteMarkdown(node)}if (tag === 'pre') {const language = node.getAttribute('data-language') ?? ''- const code = textContent(node.querySelector('code') ?? node).replace(/\n+$/g, '')+ // Drop trailing newlines: browsers leave a placeholder <br> after Enter at the end of a block.+ const code = textContent(node).replace(/\n+$/, '')const fence = codeFenceFor(code)return `${fence}${language}\n${code}\n${fence}`}diff --git a/mobile/src/components/rich-markdown/html-inline-markdown.ts b/mobile/src/components/rich-markdown/html-inline-markdown.tsindex 26509323e54..cc99828ff0d 100644--- a/mobile/src/components/rich-markdown/html-inline-markdown.ts+++ b/mobile/src/components/rich-markdown/html-inline-markdown.ts@@ -1,6 +1,49 @@-/** A node's text with non-breaking spaces turned back into the spaces the source wrote. */+import { codeFenceFor } from './markdown-code-fence'++function renderedText(node: Node): string {+ if (node.nodeType === Node.COMMENT_NODE) {+ return ''+ }+ if (node instanceof Element) {+ if (node.tagName.toLowerCase() === 'br') {+ return '\n'+ }+ return Array.from(node.childNodes).map(renderedText).join('')+ }+ return node.textContent ?? ''+}++// A code span cannot hold a line break (readers turn it into a space), and a raw newline would end a table row or heading.+function inlineCodeText(node: Node): string {+ return textContent(node).replace(/\n/g, ' ')+}++/** A node's text with line breaks kept and browser-created non-breaking spaces turned back into spaces. */export function textContent(node: Node): string {- return (node.textContent ?? '').replace(/ /g, ' ')+ return renderedText(node).replace(/ /g, ' ')+}++function codeMarkdown(code: string): string {+ if (!code) {+ return ''+ }+ const delimiter = codeFenceFor(code, 1)+ const padding =+ code.startsWith('`') ||+ code.endsWith('`') ||+ (code.startsWith(' ') && code.endsWith(' ') && /[^ ]/.test(code))+ ? ' '+ : ''+ return `${delimiter}${padding}${code}${padding}${delimiter}`+}++function isInlineCode(node: Node): boolean {+ return (+ node instanceof Element &&+ node.tagName.toLowerCase() === 'code' &&+ node.parentElement !== null &&+ node.parentElement.tagName.toLowerCase() !== 'pre'+ )}// Serialize task label as empty: checkbox chrome is replaced by list writer’s Markdown marker.@@ -27,8 +70,8 @@ export function inlineMarkdown(node: Node | null | undefined): string {if (tag === 's' || tag === 'del' || tag === 'strike') {return `~~${inlineChildren(node)}~~`}- if (tag === 'code' && node.parentElement && node.parentElement.tagName.toLowerCase() !== 'pre') {- return `\`${textContent(node)}\``+ if (isInlineCode(node)) {+ return codeMarkdown(inlineCodeText(node))}if (tag === 'a') {return `[${inlineChildren(node)}](${node.getAttribute('href') ?? ''})`@@ -43,7 +86,29 @@ export function inlineMarkdown(node: Node | null | undefined): string {}export function inlineChildren(element: Element): string {- return Array.from(element.childNodes)- .map((child) => inlineMarkdown(child))- .join('')+ return inlineNodesMarkdown(element.childNodes)+}++export function inlineNodesMarkdown(nodes: Iterable<Node>): string {+ const parts: string[] = []+ let code = ''+ for (const child of nodes) {+ if (isInlineCode(child)) {+ code += inlineCodeText(child)+ continue+ }+ const markdown = inlineMarkdown(child)+ if (!markdown) {+ continue+ }+ if (code) {+ parts.push(codeMarkdown(code))+ code = ''+ }+ parts.push(markdown)+ }+ if (code) {+ parts.push(codeMarkdown(code))+ }+ return parts.join('')}diff --git a/mobile/src/components/rich-markdown/markdown-code-block-dom.test.ts b/mobile/src/components/rich-markdown/markdown-code-block-dom.test.tsnew file mode 100644index 00000000000..dfe13edc950--- /dev/null+++ b/mobile/src/components/rich-markdown/markdown-code-block-dom.test.ts@@ -0,0 +1,39 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest'+import { createRichMarkdownEditorDocument } from './create-rich-markdown-editor-document'+import { RICH_MARKDOWN_EDITOR_MARKUP } from './document-markup'+import { quietRichMarkdownEditorHost } from './rich-markdown-editor-host.test-support'+import type { MobileRichMarkdownEditorMessage } from '../mobile-rich-markdown-editor-contract'++const stopDocuments: (() => void)[] = []++afterEach(() => {+ stopDocuments.splice(0).forEach((stop) => stop())+ document.body.innerHTML = ''+})++it.each([+ ['first<br>second', 'first\nsecond'],+ ['<code>first</code><br><br><code>second</code>', 'first\n\nsecond'],+ ['prefix <code>middle</code> suffix', 'prefix middle suffix'],+ ['<code>last line</code><br><br>', 'last line']+])('saves native code-block markup %j through input and reload', (html, literal) => {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editor = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editor.stop)+ editor.send.setMarkdown('```ts\nplaceholder\n```', 7)+ const surface = document.getElementById('editor')!+ surface.querySelector('pre')!.innerHTML = html+ surface.dispatchEvent(new Event('input', { bubbles: true }))+ const saved = `\`\`\`ts\n${literal}\n\`\`\``+ expect(messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown: saved }+ ])+ editor.send.setMarkdown(saved, 8)+ expect(surface.querySelector('pre code')?.textContent).toBe(literal)+ expect(editor.send.currentMarkdown()).toBe(saved)+})diff --git a/mobile/src/components/rich-markdown/markdown-code-delimiters.test.ts b/mobile/src/components/rich-markdown/markdown-code-delimiters.test.tsnew file mode 100644index 00000000000..f272b6656b0--- /dev/null+++ b/mobile/src/components/rich-markdown/markdown-code-delimiters.test.ts@@ -0,0 +1,69 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest'+import { createRichMarkdownEditorDocument } from './create-rich-markdown-editor-document'+import { RICH_MARKDOWN_EDITOR_MARKUP } from './document-markup'+import { quietRichMarkdownEditorHost } from './rich-markdown-editor-host.test-support'+import type { MobileRichMarkdownEditorMessage } from '../mobile-rich-markdown-editor-contract'++const stopDocuments: (() => void)[] = []++afterEach(() => {+ stopDocuments.splice(0).forEach((stop) => stop())+ window.getSelection()?.removeAllRanges()+ document.body.innerHTML = ''+})++function mount() {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editorDocument = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editorDocument.stop)+ const surface = document.getElementById('editor')!+ return { surface, messages, send: editorDocument.send }+}++it.each([+ ['a`b', '``a`b``'],+ ['a``b', '```a``b```'],+ ['`edge', '`` `edge ``'],+ ['edge`', '`` edge` ``'],+ ['`', '`` ` ``'],+ [' surrounded ', '` surrounded `'],+ [' ', '` `']+])('preserves selected inline code %j through the host and a reload', async (literal, saved) => {+ const editor = mount()+ editor.send.setMarkdown('placeholder', 7)+ const paragraph = editor.surface.querySelector('p')!+ paragraph.textContent = literal+ const range = document.createRange()+ range.selectNodeContents(paragraph)+ const selection = window.getSelection()!+ selection.removeAllRanges()+ selection.addRange(range)+ await editor.send.runCommand('inlineCode')+ expect(editor.surface.querySelector('code')?.textContent).toBe(literal)+ expect(editor.messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown: saved }+ ])+ editor.send.setMarkdown(saved, 8)+ expect(editor.surface.querySelector('p')?.textContent).toBe(literal)+ expect(+ Array.from(editor.surface.querySelectorAll('code')).map((code) => code.textContent)+ ).toEqual([literal])+ expect(editor.send.currentMarkdown()).toBe(saved)+})++it('matches whole delimiter runs and leaves unmatched runs as prose', () => {+ const editor = mount()+ const markdown = 'Use ``a```b`` and `plain` and unmatched ``` tail'+ editor.send.setMarkdown(markdown, 1)+ expect(+ Array.from(editor.surface.querySelectorAll('code')).map((code) => code.textContent)+ ).toEqual(['a```b', 'plain'])+ expect(editor.surface.querySelector('p')?.textContent).toBe(+ 'Use a```b and plain and unmatched ``` tail'+ )+})diff --git a/mobile/src/components/rich-markdown/markdown-code-fence.ts b/mobile/src/components/rich-markdown/markdown-code-fence.tsindex f80de22b461..428bef96646 100644--- a/mobile/src/components/rich-markdown/markdown-code-fence.ts+++ b/mobile/src/components/rich-markdown/markdown-code-fence.ts@@ -1,7 +1,7 @@// Choose fence longer than every contained backtick run; fixed triple fence would turn inner code into paragraphs. Reader preserves chosen opening width.-/** Longer than the longest backtick run inside, and never under three. */-export function codeFenceFor(code: string): string {+/** Longer than the longest backtick run inside, with the minimum chosen by block or inline syntax. */+export function codeFenceFor(code: string, minimumLength = 3): string {let longest = 0let longRun: RegExp | undefinedlet start = code.indexOf('`')@@ -17,7 +17,7 @@ export function codeFenceFor(code: string): string {longest = Math.max(longest, end - start)start = code.indexOf('`', end)}- return '`'.repeat(Math.max(3, longest + 1))+ return '`'.repeat(Math.max(minimumLength, longest + 1))}/** The run a line opens a block with, and the language it names, or null when it opens none. */diff --git a/mobile/src/components/rich-markdown/markdown-code-literals.test.ts b/mobile/src/components/rich-markdown/markdown-code-literals.test.tsnew file mode 100644index 00000000000..f5246b99779--- /dev/null+++ b/mobile/src/components/rich-markdown/markdown-code-literals.test.ts@@ -0,0 +1,110 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest'+import { createRichMarkdownEditorDocument } from './create-rich-markdown-editor-document'+import { RICH_MARKDOWN_EDITOR_MARKUP } from './document-markup'+import { quietRichMarkdownEditorHost } from './rich-markdown-editor-host.test-support'+import type { MobileRichMarkdownEditorMessage } from '../mobile-rich-markdown-editor-contract'++const stopDocuments: (() => void)[] = []++afterEach(() => {+ stopDocuments.splice(0).forEach((stop) => stop())+ document.body.innerHTML = ''+})++it.each([+ [+ 'fenced entities',+ '```html\n<span>& & <tag></span>\n```',+ '<span>& & <tag></span>'+ ],+ ['inline entities', 'Literal `& & <tag>` sample.', '& & <tag>']+])('preserves %s while editing a different paragraph', (_name, codeMarkdown, codeText) => {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editorDocument = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editorDocument.stop)+ const original = `${codeMarkdown}\n\nUnrelated paragraph`+ editorDocument.send.setMarkdown(original, 7)+ const surface = document.getElementById('editor')!+ expect(surface.querySelector('code')?.textContent).toBe(codeText)+ expect(editorDocument.send.currentMarkdown()).toBe(original)++ surface.lastElementChild!.append('!')+ surface.dispatchEvent(+ new InputEvent('input', { bubbles: true, inputType: 'insertText', data: '!' })+ )++ expect(messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown: `${original}!` }+ ])+})++it('preserves text after formatting the gap between inline code spans', async () => {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editorDocument = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editorDocument.stop)+ editorDocument.send.setMarkdown('`old` middle `tail`', 7)+ const paragraph = document.querySelector('#editor p')!+ const range = document.createRange()+ range.selectNodeContents(paragraph.childNodes[1])+ window.getSelection()!.removeAllRanges()+ window.getSelection()!.addRange(range)++ await editorDocument.send.runCommand('inlineCode')++ expect(editorDocument.send.currentMarkdown()).toBe('`old middle tail`')+ expect(messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown: '`old middle tail`' }+ ])+ editorDocument.send.setMarkdown(editorDocument.send.currentMarkdown(), 8)+ expect(document.querySelector('#editor code')?.textContent).toBe('old middle tail')+})++it.each([+ ['<code>a`</code><code>``b</code>', '````a```b````', 'a```b'],+ ['<code> left</code><code>right </code>', '` leftright `', ' leftright ']+])('preserves adjacent literal code through save and reopen: %s', (html, markdown, text) => {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const editorDocument = createRichMarkdownEditorDocument(quietRichMarkdownEditorHost())+ stopDocuments.push(editorDocument.stop)+ const surface = document.getElementById('editor')!+ surface.innerHTML = `<p>${html}</p>`++ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+ editorDocument.send.setMarkdown(markdown, 8)+ expect(surface.querySelector('code')?.textContent).toBe(text)+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})++it.each([+ ['heading', '<h2><code>a</code><code>b</code><pre>x</pre></h2>', '## `ab`\n\n```\nx\n```'],+ ['paragraph', '<p><code>a</code><code>b</code><pre>x</pre></p>', '`ab`\n\n```\nx\n```']+])('joins adjacent inline code beside a %s-owned code block', (_name, html, markdown) => {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const editorDocument = createRichMarkdownEditorDocument(quietRichMarkdownEditorHost())+ stopDocuments.push(editorDocument.stop)+ document.getElementById('editor')!.innerHTML = html++ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})++it.each([+ ['inline code', '<p><code>x\u00a0 z\u00a0</code> after</p>', '`x z ` after'],+ ['an inline code line break', '<p><code>first<br>second</code></p>', '`first second`'],+ ['a code block', '<pre><code>\u00a0 \u00a0if x:</code></pre>', '```\n if x:\n```']+])('saves browser-created spacing in %s as ordinary spaces', (_name, html, markdown) => {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const editorDocument = createRichMarkdownEditorDocument(quietRichMarkdownEditorHost())+ stopDocuments.push(editorDocument.stop)+ document.getElementById('editor')!.innerHTML = html++ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})diff --git a/mobile/src/components/rich-markdown/markdown-escaping.ts b/mobile/src/components/rich-markdown/markdown-escaping.tsindex 7c25e5718ec..831a641159c 100644--- a/mobile/src/components/rich-markdown/markdown-escaping.ts+++ b/mobile/src/components/rich-markdown/markdown-escaping.ts@@ -40,8 +40,12 @@ export function decodeMarkdownEntities(value: string): string {})}+export function escapeLiteralHtml(value: string): string {+ return value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char)+}+export function escapeHtml(value: string): string {- return decodeMarkdownEntities(value).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char)+ return escapeLiteralHtml(decodeMarkdownEntities(value))}/** An attribute value cannot carry a newline, which would end it in the markup being built. */diff --git a/mobile/src/components/rich-markdown/markdown-heading-code-blocks.test.ts b/mobile/src/components/rich-markdown/markdown-heading-code-blocks.test.tsnew file mode 100644index 00000000000..9cfde94a5b1--- /dev/null+++ b/mobile/src/components/rich-markdown/markdown-heading-code-blocks.test.ts@@ -0,0 +1,84 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest'+import { createRichMarkdownEditorDocument } from './create-rich-markdown-editor-document'+import { RICH_MARKDOWN_EDITOR_MARKUP } from './document-markup'+import { quietRichMarkdownEditorHost } from './rich-markdown-editor-host.test-support'+import type { MobileRichMarkdownEditorMessage } from '../mobile-rich-markdown-editor-contract'++const stopDocuments: (() => void)[] = []++afterEach(() => {+ stopDocuments.splice(0).forEach((stop) => stop())+ document.body.innerHTML = ''+})++function codeBlock(text: string, language = '') {+ const pre = document.createElement('pre')+ pre.setAttribute('data-language', language)+ pre.append(text)+ return pre+}++function saveHeading(heading: Element, markdown: string, codes: string[]) {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editorDocument = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editorDocument.stop)+ editorDocument.send.setMarkdown('seed', 7)+ const surface = document.getElementById('editor')+ if (!surface) {+ throw new Error('Missing editor')+ }+ surface.replaceChildren(heading)+ surface.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }))+ expect(messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown }+ ])+ editorDocument.send.setMarkdown(markdown, 8)+ expect(Array.from(surface.querySelectorAll('pre')).map((node) => node.textContent)).toEqual(codes)+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+ return surface+}++it('retains selected code and trailing heading text', () => {+ const heading = document.createElement('h3')+ heading.append(codeBlock('First'), 'Second')++ const surface = saveHeading(heading, '```\nFirst\n```\n\n### Second', ['First'])+ expect(surface.querySelector('h3')?.textContent).toBe('Second')+})++it('keeps inline marks and text between multiple direct code blocks', () => {+ const heading = document.createElement('h2')+ const before = document.createElement('strong')+ before.append('Before')+ const middle = document.createElement('span')+ middle.append('middle ')+ heading.append(before, codeBlock('One'), 'Split ', middle, 'text', codeBlock('Two'))++ const surface = saveHeading(+ heading,+ '## **Before**\n\n```\nOne\n```\n\n## Split middle text\n\n```\nTwo\n```',+ ['One', 'Two']+ )+ expect(Array.from(surface.querySelectorAll('h2')).map((node) => node.textContent)).toEqual([+ 'Before',+ 'Split middle text'+ ])+ expect(surface.querySelector('h2 strong')?.textContent).toBe('Before')+})++it('keeps code-only headings literal without creating an empty heading', () => {+ const heading = document.createElement('h3')+ heading.append(codeBlock(' one\u00a0&\n```\n', 'ts'), codeBlock(''))++ const surface = saveHeading(heading, '````ts\n one &\n```\n````\n\n```\n\n```', [+ ' one &\n```',+ ''+ ])+ expect(surface.querySelectorAll('h1,h2,h3,h4,h5,h6').length).toBe(0)+ expect(surface.querySelector('pre')?.getAttribute('data-language')).toBe('ts')+})diff --git a/mobile/src/components/rich-markdown/markdown-inline-render.ts b/mobile/src/components/rich-markdown/markdown-inline-render.tsindex 38dfdd5feda..9cccdcdcd30 100644--- a/mobile/src/components/rich-markdown/markdown-inline-render.ts+++ b/mobile/src/components/rich-markdown/markdown-inline-render.ts@@ -1,9 +1,14 @@-import { escapeAttr, escapeHtml, isSafeUrl } from './markdown-escaping'+import {+ createRawMarkdownCodeSpanScanner,+ type MarkdownCodeSpanScanner+} from '../../../../src/shared/markdown-code-span-runs'+import { escapeAttr, escapeHtml, escapeLiteralHtml, isSafeUrl } from './markdown-escaping'// Build global exec regex per recursive call: shared lastIndex would leak between nested parses. Escape text between recognized inline forms.export function renderInline(text: string): string {const pattern =- /(!\[[^\]]*\]\([^)]+\)|`[^`]+`|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\n]+\*|_[^_\n]+_|\[[^\]]+\]\([^)]+\)|https?:\/\/[^\s<]+)/g+ /(!\[[^\]]*\]\([^)]+\)|`+|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\n]+\*|_[^_\n]+_|\[[^\]]+\]\([^)]+\)|https?:\/\/[^\s<]+)/g+ let codeSpans: MarkdownCodeSpanScanner | undefinedlet output = ''let lastIndex = 0let match = pattern.exec(text)@@ -19,7 +24,18 @@ export function renderInline(text: string): string {} else if (/^https?:\/\//i.test(token)) {output += `<a href="${escapeAttr(token)}">${escapeHtml(token)}</a>`} else if (token.startsWith('`')) {- output += `<code>${escapeHtml(token.slice(1, -1))}</code>`+ codeSpans ??= createRawMarkdownCodeSpanScanner(text)+ const spanEnd = codeSpans.findSpanEnd(match.index)+ if (spanEnd === null) {+ output += escapeHtml(token)+ } else {+ let code = text.slice(pattern.lastIndex, spanEnd - token.length).replace(/\r\n?|\n/g, ' ')+ if (code.startsWith(' ') && code.endsWith(' ') && /[^ ]/.test(code)) {+ code = code.slice(1, -1)+ }+ output += `<code>${escapeLiteralHtml(code)}</code>`+ pattern.lastIndex = spanEnd+ }} else if (token.startsWith('~~')) {output += `<s>${renderInline(token.slice(2, -2))}</s>`} else if (token.startsWith('**') || token.startsWith('__')) {diff --git a/mobile/src/components/rich-markdown/markdown-paragraph-code-blocks.test.ts b/mobile/src/components/rich-markdown/markdown-paragraph-code-blocks.test.tsnew file mode 100644index 00000000000..ff79446fbc3--- /dev/null+++ b/mobile/src/components/rich-markdown/markdown-paragraph-code-blocks.test.ts@@ -0,0 +1,100 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest'+import { createRichMarkdownEditorDocument } from './create-rich-markdown-editor-document'+import { RICH_MARKDOWN_EDITOR_MARKUP } from './document-markup'+import { quietRichMarkdownEditorHost } from './rich-markdown-editor-host.test-support'+import type { MobileRichMarkdownEditorMessage } from '../mobile-rich-markdown-editor-contract'++const stopDocuments: (() => void)[] = []++afterEach(() => {+ stopDocuments.splice(0).forEach((stop) => stop())+ document.body.innerHTML = ''+})++function codeBlock(text: string, language = '') {+ const pre = document.createElement('pre')+ pre.setAttribute('data-language', language)+ pre.append(text)+ return pre+}++function expectRoundTrip(wrapper: Element, markdown: string, codes: string[]) {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editorDocument = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editorDocument.stop)+ editorDocument.send.setMarkdown('seed', 7)+ const editor = document.getElementById('editor')+ if (!editor) {+ throw new Error('Missing editor')+ }+ const outside = document.createElement('p')+ outside.append('Outside')+ editor.replaceChildren(wrapper, outside)+ const live = editor.innerHTML+ editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }))++ expect(editor.innerHTML).toBe(live)+ expect(messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown: `${markdown}\n\nOutside` }+ ])+ editorDocument.send.setMarkdown(`${markdown}\n\nOutside`, 8)+ expect(Array.from(editor.querySelectorAll('pre')).map((pre) => pre.textContent)).toEqual(codes)+ expect(editorDocument.send.currentMarkdown()).toBe(`${markdown}\n\nOutside`)+ return editor+}++it('retains native first-line PRE and trailing soft-line text without mutating the live paragraph', () => {+ const paragraph = document.createElement('p')+ paragraph.append(codeBlock('First'), 'Second', document.createElement('br'), 'Third')++ expectRoundTrip(paragraph, '```\nFirst\n```\n\nSecond\nThird', ['First'])+})++it('retains literal code and surrounding marked prose through transparent paragraph wrappers', () => {+ const wrapper = document.createElement('div')+ const before = document.createElement('p')+ before.innerHTML = '<strong>Before</strong>'+ const inner = document.createElement('div')+ const pre = document.createElement('pre')+ pre.setAttribute('data-language', 'ts')+ const code = document.createElement('code')+ code.append(' one\u00a0&\n```')+ pre.append(code, document.createElement('br'), 'Tail')+ inner.append(pre)+ const after = document.createElement('p')+ after.innerHTML = '<em>After</em>'+ wrapper.append(before, inner, after)++ expectRoundTrip(wrapper, '**Before**\n\n````ts\n one &\n```\nTail\n````\n\n*After*', [+ ' one &\n```\nTail'+ ])+})++it('keeps empty and multiple code blocks separate from intervening prose', () => {+ const wrapper = document.createElement('div')+ const paragraph = document.createElement('p')+ paragraph.append(codeBlock(''), 'Between', codeBlock('const x = 1', 'js'))+ wrapper.append(paragraph)++ expectRoundTrip(wrapper, '```\n\n```\n\nBetween\n\n```js\nconst x = 1\n```', ['', 'const x = 1'])+})++it('keeps unowned list blocks alongside wrapped PRE without changing list ownership', () => {+ const wrapper = document.createElement('div')+ const before = document.createElement('p')+ before.append('Before')+ const list = document.createElement('ul')+ list.innerHTML = '<li><p>Item</p></li>'+ const after = document.createElement('p')+ after.append('After')+ wrapper.append(before, codeBlock('First'), list, after)++ const editor = expectRoundTrip(wrapper, 'Before\n\n```\nFirst\n```\n\n- Item\n\nAfter', ['First'])+ expect(editor.querySelector('pre')?.closest('li')).toBe(null)+ expect(editor.querySelectorAll('li').length).toBe(1)+})diff --git a/mobile/src/components/rich-markdown/markdown-quote-blocks.test.ts b/mobile/src/components/rich-markdown/markdown-quote-blocks.test.tsnew file mode 100644index 00000000000..9241627292f--- /dev/null+++ b/mobile/src/components/rich-markdown/markdown-quote-blocks.test.ts@@ -0,0 +1,123 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest'+import { createRichMarkdownEditorDocument } from './create-rich-markdown-editor-document'+import { RICH_MARKDOWN_EDITOR_MARKUP } from './document-markup'+import { quietRichMarkdownEditorHost } from './rich-markdown-editor-host.test-support'+import type { MobileRichMarkdownEditorMessage } from '../mobile-rich-markdown-editor-contract'++const stopDocuments: (() => void)[] = []++afterEach(() => {+ stopDocuments.splice(0).forEach((stop) => stop())+ document.body.innerHTML = ''+})++function surface() {+ document.body.innerHTML = RICH_MARKDOWN_EDITOR_MARKUP+ const messages: MobileRichMarkdownEditorMessage[] = []+ const editorDocument = createRichMarkdownEditorDocument({+ ...quietRichMarkdownEditorHost(),+ postToHost: (message) => messages.push(message)+ })+ stopDocuments.push(editorDocument.stop)+ editorDocument.send.setMarkdown('> First', 7)+ return { editorDocument, editor: document.getElementById('editor')!, messages }+}++it.each([+ ['<p>First</p><p>Second</p>', '> First\n> \n> Second'],+ ['First<div>Second</div>', '> First\n> \n> Second'],+ ['<b>bold</b> text<p>second</p>', '> **bold** text\n> \n> second'],+ ['First<br>Second', '> First\n> Second'],+ [+ '<code>left</code><code>right</code><p>second</p>tail',+ '> `leftright`\n> \n> second\n> \n> tail'+ ]+])('saves native quote boundaries without changing the live DOM: %s', (html, markdown) => {+ const { editorDocument, editor, messages } = surface()+ editor.innerHTML = `<blockquote>${html}</blockquote><p>Outside</p>`+ const live = editor.innerHTML+ editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }))++ expect(editor.innerHTML).toBe(live)+ expect(messages.filter((message) => message.type === 'change')).toEqual([+ { type: 'change', generation: 7, markdown: `${markdown}\n\nOutside` }+ ])+ editorDocument.send.setMarkdown(`${markdown}\n\nOutside`, 8)+ expect(editorDocument.send.currentMarkdown()).toBe(`${markdown}\n\nOutside`)+ expect(editor.lastElementChild?.textContent).toBe('Outside')+})++it('reopens quoted paragraphs and nested quotes as separate blocks', () => {+ const { editorDocument, editor } = surface()+ const markdown = '> Outer\n> \n> > Inner\n> > \n> > Next\n> \n> End'+ editorDocument.send.setMarkdown(markdown, 8)++ expect(editor.firstElementChild?.innerHTML).toBe(+ '<p>Outer</p>\n<blockquote><p>Inner</p>\n<p>Next</p></blockquote>\n<p>End</p>'+ )+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})++it('reopens quoted headings, rules, lists and tables through the existing block readers', () => {+ const { editorDocument, editor } = surface()+ const markdown = [+ '> ## Title',+ '> ',+ '> ---',+ '> ',+ '> 3. Third',+ '> 4. Fourth',+ '> ',+ '> | a | b |',+ '> | --- | --- |',+ '> | one | two |'+ ].join('\n')+ editorDocument.send.setMarkdown(markdown, 8)++ expect(+ Array.from(editor.querySelector('blockquote')!.children).map((node) => node.tagName)+ ).toEqual(['H2', 'HR', 'OL', 'TABLE'])+ expect(editor.querySelector('ol')?.getAttribute('start')).toBe('3')+ expect(editor.querySelector('td')?.textContent).toBe('one')+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})++it.each([+ ['> - a\n> continued', '- a<br> continued'],+ ['> > nested\n> back', '> nested<br>back']+])('keeps quoted text the block readers would restructure as written: %s', (markdown, html) => {+ const { editorDocument, editor } = surface()+ editorDocument.send.setMarkdown(markdown, 8)++ expect(editor.firstElementChild?.innerHTML).toBe(`<p>${html}</p>`)+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})++it('keeps quoted code literal rather than interpreting its block markers', () => {+ const { editorDocument, editor } = surface()+ const markdown = '> ```text\n> > literal &\n> # still code\n> ```'+ editorDocument.send.setMarkdown(markdown, 8)++ expect(editor.querySelector('pre code')?.textContent).toBe('> literal &\n# still code')+ expect(editor.querySelectorAll('blockquote').length).toBe(1)+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})++it('keeps task state and read-only controls inside quotes', () => {+ const { editorDocument, editor } = surface()+ const markdown = '> - [x] Done\n> - [ ] Open'+ editorDocument.send.setEditable(false)+ editorDocument.send.setMarkdown(markdown, 8)++ expect(+ Array.from(editor.querySelectorAll('input')).map((input) => ({+ checked: input.checked,+ disabled: input.disabled+ }))+ ).toEqual([+ { checked: true, disabled: true },+ { checked: false, disabled: true }+ ])+ expect(editorDocument.send.currentMarkdown()).toBe(markdown)+})diff --git a/mobile/src/components/rich-markdown/markdown-to-html.ts b/mobile/src/components/rich-markdown/markdown-to-html.tsindex 20a29c87145..3d65100259c 100644--- a/mobile/src/components/rich-markdown/markdown-to-html.ts+++ b/mobile/src/components/rich-markdown/markdown-to-html.ts@@ -1,9 +1,10 @@-import { escapeAttr, escapeHtml } from './markdown-escaping'+import { escapeAttr, escapeLiteralHtml } from './markdown-escaping'import { renderInline } from './markdown-inline-render'import { renderListItems } from './markdown-list-render'import { parseListTree } from './markdown-list-parse'import { closesFence, openingFence } from './markdown-code-fence'import { isTableSeparator, splitTableRow } from './markdown-table-rows'+import { blockMarkdown } from './html-block-markdown'import type { RichMarkdownEditorScope } from './document-scope'/** Whether a line opens a block of its own, which is what ends the paragraph being gathered. */@@ -11,12 +12,48 @@ export function isBlockStart(line: string): boolean {return /^(```|#{1,6}\s+|>\s?|\s*(?:[-*+]|\d+[.)])\s+|\s*(-{3,}|\*{3,}|_{3,})\s*$)/.test(line)}+// Use quote blocks only when they save the source or what the literal paragraph saves; the list reader drops continuation and lazy lines.+function quoteMarkup(probe: () => Element, quote: string[], structured: string): string {+ const literal = `<p>${renderInline(quote.join('\n').trim()).replace(/\n/g, '<br />')}</p>`+ if (structured === literal) {+ return structured+ }+ const element = probe()+ element.innerHTML = structured+ const structuredMarkdown = blockMarkdown(element)+ if (structuredMarkdown.replace(/^> /gm, '').trim() === quote.join('\n').trim()) {+ return structured+ }+ element.innerHTML = literal+ return blockMarkdown(element) === structuredMarkdown ? structured : literal+}+// Read fenced/table/list blocks by their own consumed line runs, not flat replacements; empty source still needs paragraph for placeholder.export function markdownToHtml(scope: RichMarkdownEditorScope, markdown: string): string {- const lines = markdown.replace(/\r\n?/g, '\n').split('\n')- const html: string[] = []+ let lines = markdown.replace(/\r\n?/g, '\n').split('\n')+ let html: string[] = []let index = 0- while (index < lines.length) {+ const parents: { lines: string[]; html: string[]; index: number }[] = []+ let quoteProbe: Element | null = null+ // Inert document so probed images and links never load.+ const probe = () =>+ (quoteProbe ??= scope+ .getDocument()+ .implementation.createHTMLDocument('')+ .createElement('blockquote'))+ while (index < lines.length || parents.length > 0) {+ if (index >= lines.length) {+ const parent = parents.pop()+ if (!parent) {+ break+ }+ const markup = quoteMarkup(probe, lines, html.join('\n') || '<p><br /></p>')+ lines = parent.lines+ html = parent.html+ index = parent.index+ html.push(`<blockquote>${markup}</blockquote>`)+ continue+ }const line = lines[index] ?? ''if (!line.trim()) {index += 1@@ -34,7 +71,7 @@ export function markdownToHtml(scope: RichMarkdownEditorScope, markdown: string)index += 1}html.push(- `<pre data-language="${escapeAttr(fence.language)}"><code>${escapeHtml(code.join('\n'))}</code></pre>`+ `<pre data-language="${escapeAttr(fence.language)}"><code>${escapeLiteralHtml(code.join('\n'))}</code></pre>`)continue}@@ -82,9 +119,10 @@ export function markdownToHtml(scope: RichMarkdownEditorScope, markdown: string)quote.push((lines[index] ?? '').replace(/^>\s?/, ''))index += 1}- html.push(- `<blockquote><p>${renderInline(quote.join('\n').trim()).replace(/\n/g, '<br />')}</p></blockquote>`- )+ parents.push({ lines, html, index })+ lines = quote+ html = []+ index = 0continue}if (/^\s*(?:[-*+]|\d+[.)])\s+/.test(line)) {diff --git a/src/renderer/src/components/editor/markdown-code-span-scanner.ts b/src/renderer/src/components/editor/markdown-code-span-scanner.tsindex 353e43f64a5..dbb33823ca3 100644--- a/src/renderer/src/components/editor/markdown-code-span-scanner.ts+++ b/src/renderer/src/components/editor/markdown-code-span-scanner.ts@@ -1,3 +1,8 @@+import {+ createMarkdownBacktickRunLookup,+ type MarkdownCodeSpanScanner+} from '../../../../shared/markdown-code-span-runs'+export type { MarkdownCodeSpanScanner } from '../../../../shared/markdown-code-span-runs'import {createMarkdownFenceTracker,findMarkdownLineEnd,@@ -61,11 +66,6 @@ function isEscapedAt(content: string, index: number, lineStart: number): booleanreturn (index - cursor) % 2 === 1}-export type MarkdownCodeSpanScanner = {- /** Return the closing offset only for a run matching the opener’s exact length, as CommonMark requires. */- findSpanEnd: (index: number) => number | null-}-/** Index backtick runs once so each lookup binary-searches instead of rescanning the remaining document. */export function createMarkdownCodeSpanScanner(content: string): MarkdownCodeSpanScanner {const starts: number[] = []@@ -134,64 +134,7 @@ export function createMarkdownCodeSpanScanner(content: string): MarkdownCodeSpan}})- function findRunAt(index: number): number {- let low = 0- let high = starts.length - 1- let atOrBefore = -1- while (low <= high) {- const mid = (low + high) >> 1- if (starts[mid] <= index) {- atOrBefore = mid- low = mid + 1- } else {- high = mid - 1- }- }- if (atOrBefore === -1 || index >= starts[atOrBefore] + lengths[atOrBefore]) {- return -1- }- return atOrBefore- }-- function findFirstRunFrom(candidates: number[], offset: number): number {- let low = 0- let high = candidates.length - 1- let match = -1- while (low <= high) {- const mid = (low + high) >> 1- if (starts[candidates[mid]] >= offset) {- match = candidates[mid]- high = mid - 1- } else {- low = mid + 1- }- }- return match- }-- return {- findSpanEnd(index: number): number | null {- const opener = findRunAt(index)- if (opener === -1) {- return null- }- // Resume within rejected runs; escaped backticks cannot open but marked permits them to close a span.- const openStart = escaped[opener] ? Math.max(index, starts[opener] + 1) : index- const openerEnd = starts[opener] + lengths[opener]- if (openStart >= openerEnd) {- return null- }- const candidates = runsByLength.get(openerEnd - openStart)- if (!candidates) {- return null- }- const closer = findFirstRunFrom(candidates, openerEnd)- if (closer === -1 || blocks[closer] !== blocks[opener]) {- return null- }- return starts[closer] + lengths[closer]- }- }+ return createMarkdownBacktickRunLookup(starts, lengths, runsByLength, blocks, escaped)}export function skipMarkdownBacktickRun(content: string, index: number): number {diff --git a/src/shared/markdown-code-span-runs.ts b/src/shared/markdown-code-span-runs.tsnew file mode 100644index 00000000000..f4820dab551--- /dev/null+++ b/src/shared/markdown-code-span-runs.ts@@ -0,0 +1,89 @@+export type MarkdownCodeSpanScanner = {+ /** Return the closing offset only for a run matching the opener’s exact length, as CommonMark requires. */+ findSpanEnd: (index: number) => number | null+}++export function createRawMarkdownCodeSpanScanner(content: string): MarkdownCodeSpanScanner {+ const starts: number[] = []+ const lengths: number[] = []+ const runsByLength = new Map<number, number[]>()+ for (const match of content.matchAll(/`+/g)) {+ const runLength = match[0].length+ const candidates = runsByLength.get(runLength)+ if (candidates) {+ candidates.push(starts.length)+ } else {+ runsByLength.set(runLength, [starts.length])+ }+ starts.push(match.index)+ lengths.push(runLength)+ }+ return createMarkdownBacktickRunLookup(starts, lengths, runsByLength)+}++export function createMarkdownBacktickRunLookup(+ starts: number[],+ lengths: number[],+ runsByLength: Map<number, number[]>,+ blocks?: number[],+ escaped?: boolean[]+): MarkdownCodeSpanScanner {+ function findRunAt(index: number): number {+ let low = 0+ let high = starts.length - 1+ let atOrBefore = -1+ while (low <= high) {+ const mid = (low + high) >> 1+ if (starts[mid] <= index) {+ atOrBefore = mid+ low = mid + 1+ } else {+ high = mid - 1+ }+ }+ if (atOrBefore === -1 || index >= starts[atOrBefore] + lengths[atOrBefore]) {+ return -1+ }+ return atOrBefore+ }++ function findFirstRunFrom(candidates: number[], offset: number): number {+ let low = 0+ let high = candidates.length - 1+ let match = -1+ while (low <= high) {+ const mid = (low + high) >> 1+ if (starts[candidates[mid]] >= offset) {+ match = candidates[mid]+ high = mid - 1+ } else {+ low = mid + 1+ }+ }+ return match+ }++ return {+ findSpanEnd(index: number): number | null {+ const opener = findRunAt(index)+ if (opener === -1) {+ return null+ }+ // Resume within rejected runs; escaped backticks cannot open but marked permits them to close a span.+ const openStart = escaped?.[opener] ? Math.max(index, starts[opener] + 1) : index+ const openerEnd = starts[opener] + lengths[opener]+ if (openStart >= openerEnd) {+ return null+ }+ const candidates = runsByLength.get(openerEnd - openStart)+ if (!candidates) {+ return null+ }+ const closer = findFirstRunFrom(candidates, openerEnd)+ if (closer === -1 || (blocks && blocks[closer] !== blocks[opener])) {+ return null+ }+ return starts[closer] + lengths[closer]+ }+ }+}