Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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