Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(markdown): render CJK-adjacent strong emphasis (#6768)
Jiayuan Zhang4ef2944967b7
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsxindex 04b6960bdd..43a4ca68c2 100644--- a/packages/views/editor/readonly-content.test.tsx+++ b/packages/views/editor/readonly-content.test.tsx@@ -308,25 +308,46 @@ describe("ReadonlyContent issue mention Markdown", () => {expect(resolveIssueIdentifierMock).not.toHaveBeenCalled();expect(queryByTestId("issue-mention-card")).toBeNull();});+});- it("documents the CommonMark quoted-emphasis edge case before Korean particles", () => {- const unsafe = render(- <ReadonlyContent content={'**"무엇을 먼저 정해두고 시작할지"**가'} />,- );-- expect(unsafe.container.querySelector("strong")).toBeNull();- expect(unsafe.container.textContent).toContain(+describe("ReadonlyContent CJK emphasis", () => {+ it.each([+ ["Chinese punctuation", "**水温适度。**水的温度", "水温适度。"],+ ["Japanese punctuation", "**テスト。**テスト", "テスト。"],+ [+ "Korean punctuation before a particle",'**"무엇을 먼저 정해두고 시작할지"**가',- );+ '"무엇을 먼저 정해두고 시작할지"',+ ],+ ])("renders CJK-friendly strong emphasis: %s", (_name, content, strongText) => {+ const { container } = render(<ReadonlyContent content={content} />);- const safe = render(- <ReadonlyContent content={'"**무엇을 먼저 정해두고 시작할지**"가'} />,+ expect(container.querySelector("strong")?.textContent).toBe(strongText);+ expect(container.textContent).not.toContain("**");+ });++ it("repairs a trailing space before a CJK strong closing delimiter", () => {+ const { container } = render(+ <ReadonlyContent content="**为什么做,收益是什么。 **Multica 的能力边界" />,);- expect(safe.container.querySelector("strong")?.textContent).toBe(- "무엇을 먼저 정해두고 시작할지",+ expect(container.querySelector("strong")?.textContent).toBe(+ "为什么做,收益是什么。",);- expect(safe.container.textContent).toContain('"무엇을 먼저 정해두고 시작할지"가');+ expect(container.textContent).toBe("为什么做,收益是什么。 Multica 的能力边界");+ });++ it.each([+ ["inline code", "`**中文。 **后文`"],+ ["fenced code", "```md\n**中文。 **后文\n```"],+ ["indented code", " **中文。 **后文"],+ ["escaped Markdown", "\\**中文。 **后文"],+ ["non-CJK prose", "**English sentence. **next"],+ ])("does not repair trailing-space emphasis in %s", (_name, content) => {+ const { container } = render(<ReadonlyContent content={content} />);++ expect(container.querySelector("strong")).toBeNull();+ expect(container.textContent).toContain("**");});});diff --git a/packages/views/package.json b/packages/views/package.jsonindex 00629790d7..6962a3ff9c 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -104,9 +104,11 @@"rehype-raw": "^7.0.0","rehype-sanitize": "^6.0.0","remark-breaks": "^4.0.0",+ "remark-cjk-friendly": "^2.3.1","remark-gfm": "^4.0.1","remark-math": "catalog:",- "sonner": "^2.0.7"+ "sonner": "^2.0.7",+ "unist-util-visit": "^5.1.0"},"peerDependencies": {"@tanstack/react-query": "catalog:",@@ -124,6 +126,7 @@"@testing-library/jest-dom": "catalog:","@testing-library/react": "catalog:","@testing-library/user-event": "catalog:",+ "@types/mdast": "^4.0.4","@types/react": "catalog:","@types/react-dom": "catalog:","@vitejs/plugin-react": "catalog:",diff --git a/packages/views/rich-content/cjk-emphasis.ts b/packages/views/rich-content/cjk-emphasis.tsnew file mode 100644index 0000000000..3827995d25--- /dev/null+++ b/packages/views/rich-content/cjk-emphasis.ts@@ -0,0 +1,97 @@+import type { PhrasingContent, Root, Strong, Text } from "mdast";+import { visit } from "unist-util-visit";++const CJK_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;++function text(value: string): Text {+ return { type: "text", value };+}++function strong(value: string): Strong {+ return { type: "strong", children: [text(value)] };+}++function repairTextValue(value: string): PhrasingContent[] | null {+ const replacement: PhrasingContent[] = [];+ let consumed = 0;+ let cursor = 0;++ while (cursor < value.length - 1) {+ const opening = value.indexOf("**", cursor);+ if (opening === -1) break;++ const firstInner = value[opening + 2];+ if (firstInner == null || /\s|\*/u.test(firstInner)) {+ cursor = opening + 2;+ continue;+ }++ // Do not look across another delimiter run: that would reinterpret valid+ // or deliberately literal Markdown beyond the one malformed span.+ const closing = value.indexOf("**", opening + 2);+ if (closing === -1) break;++ const afterClosing = value[closing + 2];+ if (+ afterClosing == null ||+ /\s/u.test(afterClosing) ||+ (value[closing - 1] !== " " && value[closing - 1] !== "\t")+ ) {+ cursor = opening + 2;+ continue;+ }++ let whitespaceStart = closing - 1;+ while (+ whitespaceStart > opening + 2 &&+ (value[whitespaceStart - 1] === " " || value[whitespaceStart - 1] === "\t")+ ) {+ whitespaceStart--;+ }++ const inner = value.slice(opening + 2, whitespaceStart);+ if (!CJK_SCRIPT.test(inner) || !/\S/u.test(inner)) {+ cursor = opening + 2;+ continue;+ }++ if (opening > consumed) replacement.push(text(value.slice(consumed, opening)));+ replacement.push(strong(inner), text(value.slice(whitespaceStart, closing)));+ consumed = closing + 2;+ cursor = consumed;+ }++ if (replacement.length === 0) return null;+ if (consumed < value.length) replacement.push(text(value.slice(consumed)));+ return replacement;+}++/**+ * Recover the screenshot's common AI-authored form after Markdown parsing:+ * `**中文。 **next` becomes the equivalent of `**中文。** next`.+ *+ * This transformer is deliberately narrower than a raw string rewrite. It+ * only visits parsed text nodes containing CJK script characters, so code,+ * valid Markdown nodes and non-CJK prose keep their original semantics.+ * Source/value equality also excludes escaped Markdown whose AST text no+ * longer matches the author's literal input.+ */+export function remarkRepairCjkStrongTrailingWhitespace() {+ return (tree: Root, file: { value: unknown }) => {+ const source = String(file.value ?? "");++ visit(tree, "text", (node, index, parent) => {+ if (index == null || parent == null || parent.type === "strong") return;++ const start = node.position?.start.offset;+ const end = node.position?.end.offset;+ if (start == null || end == null || source.slice(start, end) !== node.value) {+ return;+ }++ const replacement = repairTextValue(node.value);+ if (!replacement) return;+ parent.children.splice(index, 1, ...replacement);+ });+ };+}diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsxindex 34f0371f96..889b701e72 100644--- a/packages/views/rich-content/rich-content.tsx+++ b/packages/views/rich-content/rich-content.tsx@@ -34,6 +34,7 @@ import ReactMarkdown, {import type { ComponentPropsWithoutRef, ReactNode } from "react";import rehypeKatex from "rehype-katex";import remarkBreaks from "remark-breaks";+import remarkCjkFriendly from "remark-cjk-friendly/parseOnly";import remarkGfm from "remark-gfm";import remarkMath from "remark-math";import rehypeRaw from "rehype-raw";@@ -68,6 +69,7 @@ import { highlightToHtml } from "../editor/utils/highlight-markdown";import { AttachmentDownloadProvider } from "../editor/attachment-download-context";import { Attachment as AttachmentRenderer } from "../editor/attachment";import { computeClosedFenceOffsets } from "./streaming-fence";+import { remarkRepairCjkStrongTrailingWhitespace } from "./cjk-emphasis";import {CodeBlockShell,RichFenceBlock,@@ -464,6 +466,8 @@ const REMARK_PLUGINS = [[remarkMath, { singleDollarTextMath: false }],remarkBreaks,[remarkGfm, { singleTilde: false }],+ remarkCjkFriendly,+ remarkRepairCjkStrongTrailingWhitespace,] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;const REHYPE_PLUGINS = [diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 696903b2e3..d91b9ac4f0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1127,6 +1127,9 @@ importers:remark-breaks:specifier: ^4.0.0version: 4.0.0+ remark-cjk-friendly:+ specifier: ^2.3.1remark-gfm:specifier: ^4.0.1version: 4.0.1@@ -1136,6 +1139,9 @@ importers:sonner:specifier: ^2.0.7+ unist-util-visit:+ specifier: ^5.1.0+ version: 5.1.0zustand:specifier: 'catalog:'version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))@@ -1155,6 +1161,9 @@ importers:'@testing-library/user-event':specifier: 'catalog:'version: 14.6.1(@testing-library/[email protected])+ '@types/mdast':+ specifier: ^4.0.4+ version: 4.0.4'@types/react':specifier: ^19.2.0version: 19.2.14@@ -7933,6 +7942,15 @@ packages:resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}+ resolution: {integrity: sha512-BoaAm8mlJ+LAYz0Qs532Y3ciTuQYgBUPZcSFbvC/ZKmEMAKgulw84YvQK1gI34t/vL2euSfuaWlqczkTBgamkw==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/mdast': '*'+ peerDependenciesMeta:+ '@types/mdast':+ optional: true+resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}@@ -8030,6 +8048,25 @@ packages:resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}+ resolution: {integrity: sha512-GcbXqTTHOsiZHyF753oIddP/J2eH8j9zpyQPhkof6B2JNxfEJabnQqxbCgzJNuNes0Y2jTNJ3LiYPSXr6eJA8w==}+ engines: {node: '>=18'}+ peerDependencies:+ micromark-util-types: '*'+ peerDependenciesMeta:+ micromark-util-types:+ optional: true++ resolution: {integrity: sha512-OkzoYVTL1ChbvQ8Cc1ayTIz7paFQz8iS9oIYmewncweUSwmWR+hkJF9spJ1lxB90XldJl26A1F4IkPOKS3bDXw==}+ engines: {node: '>=18'}+ peerDependencies:+ micromark: ^4.0.0+ micromark-util-types: ^2.0.0+ peerDependenciesMeta:+ micromark-util-types:+ optional: true+resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}@@ -9389,6 +9426,16 @@ packages:resolution: {integrity: sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==}+ resolution: {integrity: sha512-f+pKZRxCRwNEGFBKNRAZAqU91GIK1SAo3ZyFHWRUgC9zcxRR0BXKd6YwqgSsxtW0rNpUDtONj7H5nje2WL3fcA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/mdast': ^4.0.0+ unified: ^11.0.0+ peerDependenciesMeta:+ '@types/mdast':+ optional: true+resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}@@ -18923,6 +18970,16 @@ snapshots:unist-util-visit: 5.1.0vfile: 6.0.3+ dependencies:+ mdast-util-to-markdown: 2.1.2+ micromark-extension-cjk-friendly-util: 3.0.1([email protected])+ micromark-util-symbol: 2.0.1+ optionalDependencies:+ '@types/mdast': 4.0.4+ transitivePeerDependencies:+ - micromark-util-types+dependencies:'@types/mdast': 4.0.4@@ -19172,6 +19229,25 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ get-east-asian-width: 1.5.0+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ optionalDependencies:+ micromark-util-types: 2.0.2++ dependencies:+ devlop: 1.1.0+ micromark: 4.0.2+ micromark-extension-cjk-friendly-util: 3.0.1([email protected])+ micromark-util-chunked: 2.0.1+ micromark-util-resolve-all: 2.0.1+ micromark-util-symbol: 2.0.1+ optionalDependencies:+ micromark-util-types: 2.0.2+dependencies:micromark-util-character: 2.1.1@@ -20882,6 +20958,17 @@ snapshots:mdast-util-newline-to-break: 2.0.0unified: 11.0.5+ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ mdast-util-to-markdown-cjk-friendly: 1.0.0(@types/[email protected])([email protected])+ micromark-extension-cjk-friendly: 2.0.1([email protected])([email protected])+ unified: 11.0.5+ optionalDependencies:+ '@types/mdast': 4.0.4+ transitivePeerDependencies:+ - micromark+ - micromark-util-types+dependencies:'@types/mdast': 4.0.4