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