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