Skip to content

Open source CapCut alternative.

TypeScript

perf(site): su rail prefetches every page and answers a click at once

David Le4847258ba289
diff --git a/site/src/app/su/SuSidebar.tsx b/site/src/app/su/SuSidebar.tsx
index c033b120..081883be 100644
--- a/site/src/app/su/SuSidebar.tsx
+++ b/site/src/app/su/SuSidebar.tsx
@@ -1,8 +1,9 @@
"use client";
-import Link from "next/link";
-import { usePathname } from "next/navigation";
+import Link, { useLinkStatus } from "next/link";
+import { usePathname, useRouter } from "next/navigation";
import { ArrowLeft, ChevronRight } from "lucide-react";
+import { useEffect } from "react";
import { SU_NAV, suSurfaceAt } from "@/app/su/nav";
import {
@@ -26,17 +27,51 @@ import {
} from "@/components/ui/sidebar";
import { SU_APP_ORIGIN } from "@/cut/lib/hosts";
+// Every page the rail can open. A section's own address redirects to its
+// first tab, so the tabs are the pages.
+const RAIL_PAGES = SU_NAV.flatMap((surface) =>
+ surface.tabs ? surface.tabs.map((tab) => tab.href) : [surface.href],
+);
+
+/** The clicked row's answer while its page is on the way: the accent fill,
+ * breathing. A link only shows its pending state when the page was not
+ * prefetched, so a warmed click skips straight to the page. Rendered inside
+ * the link, which is where the status is read from. */
+function PendingFill() {
+ const { pending } = useLinkStatus();
+ return (
+ <span
+ aria-hidden
+ data-pending={pending || undefined}
+ className="pointer-events-none absolute inset-0 -z-10 rounded-md bg-sidebar-accent opacity-0 transition-opacity data-pending:animate-pulse data-pending:opacity-100"
+ />
+ );
+}
+
// The super-user section's left rail, the shadcn sidebar with the admin
// surfaces as its menu and a way back to the app pinned to the bottom. A
// section with tabs is a collapsible item that opens onto its tabs; it starts
// open while one of them is showing, and lands on its first tab when clicked.
+//
+// Every page is prefetched when the rail mounts. A link prefetches itself
+// once it is on screen, which leaves the tabs of a closed section cold until
+// the section opens — and a click right after opening it beat the prefetch,
+// so the page arrived from the server with nothing on screen in between.
export function SuSidebar() {
const pathname = usePathname();
+ const router = useRouter();
const here = suSurfaceAt(pathname);
+ useEffect(() => {
+ for (const href of RAIL_PAGES) router.prefetch(href);
+ }, [router]);
+
return (
<SidebarProvider className="min-h-0 w-auto shrink-0">
- <Sidebar collapsible="none" className="w-60 border-r border-sidebar-border">
+ <Sidebar
+ collapsible="none"
+ className="w-60 border-r border-sidebar-border"
+ >
<SidebarHeader className="mb-3 flex-row items-center gap-2.5 px-4 pt-4">
<span className="grid size-9 shrink-0 place-items-center p-0.5">
<img
@@ -47,7 +82,9 @@ export function SuSidebar() {
className="block h-full w-full object-contain"
/>
</span>
- <span className="text-[17px] font-semibold tracking-tight">Super user</span>
+ <span className="text-[17px] font-semibold tracking-tight">
+ Super user
+ </span>
</SidebarHeader>
<SidebarContent>
@@ -62,8 +99,9 @@ export function SuSidebar() {
<SidebarMenuButton
isActive={active}
render={<Link href={href} />}
- className="h-9 px-2.5"
+ className="relative isolate h-9 px-2.5"
>
+ <PendingFill />
<Icon />
<span>{label}</span>
</SidebarMenuButton>
@@ -91,7 +129,9 @@ export function SuSidebar() {
<SidebarMenuSubButton
isActive={active && here.tab === tab}
render={<Link href={tab.href} />}
+ className="relative isolate"
>
+ <PendingFill />
<span>{tab.label}</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
diff --git a/site/src/app/su/loading.tsx b/site/src/app/su/loading.tsx
new file mode 100644
index 00000000..84da2da6
--- /dev/null
+++ b/site/src/app/su/loading.tsx
@@ -0,0 +1,15 @@
+import { Skeleton } from "@/components/ui/skeleton";
+
+// What a page's slot shows from the moment a rail link is clicked until the
+// page arrives. Every surface opens on cards, so the stand-in is a row of
+// them; the page's own skeletons take over once it mounts.
+export default function SuLoading() {
+ return (
+ <div className="grid gap-4 pt-1 sm:grid-cols-2 lg:grid-cols-3">
+ {Array.from({ length: 3 }, (_, i) => (
+ <Skeleton key={i} className="h-[104px] rounded-xl" />
+ ))}
+ <Skeleton className="h-96 rounded-xl sm:col-span-2 lg:col-span-3" />
+ </div>
+ );
+}
diff --git a/site/src/proxy.ts b/site/src/proxy.ts
index ac60eb78..7198e4c4 100644
--- a/site/src/proxy.ts
+++ b/site/src/proxy.ts
@@ -99,13 +99,37 @@ const passesThrough = (pathname: string) =>
// header that says so.
const SU_ROOT = "/su";
-async function suHost(req: NextRequest, pathname: string): Promise<NextResponse> {
- if (underPath(pathname, "/api")) return NextResponse.next();
-
+// The gate's answer is held per cookie for a short while. A page visit is
+// several requests — the document, then the router's prefetch of every page
+// on the rail, each a handful of segment fetches — and every one of them
+// passed through the gate, so a visit cost dozens of session lookups and
+// each prefetch waited on one. The hold is short because the answer decides
+// who is served the section's code; the data routes check the role on every
+// request regardless.
+const GATE_HOLD_MS = 30_000;
+const GATE_HOLD_MAX = 256;
+const gateHeld = new Map<string, { superUser: boolean; until: number }>();
+
+async function gateAnswer(cookie: string): Promise<{ status: number; superUser: boolean }> {
+ const held = gateHeld.get(cookie);
+ if (held && held.until > Date.now()) return { status: 200, superUser: held.superUser };
const account = await fetch(`${SU_APP_ORIGIN}/api/account/me`, {
cache: "no-store",
- headers: { cookie: req.headers.get("cookie") ?? "" },
+ headers: { cookie },
});
+ if (!account.ok) return { status: account.status, superUser: false };
+ const { superUser } = (await account.json()) as { superUser: boolean };
+ if (cookie) {
+ if (gateHeld.size >= GATE_HOLD_MAX) gateHeld.delete(gateHeld.keys().next().value!);
+ gateHeld.set(cookie, { superUser: superUser === true, until: Date.now() + GATE_HOLD_MS });
+ }
+ return { status: 200, superUser: superUser === true };
+}
+
+async function suHost(req: NextRequest, pathname: string): Promise<NextResponse> {
+ if (underPath(pathname, "/api")) return NextResponse.next();
+
+ const account = await gateAnswer(req.headers.get("cookie") ?? "");
if (account.status === 401) {
// The callback has to carry the exact origin sign-in trusts (src/lib/auth.ts),
// so hosted names it from the constant; dev's su.localhost is plain http on
@@ -116,11 +140,10 @@ async function suHost(req: NextRequest, pathname: string): Promise<NextResponse>
`${SU_APP_ORIGIN}/sign-in?callbackURL=${encodeURIComponent(here)}`,
);
}
- if (!account.ok) {
+ if (account.status !== 200) {
return new NextResponse("The super-user gate is unavailable.", { status: 503 });
}
- const { superUser } = (await account.json()) as { superUser: boolean };
- if (superUser !== true) return NextResponse.redirect(`${SU_APP_ORIGIN}/app`);
+ if (!account.superUser) return NextResponse.redirect(`${SU_APP_ORIGIN}/app`);
const url = req.nextUrl.clone();
url.pathname = `${SU_ROOT}${pathname === "/" ? "" : pathname}`;