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