From 012f54c4841dfeb6a76c4ecc196688872cb9ecbc Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:36:18 -0400 Subject: [PATCH] feat(chat): render Markdown and copy code blocks --- package-lock.json | 103 ++++++++++++++++++ package.json | 1 + scripts/package-licenses.mjs | 2 +- .../components/ChannelConversation.tsx | 14 +-- .../components/ChannelMessageContent.tsx | 81 ++++++++++++++ .../components/channel-message-content.css | 19 ++++ tests/channel-message-content.test.ts | 57 ++++++++++ 7 files changed, 264 insertions(+), 13 deletions(-) create mode 100644 src/client/channel/components/ChannelMessageContent.tsx create mode 100644 src/client/channel/components/channel-message-content.css create mode 100644 tests/channel-message-content.test.ts diff --git a/package-lock.json b/package-lock.json index cf78910f2..d8b7198d8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "@vitejs/plugin-react": "6.0.5", "@zip.js/zip.js": "2.24.0", "esbuild": "0.28.2", + "markdown-it": "15.0.3", "qrcode.react": "4.2.0", "react": "19.2.8", "react-dom": "19.2.8", @@ -999,6 +1000,23 @@ "node": ">=18.0.0" } }, + "node_modules/argparse": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz", + "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1043,6 +1061,19 @@ "node": ">=8" } }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -1418,6 +1449,26 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1428,6 +1479,41 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/markdown-it": { + "version": "15.0.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", + "integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^3.0.3", + "entities": "^8.1.0", + "linkify-it": "^6.1.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1", + "uc.micro": "^3.0.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "dev": true, + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.18", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", @@ -1517,6 +1603,16 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qrcode.react": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz", @@ -1721,6 +1817,13 @@ "node": ">=14.17" } }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "dev": true, + "license": "MIT" + }, "node_modules/undici-types": { "version": "7.18.2", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", diff --git a/package.json b/package.json index 87378f93e..337f350f9 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "@vitejs/plugin-react": "6.0.5", "@zip.js/zip.js": "2.24.0", "esbuild": "0.28.2", + "markdown-it": "15.0.3", "qrcode.react": "4.2.0", "react": "19.2.8", "react-dom": "19.2.8", diff --git a/scripts/package-licenses.mjs b/scripts/package-licenses.mjs index 12b4c3418..a33243ec7 100644 --- a/scripts/package-licenses.mjs +++ b/scripts/package-licenses.mjs @@ -14,7 +14,7 @@ const section = (label, body) => `\n===== ${label} =====\n\n${body.trim()}\n`; // The packages the Vite bundle ships to the Browser. Nothing installs // node_modules at runtime any more, so this list is the notice contract rather // than package.json's dependencies field. -const WEB_BUNDLE_PACKAGES = ["@oddbird/popover-polyfill", "@zip.js/zip.js", "react", "react-dom", "qrcode.react", "sdp-transform", "semver", "zod"]; +const WEB_BUNDLE_PACKAGES = ["@oddbird/popover-polyfill", "@zip.js/zip.js", "markdown-it", "react", "react-dom", "qrcode.react", "sdp-transform", "semver", "zod"]; // Both binaries embed the Web bundle, which serves its own notice file. const WEB_NOTICE_LINE = "Web dependencies: served at /third-party-licenses.txt\n"; diff --git a/src/client/channel/components/ChannelConversation.tsx b/src/client/channel/components/ChannelConversation.tsx index d9399c2b8..d12003231 100644 --- a/src/client/channel/components/ChannelConversation.tsx +++ b/src/client/channel/components/ChannelConversation.tsx @@ -7,6 +7,7 @@ import { MAX_MESSAGE_CODE_POINTS, type ChannelMessage, type ChannelUser, type Ch import { ChannelAction } from "./ChannelAction"; import { messageAuthorName } from "../presentation"; import { ChannelAttachment } from "./ChannelAttachment"; +import { ChannelMessageContent } from "./ChannelMessageContent"; import { type AttachmentLimits, type DraftFile, type ChannelAttachments, fileSize } from "../attachments"; import { ChannelRoomStart, type ChannelEntry } from "./ChannelRoomStart"; import { ChannelContentReactions } from "./ChannelContentReactions"; @@ -405,7 +406,7 @@ const MessageRow = memo(function MessageRow({ roomId, message, grouped, name, av {message.reply && } - {message.text &&

} + {message.text && } {message.attachments.map(file => )} ; }); - -function MessageText({ message, users, selfUserId }: { message: ChannelMessage; users: ChannelUserSummary[]; selfUserId?: string | null }) { - let cursor = 0; - const parts = (message.mentions ?? []).map((mention, index) => { - const plain = message.text.slice(cursor, mention.start); - cursor = mention.end; - return {plain} user.id === mention.userId)?.name}> - {message.text.slice(mention.start, mention.end)}; - }); - return <>{parts}{message.text.slice(cursor)}; -} diff --git a/src/client/channel/components/ChannelMessageContent.tsx b/src/client/channel/components/ChannelMessageContent.tsx new file mode 100644 index 000000000..f6a483044 --- /dev/null +++ b/src/client/channel/components/ChannelMessageContent.tsx @@ -0,0 +1,81 @@ +import { createElement, Fragment, useMemo, type ReactNode } from "react"; +import MarkdownIt, { type Token } from "markdown-it"; +import type { ChannelMessage, ChannelUserSummary } from "../protocol"; +import { ChannelAction } from "./ChannelAction"; +import { useClipboardResult } from "../../ui/use-clipboard-result"; +import { useCopy } from "../../ui/copy"; +import "./channel-message-content.css"; + +const markdown = new MarkdownIt({ html: false, breaks: true, linkify: true, typographer: false }) + .disable(["image", "table", "heading", "lheading", "hr"]); +const tags = new Set(["p", "em", "strong", "s", "ul", "ol", "li", "blockquote"]); + +function CodeBlock({ text }: { text: string }) { + const { lang } = useCopy(), zh = lang === "zh", clipboard = useClipboardResult(text); + return
+
+
{text}
+ {clipboard.status === "failed" && {zh ? "未能复制,请选择代码后手动复制。" : "Couldn't copy. Select the code and copy it manually."}} +
; +} + +/** Raw messages stay unchanged. Only confirmed identity ranges become mention marks. */ +export function ChannelMessageContent({ message, users, selfUserId }: { + message: Pick; users: readonly ChannelUserSummary[]; selfUserId?: string | null; +}) { + const { marker, references, tokens } = useMemo(() => { + // Choose a delimiter absent from the raw message so user text cannot forge a reference. + let marker = "\uE000"; + while (message.text.includes(marker) || message.text.toLowerCase().includes(encodeURI(marker).toLowerCase())) marker += "\uE000"; + const mentions = message.mentions ?? []; + const references = mentions.map((mention, index) => ({ mention, marker: `${marker}${index}${marker}`, + text: message.text.slice(mention.start, mention.end) })); + let cursor = 0; + const source = references.map(reference => { + const plain = message.text.slice(cursor, reference.mention.start); + cursor = reference.mention.end; + return plain + reference.marker; + }).join("") + message.text.slice(cursor); + return { marker, references, tokens: markdown.parse(source, {}) }; + }, [message.text, message.mentions]); + const restore = (text: string) => references.reduce((text, reference) => text.split(reference.marker).join(reference.text), text); + const plain = (text: string): ReactNode => text.split(marker).map((part, index, parts) => { + if (index % 2 === 0) return part; + const reference = references[Number(part)]; + if (!reference || String(Number(part)) !== part) return marker + part + (index < parts.length - 1 ? marker : ""); + return user.id === reference.mention.userId)?.name}>{reference.text}; + }); + function render(tokens: Token[]): ReactNode[] { + let index = 0; + function children(): ReactNode[] { + const result: ReactNode[] = []; + while (index < tokens.length) { + const token = tokens[index++], key = index; + if (token.nesting === -1) break; + if (token.type === "inline") result.push({render(token.children ?? [])}); + else if (token.type === "text") result.push({plain(token.content)}); + else if (token.type === "code_inline") result.push({restore(token.content)}); + else if (token.type === "fence" || token.type === "code_block") result.push(); + else if (token.type === "softbreak" || token.type === "hardbreak") result.push(
); + else if (token.nesting === 1) { + const inner = children(); + if (token.tag === "a") { + const href = references.reduce((href, reference) => href.split(encodeURI(reference.marker)).join(encodeURI(reference.text)), + restore(String(token.attrGet("href") ?? ""))); + // Chat links never navigate within the app or execute another URL scheme. + result.push(/^(?:https?:\/\/|mailto:)/i.test(href) + ? {inner} : {inner}); + } else if (tags.has(token.tag)) result.push(createElement(token.tag, { key, + ...(token.tag === "ol" && token.attrGet("start") ? { start: Number(token.attrGet("start")) } : {}) }, inner)); + else result.push({inner}); + } + } + return result; + } + return children(); + } + return
{render(tokens)}
; +} diff --git a/src/client/channel/components/channel-message-content.css b/src/client/channel/components/channel-message-content.css new file mode 100644 index 000000000..4316f7784 --- /dev/null +++ b/src/client/channel/components/channel-message-content.css @@ -0,0 +1,19 @@ +.c3-message-markdown { max-width: 80ch; min-width: 0; } +.c3-message-markdown > :not(:first-child) { margin-top: .6em; } +.c3-message .c3-message-markdown p { white-space: normal; } +.c3-message-markdown :is(ul, ol) { margin-block: .3em; padding-inline-start: 1.6em; } +.c3-message-markdown ul { list-style: disc; } +.c3-message-markdown ol { list-style: decimal; } +.c3-message-markdown li > p { margin: 0; } +.c3-message-markdown blockquote { margin-inline: 0; padding-inline-start: .8em; border-inline-start: 3px solid var(--line); color: var(--muted); } +.c3-message-markdown a { color: var(--action); text-decoration: underline; overflow-wrap: anywhere; } +.c3-message-markdown code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: .9em; } +.c3-message-markdown :not(pre) > code { padding: .12em .3em; border-radius: 4px; background: var(--wall); white-space: pre-wrap; } +.c3-code-block { min-width: 0; border: 1px solid var(--line); border-radius: var(--c3-inset-radius); background: var(--wall); overflow: hidden; } +.c3-code-actions { display: flex; justify-content: flex-end; padding: 3px 5px; border-bottom: 1px solid var(--line); } +.c3-code-block pre { margin: 0; padding: 10px 12px; overflow-x: auto; white-space: pre; tab-size: 4; } +.c3-code-block pre code { white-space: inherit; } +.c3-code-block small { display: block; padding: 0 12px 10px; color: var(--danger); } +@media (hover: none), (any-pointer: coarse) { + .c3-message-markdown > p:only-child { min-height: 44px; padding-block: max(0px, calc((44px - 1lh) / 2)); } +} diff --git a/tests/channel-message-content.test.ts b/tests/channel-message-content.test.ts new file mode 100644 index 000000000..08d13640e --- /dev/null +++ b/tests/channel-message-content.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from "vitest"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { ChannelMessageContent } from "../src/client/channel/components/ChannelMessageContent"; +import { setCopy } from "../src/client/ui/copy"; + +const users = [{ id: "bo", name: "Bo", version: "0".repeat(64) }]; +function render(text: string, mentions: { userId: string; start: number; end: number }[] = []) { + setCopy({ lang: "en", vis: false }); + return renderToStaticMarkup(createElement(ChannelMessageContent, { message: { text, mentions }, users, selfUserId: "bo" })); +} + +test("chat uses readable emphasis, lists, quotes, explicit and automatic links with line breaks", () => { + const html = render("**bold** *italic* ~~gone~~ `literal *code*`\nnext\n\n- one\n- two\n\n> quote\n\n[docs](https://example.org/path) https://example.org/"); + for (const tag of ["strong", "em", "s", "code", "ul", "li", "blockquote", "br", "a"]) expect(html).toContain(`<${tag}`); + expect(html).toContain('rel="noopener noreferrer"'); + expect(html).toContain("literal *code*"); +}); + +test("HTML and images stay literal, unsafe links never become navigation and code stays text", () => { + const html = render(' ![remote](https://example.org/private.png) [bad](javascript:alert(1)) [data](data:text/html,hello)\n\n```html\n\n```'); + expect(html).not.toMatch(/<(?:img|script|iframe)\b/); + expect(html).not.toMatch(/href="(?:javascript:|data:)/); + expect(html).toContain("<script>alert(1)</script>"); + expect(html).toContain("Copy code"); +}); + +test("only confirmed UTF-16 ranges become identity mentions, while code and destinations remain literal", () => { + const text = "😀 **@Bo** and @Fake\n\n`@Bo`\n\n```\n@Bo\n```\n\n[link](https://example.org/@Bo)"; + const starts = [...text.matchAll(/@Bo/g)].map(match => match.index); + const mentions = starts.map(start => ({ userId: "bo", start, end: start + 3 })); + const html = render(text, mentions); + expect(html.match(/@Bo'); + expect(html).toContain("and @Fake"); + expect(html).toContain("@Bo"); + expect(html).toContain('href="https://example.org/@Bo"'); + expect(html).not.toContain("\uE000"); +}); + +test("literal internal-marker-like text cannot forge a mention and code content is not syntax highlighted", () => { + const text = "\uE0000\uE000 **@Bo**\n\n```js\nconst value = '';\n```"; + const start = text.indexOf("@Bo"); + const html = render(text, [{ userId: "bo", start, end: start + 3 }]); + expect(html.match(/ { + const href = "https://example.org/%EE%80%800%EE%80%80"; + const text = `@Bo [literal](${href})`; + const html = render(text, [{ userId: "bo", start: 0, end: 3 }]); + expect(html).toContain(`href="${href}"`); + expect(html.match(/