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.

346 linesCodeBlameRaw
1/**
2 * A doc's page under the shared header: its icon and title, who
3 * edited it and where it came from, agents' suggestions, the live editor
4 * (or its saved Markdown until the editor loads, and for a reader without
5 * script), what is inside it and what links to it, and comments on the
6 * whole doc. The editor and everything it brings load only in the
7 * browser, after the page shows.
8 */
9import type { FolioSuggestion, FoliosLiveEvent, MemberProfile } from "@g1t/contracts";
10import { AlertTriangle, Check, MessageSquareQuote, SmilePlus, Sparkles } from "lucide-react";
11import { type ComponentType, Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
12import { Link, useRevalidator, useRouteLoaderData } from "react-router";
13import { usePageNavigation } from "../../../lib/use-page-navigation";
14
15import { usercontentFrom } from "../../../lib/addresses";
16import { canDo, readingTime } from "../../../lib/folios";
17import { Markdown } from "../../markdown";
18import { TimeAgo } from "../../ui";
19import { Button } from "../../ui/button";
20import { foliosRequest, useFoliosData } from "../actions";
21import { FolioGlyph, type FolioBodyProps } from "../kinds";
22import { Face } from "../parts";
23import { type Who, whoAre } from "../who";
24import type { DocEditorProps } from "./editor";
25import { EditorSkeleton } from "./editor-skeleton";
26import { Discussion, IconPicker, SuggestionCard, type PageThread } from "./page-parts";
27
28/** The BlockNote editor, loaded only in the browser: the server renders the doc's Markdown instead. */
29const DocEditor = lazy((): Promise<{ default: ComponentType<DocEditorProps> }> => (import.meta.env.SSR ? Promise.resolve({ default: () => null }) : import("./editor")));
30
31function useHydrated() {
32 const [hydrated, setHydrated] = useState(false);
33 useEffect(() => setHydrated(true), []);
34 return hydrated;
35}
36
37export default function DocBody({ slug, page, folio, live, role, showComments, onPresence, onFolio, onRole, onError }: FolioBodyProps) {
38 const layout = useFoliosData();
39 const root = useRouteLoaderData("root");
40 const usercontent = usercontentFrom(root);
41 const { navigate } = usePageNavigation();
42 const revalidator = useRevalidator();
43 const hydrated = useHydrated();
44 const editable = canDo(role, "edit");
45 const send = useCallback(
46 async (intent: string, body: Record<string, unknown>, reload = true) => {
47 const done = await foliosRequest(slug, intent, { folio_id: folio.id, ...body });
48 if (!done.ok) onError(done.error.message);
49 else if (reload) void revalidator.revalidate();
50 return done;
51 },
52 [slug, folio.id, onError, revalidator],
53 );
54
55 // The title follows the folio, and anyone renaming it live.
56 const [title, setTitle] = useState(folio.title);
57 const titleFocused = useRef(false);
58 useEffect(() => {
59 if (!titleFocused.current) setTitle(folio.title);
60 }, [folio.title]);
61 const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
62 const saveTitle = (next: string) => {
63 setTitle(next);
64 onFolio({ ...folio, title: next });
65 if (saveTimer.current) clearTimeout(saveTimer.current);
66 saveTimer.current = setTimeout(() => void send("update", { change: { title: next } }, false), 700);
67 };
68
69 const [suggestions, setSuggestions] = useState<FolioSuggestion[]>(page.suggestions);
70 useEffect(() => setSuggestions(page.suggestions), [page.suggestions]);
71 const [threads, setThreads] = useState<PageThread[]>([]);
72 const [names, setNames] = useState<Map<string, Who>>(new Map());
73 useEffect(() => {
74 const keys = threads.flatMap((t) => t.comments.map((c) => c.author));
75 if (keys.some((k) => !names.has(k))) void whoAre(slug, keys).then((found) => setNames((was) => new Map([...was, ...found])));
76 }, [threads, slug, names]);
77
78 const onEvent = useCallback(
79 (event: FoliosLiveEvent) => {
80 if (event.type === "folio.updated") onFolio(event.folio);
81 else if (event.type === "folio.trashed") void revalidator.revalidate();
82 else if (event.type === "access") {
83 onRole(event.role);
84 if (!event.role) navigate(`/${slug}/-/artifacts`);
85 } else if (event.type === "suggestion.created") setSuggestions((was) => [...was.filter((s) => s.id !== event.suggestion.id), event.suggestion]);
86 else if (event.type === "suggestion.updated") setSuggestions((was) => (event.suggestion.status === "open" ? was.map((s) => (s.id === event.suggestion.id ? event.suggestion : s)) : was.filter((s) => s.id !== event.suggestion.id)));
87 else if (event.type === "version.created" || event.type === "folio.staleness" || event.type === "folio.access") void revalidator.revalidate();
88 },
89 [navigate, slug, revalidator, onFolio, onRole],
90 );
91 // The room's notices (a rename, a suggestion, a change of access), from the page's connection.
92 useEffect(() => live?.onEvent(onEvent), [live, onEvent]);
93
94 const decide = async (id: string, decision: "accept" | "reject") => {
95 setSuggestions((was) => was.filter((s) => s.id !== id));
96 const done = await send("decide", { suggestion_id: id, decision }, false);
97 if (!done.ok) void revalidator.revalidate();
98 };
99 const acceptAll = async () => {
100 const all = suggestions;
101 setSuggestions([]);
102 for (const s of all) await send("decide", { suggestion_id: s.id, decision: "accept" }, false);
103 void revalidator.revalidate();
104 };
105
106 const people = useCallback(
107 (key: string): Pick<MemberProfile, "kind" | "id" | "name" | "display_name" | "avatar"> => {
108 const at = key.indexOf(":");
109 const kind = key.slice(0, at) === "agent" ? "agent" : "user";
110 const id = key.slice(at + 1);
111 if (layout?.me.key === key) return { kind: "user", id, name: layout.me.name, display_name: layout.me.display_name, avatar: layout.me.avatar };
112 const found = names.get(key);
113 return { kind, id, name: found?.name ?? "someone", display_name: found?.display_name ?? (kind === "agent" ? "A deleted agent" : "Someone"), avatar: found?.avatar ?? null };
114 },
115 [layout, names],
116 );
117
118 const threadRequest = async (path: string, method: string, body: unknown) => {
119 try {
120 const r = await fetch(`/${slug}/-/artifacts/threads/${folio.id}${path}`, { method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
121 if (!r.ok) {
122 const result = (await r.json().catch(() => null)) as { error?: { message?: string } } | null;
123 onError(result?.error?.message ?? "That comment didn't go through.");
124 return false;
125 }
126 return true;
127 } catch {
128 onError("That comment didn't go through.");
129 return false;
130 }
131 };
132 /** A comment's text as the editor's comments hold it: blocks, with @mentions as mentions. */
133 const commentBody = (text: string) => {
134 const parts: unknown[] = [];
135 for (const piece of text.split(/(@[a-z0-9][a-z0-9-]*)/i)) {
136 const who = piece.startsWith("@") ? layout?.mentionables.find((m) => m.name.toLowerCase() === piece.slice(1).toLowerCase()) : null;
137 if (who) parts.push({ type: "mention", props: { kind: who.kind, id: who.id, name: who.name, href: "" } });
138 else if (piece) parts.push({ type: "text", text: piece, styles: {} });
139 }
140 return [{ type: "paragraph", content: parts, children: [] }];
141 };
142
143 const reading = useMemo(() => readingTime(page.text), [page.text]);
144 const trashed = !!folio.trashed_at;
145
146 return (
147 <div className="-mt-6">
148 <article className={`mx-auto pt-10 ${showComments ? "max-w-6xl" : "max-w-3xl"}`}>
149 <div className={showComments ? "xl:max-w-3xl" : ""}>
150 {trashed && (
151 <p className="mb-6 rounded-lg border border-warn/30 bg-warn/10 px-3 py-2 text-sm text-warn">
152 This is in the trash.{" "}
153 <Link to={`/${slug}/-/artifacts/trash`} className="underline">
154 Open the trash
155 </Link>{" "}
156 to restore it.
157 </p>
158 )}
159 {/* Icon and title. */}
160 <div className="group">
161 {folio.icon && (
162 <IconPicker value={folio.icon} onChange={(icon) => editable && send("update", { change: { icon } })}>
163 <Button type="button" disabled={!editable} aria-label="Change the icon" variant="ghost" size="inline" className="-ml-1 mb-2 rounded-lg p-1 text-5xl leading-none disabled:hover:bg-transparent">
164 {folio.icon}
165 </Button>
166 </IconPicker>
167 )}
168 {editable && !trashed && (
169 <div className="mb-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100">
170 {!folio.icon && (
171 <IconPicker value={null} onChange={(icon) => send("update", { change: { icon } })}>
172 <Button type="button" variant="ghost" size="xs" className="text-faint font-normal">
173 <SmilePlus size={13} /> Add icon
174 </Button>
175 </IconPicker>
176 )}
177 </div>
178 )}
179 {editable && !trashed ? (
180 <textarea
181 value={title}
182 rows={1}
183 placeholder="Untitled"
184 aria-label="Title"
185 onFocus={() => (titleFocused.current = true)}
186 onBlur={() => (titleFocused.current = false)}
187 onChange={(e) => saveTitle(e.target.value.replace(/\n/g, " "))}
188 onKeyDown={(e) => {
189 if (e.key === "Enter") {
190 e.preventDefault();
191 (document.querySelector(".g1t-editor .bn-editor") as HTMLElement | null)?.focus();
192 }
193 }}
194 className="field-sizing-content w-full resize-none bg-transparent font-display text-4xl leading-tight font-semibold tracking-tight text-fg outline-none placeholder:text-faint/60"
195 />
196 ) : (
197 <h1 className="font-display text-4xl leading-tight font-semibold tracking-tight">{folio.title || "Untitled"}</h1>
198 )}
199 </div>
200 {/* Who wrote it, who owns it, where it came from. */}
201 <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-faint">
202 {folio.edited_by && (
203 <span className="flex items-center gap-1.5">
204 <Face who={folio.edited_by} size={16} />
205 Edited by <span className="text-muted">{folio.edited_by.display_name}</span> · <TimeAgo at={folio.edited_at} />
206 </span>
207 )}
208 <span className="flex items-center gap-1.5">
209 Owner <Face who={folio.owner} size={16} /> <span className="text-muted">{folio.owner.display_name}</span>
210 </span>
211 {folio.source && (
212 <Link to={folio.source.href} className="inline-flex items-center gap-1 hover:text-fg">
213 <MessageSquareQuote size={13} /> From a conversation
214 </Link>
215 )}
216 <span>
217 {reading.words.toLocaleString()} words · {reading.minutes} min read
218 </span>
219 {!editable && <span className="rounded-full bg-raised px-2 py-0.5">{role === "comment" ? "Can comment" : "Can view"}</span>}
220 </div>
221 {folio.stale && (
222 <div className="mt-5 flex flex-wrap items-center gap-3 rounded-lg border border-warn/30 bg-warn/8 px-3 py-2.5 text-sm">
223 <AlertTriangle size={15} className="shrink-0 text-warn" />
224 <span className="min-w-0 grow text-fg-soft">Possibly out of date: code this doc cites changed since it was last brought up to date.</span>
225 {editable && (
226 <Button type="button" onClick={() => send("mark_current", {})} variant="link" size="inline" className="text-xs text-warn">
227 It&apos;s current
228 </Button>
229 )}
230 </div>
231 )}
232
233 {/* Agents' suggestions, all together on a narrower screen (beside their blocks on a wide one). */}
234 {suggestions.length > 0 && (
235 <div className="mt-6 rounded-xl border border-accent/30 bg-accent/5 p-3 2xl:hidden">
236 <div className="mb-2 flex items-center gap-2">
237 <Sparkles size={14} className="text-accent" />
238 <span className="grow text-sm font-medium">
239 {suggestions.length} {suggestions.length === 1 ? "suggestion" : "suggestions"} waiting
240 </span>
241 {editable && suggestions.length > 1 && (
242 <Button type="button" onClick={acceptAll} variant="link" size="inline" className="text-xs">
243 Accept all
244 </Button>
245 )}
246 </div>
247 <div className="space-y-2">
248 {suggestions.map((s) => (
249 <SuggestionCard key={s.id} suggestion={s} canDecide={editable} onDecide={decide} compact />
250 ))}
251 </div>
252 </div>
253 )}
254 {suggestions.length > 1 && editable && (
255 <div className="mt-4 hidden justify-end 2xl:flex">
256 <Button type="button" onClick={acceptAll} variant="link" size="sm" className="bg-accent/15 px-3 text-xs hover:bg-accent/25">
257 <Check size={13} /> Accept all {suggestions.length} suggestions
258 </Button>
259 </div>
260 )}
261 </div>
262
263 {/* The doc itself: live once the editor loads; its saved Markdown until then. */}
264 <div className="mt-6">
265 {hydrated && live && !trashed ? (
266 <Suspense fallback={<ReadView markdown={page.text} />}>
267 <DocEditor
268 key={folio.id}
269 slug={slug}
270 folioId={folio.id}
271 provider={live}
272 role={role}
273 me={layout?.me ?? { key: "", name: "", display_name: "", avatar: null }}
274 mentionables={layout?.mentionables ?? []}
275 usercontent={usercontent}
276 suggestions={suggestions}
277 showComments={showComments}
278 onPresence={onPresence}
279 onPageThreads={setThreads}
280 renderSuggestion={(s) => <SuggestionCard suggestion={s} canDecide={editable} onDecide={decide} />}
281 projects={[]}
282 />
283 </Suspense>
284 ) : (
285 <ReadView markdown={page.text} />
286 )}
287 </div>
288
289 <div className={showComments ? "xl:max-w-3xl" : ""}>
290 {(page.children.length > 0 || page.backlinks.length > 0) && (
291 <div className="mt-14 grid gap-6 border-t border-line pt-8 sm:grid-cols-2">
292 {page.children.length > 0 && (
293 <section>
294 <h2 className="mb-2 text-xs font-medium tracking-wide text-faint uppercase">Inside</h2>
295 <ul className="space-y-1">
296 {page.children.map((c) => (
297 <li key={c.id}>
298 <Link to={c.path} className="flex items-center gap-2 rounded-md px-2 py-1 text-sm hover:bg-raised">
299 <FolioGlyph folio={c} /> {c.title || "Untitled"}
300 </Link>
301 </li>
302 ))}
303 </ul>
304 </section>
305 )}
306 {page.backlinks.length > 0 && (
307 <section>
308 <h2 className="mb-2 text-xs font-medium tracking-wide text-faint uppercase">Linked from</h2>
309 <ul className="space-y-1">
310 {page.backlinks.map((c) => (
311 <li key={c.id}>
312 <Link to={c.path} className="flex items-center gap-2 rounded-md px-2 py-1 text-sm hover:bg-raised">
313 <FolioGlyph folio={c} /> {c.title || "Untitled"}
314 </Link>
315 </li>
316 ))}
317 </ul>
318 </section>
319 )}
320 </div>
321 )}
322 {hydrated && (
323 <Discussion
324 threads={threads}
325 people={people}
326 canComment={canDo(role, "comment")}
327 onPost={(text) => threadRequest("", "POST", { initialComment: { body: commentBody(text) }, page_level: true })}
328 onReply={(thread, text) => threadRequest(`/${encodeURIComponent(thread)}/comments`, "POST", { comment: { body: commentBody(text) } })}
329 onResolve={(thread, resolved) => void threadRequest(`/${encodeURIComponent(thread)}/${resolved ? "resolve" : "unresolve"}`, "POST", {})}
330 />
331 )}
332 </div>
333 </article>
334 </div>
335 );
336}
337
338/** The doc as Markdown: what shows before the editor loads, and what a reader without script sees. */
339function ReadView({ markdown }: { markdown: string }) {
340 if (!markdown.trim()) return <EditorSkeleton />;
341 return (
342 <div className="docs-read">
343 <Markdown source={markdown} />
344 </div>
345 );
346}