Skip to content
289 linesCodeBlameRaw
1import { Check, Copy } from "lucide-react";
2import { Fragment, type ReactNode, useEffect, useMemo, useState } from "react";
3import { Link } from "react-router";
4
5import { MemberCard } from "./profile-card";
6import { Button } from "../ui/button";
7import { Hint } from "../ui/hint";
8import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
9import { type Block, type Span, blocks, onlyEmoji } from "../../lib/chat";
10// The workspace's own emoji, drawn where `:name:` is written (components/emoji).
11import { useEmojiContext } from "../emoji/context";
12import { renderEmoji } from "../emoji/render";
13import { onlyEmojiOrCustom } from "../../lib/emoji";
14
15/** How the text's references resolve, from what the page knows. */
16export type TextContext = {
17 slug: string;
18 /** The viewer's username: a mention of them stands out more. */
19 me: string | null;
20 /** Handles of the workspace's agents: their mentions go to the agent. */
21 agents: ReadonlySet<string>;
22 /**
23 * Who each lowercased handle is (`mentionNames`): a mention shows as
24 * `@Ana Lima`, the name people know. The text keeps `@ana`.
25 */
26 names?: ReadonlyMap<string, string>;
27 /** Channels by name, for `#name`. */
28 channels: ReadonlySet<string>;
29 /** The project `#123` means when no repository is named, if any. */
30 project: string | null;
31 /** Where a link into Code goes instead, for a member without Code access. */
32 codeLink?: (href: string) => string;
33};
34
35const PILL = "rounded-[4px] px-1 py-px font-medium";
36
37function SpanView({ span, context }: { span: Span; context: TextContext }): ReactNode {
38 const emoji = useEmojiContext();
39 switch (span.t) {
40 case "text":
41 return renderEmoji(span.v, emoji.byName, emoji.usercontent);
42 case "code":
43 return <code className="rounded-[4px] border border-line bg-raised px-1 py-px font-mono text-[0.84em] text-fg-soft">{span.v}</code>;
44 case "strong":
45 return <strong className="font-semibold text-fg">{spans(span.c, context)}</strong>;
46 case "em":
47 return <em>{spans(span.c, context)}</em>;
48 case "del":
49 return <del className="text-muted">{spans(span.c, context)}</del>;
50 case "link": {
51 if (span.href.startsWith("/")) {
52 return (
53 <Link to={context.codeLink ? context.codeLink(span.href) : span.href} className="text-accent underline-offset-2 hover:underline">
54 {spans(span.c, context)}
55 </Link>
56 );
57 }
58 return (
59 <a href={span.href} target="_blank" rel="noopener noreferrer nofollow ugc" className="text-accent underline-offset-2 hover:underline">
60 {spans(span.c, context)}
61 </a>
62 );
63 }
64 case "mention": {
65 const name = span.name.toLowerCase();
66 const self = context.me != null && name === context.me.toLowerCase();
67 const agent = context.agents.has(name);
68 const to = agent ? `/${context.slug}/-/agents/${name}` : name.includes("/") ? `/${context.slug}/-/teams/${name.split("/")[1]}` : `/u/${name}`;
69 const pill = `${PILL} transition-colors ${self ? "bg-warn/20 text-warn hover:bg-warn/30" : "bg-accent/15 text-accent hover:bg-accent/25"}`;
70 // A person or an agent: their card. A team: its page.
71 if (name.includes("/")) {
72 return (
73 <Link to={to} className={pill}>
74 @{span.name}
75 </Link>
76 );
77 }
78 const shown = context.names?.get(name);
79 return (
80 <MemberCard member={{ kind: agent ? "agent" : "user", name, display_name: shown }} className={`inline ${pill}`}>
81 @{shown ?? span.name}
82 </MemberCard>
83 );
84 }
85 case "channel":
86 return context.channels.has(span.name) ? (
87 <Link to={`/${context.slug}/-/chat/${span.name}`} className={`${PILL} bg-accent/10 text-accent hover:bg-accent/20`}>
88 #{span.name}
89 </Link>
90 ) : (
91 `#${span.name}`
92 );
93 case "ref": {
94 const repo = span.repo ? (span.repo.includes("/") ? span.repo : `${context.slug}/${span.repo}`) : context.project ? `${context.slug}/${context.project}` : null;
95 const label = `${span.repo ? span.repo : ""}#${span.number}`;
96 if (!repo) return <span className="font-medium text-fg-soft">{label}</span>;
97 // Issues and pull requests share numbers; the issue page sends a pull on.
98 const href = `/${repo}/issues/${span.number}`;
99 return (
100 <Link to={context.codeLink ? context.codeLink(href) : href} className="font-medium text-accent hover:underline">
101 {label}
102 </Link>
103 );
104 }
105 }
106}
107
108function spans(list: Span[], context: TextContext): ReactNode {
109 return list.map((span, index) => <SpanView key={index} span={span} context={context} />);
110}
111
112function lines(list: Span[][], context: TextContext): ReactNode {
113 return list.map((line, index) => (
114 <Fragment key={index}>
115 {index > 0 && <br />}
116 {spans(line, context)}
117 </Fragment>
118 ));
119}
120
121/** A run of blocks, a little apart. */
122function BlocksView({ list, context, className = "space-y-1.5" }: { list: Block[]; context: TextContext; className?: string }) {
123 return (
124 <div className={className}>
125 {list.map((block, index) => (
126 <BlockView key={index} block={block} context={context} />
127 ))}
128 </div>
129 );
130}
131
132function ListItem({ item, context }: { item: Block[]; context: TextContext }) {
133 // An item of one paragraph is its lines; one with more holds its blocks.
134 if (item.length === 1 && item[0]!.t === "p") return <li className="pl-0.5">{lines(item[0]!.lines, context)}</li>;
135 return (
136 <li className="pl-0.5">
137 <BlocksView list={item} context={context} className="space-y-1" />
138 </li>
139 );
140}
141
142function BlockView({ block, context }: { block: Block; context: TextContext }) {
143 switch (block.t) {
144 case "p":
145 return <p>{lines(block.lines, context)}</p>;
146 case "heading":
147 // Chat, not a document: a heading is a bold line with room above it, the top two a touch larger.
148 return <p className={`pt-1.5 font-semibold tracking-[-0.005em] text-fg first:pt-0 ${block.level <= 2 ? "text-base" : ""}`}>{spans(block.c, context)}</p>;
149 case "table":
150 return <TableView block={block} context={context} />;
151 case "hr":
152 return <hr className="my-2 border-line" />;
153 case "code":
154 return <CodeBlock language={block.lang} code={block.v} />;
155 case "list": {
156 const Tag = block.ordered ? "ol" : "ul";
157 return (
158 <Tag start={block.ordered && block.start !== 1 ? block.start : undefined} className={`space-y-0.5 pl-5 ${block.ordered ? "list-decimal" : "list-disc"} marker:text-faint`}>
159 {block.items.map((item, index) => (
160 <ListItem key={index} item={item} context={context} />
161 ))}
162 </Tag>
163 );
164 }
165 case "quote":
166 return (
167 <blockquote className="border-l-2 border-line-strong pl-3 text-muted">
168 <BlocksView list={block.c} context={context} className="space-y-1" />
169 </blockquote>
170 );
171 }
172}
173
174/**
175 * A table, as the theme draws tables in rendered Markdown: a quiet header
176 * row, lines between rows, and its columns aligned as written. A wide one
177 * scrolls sideways inside the message, never the page, and takes focus so
178 * it can be scrolled from the keyboard.
179 */
180function TableView({ block, context }: { block: Extract<Block, { t: "table" }>; context: TextContext }) {
181 const align = (index: number) => block.align[index] ?? undefined;
182 return (
183 <Table frameProps={{ role: "region", "aria-label": "Table", tabIndex: 0, className: "my-1 rounded-lg border border-line" }} className="min-w-max text-[0.8125rem] leading-snug sm:min-w-full">
184 <TableHeader>
185 <TableRow>
186 {block.head.map((cell, index) => (
187 <TableHead key={index} scope="col" style={{ textAlign: align(index) }}>
188 {spans(cell, context)}
189 </TableHead>
190 ))}
191 </TableRow>
192 </TableHeader>
193 <TableBody>
194 {block.rows.map((row, at) => (
195 <TableRow key={at}>
196 {row.map((cell, index) => (
197 <TableCell key={index} style={{ textAlign: align(index) }} className={align(index) === "right" ? "whitespace-nowrap tabular-nums" : "max-w-lg"}>
198 {spans(cell, context)}
199 </TableCell>
200 ))}
201 </TableRow>
202 ))}
203 </TableBody>
204 </Table>
205 );
206}
207
208type Token = { content: string; color?: string };
209
210/**
211 * Fenced code: plain at once, coloured once the highlighter has loaded
212 * when its language is one g1t knows (lib/shiki.ts), with a copy button.
213 * The colours are tokens drawn as text, never HTML.
214 */
215function CodeBlock({ language, code }: { language: string | null; code: string }) {
216 const [rows, setRows] = useState<Token[][] | null>(null);
217 const [copied, setCopied] = useState(false);
218 useEffect(() => {
219 setRows(null);
220 if (!language || code.length > 20_000) return;
221 let cancelled = false;
222 void import("../../lib/shiki")
223 .then(async ({ getHighlighter, languageNamed, tokenRows }) => {
224 const lang = languageNamed(language);
225 if (!lang) return null;
226 return tokenRows(await getHighlighter(), code, lang);
227 })
228 .then((tokens) => {
229 if (!cancelled && tokens) setRows(tokens);
230 })
231 .catch(() => {});
232 return () => {
233 cancelled = true;
234 };
235 }, [language, code]);
236 return (
237 <div className="group/code relative my-1">
238 <pre className="overflow-x-auto rounded-md border border-line bg-bg px-3 py-2 pointer-coarse:pr-10 font-mono text-[0.8125rem] leading-relaxed text-fg-soft [scrollbar-width:thin]">
239 <code>
240 {rows
241 ? rows.map((row, index) => (
242 <span key={index} className="block min-h-lh">
243 {row.map((token, at) => (
244 <span key={at} style={token.color ? { color: token.color } : undefined}>
245 {token.content}
246 </span>
247 ))}
248 </span>
249 ))
250 : code}
251 </code>
252 </pre>
253 <div className="absolute top-1.5 right-1.5 flex items-center gap-2 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100">
254 {language && <span className="font-mono text-[0.6875rem] text-faint pointer-coarse:hidden">{language}</span>}
255 <Hint label={copied ? "Copied" : "Copy code"}>
256 <Button
257 type="button"
258 aria-label="Copy code"
259 onClick={() => {
260 void navigator.clipboard?.writeText(code).then(() => {
261 setCopied(true);
262 setTimeout(() => setCopied(false), 1500);
263 });
264 }}
265 variant="outline" size="icon"
266 className="size-6 bg-raised text-muted"
267 >
268 {copied ? <Check size={12} className="text-success" /> : <Copy size={12} />}
269 </Button>
270 </Hint>
271 </div>
272 </div>
273 );
274}
275
276/** A message's text, rendered from parsed blocks: never as HTML. */
277export function MessageText({ body, context }: { body: string; context: TextContext }) {
278 const parsed = useMemo(() => blocks(body), [body]);
279 const emoji = useEmojiContext();
280 if (onlyEmoji(body)) return <p className="text-3xl leading-tight">{body.trim()}</p>;
281 if (onlyEmojiOrCustom(body, emoji.byName)) return <p className="text-3xl leading-tight">{renderEmoji(body.trim(), emoji.byName, emoji.usercontent, 32)}</p>;
282 return (
283 <div className="space-y-1.5 text-[0.9375rem] leading-[1.55] break-words text-fg-soft">
284 {parsed.map((block, index) => (
285 <BlockView key={index} block={block} context={context} />
286 ))}
287 </div>
288 );
289}