feat(chat): render Markdown and copy code blocks
This commit is contained in:
1 parent
f2c2fb1051
commit
012f54c484
7 files changed
+264
-13
No files matched your search
@@ -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 && <button type="button" className="c3-message-reference" disabled={!onMessage} onClick={() => onMessage?.(message.reply!.seq)}>
|
||||
<Glyph name="reply" size={14} /><strong>{message.reply.archivedAuthorName ?? users.find(user => user.id === message.reply!.userId)?.name ?? (lang === "zh" ? "用户" : "User")}</strong>
|
||||
<span>{message.reply.text || (lang === "zh" ? "附件" : "Attachment")}</span></button>}
|
||||
{message.text && <p><MessageText message={message} users={users} selfUserId={selfUserId} /></p>}
|
||||
{message.text && <ChannelMessageContent message={message} users={users} selfUserId={selfUserId} />}
|
||||
{message.attachments.map(file => <ChannelAttachment key={file.id} roomId={roomId} messageSeq={message.seq} file={file} client={attachments}
|
||||
inlineImage={message.inlineImages?.[file.id]} />)}
|
||||
<ChannelContentReactions reactions={message.reactions} session={interaction} target={{ messageSeq: message.seq }} disabled={!available}
|
||||
@@ -417,14 +418,3 @@ const MessageRow = memo(function MessageRow({ roomId, message, grouped, name, av
|
||||
</article>
|
||||
</>;
|
||||
});
|
||||
|
||||
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 <span key={index}>{plain}<mark className={`c3-message-mention${mention.userId === selfUserId ? " is-self" : ""}`} title={users.find(user => user.id === mention.userId)?.name}>
|
||||
{message.text.slice(mention.start, mention.end)}</mark></span>;
|
||||
});
|
||||
return <>{parts}{message.text.slice(cursor)}</>;
|
||||
}
|
||||
@@ -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 <div className="c3-code-block">
|
||||
<div className="c3-code-actions"><ChannelAction icon={clipboard.status === "copied" ? "check" : "copy"}
|
||||
label={clipboard.status === "copied" ? (zh ? "已复制" : "Copied") : (zh ? "复制代码" : "Copy code")}
|
||||
quiet disabled={!text} onClick={clipboard.copy} /></div>
|
||||
<pre tabIndex={0}><code>{text}</code></pre>
|
||||
{clipboard.status === "failed" && <small role="status">{zh ? "未能复制,请选择代码后手动复制。" : "Couldn't copy. Select the code and copy it manually."}</small>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** Raw messages stay unchanged. Only confirmed identity ranges become mention marks. */
|
||||
export function ChannelMessageContent({ message, users, selfUserId }: {
|
||||
message: Pick<ChannelMessage, "text" | "mentions">; 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 <mark key={index} className={`c3-message-mention${reference.mention.userId === selfUserId ? " is-self" : ""}`}
|
||||
title={users.find(user => user.id === reference.mention.userId)?.name}>{reference.text}</mark>;
|
||||
});
|
||||
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(<Fragment key={key}>{render(token.children ?? [])}</Fragment>);
|
||||
else if (token.type === "text") result.push(<Fragment key={key}>{plain(token.content)}</Fragment>);
|
||||
else if (token.type === "code_inline") result.push(<code key={key}>{restore(token.content)}</code>);
|
||||
else if (token.type === "fence" || token.type === "code_block") result.push(<CodeBlock key={key} text={restore(token.content)} />);
|
||||
else if (token.type === "softbreak" || token.type === "hardbreak") result.push(<br key={key} />);
|
||||
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)
|
||||
? <a key={key} href={href} target="_blank" rel="noopener noreferrer">{inner}</a> : <Fragment key={key}>{inner}</Fragment>);
|
||||
} 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(<Fragment key={key}>{inner}</Fragment>);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return children();
|
||||
}
|
||||
return <div className="c3-message-markdown">{render(tokens)}</div>;
|
||||
}
|
||||
@@ -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)); }
|
||||
}
|
||||
Reference in new issue
Block a user