Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(rich-content): parse a comment's Markdown once and reuse it across mounts (MUL-9538) (#10911)
Jiayuan Zhang26fbe260b16b
diff --git a/packages/views/editor/code-block-static.tsx b/packages/views/editor/code-block-static.tsxindex 71a5c6c449..74332aeae7 100644--- a/packages/views/editor/code-block-static.tsx+++ b/packages/views/editor/code-block-static.tsx@@ -15,9 +15,8 @@*/import { useMemo, type CSSProperties } from "react";-import { toHtml } from "hast-util-to-html";import { cn } from "@multica/ui/lib/utils";-import { highlightCode } from "./syntax-highlight";+import { highlightCodeHtml } from "./syntax-highlight";import { highlightToLines } from "../common/task-transcript/diff-highlight";import "./styles/code.css";@@ -51,8 +50,7 @@ export function CodeBlockStatic({return { html: numberedLinesHtml(lines), lineCount: lines.length };}try {- const tree = highlightCode(code, language);- return { html: toHtml(tree) as string, lineCount: 0 };+ return { html: highlightCodeHtml(code, language), lineCount: 0 };} catch {// Keep an unexpected highlighter failure from breaking the preview.return { html: escapeHtml(code), lineCount: 0 };diff --git a/packages/views/editor/syntax-highlight.ts b/packages/views/editor/syntax-highlight.tsindex 57434d1ad0..ba01a0c221 100644--- a/packages/views/editor/syntax-highlight.ts+++ b/packages/views/editor/syntax-highlight.ts@@ -1,3 +1,4 @@+import { toHtml } from "hast-util-to-html";import { common, createLowlight } from "lowlight";const baseLowlight = createLowlight(common);@@ -23,3 +24,28 @@ export function highlightCode(value: string, language?: string) {? baseLowlight.highlight(normalizedLanguage, value): baseLowlight.highlight("plaintext", value);}++const HIGHLIGHTED_HTML_LIMIT = 300;+const highlightedHtml = new Map<string, string>();++/**+ * `highlightCode` serialized to HTML, cached by language and source. A code+ * block highlights again every time its comment remounts (scrolled back into a+ * virtualized timeline, the issue reopened), for an identical result.+ */+export function highlightCodeHtml(value: string, language?: string): string {+ const key = `${language?.trim().toLowerCase() ?? ""}\u0000${value}`;+ const hit = highlightedHtml.get(key);+ if (hit !== undefined) {+ // Least recently used goes first.+ highlightedHtml.delete(key);+ highlightedHtml.set(key, hit);+ return hit;+ }+ const html = toHtml(highlightCode(value, language));+ highlightedHtml.set(key, html);+ if (highlightedHtml.size > HIGHLIGHTED_HTML_LIMIT) {+ highlightedHtml.delete(highlightedHtml.keys().next().value!);+ }+ return html;+}diff --git a/packages/views/rich-content/rich-code-block.tsx b/packages/views/rich-content/rich-code-block.tsxindex 4f1f3720c9..0067eee5d9 100644--- a/packages/views/rich-content/rich-code-block.tsx+++ b/packages/views/rich-content/rich-code-block.tsx@@ -25,7 +25,6 @@*/import { memo, useEffect, useMemo, useState, type ReactNode } from "react";-import { toHtml } from "hast-util-to-html";import { Check, Copy } from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";@@ -41,7 +40,7 @@ import {HTML_BLOCK_DEFAULT_RESERVED_PX,reservedHtmlBlockHeightPx,} from "../editor/html-block-preview";-import { highlightCode } from "../editor/syntax-highlight";+import { highlightCodeHtml } from "../editor/syntax-highlight";import { LazyRichBlock } from "./lazy-rich-block";/**@@ -90,8 +89,7 @@ export function StaticCodeBody({const html = useMemo(() => {const code = body.replace(/\n$/, "");try {- const tree = highlightCode(code, language);- return toHtml(tree);+ return highlightCodeHtml(code, language);} catch {return null;}diff --git a/packages/views/rich-content/rich-content-render-cache.test.tsx b/packages/views/rich-content/rich-content-render-cache.test.tsxnew file mode 100644index 0000000000..f465d76a36--- /dev/null+++ b/packages/views/rich-content/rich-content-render-cache.test.tsx@@ -0,0 +1,102 @@+/**+ * A comment remounts whenever it scrolls back into a virtualized timeline or+ * its issue reopens. Settled content is parsed once and its rendered tree+ * reused; streaming content is never cached (MUL-9538).+ */+import { describe, expect, it, vi } from "vitest";+import { render } from "@testing-library/react";+import ReactMarkdown from "react-markdown";++vi.mock("../issues/hooks", () => ({+ useResolveIssueIdentifier: () => null,+}));++vi.mock("../i18n", async () => {+ const editor = (await import("../locales/en/editor.json")).default;+ return {+ useT: () => ({+ t: (select: (bundle: typeof editor) => string) => select(editor),+ }),+ useTimeAgo: () => "just now",+ };+});++vi.mock("@multica/core/api", () => ({+ api: { getAttachmentTextContent: vi.fn() },+ PreviewTooLargeError: class extends Error {},+ PreviewUnsupportedError: class extends Error {},+}));++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({+ issueDetail: (id: string) => `/acme/issues/${id}`,+ projectDetail: (id: string) => `/acme/projects/${id}`,+ }),+ useWorkspaceSlug: () => "acme",+}));++vi.mock("../navigation", () => ({+ useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ resolveClickIntent: () => "push",+ useAppOrigin: () => null,+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));++vi.mock("../issues/components/issue-mention-card", () => ({+ IssueMentionCard: ({ issueId }: { issueId: string }) => <span>{issueId}</span>,+}));++vi.mock("../projects/components/project-chip", () => ({+ ProjectChip: ({ projectId }: { projectId: string }) => <span>{projectId}</span>,+}));++vi.mock("../editor/link-hover-card", () => ({+ useLinkHover: () => ({}),+ LinkHoverCard: () => null,+}));++// Surface what the file-card renderer received, so the assertion is about the+// emitted attachment rather than incidental chrome.+vi.mock("../editor/attachment", () => ({+ Attachment: ({ attachment }: { attachment: { url: string; filename: string } }) => (+ <span data-testid="file-card" data-url={attachment.url}>+ {attachment.filename}+ </span>+ ),+}));++vi.mock("react-markdown", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react-markdown")>();+ return { ...actual, default: vi.fn(actual.default) };+});++import { RichContent } from "./rich-content";++const parses = () => vi.mocked(ReactMarkdown).mock.calls.length;++describe("RichContent render cache", () => {+ it("parses settled content once across remounts", () => {+ const content = "Cached **once**\n\n| a | b |\n|---|---|\n| 1 | 2 |";+ const before = parses();+ const first = render(<RichContent content={content} />);+ const html = first.container.innerHTML;+ first.unmount();+ const second = render(<RichContent content={content} />);++ expect(parses() - before).toBe(1);+ expect(second.container.innerHTML).toBe(html);+ expect(second.container.querySelector("strong")?.textContent).toBe("once");+ });++ it("parses streaming content on every mount", () => {+ const content = "Still **arriving**";+ const before = parses();+ render(<RichContent content={content} phase="streaming" />).unmount();+ render(<RichContent content={content} phase="streaming" />);++ expect(parses() - before).toBe(2);+ });+});diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsxindex 4429cf2ddf..505890cc0b 100644--- a/packages/views/rich-content/rich-content.tsx+++ b/packages/views/rich-content/rich-content.tsx@@ -25,7 +25,7 @@* settled-but-malformed fence still renders as source.*/-import { createContext, isValidElement, memo, useContext, useMemo, useRef } from "react";+import { createContext, isValidElement, memo, useContext, useMemo, useRef, type ReactElement } from "react";import ReactMarkdown, {type Components,type ExtraProps,@@ -501,6 +501,62 @@ const REHYPE_PLUGINS = [rehypeKatex,] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;+/**+ * Rendered Markdown by source text. A comment mounts again whenever it scrolls+ * back into a virtualized timeline or its issue is reopened, and parsing it+ * (remark, rehype, sanitize, KaTeX) and building its element tree is most of+ * that mount. Plugins, components and the URL transform are module constants,+ * so the tree is a pure function of the processed source and React can reuse+ * the elements across mounts. Settled content only: streaming text changes on+ * every token and would only churn the cache (MUL-9538).+ */+interface RenderedMarkdown {+ processed: string;+ closedFences: ReturnType<typeof computeClosedFences>;+ element: ReactElement;+}++const RENDERED_MARKDOWN_LIMIT = 150;+const renderedMarkdown = new Map<string, RenderedMarkdown>();++function renderMarkdown(content: string, cdnDomain: string): RenderedMarkdown {+ const processed = highlightToHtml(+ preprocessMarkdown(content, { cdnDomain, autolinkIssueIdentifiers: true }),+ );+ return {+ processed,+ // Derived from the SAME string handed to ReactMarkdown, so offsets line up+ // with the hast node positions the `code`/`pre` renderers observe. Computing+ // it from the raw pre-preprocess text would mis-match every rewritten node.+ closedFences: computeClosedFences(processed),+ // react-markdown's synchronous renderer is a plain function of its options.+ element: ReactMarkdown({+ children: processed,+ remarkPlugins: REMARK_PLUGINS,+ rehypePlugins: REHYPE_PLUGINS,+ urlTransform: markdownUrlTransform,+ components: COMPONENTS,+ }),+ };+}++function cachedRenderMarkdown(content: string, cdnDomain: string): RenderedMarkdown {+ const key = `${cdnDomain}\u0000${content}`;+ const hit = renderedMarkdown.get(key);+ if (hit) {+ // Least recently used goes first.+ renderedMarkdown.delete(key);+ renderedMarkdown.set(key, hit);+ return hit;+ }+ const rendered = renderMarkdown(content, cdnDomain);+ renderedMarkdown.set(key, rendered);+ if (renderedMarkdown.size > RENDERED_MARKDOWN_LIMIT) {+ renderedMarkdown.delete(renderedMarkdown.keys().next().value!);+ }+ return rendered;+}+// Componentexport interface RichContentProps {@@ -540,18 +596,11 @@ export const RichContent = memo(function RichContent({// late config arrival reprocesses exactly once.const cdnDomain = useConfigStore((s) => s.cdnDomain);- const processed = useMemo(- () =>- highlightToHtml(- preprocessMarkdown(content, { cdnDomain, autolinkIssueIdentifiers: true }),- ),- [content, cdnDomain],+ const settled = phase === "settled";+ const { processed, closedFences, element } = useMemo(+ () => (settled ? cachedRenderMarkdown : renderMarkdown)(content, cdnDomain),+ [content, cdnDomain, settled],);-- // Derived from the SAME string handed to ReactMarkdown, so offsets line up- // with the hast node positions the `code`/`pre` renderers observe. Computing- // it from the raw pre-preprocess text would mis-match every rewritten node.- const closedFences = useMemo(() => computeClosedFences(processed), [processed]);const tableSource = useMemo(() => ({ source: content, rendered: processed }), [content, processed]);const wrapperRef = useRef<HTMLDivElement>(null);@@ -568,18 +617,11 @@ export const RichContent = memo(function RichContent({() => (<ClosedFenceContext.Provider value={closedFences}><RichTableSourceContext.Provider value={tableSource}>- <ReactMarkdown- remarkPlugins={REMARK_PLUGINS}- rehypePlugins={REHYPE_PLUGINS}- urlTransform={markdownUrlTransform}- components={COMPONENTS}- >- {processed}- </ReactMarkdown>+ {element}</RichTableSourceContext.Provider></ClosedFenceContext.Provider>),- [processed, closedFences, tableSource],+ [element, closedFences, tableSource],);return (