Skip to content
136 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 { Link, data, redirect, useNavigate } from "react-router";
5
6import type { Route } from "./+types/folio";
7import { foliosRequest } from "../../../components/folios/actions";
8import { EditorSkeleton } from "../../../components/folios/doc/editor-skeleton";
9import { FOLIO_KIND_UI } from "../../../components/folios/kinds";
10import type { LiveStatus } from "../../../components/folios/provider";
11import { FolioHeader, type Presence } from "../../../components/folios/shell";
12import { ErrorText } from "../../../components/ui";
13import { page as pageMeta } from "../../../lib/meta";
14import { folios } from "../../../lib/services.server";
15import { requireUser, roleIn } from "../../../lib/session.server";
16
17export function meta({ loaderData: loaded, params, ...args }: Route.MetaArgs) {
18 const f = loaded && "page" in loaded ? loaded.page.folio : null;
19 return pageMeta(args, { title: `${f ? `${f.icon ? `${f.icon} ` : ""}${f.title || "Untitled"}` : "Artifact"} · ${params.owner} · g1t`, description: f?.excerpt, type: "article" });
20}
21
22type Loaded = { page: FolioPage } | { denied: string };
23
24export async function loader({ params, context, request }: Route.LoaderArgs) {
25 const viewer = requireUser(context, request);
26 if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 });
27 const id = folioIdFrom(params.folio);
28 if (!id) throw data(null, { status: 404 });
29 const found = await folios.page(params.owner.toLowerCase(), viewer, id);
30 if (!found.ok) {
31 // One they can't read and one that doesn't exist look the same: both can be asked for.
32 if (found.error.code === "not_found" || found.error.code === "forbidden") return data<Loaded>({ denied: id }, { status: 403 });
33 throw data(null, { status: 503 });
34 }
35 // An old address (renamed since) goes to the current one.
36 const url = new URL(request.url);
37 if (url.pathname !== found.value.folio.path) throw redirect(`${found.value.folio.path}${url.search}`);
38 return { page: found.value } as Loaded;
39}
40
41/** One artifact: the shared header, then its kind's page (a doc's editor, for now). */
42export default function FolioView({ loaderData, params }: Route.ComponentProps) {
43 const slug = params.owner.toLowerCase();
44 if ("denied" in loaderData) return <NeedAccess slug={slug} id={loaderData.denied} />;
45 return <Opened slug={slug} page={loaderData.page} />;
46}
47
48function Opened({ slug, page }: { slug: string; page: FolioPage }) {
49 const navigate = useNavigate();
50 const [folio, setFolio] = useState<Folio>(page.folio);
51 useEffect(() => setFolio(page.folio), [page.folio]);
52 const [role, setRole] = useState<DocRole>(page.folio.viewer_role);
53 useEffect(() => setRole(page.folio.viewer_role), [page.folio.viewer_role, page.folio.id]);
54 const [presence, setPresence] = useState<Presence[]>([]);
55 const [status, setStatus] = useState<LiveStatus>("connecting");
56 const [showComments, setShowComments] = useState(false);
57 const [error, setError] = useState<string | null>(null);
58 const onRole = useCallback((next: DocRole | null) => next && setRole(next), []);
59 const ui = FOLIO_KIND_UI[folio.kind];
60 const Body = ui.Body;
61 return (
62 <div>
63 <FolioHeader
64 slug={slug}
65 folio={{ ...folio, viewer_role: role }}
66 breadcrumbs={page.breadcrumbs}
67 presence={presence}
68 status={status}
69 comments={folio.kind === "doc" ? { open: showComments, onToggle: () => setShowComments(!showComments) } : null}
70 onError={setError}
71 onTrashed={() => navigate(`/${slug}/-/artifacts`)}
72 />
73 {error && (
74 <div className="mx-auto mt-4 max-w-3xl">
75 <ErrorText>{error}</ErrorText>
76 </div>
77 )}
78 {Body ? (
79 <Suspense
80 fallback={
81 <div className="mx-auto max-w-3xl pt-10">
82 <EditorSkeleton />
83 </div>
84 }
85 >
86 <Body slug={slug} page={page} folio={folio} role={role} showComments={showComments} onPresence={setPresence} onStatus={setStatus} onFolio={setFolio} onRole={onRole} onError={setError} />
87 </Suspense>
88 ) : (
89 <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>
90 )}
91 </div>
92 );
93}
94
95/** "You need access": ask the owner and the people with full access, at most once a day. */
96function NeedAccess({ slug, id }: { slug: string; id: string }) {
97 const [state, setState] = useState<"idle" | "busy" | "sent">("idle");
98 const [message, setMessage] = useState("");
99 const [error, setError] = useState<string | null>(null);
100 return (
101 <div className="mx-auto mt-16 flex max-w-md flex-col items-center text-center">
102 <span className="flex size-12 items-center justify-center rounded-full bg-raised text-muted">
103 <Lock size={20} />
104 </span>
105 <h1 className="mt-4 text-xl font-semibold tracking-tight">You need access</h1>
106 <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>
107 {state === "sent" ? (
108 <p className="mt-6 text-sm text-success">Asked. You&apos;ll get a notification when they let you in.</p>
109 ) : (
110 <form
111 className="mt-6 flex w-full flex-col gap-2"
112 onSubmit={async (e) => {
113 e.preventDefault();
114 setState("busy");
115 setError(null);
116 const done = await foliosRequest(slug, "request_access", { folio_id: id, message: message.trim() || null });
117 if (done.ok) setState("sent");
118 else {
119 setState("idle");
120 setError(done.error.message);
121 }
122 }}
123 >
124 <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" />
125 <button type="submit" disabled={state === "busy"} className="inline-flex h-9 items-center justify-center rounded-md bg-accent px-4 text-sm font-medium text-bg hover:bg-accent-hover disabled:opacity-60">
126 {state === "busy" ? "Asking…" : "Ask for access"}
127 </button>
128 {error && <ErrorText>{error}</ErrorText>}
129 </form>
130 )}
131 <Link to={`/${slug}/-/artifacts`} className="mt-6 text-xs text-muted hover:text-fg">
132 Back to Artifacts
133 </Link>
134 </div>
135 );
136}