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.

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