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.

328 linesCodeBlameRaw
1import {
2 AlertTriangle,
3 Check,
4 Copy,
5 Info,
6 Lightbulb,
7 Link2,
8 MessageSquareWarning,
9 OctagonAlert,
10} from "lucide-react";
11import type { Root } from "hast";
12import type { Components } from "react-markdown";
13import { type ReactNode, createContext, isValidElement, useContext, useEffect, useMemo, useRef, useState } from "react";
14import { Link } from "react-router";
15import rehypeRaw from "rehype-raw";
16import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
17import remarkGfm from "remark-gfm";
18
19import { Button } from "./ui/button";
20import { Checkbox } from "./ui/checkbox";
21import { WeightedLru } from "../lib/content-cache";
22import { type AlertKind, G1T_MENTION_HREF, type MarkdownRepo, rehypeAlerts, rehypeReferences } from "../lib/markdown-plugins";
23import { markdownTree, markdownWeight, renderMarkdownTree } from "../lib/markdown-tree";
24import { imageSource } from "../lib/usercontent";
25import { UserCard } from "./user-card";
26
27/** The text inside a React tree, for anchors and copying. */
28function textOf(node: ReactNode): string {
29 if (node == null || typeof node === "boolean") return "";
30 if (typeof node === "string" || typeof node === "number") return String(node);
31 if (Array.isArray(node)) return node.map(textOf).join("");
32 if (isValidElement<{ children?: ReactNode }>(node)) return textOf(node.props.children);
33 return "";
34}
35
36/** An anchor id for a heading, so sections can be linked to. */
37function slug(children: ReactNode): string {
38 return textOf(children)
39 .toLowerCase()
40 .replace(/[^a-z0-9]+/g, "-")
41 .replace(/^-|-$/g, "");
42}
43
44/** What raw HTML may stay: GitHub's own allow-list, as `rehype-sanitize` ships it. */
45const SCHEMA = {
46 ...defaultSchema,
47 attributes: {
48 ...defaultSchema.attributes,
49 // Fenced blocks say their language in a class.
50 code: [...(defaultSchema.attributes?.code ?? []), ["className", /^language-./]],
51 },
52};
53
54/**
55 * Parsed markdown, by repository and text: parsing and the plugins are
56 * nine tenths of rendering a README, and a page's markdown is rendered
57 * again on every view (and on every revalidation in the browser). The tree
58 * depends only on the text and the repository its references point into
59 * (lib/markdown-tree.ts). A tree takes about 20 bytes a character of its
60 * text, so 400,000 characters of markdown, about 8 MB, per
61 * isolate or tab.
62 */
63const trees = new WeightedLru<{ tree: Root; weight: number }>(400_000, (entry) => entry.weight);
64
65function treeOf(source: string, repo: MarkdownRepo | undefined, workspace: string | undefined): Root {
66 const key = `${repo ? `${repo.namespace}/${repo.name}` : workspace ? `${workspace}/-` : ""}\n${source}`;
67 const kept = trees.get(key);
68 if (kept) return kept.tree;
69 const tree = markdownTree(source, {
70 remarkPlugins: [remarkGfm],
71 rehypePlugins: [rehypeRaw, [rehypeSanitize, SCHEMA], rehypeAlerts, [rehypeReferences, { repo, workspace }]],
72 });
73 trees.set(key, { tree, weight: markdownWeight(source) });
74 return tree;
75}
76
77const ALERT: Record<AlertKind, { title: string; icon: ReactNode; tone: string }> = {
78 note: { title: "Note", icon: <Info size={15} />, tone: "border-info/60 [&_.alert-title]:text-info" },
79 tip: { title: "Tip", icon: <Lightbulb size={15} />, tone: "border-success/60 [&_.alert-title]:text-accent" },
80 important: {
81 title: "Important",
82 icon: <MessageSquareWarning size={15} />,
83 tone: "border-merged/60 [&_.alert-title]:text-merged",
84 },
85 warning: { title: "Warning", icon: <AlertTriangle size={15} />, tone: "border-warn/60 [&_.alert-title]:text-warn" },
86 caution: { title: "Caution", icon: <OctagonAlert size={15} />, tone: "border-danger/60 [&_.alert-title]:text-danger" },
87};
88
89function Heading({ level, children }: { level: 1 | 2 | 3 | 4; children: ReactNode }) {
90 const id = slug(children);
91 const Tag = `h${level}` as const;
92 return (
93 <Tag id={id} className="group relative scroll-mt-20">
94 {children}
95 {id && (
96 <a
97 href={`#${id}`}
98 aria-label="Link to this section"
99 className="ml-2 inline-flex align-middle text-faint no-underline opacity-0 transition-opacity group-hover:opacity-100 hover:text-fg"
100 >
101 <Link2 size={14} />
102 </a>
103 )}
104 </Tag>
105 );
106}
107
108/**
109 * A fenced code block: plain at once, coloured in the browser when its
110 * language is known, with a button to copy it.
111 */
112function CodeBlock({ language, code }: { language: string | null; code: string }) {
113 const [html, setHtml] = useState<string[] | null>(null);
114 const [copied, setCopied] = useState(false);
115 const block = useRef<HTMLPreElement>(null);
116 useEffect(() => {
117 if (!language) return;
118 let cancelled = false;
119 const element = block.current;
120 if (!element) return;
121 const observer = new IntersectionObserver(
122 ([entry]) => {
123 if (!entry?.isIntersecting) return;
124 observer.disconnect();
125 void import("../lib/shiki")
126 .then(async ({ getHighlighter, languageNamed, linesToHtml }) => {
127 const lang = languageNamed(language);
128 if (!lang) return null;
129 return linesToHtml(await getHighlighter(), code, lang);
130 })
131 .then((lines) => {
132 if (!cancelled && lines) setHtml(lines);
133 })
134 .catch(() => {});
135 },
136 { rootMargin: "400px 0px" },
137 );
138 observer.observe(element);
139 return () => {
140 cancelled = true;
141 observer.disconnect();
142 };
143 }, [language, code]);
144 return (
145 <div className="group relative">
146 <pre ref={block}>
147 <code>
148 {html
149 ? html.map((line, index) => (
150 <span key={index} className="block" dangerouslySetInnerHTML={{ __html: line || " " }} />
151 ))
152 : code}
153 </code>
154 </pre>
155 <div className="absolute top-2 right-2 flex items-center gap-2 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100">
156 {language && <span className="font-mono text-[0.6875rem] text-faint">{language}</span>}
157 <Button
158 type="button"
159 aria-label="Copy"
160 onClick={() => {
161 void navigator.clipboard?.writeText(code).then(() => {
162 setCopied(true);
163 setTimeout(() => setCopied(false), 1500);
164 });
165 }}
166 variant="outline"
167 size="inline"
168 className="bg-raised p-1.5 text-muted"
169 >
170 {copied ? <Check size={13} className="text-success" /> : <Copy size={13} />}
171 </Button>
172 </div>
173 </div>
174 );
175}
176
177function isExternal(href: string) {
178 return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("//");
179}
180
181/**
182 * Renders markdown the way people expect from a forge: GitHub flavoured
183 * markdown (tables, task lists, footnotes, strikethrough, autolinks), the
184 * HTML GitHub allows, alerts, highlighted code, heading anchors, and
185 * references (`#12`, `owner/repo#12`, `workspace#12`, `@name`, commit
186 * hashes) read in `repo`, or in `workspace` for a workspace's own text
187 * (lib/refs.ts). Anything an author writes is sanitized, so untrusted
188 * content is safe to pass in.
189 */
190export function Markdown({
191 source,
192 repo,
193 workspace,
194 base,
195 rawBase,
196}: {
197 source: string;
198 /** The repository the text belongs to, for its references. */
199 repo?: MarkdownRepo;
200 /** The workspace the text belongs to when it is no repository's (a work item's), for its references. */
201 workspace?: string;
202 /** Where relative links point, e.g. `/acme/web/blob/main/docs` for a file's own folder. */
203 base?: string;
204 /**
205 * Where relative images point: the same folder's raw files, e.g.
206 * `/acme/web/raw/<commit>/docs`, under `/acme/web/raw/<commit>`. An image
207 * path starting with `/` is from the repository's root.
208 */
209 rawBase?: string;
210}) {
211 // The same text renders to the same elements with the same components, so
212 // a page that revalidates (a live refresh) leaves the text as it is
213 // rather than mounting it again and reloading its pictures. The
214 // components never change: where links and pictures point comes from
215 // context, so a new commit (a README's pictures are that commit's files)
216 // updates their addresses in place rather than replacing every element.
217 const tree = useMemo(() => treeOf(source, repo, workspace), [source, repo?.namespace, repo?.name, workspace]);
218 const rendered = useMemo(() => renderMarkdownTree(tree, COMPONENTS), [tree]);
219 const bases = useMemo(() => ({ base, rawBase }), [base, rawBase]);
220 return (
221 <MarkdownBases.Provider value={bases}>
222 {/* A long word or address breaks rather than widening the page. */}
223 <div className="prose wrap-break-word">{rendered}</div>
224 </MarkdownBases.Provider>
225 );
226}
227
228/** Where a document's relative links (`base`) and pictures (`rawBase`) point. */
229const MarkdownBases = createContext<{ base?: string; rawBase?: string }>({});
230
231/** A link: a reference or mention within the site, an anchor, an address elsewhere, or a file beside the document. */
232function MarkdownLink({ href = "", children, node }: { href?: string; children?: ReactNode; node?: { properties?: unknown } }) {
233 const { base } = useContext(MarkdownBases);
234 const ref = (node?.properties as { dataRef?: string } | undefined)?.dataRef;
235 if (ref === "mention") {
236 // `@name` may be a person (with a card) or a workspace (none).
237 const name = href === G1T_MENTION_HREF ? "g1t" : href.replace(/^\//, "");
238 return (
239 <UserCard username={name}>
240 <Link to={href} prefetch="intent" className="font-medium">
241 {children}
242 </Link>
243 </UserCard>
244 );
245 }
246 if (ref) {
247 return (
248 <Link
249 to={href}
250 prefetch="intent"
251 className={ref === "commit" ? "font-mono text-[0.9em]" : ref === "mention" ? "font-medium" : ""}
252 >
253 {children}
254 </Link>
255 );
256 }
257 if (href.startsWith("#")) return <a href={href}>{children}</a>;
258 if (isExternal(href)) {
259 return (
260 <a href={href} rel="noreferrer nofollow ugc" target="_blank">
261 {children}
262 </a>
263 );
264 }
265 // A link within the site, or relative to the document's folder.
266 const to = href.startsWith("/") || !base ? href : `${base}/${href.replace(/^\.\//, "")}`;
267 return <Link to={to}>{children}</Link>;
268}
269
270/** A picture; a relative one is the document's commit's file. */
271function MarkdownImage({ src, alt }: { src?: unknown; alt?: string }) {
272 const { rawBase } = useContext(MarkdownBases);
273 const at = typeof src === "string" ? imageSource(src, rawBase) : undefined;
274 return <img src={at} alt={alt ?? ""} loading="lazy" className="inline max-w-full rounded" />;
275}
276
277/**
278 * How each element is drawn, made once: a component that is the same on
279 * every render keeps the elements it drew, where a new one (even an
280 * identical function) has React take them down and put them back.
281 */
282const COMPONENTS: Components = {
283 h1: ({ children }) => <Heading level={1}>{children}</Heading>,
284 h2: ({ children }) => <Heading level={2}>{children}</Heading>,
285 h3: ({ children }) => <Heading level={3}>{children}</Heading>,
286 h4: ({ children }) => <Heading level={4}>{children}</Heading>,
287 a: MarkdownLink,
288 blockquote({ children, node }) {
289 const kind = (node?.properties as { dataAlert?: AlertKind } | undefined)?.dataAlert;
290 if (!kind || !ALERT[kind]) return <blockquote>{children}</blockquote>;
291 const alert = ALERT[kind];
292 return (
293 <div className={`markdown-alert border-l-2 py-1 pl-4 ${alert.tone}`}>
294 <p className="alert-title flex items-center gap-2 text-sm font-medium">
295 {alert.icon}
296 {alert.title}
297 </p>
298 <div className="mt-1 [&>*+*]:mt-3">{children}</div>
299 </div>
300 );
301 },
302 pre({ children }) {
303 const code = Array.isArray(children) ? children[0] : children;
304 if (isValidElement<{ className?: string; children?: ReactNode }>(code)) {
305 const language = /language-([\w+-]+)/.exec(code.props.className ?? "")?.[1] ?? null;
306 return <CodeBlock language={language} code={textOf(code.props.children).replace(/\n$/, "")} />;
307 }
308 return <pre>{children}</pre>;
309 },
310 // A wide table scrolls on its own, inside the text, not the page.
311 table: ({ children }) => (
312 <div className="overflow-x-auto">
313 <table className="max-sm:[&_td]:min-w-32 max-sm:[&_th]:whitespace-nowrap">{children}</table>
314 </div>
315 ),
316 input({ type, checked, disabled }) {
317 // Task list boxes: shown, not editable.
318 return type === "checkbox" ? (
319 <Checkbox
320 checked={checked === true}
321 disabled={disabled !== false}
322 aria-label={checked ? "Done" : "Not done"}
323 className="mr-1.5 inline-flex translate-y-0.5 disabled:cursor-default disabled:opacity-100"
324 />
325 ) : null;
326 },
327 img: MarkdownImage,
328};