Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

App shell: sidebar that remembers itself, branded 404/error, route skeletons

Claude6d464118626e
diff --git a/src/app/(studio)/apps/loading.tsx b/src/app/(studio)/apps/loading.tsx
new file mode 100644
index 00000000..4f32d025
--- /dev/null
+++ b/src/app/(studio)/apps/loading.tsx
@@ -0,0 +1,5 @@
+import { GalleryPageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <GalleryPageSkeleton title="Apps" />;
+}
diff --git a/src/app/(studio)/effects/loading.tsx b/src/app/(studio)/effects/loading.tsx
new file mode 100644
index 00000000..05300cc2
--- /dev/null
+++ b/src/app/(studio)/effects/loading.tsx
@@ -0,0 +1,5 @@
+import { GalleryPageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <GalleryPageSkeleton title="Effects" />;
+}
diff --git a/src/app/(studio)/elements/[id]/page.tsx b/src/app/(studio)/elements/[id]/page.tsx
index ca2a30ef..6624ab21 100644
--- a/src/app/(studio)/elements/[id]/page.tsx
+++ b/src/app/(studio)/elements/[id]/page.tsx
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Suspense } from "react";
-import { ElementStudio } from "@/components/elements-view";
+import { ElementStudio } from "@/components/element-studio";
+import { StudioSkeleton } from "@/components/skeletons";
export const metadata: Metadata = { title: "Element" };
@@ -11,7 +12,7 @@ async function Studio({ params }: { params: PageProps<"/elements/[id]">["params"
export default function Page({ params }: PageProps<"/elements/[id]">) {
return (
- <Suspense fallback={null}>
+ <Suspense fallback={<StudioSkeleton />}>
<Studio params={params} />
</Suspense>
);
diff --git a/src/app/(studio)/elements/loading.tsx b/src/app/(studio)/elements/loading.tsx
new file mode 100644
index 00000000..69ee2c2e
--- /dev/null
+++ b/src/app/(studio)/elements/loading.tsx
@@ -0,0 +1,5 @@
+import { PageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <PageSkeleton title="Elements" rows={2} />;
+}
diff --git a/src/app/(studio)/error.tsx b/src/app/(studio)/error.tsx
new file mode 100644
index 00000000..3b06ba0d
--- /dev/null
+++ b/src/app/(studio)/error.tsx
@@ -0,0 +1,12 @@
+"use client";
+
+import { useEffect } from "react";
+import { ErrorState } from "@/components/empty-state";
+
+/** Catches render errors in any studio page; the sidebar (layout) stays usable. */
+export default function Error({ error, retry }: { error: unknown; retry: () => void }) {
+ useEffect(() => {
+ console.error(error);
+ }, [error]);
+ return <ErrorState error={error} retry={retry} />;
+}
diff --git a/src/app/(studio)/layout.tsx b/src/app/(studio)/layout.tsx
index 381172e9..c5e759ca 100644
--- a/src/app/(studio)/layout.tsx
+++ b/src/app/(studio)/layout.tsx
@@ -1,17 +1,5 @@
-import { AppSidebar } from "@/components/app-sidebar";
-import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
-import { GlobalShortcuts } from "@/components/global-shortcuts";
+import { StudioChrome } from "@/components/app-sidebar";
export default function StudioLayout({ children }: { children: React.ReactNode }) {
- return (
- <SidebarProvider
- style={{ "--sidebar-width": "15.5rem", "--sidebar-width-icon": "3.25rem" } as React.CSSProperties}
- >
- <AppSidebar />
- <SidebarInset className="min-h-svh min-w-0 md:m-0 md:mt-2 md:rounded-none md:rounded-tl-xl md:border-l-[0.5px] md:border-t-[0.5px] md:shadow-[-2px_0_6px_rgba(0,0,0,.02)] md:peer-data-[variant=inset]:m-0 md:peer-data-[variant=inset]:mt-2 md:peer-data-[variant=inset]:rounded-none md:peer-data-[variant=inset]:rounded-tl-xl">
- {children}
- </SidebarInset>
- <GlobalShortcuts />
- </SidebarProvider>
- );
+ return <StudioChrome>{children}</StudioChrome>;
}
diff --git a/src/app/(studio)/library/loading.tsx b/src/app/(studio)/library/loading.tsx
new file mode 100644
index 00000000..b11d4dca
--- /dev/null
+++ b/src/app/(studio)/library/loading.tsx
@@ -0,0 +1,5 @@
+import { PageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <PageSkeleton title="Library" wide rows={3} />;
+}
diff --git a/src/app/(studio)/loading.tsx b/src/app/(studio)/loading.tsx
new file mode 100644
index 00000000..ed76b86b
--- /dev/null
+++ b/src/app/(studio)/loading.tsx
@@ -0,0 +1,5 @@
+import { StudioSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <StudioSkeleton />;
+}
diff --git a/src/app/(studio)/models/loading.tsx b/src/app/(studio)/models/loading.tsx
new file mode 100644
index 00000000..4bacd315
--- /dev/null
+++ b/src/app/(studio)/models/loading.tsx
@@ -0,0 +1,5 @@
+import { PageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <PageSkeleton title="Models" wide rows={6} />;
+}
diff --git a/src/app/(studio)/motions/loading.tsx b/src/app/(studio)/motions/loading.tsx
new file mode 100644
index 00000000..7e775eb5
--- /dev/null
+++ b/src/app/(studio)/motions/loading.tsx
@@ -0,0 +1,5 @@
+import { GalleryPageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <GalleryPageSkeleton title="Camera motions" />;
+}
diff --git a/src/app/(studio)/not-found.tsx b/src/app/(studio)/not-found.tsx
new file mode 100644
index 00000000..bd480414
--- /dev/null
+++ b/src/app/(studio)/not-found.tsx
@@ -0,0 +1,6 @@
+import { NotFoundState } from "@/components/empty-state";
+
+/** Shown inside the app shell when a studio page calls notFound() (unknown app, element…). */
+export default function NotFound() {
+ return <NotFoundState />;
+}
diff --git a/src/app/(studio)/settings/loading.tsx b/src/app/(studio)/settings/loading.tsx
new file mode 100644
index 00000000..1b332687
--- /dev/null
+++ b/src/app/(studio)/settings/loading.tsx
@@ -0,0 +1,5 @@
+import { PageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <PageSkeleton title="Settings" />;
+}
diff --git a/src/app/(studio)/status/loading.tsx b/src/app/(studio)/status/loading.tsx
new file mode 100644
index 00000000..27921b49
--- /dev/null
+++ b/src/app/(studio)/status/loading.tsx
@@ -0,0 +1,5 @@
+import { PageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <PageSkeleton title="Project status" rows={6} />;
+}
diff --git a/src/app/(studio)/workflows/loading.tsx b/src/app/(studio)/workflows/loading.tsx
new file mode 100644
index 00000000..dc29ccf9
--- /dev/null
+++ b/src/app/(studio)/workflows/loading.tsx
@@ -0,0 +1,5 @@
+import { PageSkeleton } from "@/components/skeletons";
+
+export default function Loading() {
+ return <PageSkeleton title="ComfyUI workflows" wide />;
+}
diff --git a/src/app/not-found.tsx b/src/app/not-found.tsx
new file mode 100644
index 00000000..88523159
--- /dev/null
+++ b/src/app/not-found.tsx
@@ -0,0 +1,14 @@
+import type { Metadata } from "next";
+import { StudioChrome } from "@/components/app-sidebar";
+import { NotFoundState } from "@/components/empty-state";
+
+export const metadata: Metadata = { title: "Not found" };
+
+/** Unknown URLs anywhere in the app: the branded state inside the usual app frame. */
+export default function NotFound() {
+ return (
+ <StudioChrome>
+ <NotFoundState />
+ </StudioChrome>
+ );
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index cc5364b1..998dff6d 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -1,9 +1,9 @@
"use client";
import Link from "next/link";
-import { usePathname } from "next/navigation";
+import { usePathname, useSearchParams } from "next/navigation";
import { useTheme } from "next-themes";
-import { Suspense } from "react";
+import { Suspense, useCallback, useState } from "react";
import {
AtSign,
MessageCircle,
@@ -14,6 +14,7 @@ import {
Brush,
AudioLines,
Boxes,
+ ChevronRight,
Clapperboard,
Cpu,
Film,
@@ -36,6 +37,7 @@ import {
Library,
PersonStanding,
Scissors,
+ type LucideIcon,
} from "lucide-react";
import {
Sidebar,
@@ -44,17 +46,46 @@ import {
SidebarGroup,
SidebarGroupLabel,
SidebarHeader,
+ SidebarInset,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
+ SidebarProvider,
SidebarRail,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { Kbd } from "@/components/ui/kbd";
+import { GlobalShortcuts } from "@/components/global-shortcuts";
import { useEngineMode, useStatus } from "@/lib/api";
+import { groupId, NAV_CLOSED_KEY, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";
import { cn } from "@/lib/utils";
-const NAV = [
+interface NavItem {
+ href: string;
+ label: string;
+ icon: LucideIcon;
+ /** Shorter label for compact groups (the full one is the tooltip). */
+ short?: string;
+}
+
+interface NavGroupDef {
+ label: string;
+ items: NavItem[];
+ /** Can be folded away; the choice is remembered. */
+ collapsible?: boolean;
+ /** Two small items per row. */
+ compact?: boolean;
+}
+
+/** The sidebar. Add a destination with one line in the right group. */
+const NAV: NavGroupDef[] = [
+ {
+ label: "Library",
+ items: [
+ { href: "/library", label: "All creations", icon: Library },
+ { href: "/library?tab=favorites", label: "Favorites", icon: Star },
+ ],
+ },
{
label: "Create",
items: [
@@ -84,56 +115,141 @@ const NAV = [
{ href: "/upscale", label: "Upscale", icon: ZoomIn },
{ href: "/audio", label: "Audio", icon: AudioLines },
],
- },
- {
- label: "Library",
- items: [
- { href: "/library", label: "All creations", icon: Library },
- { href: "/library?tab=favorites", label: "Favorites", icon: Star },
- ],
+ collapsible: true,
},
{
label: "Engine",
items: [
{ href: "/models", label: "Models", icon: Boxes },
- { href: "/workflows", label: "ComfyUI workflows", icon: Workflow },
+ { href: "/workflows", label: "ComfyUI workflows", short: "Workflows", icon: Workflow },
{ href: "/settings", label: "Settings", icon: Settings },
- { href: "/status", label: "Project status", icon: ListChecks },
+ { href: "/status", label: "Project status", short: "Status", icon: ListChecks },
],
+ collapsible: true,
+ compact: true,
},
];
+const NO_SEARCH = new URLSearchParams();
+
function StatusDot({ ok }: { ok: boolean | undefined }) {
return <span className={cn("size-1.5 shrink-0 rounded-full", ok ? "bg-success" : "bg-subtle-foreground")} />;
}
-function NavGroups({ pathname }: { pathname: string }) {
- return NAV.map((group) => (
- <SidebarGroup key={group.label} className="py-1">
- <SidebarGroupLabel className="text-[11px] font-medium uppercase tracking-wide">{group.label}</SidebarGroupLabel>
- <SidebarMenu>
- {group.items.map((item) => {
- const [path, query] = item.href.split("?");
- const active = !!pathname && !query && (path === "/" ? pathname === "/" : pathname === path || pathname.startsWith(`${path}/`));
- return (
- <SidebarMenuItem key={item.href}>
- <SidebarMenuButton asChild isActive={active} tooltip={item.label} className="h-8 text-[13px] data-[active=true]:font-semibold">
- <Link href={item.href}>
- <item.icon />
- <span>{item.label}</span>
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
+function Items({ group, pathname, search }: { group: NavGroupDef; pathname: string; search: URLSearchParams }) {
+ const hrefs = group.items.map((i) => i.href);
+ return group.items.map((item) => {
+ const active = navActive(item.href, pathname, search, hrefs);
+ return (
+ <SidebarMenuItem key={item.href} className={cn(group.compact && "min-w-0")}>
+ <SidebarMenuButton
+ asChild
+ isActive={active}
+ tooltip={item.label}
+ className={cn("h-8 text-[13px] data-[active=true]:font-semibold", group.compact && "h-7 gap-1.5 px-2 text-[12px]")}
+ >
+ <Link href={item.href} aria-current={active ? "page" : undefined} title={group.compact && item.short ? item.label : undefined}>
+ <item.icon />
+ <span>{group.compact ? (item.short ?? item.label) : item.label}</span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ );
+ });
+}
+
+/** Query links (`?tab=favorites`) need the search params, which only exist at request time. */
+function WithSearch({ group, pathname }: { group: NavGroupDef; pathname: string }) {
+ return <Items group={group} pathname={pathname} search={useSearchParams()} />;
+}
+
+/** Reads the pathname (runtime data) inside Suspense so routes can still prerender. */
+function ActiveItems({ group }: { group: NavGroupDef }) {
+ const pathname = usePathname();
+ if (!group.items.some((i) => i.href.includes("?"))) return <Items group={group} pathname={pathname} search={NO_SEARCH} />;
+ return (
+ <Suspense fallback={<Items group={group} pathname={pathname} search={NO_SEARCH} />}>
+ <WithSearch group={group} pathname={pathname} />
+ </Suspense>
+ );
+}
+
+function readClosed(): string[] {
+ try {
+ return typeof window === "undefined" ? [] : parseClosed(localStorage.getItem(NAV_CLOSED_KEY));
+ } catch {
+ return [];
+ }
+}
+
+function NavGroup({ group, open, onToggle }: { group: NavGroupDef; open: boolean; onToggle: () => void }) {
+ const id = groupId(group.label);
+ return (
+ <SidebarGroup data-nav-group={id} data-open={open ? "true" : "false"} className="group/nav py-1">
+ {group.collapsible ? (
+ <SidebarGroupLabel asChild className="text-[11px] font-medium tracking-wide uppercase">
+ <button
+ type="button"
+ data-nav-toggle
+ aria-expanded={open}
+ aria-controls={`nav-${id}`}
+ onClick={onToggle}
+ className="w-full cursor-pointer hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
+ >
+ {group.label}
+ <ChevronRight className="ml-auto size-3.5 transition-transform group-data-[open=true]/nav:rotate-90" />
+ </button>
+ </SidebarGroupLabel>
+ ) : (
+ <SidebarGroupLabel className="text-[11px] font-medium tracking-wide uppercase">{group.label}</SidebarGroupLabel>
+ )}
+ <SidebarMenu id={`nav-${id}`} data-nav-items className={cn(group.compact && "grid grid-cols-2 gap-0.5")}>
+ <Suspense fallback={<Items group={group} pathname="" search={NO_SEARCH} />}>
+ <ActiveItems group={group} />
+ </Suspense>
</SidebarMenu>
</SidebarGroup>
- ));
+ );
}
-/** Reads the pathname (runtime data) inside Suspense so routes can still prerender. */
-function ActiveNav() {
- return <NavGroups pathname={usePathname()} />;
+/**
+ * Inline script that runs while the HTML is parsed: the server always renders the sidebar
+ * expanded, this applies the remembered state before the first paint. On the client it renders as
+ * inert text/plain (React warns about executable scripts it renders itself).
+ */
+function SidebarStateScript() {
+ return (
+ <script
+ type={typeof window === "undefined" ? "text/javascript" : "text/plain"}
+ suppressHydrationWarning
+ dangerouslySetInnerHTML={{ __html: SIDEBAR_STATE_SCRIPT }}
+ />
+ );
+}
+
+/** SidebarProvider that starts from the remembered expanded/collapsed state (the shadcn cookie). */
+export function SidebarShell({ children, style }: { children: React.ReactNode; style?: React.CSSProperties }) {
+ const [defaultOpen] = useState(() => (typeof document === "undefined" ? true : sidebarOpenFromCookie(document.cookie)));
+ return (
+ <SidebarProvider defaultOpen={defaultOpen} style={style}>
+ {children}
+ </SidebarProvider>
+ );
+}
+
+/** The app frame: sidebar + inset sheet. Used by the studio layout and the root not-found page. */
+export function StudioChrome({ children }: { children: React.ReactNode }) {
+ return (
+ // The shell stays static: the remembered collapsed state is read on the client (and applied
+ // before first paint by AppSidebar's inline script), not from cookies() on the server.
+ <SidebarShell style={{ "--sidebar-width": "15.5rem", "--sidebar-width-icon": "3.25rem" } as React.CSSProperties}>
+ <AppSidebar />
+ <SidebarInset className="min-h-svh min-w-0 md:m-0 md:mt-2 md:rounded-none md:rounded-tl-xl md:border-l-[0.5px] md:border-t-[0.5px] md:shadow-[-2px_0_6px_rgba(0,0,0,.02)] md:peer-data-[variant=inset]:m-0 md:peer-data-[variant=inset]:mt-2 md:peer-data-[variant=inset]:rounded-none md:peer-data-[variant=inset]:rounded-tl-xl">
+ {children}
+ </SidebarInset>
+ <GlobalShortcuts />
+ </SidebarShell>
+ );
}
export function AppSidebar() {
@@ -143,89 +259,103 @@ export function AppSidebar() {
const comfy = status?.providers.comfyui?.configured;
const mode = useEngineMode();
const ready = mode === "open" ? comfy : mode === "cloud" ? cloud : cloud || comfy;
+ const [closed, setClosed] = useState(readClosed);
+ const toggle = useCallback((id: string) => {
+ setClosed((c) => {
+ const next = c.includes(id) ? c.filter((x) => x !== id) : [...c, id];
+ try {
+ localStorage.setItem(NAV_CLOSED_KEY, JSON.stringify(next));
+ } catch {}
+ return next;
+ });
+ }, []);
return (
- <Sidebar variant="inset" collapsible="icon">
- <SidebarHeader className="pt-3">
- <div className="flex h-9 items-center justify-between gap-2 px-1 group-data-[collapsible=icon]:justify-center">
- <Link href="/" className="flex items-center gap-2 group-data-[collapsible=icon]:hidden">
- <span className="grid size-7 place-items-center rounded-lg bg-primary text-primary-foreground shadow-soft">
- <Clapperboard className="size-4" />
- </span>
- <span className="font-heading text-[22px] leading-none">Fuobe</span>
+ <>
+ <Sidebar variant="inset" collapsible="icon">
+ <SidebarHeader className="pt-3">
+ <div className="flex h-9 items-center justify-between gap-2 px-1 group-data-[collapsible=icon]:justify-center">
+ <Link href="/" className="flex items-center gap-2 group-data-[collapsible=icon]:hidden">
+ <span className="grid size-7 place-items-center rounded-lg bg-primary text-primary-foreground shadow-soft">
+ <Clapperboard className="size-4" />
+ </span>
+ <span className="font-heading text-[22px] leading-none">Fuobe</span>
+ </Link>
+ <SidebarTrigger className="text-muted-foreground" />
+ </div>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <SidebarMenuButton asChild tooltip="New creation" className="h-8 text-[13px]">
+ <Link href="/">
+ <Plus />
+ <span>New creation</span>
+ <span className="ml-auto flex gap-0.5 group-data-[collapsible=icon]:hidden">
+ <Kbd>⌘</Kbd>
+ <Kbd>K</Kbd>
+ </span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarHeader>
+ <SidebarContent className="scrollbar-none">
+ {NAV.map((group) => {
+ const id = groupId(group.label);
+ return <NavGroup key={id} group={group} open={!group.collapsible || !closed.includes(id)} onToggle={() => toggle(id)} />;
+ })}
+ </SidebarContent>
+ <SidebarFooter className="gap-1 border-t border-sidebar-border">
+ <Link
+ href="/settings"
+ className="flex flex-col gap-1.5 rounded-md px-2 py-1.5 text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden"
+ >
+ {mode !== "open" && (
+ <span className="flex items-center gap-2">
+ <StatusDot ok={cloud} /> Cloud models
+ <span className="ml-auto">{cloud ? "connected" : "add key"}</span>
+ </span>
+ )}
+ {mode !== "cloud" && (
+ <span className="flex items-center gap-2">
+ <StatusDot ok={comfy} /> ComfyUI
+ <span className="ml-auto">{comfy ? "online" : "offline"}</span>
+ </span>
+ )}
+ {mode !== "both" && (
+ <span className="text-[11px] text-subtle-foreground">{mode === "open" ? "Open source only" : "Paid APIs only"}</span>
+ )}
+ {status && !ready && status.demoMode !== "off" && (
+ <span className="mt-0.5 rounded-sm bg-highlight/25 px-1.5 py-0.5 text-[11px] text-highlight-foreground dark:text-highlight">
+ Demo mode · placeholder outputs
+ </span>
+ )}
</Link>
- <SidebarTrigger className="text-muted-foreground" />
- </div>
- <SidebarMenu>
- <SidebarMenuItem>
- <SidebarMenuButton asChild tooltip="New creation" className="h-8 text-[13px]">
- <Link href="/">
- <Plus />
- <span>New creation</span>
- <span className="ml-auto flex gap-0.5 group-data-[collapsible=icon]:hidden">
- <Kbd>⌘</Kbd>
- <Kbd>K</Kbd>
- </span>
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- </SidebarMenu>
- </SidebarHeader>
- <SidebarContent className="scrollbar-none">
- <Suspense fallback={<NavGroups pathname="" />}>
- <ActiveNav />
- </Suspense>
- </SidebarContent>
- <SidebarFooter className="border-t border-sidebar-border">
- <Link
- href="/settings"
- className="flex flex-col gap-1.5 rounded-md px-2 py-1.5 text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden"
- >
- {mode !== "open" && (
- <span className="flex items-center gap-2">
- <StatusDot ok={cloud} /> Cloud models
- <span className="ml-auto">{cloud ? "connected" : "add key"}</span>
- </span>
- )}
- {mode !== "cloud" && (
- <span className="flex items-center gap-2">
- <StatusDot ok={comfy} /> ComfyUI
- <span className="ml-auto">{comfy ? "online" : "offline"}</span>
- </span>
- )}
- {mode !== "both" && (
- <span className="text-[11px] text-subtle-foreground">{mode === "open" ? "Open source only" : "Paid APIs only"}</span>
- )}
- {status && !ready && status.demoMode !== "off" && (
- <span className="mt-0.5 rounded-sm bg-highlight/25 px-1.5 py-0.5 text-[11px] text-highlight-foreground dark:text-highlight">
- Demo mode · placeholder outputs
- </span>
- )}
- </Link>
- <SidebarMenu>
- <SidebarMenuItem>
- <SidebarMenuButton
- tooltip="Toggle theme"
- className="h-8 text-[13px]"
- onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
- >
- <Sun className="hidden dark:block" />
- <Moon className="dark:hidden" />
- <span className="hidden dark:inline">Light mode</span>
- <span className="dark:hidden">Dark mode</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- <SidebarMenuItem>
- <SidebarMenuButton asChild tooltip="Open source" className="h-8 text-[13px]">
- <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer">
- <Cpu />
- <span>Open source on GitHub</span>
- </a>
- </SidebarMenuButton>
- </SidebarMenuItem>
- </SidebarMenu>
- </SidebarFooter>
- <SidebarRail />
- </Sidebar>
+ <SidebarMenu className="flex-row gap-1 group-data-[collapsible=icon]:flex-col">
+ <SidebarMenuItem className="min-w-0 flex-1">
+ <SidebarMenuButton
+ tooltip="Toggle theme"
+ className="h-8 text-[13px]"
+ onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
+ >
+ <Sun className="hidden dark:block" />
+ <Moon className="dark:hidden" />
+ <span className="hidden dark:inline">Light mode</span>
+ <span className="dark:hidden">Dark mode</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ <SidebarMenuItem className="shrink-0">
+ <SidebarMenuButton asChild tooltip="Open source on GitHub" className="h-8 w-8 justify-center p-0 text-[13px]">
+ <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer" title="Open source on GitHub">
+ <Cpu />
+ <span className="sr-only">Open source on GitHub</span>
+ </a>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarFooter>
+ <SidebarRail />
+ </Sidebar>
+ <SidebarStateScript />
+ </>
);
}
diff --git a/src/components/element-studio.tsx b/src/components/element-studio.tsx
new file mode 100644
index 00000000..022927f9
--- /dev/null
+++ b/src/components/element-studio.tsx
@@ -0,0 +1,95 @@
+"use client";
+
+import { AtSign, GraduationCap, Loader2, Pencil, RotateCcw } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { NotFoundState, PageState } from "@/components/empty-state";
+import { ElementDialog } from "@/components/elements-view";
+import { StudioSkeleton } from "@/components/skeletons";
+import { StudioPage } from "@/components/studio/studio-page";
+import type { StudioConfig } from "@/components/studio/studio-context";
+import { TrainDialog } from "@/components/train-dialog";
+import { Button } from "@/components/ui/button";
+import { useElement } from "@/lib/api";
+
+/**
+ * A studio for one element: the prompt starts with its @handle, references are resolved by the
+ * server. Lives apart from the Elements list so /elements doesn't load the composer.
+ */
+export function ElementStudio({ id }: { id: string }) {
+ const q = useElement(id);
+ const [editing, setEditing] = useState(false);
+ const [training, setTraining] = useState(false);
+ const el = q.data;
+ const config = useMemo<StudioConfig | null>(() => {
+ if (!el) return null;
+ return {
+ feature: `element:${el.id}`,
+ title: el.name,
+ hero:
+ el.kind === "character"
+ ? `Where should ${el.name} go next?`
+ : el.kind === "location"
+ ? `What happens at ${el.name}?`
+ : el.kind === "prop"
+ ? `Where should ${el.name} show up?`
+ : `What should look like ${el.name}?`,
+ subtitle: `Mention @${el.handle} in any studio to use ${el.kind === "character" ? "them" : "it"} there too.`,
+ placeholder: `Describe a scene with @${el.handle}…`,
+ kind: "image",
+ ops: ["t2i", "edit"],
+ feed: { features: [`element:${el.id}`, `character:${el.id}`] },
+ slots: [],
+ multiRef: { label: "Add ref", max: 8 },
+ defaultModels: { cloud: "nano-banana-pro", open: "oss-qwen-edit" },
+ };
+ }, [el]);
+
+ if (q.isError) {
+ const missing = /not found|404/i.test((q.error as Error).message);
+ return missing ? (
+ <NotFoundState title="No such element">It may have been deleted. Your other characters, places and props are on the Elements page.</NotFoundState>
+ ) : (
+ <PageState
+ icon={AtSign}
+ title="Couldn’t load this element"
+ actions={
+ <>
+ <Button onClick={() => void q.refetch()}>
+ <RotateCcw /> Try again
+ </Button>
+ <Button asChild variant="outline">
+ <Link href="/elements">All elements</Link>
+ </Button>
+ </>
+ }
+ >
+ {(q.error as Error).message}
+ </PageState>
+ );
+ }
+ if (!config || !el) return <StudioSkeleton />;
+ return (
+ <>
+ <StudioPage
+ config={config}
+ initialPrompt={`@${el.handle} `}
+ header={
+ <>
+ {el.kind !== "voice" && (
+ <Button variant={el.loras.length ? "ghost" : "secondary"} size="sm" onClick={() => setTraining(true)}>
+ {el.status === "training" ? <Loader2 className="animate-spin" /> : <GraduationCap />}
+ <span className="hidden sm:inline">{el.status === "training" ? "Training…" : el.loras.length ? `Trained · ${el.loras.length}` : "Train"}</span>
+ </Button>
+ )}
+ <Button variant="ghost" size="sm" onClick={() => setEditing(true)} aria-label={`Edit ${el.name}`}>
+ <Pencil /> <span className="hidden sm:inline">Edit</span>
+ </Button>
+ </>
+ }
+ />
+ <ElementDialog open={editing} onOpenChange={setEditing} element={el} />
+ <TrainDialog open={training} onOpenChange={setTraining} element={el} />
+ </>
+ );
+}
diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsx
index d417f148..ab31236b 100644
--- a/src/components/elements-view.tsx
+++ b/src/components/elements-view.tsx
@@ -1,25 +1,33 @@
"use client";
-import { AtSign, AudioLines, Check, Copy, GraduationCap, Loader2, Pencil, Plus, Trash2, X } from "lucide-react";
+import { AtSign, AudioLines, Check, Copy, GraduationCap, Loader2, Plus, Trash2, X } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useMemo, useState } from "react";
import { nanoid } from "nanoid";
import { toast } from "sonner";
-import { PageShell } from "@/components/page-shell";
-import { PageHeader } from "@/components/preset-gallery";
+import { PageHeader, PageShell } from "@/components/page-shell";
+import { PageSkeleton } from "@/components/skeletons";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Skeleton } from "@/components/ui/skeleton";
-import { StudioPage } from "@/components/studio/studio-page";
import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { ELEMENT_ICONS } from "@/components/studio/prompt-input";
import { VoiceRecorder } from "@/components/studio/voice-recorder";
-import { TrainDialog } from "@/components/train-dialog";
-import type { StudioConfig } from "@/components/studio/studio-context";
-import { useDeleteElement, useElement, useElements, useSaveElement } from "@/lib/api";
+import { useDeleteElement, useElements, useSaveElement } from "@/lib/api";
import { ELEMENT_KINDS, elementKindInfo, handleFor, type ElementKind, type StudioElement } from "@/lib/catalog/elements";
import { cn } from "@/lib/utils";
@@ -40,7 +48,10 @@ function PhotoGrid({ photos, setPhotos }: { photos: SlotValue[]; setPhotos: Reac
void fileToSlot(f, (v) =>
setPhotos((ps) => {
if (!v) return ps.filter((p) => p.id !== id);
- return ps.some((p) => p.id === id) ? ps.map((p) => (p.id === id ? { ...v, id } : p)) : [...ps, { ...v, id }];
+ if (ps.some((p) => p.id === id)) return ps.map((p) => (p.id === id ? { ...v, id } : p));
+ // Only the first (uploading) call adds the photo; a finished upload of a photo the user
+ // already removed must not bring it back.
+ return v.uploading ? [...ps, { ...v, id }] : ps;
}),
);
}
@@ -283,16 +294,38 @@ function ElementCard({ el }: { el: StudioElement }) {
<Icon className="size-3" /> {elementKindInfo(el.kind).label}
</span>
</div>
- <button
- onClick={() => {
- del.mutate(el.id);
- toast(`Deleted ${el.name}`);
- }}
- className="absolute top-2 right-2 grid size-8 place-items-center rounded-lg bg-background/80 text-muted-foreground opacity-0 backdrop-blur transition group-hover:opacity-100 hover:text-destructive"
- aria-label={`Delete ${el.name}`}
- >
- <Trash2 className="size-4" />
- </button>
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <button
+ className="absolute top-2 right-2 grid size-8 place-items-center rounded-lg bg-background/80 text-muted-foreground backdrop-blur transition outline-none group-hover:opacity-100 hover:text-destructive focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring sm:opacity-0"
+ aria-label={`Delete ${el.name}`}
+ >
+ <Trash2 className="size-4" />
+ </button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {el.name}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ @{el.handle} will stop working in prompts{el.loras.length ? " and its trained identity is removed" : ""}. Images you already made stay in your library.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() =>
+ del.mutate(el.id, {
+ onSuccess: () => toast(`Deleted ${el.name}`),
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
);
}
@@ -315,13 +348,14 @@ function ElementsBody() {
<Plus /> New element
</Button>
</PageHeader>
- <div className="mb-5 flex gap-1">
+ <div role="group" aria-label="Kinds" className="scrollbar-none -mx-1 mb-5 flex gap-1 overflow-x-auto px-1">
{(["all", ...ELEMENT_KINDS.map((k) => k.kind)] as const).map((k) => (
<button
key={k}
onClick={() => setTab(k)}
+ aria-pressed={tab === k}
className={cn(
- "h-8 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-accent",
+ "h-8 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent",
tab === k && "bg-secondary text-foreground",
)}
>
@@ -367,74 +401,8 @@ function ElementsBody() {
export function ElementsView() {
return (
- <Suspense fallback={null}>
+ <Suspense fallback={<PageSkeleton title="Elements" rows={2} />}>
<ElementsBody />
</Suspense>
);
}
-
-/** A studio for one element: the prompt starts with its @handle, references are resolved by the server. */
-export function ElementStudio({ id }: { id: string }) {
- const q = useElement(id);
- const [editing, setEditing] = useState(false);
- const [training, setTraining] = useState(false);
- const el = q.data;
- const config = useMemo<StudioConfig | null>(() => {
- if (!el) return null;
- return {
- feature: `element:${el.id}`,
- title: el.name,
- hero:
- el.kind === "character"
- ? `Where should ${el.name} go next?`
- : el.kind === "location"
- ? `What happens at ${el.name}?`
- : el.kind === "prop"
- ? `Where should ${el.name} show up?`
- : `What should look like ${el.name}?`,
- subtitle: `Mention @${el.handle} in any studio to use ${el.kind === "character" ? "them" : "it"} there too.`,
- placeholder: `Describe a scene with @${el.handle}…`,
- kind: "image",
- ops: ["t2i", "edit"],
- feed: { features: [`element:${el.id}`, `character:${el.id}`] },
- slots: [],
- multiRef: { label: "Add ref", max: 8 },
- defaultModels: { cloud: "nano-banana-pro", open: "oss-qwen-edit" },
- };
- }, [el]);
- if (q.isError)
- return (
- <PageShell>
- <p className="text-muted-foreground">Element not found.</p>
- </PageShell>
- );
- if (!config || !el)
- return (
- <PageShell>
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- </PageShell>
- );
- return (
- <>
- <StudioPage
- config={config}
- initialPrompt={`@${el.handle} `}
- header={
- <>
- {el.kind !== "voice" && (
- <Button variant={el.loras.length ? "ghost" : "secondary"} size="sm" onClick={() => setTraining(true)}>
- {el.status === "training" ? <Loader2 className="animate-spin" /> : <GraduationCap />}
- {el.status === "training" ? "Training…" : el.loras.length ? `Trained · ${el.loras.length}` : "Train"}
- </Button>
- )}
- <Button variant="ghost" size="sm" onClick={() => setEditing(true)}>
- <Pencil /> Edit
- </Button>
- </>
- }
- />
- <ElementDialog open={editing} onOpenChange={setEditing} element={el} />
- <TrainDialog open={training} onOpenChange={setTraining} element={el} />
- </>
- );
-}
diff --git a/src/components/empty-state.tsx b/src/components/empty-state.tsx
new file mode 100644
index 00000000..7f2a05f4
--- /dev/null
+++ b/src/components/empty-state.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { ArrowLeft, Compass, Home, RotateCcw, TriangleAlert } from "lucide-react";
+import { Suspense } from "react";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Button } from "@/components/ui/button";
+
+/** A calm full-page state (Liner style): serif headline, one muted line, one or two actions. */
+export function PageState({
+ icon: Icon = Compass,
+ title,
+ children,
+ actions,
+}: {
+ icon?: typeof Compass;
+ title: string;
+ children?: React.ReactNode;
+ actions?: React.ReactNode;
+}) {
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <div className="sticky top-0 z-20 flex h-12 items-center px-3 md:hidden">
+ <SidebarTrigger />
+ </div>
+ <div className="mx-auto flex w-full max-w-[520px] flex-1 flex-col items-center justify-center px-6 pb-[12vh] text-center">
+ <span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">
+ <Icon className="size-5" />
+ </span>
+ <h1 className="mt-5 font-heading text-[34px] leading-tight text-balance">{title}</h1>
+ {children && <div className="mt-2 text-[15px] text-pretty text-muted-foreground">{children}</div>}
+ {actions && <div className="mt-7 flex flex-wrap justify-center gap-2">{actions}</div>}
+ </div>
+ </div>
+ );
+}
+
+/** Where to send someone from a dead link, based on the section they were in. */
+const SECTIONS: { prefix: string; href: string; label: string }[] = [
+ { prefix: "/apps", href: "/apps", label: "Browse apps" },
+ { prefix: "/elements", href: "/elements", label: "All elements" },
+ { prefix: "/motions", href: "/motions", label: "Camera motions" },
+ { prefix: "/effects", href: "/effects", label: "Effects" },
+ { prefix: "/library", href: "/library", label: "Your library" },
+ { prefix: "/cinema", href: "/cinema", label: "Cinema projects" },
+ { prefix: "/canvas", href: "/canvas", label: "Your canvases" },
+];
+
+function SectionLink() {
+ const pathname = usePathname() ?? "";
+ const s = SECTIONS.find((x) => pathname === x.prefix || pathname.startsWith(`${x.prefix}/`));
+ if (!s) return null;
+ return (
+ <Button asChild variant="outline">
+ <Link href={s.href}>
+ <ArrowLeft /> {s.label}
+ </Link>
+ </Button>
+ );
+}
+
+export function NotFoundState({ title = "Nothing here", children }: { title?: string; children?: React.ReactNode }) {
+ return (
+ <PageState
+ title={title}
+ actions={
+ <>
+ <Suspense fallback={null}>
+ <SectionLink />
+ </Suspense>
+ <Button asChild>
+ <Link href="/">
+ <Home /> Back to Home
+ </Link>
+ </Button>
+ </>
+ }
+ >
+ {children ?? "The page you’re looking for moved, or never existed. Everything you made is still in your library."}
+ </PageState>
+ );
+}
+
+export function ErrorState({ error, retry }: { error: unknown; retry?: () => void }) {
+ const digest = error && typeof error === "object" && "digest" in error ? String((error as { digest?: string }).digest ?? "") : "";
+ const message = error instanceof Error ? error.message : "";
+ return (
+ <PageState
+ icon={TriangleAlert}
+ title="Something went wrong"
+ actions={
+ <>
+ {retry && (
+ <Button onClick={retry}>
+ <RotateCcw /> Try again
+ </Button>
+ )}
+ <Button asChild variant="outline">
+ <Link href="/">
+ <Home /> Back to Home
+ </Link>
+ </Button>
+ </>
+ }
+ >
+ <p>This page hit an error. Your creations and settings are safe.</p>
+ {(message || digest) && (
+ <p className="mt-3 rounded-lg bg-muted px-3 py-2 font-mono text-[12px] break-words text-muted-foreground">
+ {message}
+ {digest && <span className="block text-subtle-foreground">ref {digest}</span>}
+ </p>
+ )}
+ </PageState>
+ );
+}
diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsx
index 6ab77b7a..2c758d59 100644
--- a/src/components/preset-gallery.tsx
+++ b/src/components/preset-gallery.tsx
@@ -6,6 +6,7 @@ import { memo, useCallback, useDeferredValue, useEffect, useMemo, useRef, useSta
import { PageHeader } from "@/components/page-shell";
import { PRESET_ICONS } from "@/components/preset-icons";
import { PresetPreview, usePreviewPlayback } from "@/components/preset-preview";
+import { GALLERY_GRID } from "@/components/skeletons";
import { useEngineMode } from "@/lib/api";
import { searchText, type PresetCardData } from "@/lib/preset-cards";
import { cn } from "@/lib/utils";
@@ -146,7 +147,7 @@ function useFadeEdges<T extends HTMLElement>() {
const FIRST_PAGE = 30;
const PAGE = 40;
-const GRID = "grid grid-cols-2 gap-1 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";
+const GRID = GALLERY_GRID;
export function PresetGallery({
presets,
@@ -299,29 +300,3 @@ export function PresetGallery({
</div>
);
}
-
-/** Skeleton for the gallery pages (loading.tsx). */
-export function PresetGallerySkeleton() {
- return (
- <div className="space-y-4" aria-hidden>
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
- <div className="h-9 w-full animate-pulse rounded-full bg-muted sm:w-80" />
- <div className="h-9 w-56 animate-pulse rounded-full bg-muted sm:ml-auto" />
- </div>
- <div className="flex gap-1 overflow-hidden">
- {Array.from({ length: 9 }, (_, i) => (
- <div key={i} className="h-8 w-20 shrink-0 animate-pulse rounded-full bg-muted" />
- ))}
- </div>
- <div className={GRID}>
- {Array.from({ length: 10 }, (_, i) => (
- <div key={i} className="space-y-2 p-1.5">
- <div className="aspect-[4/3] animate-pulse rounded-lg bg-muted" />
- <div className="h-3.5 w-2/3 animate-pulse rounded bg-muted" />
- <div className="h-3 w-full animate-pulse rounded bg-muted" />
- </div>
- ))}
- </div>
- </div>
- );
-}
diff --git a/src/components/skeletons.tsx b/src/components/skeletons.tsx
new file mode 100644
index 00000000..937284c3
--- /dev/null
+++ b/src/components/skeletons.tsx
@@ -0,0 +1,90 @@
+import { Skeleton } from "@/components/ui/skeleton";
+import { PageHeader, PageShell } from "@/components/page-shell";
+
+/*
+ * Route skeletons (loading.tsx). Server components with no data: they are part of each route's
+ * prefetched shell, so a click in the sidebar paints the next page's frame immediately.
+ */
+
+/** A studio: sticky title bar, hero line, the pill composer. */
+export function StudioSkeleton() {
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col" aria-busy="true" aria-label="Loading">
+ <div className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 sm:px-6">
+ <Skeleton className="h-6 w-32 rounded-lg" />
+ <Skeleton className="ml-auto h-9 w-44 rounded-full" />
+ </div>
+ <div className="mx-auto flex w-full max-w-[760px] flex-col items-center px-3 pt-[16vh] sm:px-6">
+ <Skeleton className="h-9 w-2/3 max-w-[420px] rounded-xl" />
+ <Skeleton className="mt-3 h-4 w-1/2 max-w-[300px]" />
+ <div className="mt-10 w-full rounded-[20px] border bg-background p-2.5 shadow-soft sm:rounded-composer">
+ <Skeleton className="h-14 w-full rounded-xl bg-muted/60" />
+ <div className="mt-2 flex items-center gap-1.5">
+ <Skeleton className="h-8 w-28 rounded-full" />
+ <Skeleton className="h-8 w-16 rounded-full" />
+ <Skeleton className="h-8 w-16 rounded-full" />
+ <Skeleton className="ml-auto size-10 rounded-full" />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export const GALLERY_GRID = "grid grid-cols-2 gap-1 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";
+
+/** Gallery body: filter row, category strip, card grid. */
+export function GallerySkeleton({ cards = 10 }: { cards?: number }) {
+ return (
+ <div className="space-y-4" aria-busy="true" aria-label="Loading">
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <Skeleton className="h-9 w-full rounded-full sm:w-80" />
+ <Skeleton className="h-9 w-64 rounded-full sm:ml-auto" />
+ </div>
+ <div className="flex gap-1 overflow-hidden">
+ {Array.from({ length: 9 }, (_, i) => (
+ <Skeleton key={i} className="h-8 w-20 shrink-0 rounded-full" />
+ ))}
+ </div>
+ <div className={GALLERY_GRID}>
+ {Array.from({ length: cards }, (_, i) => (
+ <div key={i} className="space-y-2 p-1.5">
+ <Skeleton className="aspect-[4/3] rounded-lg" />
+ <Skeleton className="h-3.5 w-2/3" />
+ <Skeleton className="h-3 w-full" />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** A gallery page with its real title, so only the cards are placeholders. */
+export function GalleryPageSkeleton({ title }: { title: string }) {
+ return (
+ <PageShell>
+ <div className="pb-6">
+ <h1 className="font-heading text-[34px] leading-tight">{title}</h1>
+ <Skeleton className="mt-2 h-4 w-full max-w-[620px]" />
+ <Skeleton className="mt-2 h-4 w-2/3 max-w-[420px]" />
+ </div>
+ <GallerySkeleton />
+ </PageShell>
+ );
+}
+
+/** A settings-style page: title, description, a few blocks. */
+export function PageSkeleton({ title, wide, rows = 4 }: { title?: string; wide?: boolean; rows?: number }) {
+ return (
+ <PageShell wide={wide}>
+ <div aria-busy="true" aria-label="Loading">
+ {title ? <PageHeader title={title} /> : <Skeleton className="mb-8 h-10 w-56 rounded-xl" />}
+ <div className="space-y-3">
+ {Array.from({ length: rows }, (_, i) => (
+ <Skeleton key={i} className="h-24 w-full rounded-xl" />
+ ))}
+ </div>
+ </div>
+ </PageShell>
+ );
+}
diff --git a/src/lib/nav.ts b/src/lib/nav.ts
new file mode 100644
index 00000000..3b4e556b
--- /dev/null
+++ b/src/lib/nav.ts
@@ -0,0 +1,53 @@
+/** Sidebar helpers (pure, so they're testable): active state, and the remembered group and collapse state. */
+
+/** Group labels the user collapsed, in localStorage. */
+export const NAV_CLOSED_KEY = "fuobe:nav-closed";
+/** Written by the shadcn SidebarProvider ("true" / "false"). */
+export const SIDEBAR_COOKIE = "sidebar_state";
+
+export const groupId = (label: string) => label.toLowerCase().replace(/[^a-z0-9]+/g, "-");
+
+function pathMatches(path: string, pathname: string) {
+ return path === "/" ? pathname === "/" : pathname === path || pathname.startsWith(`${path}/`);
+}
+
+function queryMatches(query: string, search: URLSearchParams) {
+ return [...new URLSearchParams(query)].every(([k, v]) => search.get(k) === v);
+}
+
+/**
+ * Whether a nav link is the current page. A link with a query (`/library?tab=favorites`) is active
+ * when the path and every one of its params match; a plain link is active on its path (and below it)
+ * unless a sibling query link to the same path matches better.
+ */
+export function navActive(href: string, pathname: string, search: URLSearchParams, siblings: string[] = []): boolean {
+ if (!pathname) return false;
+ const [path, query] = href.split("?");
+ if (!pathMatches(path, pathname)) return false;
+ if (query) return queryMatches(query, search);
+ return !siblings.some((s) => {
+ const [p, q] = s.split("?");
+ return !!q && p === path && pathMatches(p, pathname) && queryMatches(q, search);
+ });
+}
+
+/** Read the collapsed groups (ids) from storage; tolerant of anything unexpected. */
+export function parseClosed(raw: string | null | undefined): string[] {
+ try {
+ const v = JSON.parse(raw ?? "[]");
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+export function sidebarOpenFromCookie(cookie: string): boolean {
+ return !new RegExp(`(?:^|;\\s*)${SIDEBAR_COOKIE}=false(?:;|$)`).test(cookie);
+}
+
+/**
+ * Inline script that applies the remembered state to the server-rendered sidebar before the first
+ * paint: the collapsed rail (cookie) and collapsed groups (localStorage). React's first client render
+ * reads the same values, so hydration matches the patched DOM.
+ */
+export const SIDEBAR_STATE_SCRIPT = `(function(){try{var d=document;if(/(?:^|;\\s*)${SIDEBAR_COOKIE}=false(?:;|$)/.test(d.cookie)){var s=d.querySelector('[data-slot="sidebar"]');if(s){s.setAttribute("data-state","collapsed");s.setAttribute("data-collapsible","icon")}}var c=JSON.parse(localStorage.getItem("${NAV_CLOSED_KEY}")||"[]");if(Array.isArray(c))c.forEach(function(g){var e=d.querySelector('[data-nav-group="'+String(g).replace(/[^a-z0-9-]/g,"")+'"]');if(e){e.setAttribute("data-open","false");var b=e.querySelector("[data-nav-toggle]");if(b)b.setAttribute("aria-expanded","false")}})}catch(e){}})()`;
diff --git a/tests/nav.test.ts b/tests/nav.test.ts
new file mode 100644
index 00000000..2ffca1bc
--- /dev/null
+++ b/tests/nav.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import { groupId, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";
+
+const q = (s = "") => new URLSearchParams(s);
+const LIBRARY = ["/library", "/library?tab=favorites"];
+
+describe("sidebar active state", () => {
+ it("matches a path and the pages below it", () => {
+ expect(navActive("/apps", "/apps", q())).toBe(true);
+ expect(navActive("/apps", "/apps/app-face-swap", q())).toBe(true);
+ expect(navActive("/apps", "/apps-old", q())).toBe(false);
+ expect(navActive("/", "/", q())).toBe(true);
+ expect(navActive("/", "/image", q())).toBe(false);
+ expect(navActive("/image", "", q())).toBe(false);
+ });
+
+ it("lights up query links when their params match", () => {
+ expect(navActive("/library?tab=favorites", "/library", q("tab=favorites"), LIBRARY)).toBe(true);
+ expect(navActive("/library?tab=favorites", "/library", q(), LIBRARY)).toBe(false);
+ expect(navActive("/library?tab=favorites", "/library", q("tab=trash"), LIBRARY)).toBe(false);
+ });
+
+ it("hands the active state from the plain link to the better-matching query link", () => {
+ expect(navActive("/library", "/library", q(), LIBRARY)).toBe(true);
+ expect(navActive("/library", "/library", q("tab=favorites"), LIBRARY)).toBe(false);
+ // Other tabs have no link of their own, so "All creations" stays lit.
+ expect(navActive("/library", "/library", q("tab=trash"), LIBRARY)).toBe(true);
+ });
+});
+
+describe("remembered sidebar state", () => {
+ it("reads the shadcn cookie", () => {
+ expect(sidebarOpenFromCookie("")).toBe(true);
+ expect(sidebarOpenFromCookie("sidebar_state=true")).toBe(true);
+ expect(sidebarOpenFromCookie("a=1; sidebar_state=false; b=2")).toBe(false);
+ expect(sidebarOpenFromCookie("sidebar_state=false")).toBe(false);
+ expect(sidebarOpenFromCookie("my_sidebar_state=false")).toBe(true);
+ });
+
+ it("parses the collapsed groups defensively", () => {
+ expect(parseClosed('["studios","engine"]')).toEqual(["studios", "engine"]);
+ expect(parseClosed("not json")).toEqual([]);
+ expect(parseClosed('{"a":1}')).toEqual([]);
+ expect(parseClosed(null)).toEqual([]);
+ expect(parseClosed('["studios", 3]')).toEqual(["studios"]);
+ });
+
+ it("uses stable group ids", () => {
+ expect(groupId("Studios")).toBe("studios");
+ expect(groupId("Shorts & Marketing")).toBe("shorts-marketing");
+ });
+
+ it("ships a pre-paint script that is valid JavaScript", () => {
+ expect(() => new Function(SIDEBAR_STATE_SCRIPT)).not.toThrow();
+ expect(SIDEBAR_STATE_SCRIPT).toContain("sidebar_state=false");
+ expect(SIDEBAR_STATE_SCRIPT).toContain("fuobe:nav-closed");
+ });
+
+ it("applies the cookie and the collapsed groups to the DOM", () => {
+ const attrs = new Map<string, Record<string, string>>();
+ const el = (key: string) => ({
+ setAttribute: (k: string, v: string) => attrs.set(key, { ...attrs.get(key), [k]: v }),
+ querySelector: (s: string) => (s === "[data-nav-toggle]" ? el(`${key}/toggle`) : null),
+ });
+ const document = {
+ cookie: "x=1; sidebar_state=false",
+ querySelector: (s: string) => (s === '[data-slot="sidebar"]' ? el("sidebar") : s === '[data-nav-group="studios"]' ? el("studios") : null),
+ };
+ const localStorage = { getItem: () => '["studios","gone"]' };
+ new Function("document", "localStorage", SIDEBAR_STATE_SCRIPT)(document, localStorage);
+ expect(attrs.get("sidebar")).toEqual({ "data-state": "collapsed", "data-collapsible": "icon" });
+ expect(attrs.get("studios")).toEqual({ "data-open": "false" });
+ expect(attrs.get("studios/toggle")).toEqual({ "aria-expanded": "false" });
+ });
+});