| 1 | import { FOLIO_KIND_NOUNS, folioIdFrom, type DocRole, type Folio, type FolioPage } from "@g1t/contracts"; |
| 2 | import { Lock } from "lucide-react"; |
| 3 | import { Suspense, useCallback, useEffect, useState } from "react"; |
| 4 | import { type HtmlLinkDescriptor, Link, data, redirect, useNavigate } from "react-router"; |
| 5 | import editorChunk from "virtual:g1t-editor-chunk"; |
| 6 | |
| 7 | import type { Route } from "./+types/folio"; |
| 8 | import { foliosRequest } from "../../../components/folios/actions"; |
| 9 | import { EditorSkeleton } from "../../../components/folios/doc/editor-skeleton"; |
| 10 | import { FOLIO_KIND_UI } from "../../../components/folios/kinds"; |
| 11 | import { FolioProvider, type LiveStatus, pageStateBytes } from "../../../components/folios/provider"; |
| 12 | import { FolioHeader, type Presence } from "../../../components/folios/shell"; |
| 13 | import { ErrorText } from "../../../components/ui"; |
| 14 | import { Button } from "../../../components/ui/button"; |
| 15 | import { type OfferedTicket, offerTicket } from "../../../lib/live-socket"; |
| 16 | import { page as pageMeta } from "../../../lib/meta"; |
| 17 | import { folios } from "../../../lib/services.server"; |
| 18 | import { requireUser, roleIn } from "../../../lib/session.server"; |
| 19 | import { socketTicketFor } from "../../../lib/socket-ticket.server"; |
| 20 | |
| 21 | export function meta({ loaderData: loaded, params, ...args }: Route.MetaArgs) { |
| 22 | const f = loaded && "page" in loaded ? loaded.page.folio : null; |
| 23 | return pageMeta(args, { title: `${f ? `${f.icon ? `${f.icon} ` : ""}${f.title || "Untitled"}` : "Artifact"} · ${params.owner} · g1t`, description: f?.excerpt, type: "article" }); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * The doc editor's code and what it imports, fetched with the page rather |
| 28 | * than after the page's own code has run and asked for them. The server |
| 29 | * knows the files (vite.config.ts `editorChunk`); the browser reads them |
| 30 | * back from the page the server sent, so both render the same links. |
| 31 | */ |
| 32 | function editorFiles(): string[] { |
| 33 | if (editorChunk.length) return editorChunk; |
| 34 | if (typeof document === "undefined") return []; |
| 35 | return [...document.querySelectorAll('link[rel="modulepreload"][data-doc-editor]')].map((link) => link.getAttribute("href") ?? "").filter(Boolean); |
| 36 | } |
| 37 | |
| 38 | export const links: Route.LinksFunction = () => editorFiles().map((href) => ({ rel: "modulepreload", href, "data-doc-editor": "" }) as unknown as HtmlLinkDescriptor); |
| 39 | |
| 40 | /** The live socket's path in this workspace (lib/socket-ticket.ts `socketPath`). */ |
| 41 | const livePath = (slug: string) => `/${slug}/-/artifacts/live`; |
| 42 | |
| 43 | type Loaded = { page: FolioPage; ticket: OfferedTicket | null } | { denied: string }; |
| 44 | |
| 45 | export async function loader({ params, context, request }: Route.LoaderArgs) { |
| 46 | const viewer = requireUser(context, request); |
| 47 | if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 }); |
| 48 | const id = folioIdFrom(params.folio); |
| 49 | if (!id) throw data(null, { status: 404 }); |
| 50 | const slug = params.owner.toLowerCase(); |
| 51 | // A page opened with an access token gets its room's socket ticket with |
| 52 | // the page, so the socket opens without asking for one (lib/live-socket.ts). |
| 53 | const [found, ticket] = await Promise.all([folios.page(slug, viewer, id), socketTicketFor(context, request, livePath(slug))]); |
| 54 | if (!found.ok) { |
| 55 | // One they can't read and one that doesn't exist look the same: both can be asked for. |
| 56 | if (found.error.code === "not_found" || found.error.code === "forbidden") return data<Loaded>({ denied: id }, { status: 403 }); |
| 57 | throw data(null, { status: 503 }); |
| 58 | } |
| 59 | // An old address (renamed since) goes to the current one. |
| 60 | const url = new URL(request.url); |
| 61 | if (url.pathname !== found.value.folio.path) throw redirect(`${found.value.folio.path}${url.search}`); |
| 62 | return { page: found.value, ticket } as Loaded; |
| 63 | } |
| 64 | |
| 65 | /** One artifact: the shared header, then its kind's page (a doc's editor, for now). */ |
| 66 | export default function FolioView({ loaderData, params }: Route.ComponentProps) { |
| 67 | const slug = params.owner.toLowerCase(); |
| 68 | if ("denied" in loaderData) return <NeedAccess slug={slug} id={loaderData.denied} />; |
| 69 | return <Opened slug={slug} page={loaderData.page} ticket={loaderData.ticket} />; |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * The page connects to the folio's room as soon as it hydrates, before |
| 74 | * the body's code (and the editor's, far larger) has arrived, and seeds |
| 75 | * the document from the state the page carried, so the editor opens on |
| 76 | * it at once and the room sends only what changed since. The room never |
| 77 | * gates the page: the text is readable from the first byte, the editor |
| 78 | * works before the room answers, and the header's dot says when it has. |
| 79 | */ |
| 80 | function useLive(slug: string, page: FolioPage, ticket: OfferedTicket | null): { live: FolioProvider | null; status: LiveStatus } { |
| 81 | const [live, setLive] = useState<FolioProvider | null>(null); |
| 82 | const [status, setStatus] = useState<LiveStatus>("connecting"); |
| 83 | const id = page.folio.id; |
| 84 | const state = page.state; |
| 85 | useEffect(() => { |
| 86 | offerTicket(livePath(slug), ticket); |
| 87 | const scheme = window.location.protocol === "https:" ? "wss" : "ws"; |
| 88 | const provider = new FolioProvider(`${scheme}://${window.location.host}${livePath(slug)}?folio=${encodeURIComponent(id)}`, { state: pageStateBytes(state) }); |
| 89 | const off = provider.onStatus(setStatus); |
| 90 | setLive(provider); |
| 91 | return () => { |
| 92 | off(); |
| 93 | provider.destroy(); |
| 94 | setLive(null); |
| 95 | }; |
| 96 | // The same folio keeps its connection through a revalidation; only another folio reconnects. |
| 97 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 98 | }, [slug, id]); |
| 99 | return { live, status }; |
| 100 | } |
| 101 | |
| 102 | function Opened({ slug, page, ticket }: { slug: string; page: FolioPage; ticket: OfferedTicket | null }) { |
| 103 | const navigate = useNavigate(); |
| 104 | const [folio, setFolio] = useState<Folio>(page.folio); |
| 105 | useEffect(() => setFolio(page.folio), [page.folio]); |
| 106 | const [role, setRole] = useState<DocRole>(page.folio.viewer_role); |
| 107 | useEffect(() => setRole(page.folio.viewer_role), [page.folio.viewer_role, page.folio.id]); |
| 108 | const [presence, setPresence] = useState<Presence[]>([]); |
| 109 | const { live, status } = useLive(slug, page, ticket); |
| 110 | const [showComments, setShowComments] = useState(false); |
| 111 | const [error, setError] = useState<string | null>(null); |
| 112 | const onRole = useCallback((next: DocRole | null) => next && setRole(next), []); |
| 113 | const ui = FOLIO_KIND_UI[folio.kind]; |
| 114 | const Body = ui.Body; |
| 115 | return ( |
| 116 | <div> |
| 117 | <FolioHeader |
| 118 | slug={slug} |
| 119 | folio={{ ...folio, viewer_role: role }} |
| 120 | breadcrumbs={page.breadcrumbs} |
| 121 | presence={presence} |
| 122 | status={status} |
| 123 | comments={folio.kind === "doc" ? { open: showComments, onToggle: () => setShowComments(!showComments) } : null} |
| 124 | onError={setError} |
| 125 | onTrashed={() => navigate(`/${slug}/-/artifacts`)} |
| 126 | /> |
| 127 | {error && ( |
| 128 | <div className="mx-auto mt-4 max-w-3xl"> |
| 129 | <ErrorText>{error}</ErrorText> |
| 130 | </div> |
| 131 | )} |
| 132 | {Body ? ( |
| 133 | <Suspense |
| 134 | fallback={ |
| 135 | <div className="mx-auto max-w-3xl pt-10"> |
| 136 | <EditorSkeleton /> |
| 137 | </div> |
| 138 | } |
| 139 | > |
| 140 | <Body slug={slug} page={page} folio={folio} live={live} role={role} showComments={showComments} onPresence={setPresence} onFolio={setFolio} onRole={onRole} onError={setError} /> |
| 141 | </Suspense> |
| 142 | ) : ( |
| 143 | <p className="mx-auto mt-16 max-w-md text-center text-sm text-muted">This is a {FOLIO_KIND_NOUNS[folio.kind]}. Opening {ui.label.toLowerCase()} here is coming soon.</p> |
| 144 | )} |
| 145 | </div> |
| 146 | ); |
| 147 | } |
| 148 | |
| 149 | /** "You need access": ask the owner and the people with full access, at most once a day. */ |
| 150 | function NeedAccess({ slug, id }: { slug: string; id: string }) { |
| 151 | const [state, setState] = useState<"idle" | "busy" | "sent">("idle"); |
| 152 | const [message, setMessage] = useState(""); |
| 153 | const [error, setError] = useState<string | null>(null); |
| 154 | return ( |
| 155 | <div className="mx-auto mt-16 flex max-w-md flex-col items-center text-center"> |
| 156 | <span className="flex size-12 items-center justify-center rounded-full bg-raised text-muted"> |
| 157 | <Lock size={20} /> |
| 158 | </span> |
| 159 | <h1 className="mt-4 text-xl font-semibold tracking-tight">You need access</h1> |
| 160 | <p className="mt-1 text-sm text-muted">Ask for access, and its owner hears of it. If it was deleted, nobody can open it any more.</p> |
| 161 | {state === "sent" ? ( |
| 162 | <p className="mt-6 text-sm text-success">Asked. You'll get a notification when they let you in.</p> |
| 163 | ) : ( |
| 164 | <form |
| 165 | className="mt-6 flex w-full flex-col gap-2" |
| 166 | onSubmit={async (e) => { |
| 167 | e.preventDefault(); |
| 168 | setState("busy"); |
| 169 | setError(null); |
| 170 | const done = await foliosRequest(slug, "request_access", { folio_id: id, message: message.trim() || null }); |
| 171 | if (done.ok) setState("sent"); |
| 172 | else { |
| 173 | setState("idle"); |
| 174 | setError(done.error.message); |
| 175 | } |
| 176 | }} |
| 177 | > |
| 178 | <input aria-label="Message" placeholder="Add a message (optional)" value={message} onChange={(e) => setMessage(e.target.value)} maxLength={500} className="h-9 w-full rounded-md border border-line bg-bg px-3 text-sm outline-none focus:border-accent/60" /> |
| 179 | <Button type="submit" disabled={state === "busy"} variant="accent" className="px-4 disabled:opacity-60"> |
| 180 | {state === "busy" ? "Asking…" : "Ask for access"} |
| 181 | </Button> |
| 182 | {error && <ErrorText>{error}</ErrorText>} |
| 183 | </form> |
| 184 | )} |
| 185 | <Link to={`/${slug}/-/artifacts`} className="mt-6 text-xs text-muted hover:text-fg"> |
| 186 | Back to Artifacts |
| 187 | </Link> |
| 188 | </div> |
| 189 | ); |
| 190 | } |