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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Shell: skip link, a Main nav landmark, a shorter sidebar and a ⌘K palette
Claudeb16bcb528e70
diff --git a/src/app/api/palette/route.ts b/src/app/api/palette/route.tsnew file mode 100644index 00000000..85bab563--- /dev/null+++ b/src/app/api/palette/route.ts@@ -0,0 +1,9 @@+import { paletteIndex } from "@/lib/palette-index";++/**+ * The ⌘K palette's catalog: apps, camera motions, effects and models, slim (names, categories, where+ * each opens). Static, so it's prerendered at build time; the palette loads it once, on first open.+ */+export async function GET() {+ return Response.json(paletteIndex());+}diff --git a/src/app/globals.css b/src/app/globals.cssindex f4cf522a..1178625a 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -52,7 +52,7 @@--brand-faint-hover: oklch(0.52 0.21 282 / 12%);--highlight: oklch(0.88 0.16 95); /* Spark #f9d544: credits, "New", favorites */--highlight-foreground: oklch(0.30 0.06 85); /* #3c2b02 */- --subtle-foreground: oklch(0.799 0.004 286); /* #bdbdc0 placeholders, disabled, tertiary */+ --subtle-foreground: oklch(0.799 0.004 286); /* #bdbdc0 placeholders, disabled controls, icons; too faint for text (1.9:1), use muted */--border-strong: oklch(0.667 0.004 286 / 48%);--success: oklch(0.56 0.13 147);--warning: oklch(0.62 0.15 60);@@ -214,6 +214,8 @@--animate-fade-up: fade-up 200ms cubic-bezier(0.08, 0.82, 0.17, 1) both;--animate-pop-in: pop-in 120ms ease-out both;--animate-caret: caret-blink 1s step-end infinite;+ /* Click feedback while a link's route loads: shows only if the navigation takes a moment. */+ --animate-pending-in: pending-in 150ms ease-out 120ms both;@keyframes shimmer-text {from { mask-position: 100% 0; }@@ -231,6 +233,10 @@from { opacity: 0; transform: scale(0.95); }to { opacity: 1; transform: scale(1); }}+ @keyframes pending-in {+ from { opacity: 0; }+ to { opacity: 1; }+ }@keyframes caret-blink {0%, 49% { opacity: 1; }50%, 100% { opacity: 0; }diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 027f9be6..4a610b7b 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -1,59 +1,10 @@"use client";-import Link from "next/link";+import { useLinkStatus } from "next/link";import { usePathname, useSearchParams } from "next/navigation";import { useTheme } from "next-themes";import { Fragment, Suspense, useCallback, useEffect, useRef, useState } from "react";-import {- AtSign,- MessageCircle,- GalleryHorizontal,- Layers,- Layers2,- Crop,- FastForward,- Brush,- AudioLines,- Boxes,- ChevronRight,- Clapperboard,- Cpu,- Film,- Home,- ImageIcon,- LayoutGrid,- ListChecks,- Mic2,- Moon,- Network,- Plus,- Settings,- SlidersHorizontal,- Sparkles,- Star,- Sun,- Video,- Wand2,- Workflow,- ZoomIn,- Library,- PersonStanding,- Scissors,- Shapes,- Smartphone,- Megaphone,- Target,- Images,- Camera,- Shirt,- UserRoundCog,- Tv,- Presentation,- Box,- Swords,- TrendingUp,- type LucideIcon,-} from "lucide-react";+import { ChevronRight, Clapperboard, Moon, Plus, Search, Sun, X } from "lucide-react";import {Sidebar,SidebarContent,@@ -71,105 +22,36 @@ import {SidebarTrigger,useSidebar,} from "@/components/ui/sidebar";+import { Button } from "@/components/ui/button";import { Kbd } from "@/components/ui/kbd";-import { GlobalShortcuts } from "@/components/global-shortcuts";+import { CommandPalette, CommandPaletteProvider, useCommandPalette } from "@/components/command-palette";+import { IntentLink } from "@/components/intent-link";import { JobNotifications } from "@/components/job-notifications";+import { NAV, type NavGroupDef } from "@/components/nav-items";import { useEngineMode, useStatus } from "@/lib/api";-import { groupId, NAV_CLOSED_KEY, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";+import { useModKey } from "@/lib/keys";+import { groupId, isFullScreenStudio, NAV_CLOSED_KEY, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";import { cn } from "@/lib/utils";-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: [- { href: "/", label: "Home", icon: Home },- { href: "/assist", label: "Assist", icon: MessageCircle },- { href: "/image", label: "Image", icon: ImageIcon },- { href: "/video", label: "Video", icon: Video },- { href: "/edit", label: "Edit", icon: Wand2 },- { href: "/layers", label: "Layers", icon: Layers2 },- { href: "/inpaint", label: "Inpaint", icon: Brush },- { href: "/color-grade", label: "Color grading", icon: SlidersHorizontal },- { href: "/motions", label: "Camera motions", icon: Film },- { href: "/effects", label: "Effects", icon: Sparkles },- { href: "/storyboard", label: "Storyboard", icon: GalleryHorizontal },- { href: "/canvas", label: "Canvas", icon: Network },- { href: "/apps", label: "Apps", icon: LayoutGrid },- ],- },- {- label: "Studios",- items: [- { href: "/cinema", label: "Cinema Studio", icon: Clapperboard },- { href: "/shorts", label: "Shorts Studio", icon: Smartphone },- { href: "/mixed-media", label: "Mixed Media", icon: Shapes },- { href: "/marketing", label: "Marketing Studio", icon: Megaphone },- { href: "/ads", label: "Ads Studio", icon: Target },- { href: "/moodboards", label: "Moodboards", icon: Images },- { href: "/photodump", label: "Photodump", icon: Camera },- { href: "/fashion-factory", label: "Fashion Factory", icon: Shirt },- { href: "/character-sheet", label: "Character Sheet", icon: UserRoundCog },- { href: "/faceless", label: "Faceless Studio", icon: Tv },- { href: "/explainer", label: "Explainer", icon: Presentation },- { href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },- { href: "/motion-control", label: "Motion control", icon: PersonStanding },- { href: "/video-edit", label: "Edit video", icon: Scissors },- { href: "/extend", label: "Extend video", icon: FastForward },- { href: "/reframe", label: "Reframe", icon: Crop },- { href: "/video-tools", label: "Video tools", icon: Layers },- { href: "/elements", label: "Elements", icon: AtSign },- { href: "/upscale", label: "Upscale", icon: ZoomIn },- { href: "/audio", label: "Audio", icon: AudioLines },- { href: "/katana", label: "Katana", icon: Swords },- { href: "/image-to-3d", label: "Image to 3D", icon: Box },- { href: "/virality", label: "Virality predictor", icon: TrendingUp },- ],- collapsible: true,- },- {- label: "Engine",- items: [- { href: "/models", label: "Models", icon: Boxes },- { href: "/workflows", label: "ComfyUI workflows", short: "Workflows", icon: Workflow },- { href: "/settings", label: "Settings", icon: Settings },- { 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")} />;}+/**+ * The row's label. While the clicked row's route loads (useLinkStatus) it shimmers and the row+ * tints, so the click shows at once even when the next page takes a moment.+ */+function NavLabel({ children }: { children: React.ReactNode }) {+ const { pending } = useLinkStatus();+ return (+ <span data-pending={pending || undefined} className={cn(pending && "shimmer-text animate-shimmer-text")}>+ {children}+ </span>+ );+}+function Items({ group, pathname, search }: { group: NavGroupDef; pathname: string; search: URLSearchParams }) {const hrefs = group.items.map((i) => i.href);return group.items.map((item) => {@@ -180,12 +62,15 @@ function Items({ group, pathname, search }: { group: NavGroupDef; pathname: striasChildisActive={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]")}+ className={cn(+ "h-8 text-[13px] has-[[data-pending]]:bg-sidebar-accent 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}>+ <IntentLink href={item.href} eager={item.eager} 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>+ <NavLabel>{group.compact ? (item.short ?? item.label) : item.label}</NavLabel>+ </IntentLink></SidebarMenuButton></SidebarMenuItem>);@@ -208,11 +93,12 @@ function ActiveItems({ group }: { group: NavGroupDef }) {);}+/** The folded groups: remembered in this browser, else Studios and Engine (DEFAULT_NAV_CLOSED), also on the server. */function readClosed(): string[] {try {- return typeof window === "undefined" ? [] : parseClosed(localStorage.getItem(NAV_CLOSED_KEY));+ return parseClosed(typeof window === "undefined" ? null : localStorage.getItem(NAV_CLOSED_KEY));} catch {- return [];+ return parseClosed(null);}}@@ -231,7 +117,9 @@ function NavGroup({ group, open, onToggle }: { group: NavGroupDef; open: booleanclassName="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" />+ {/* Folded, the label says how much is inside. */}+ <span className="ml-auto font-normal tracking-normal tabular-nums group-data-[open=true]/nav:hidden">{group.items.length}</span>+ <ChevronRight className="ml-1 size-3.5 transition-transform group-data-[open=true]/nav:ml-auto group-data-[open=true]/nav:rotate-90" /></button></SidebarGroupLabel>) : (@@ -261,29 +149,75 @@ function SidebarStateScript() {);}-/** SidebarProvider that starts from the remembered expanded/collapsed state (the shadcn cookie). */+/** Tells the shell which page is open (the pathname is runtime data, so it's read inside Suspense). */+function PathWatcher({ onPath }: { onPath: (pathname: string) => void }) {+ const pathname = usePathname();+ useEffect(() => onPath(pathname), [pathname, onPath]);+ return null;+}++/**+ * SidebarProvider that starts from the remembered expanded/collapsed state (the shadcn cookie). On a+ * full-screen studio (isFullScreenStudio) the sidebar folds to its rail instead; opening it there+ * lasts until you leave that page, and neither writes the cookie.+ */export function SidebarShell({ children, style }: { children: React.ReactNode; style?: React.CSSProperties }) {- const [defaultOpen] = useState(() => (typeof document === "undefined" ? true : sidebarOpenFromCookie(document.cookie)));+ const [remembered, setRemembered] = useState(() => (typeof document === "undefined" ? true : sidebarOpenFromCookie(document.cookie)));+ // The first client render reads the URL itself, as the pre-paint script does, so hydration matches.+ const [path, setPath] = useState(() => (typeof window === "undefined" ? "" : window.location.pathname));+ const [peek, setPeek] = useState<{ path: string; open: boolean } | null>(null);+ const full = isFullScreenStudio(path);+ const open = full ? peek?.path === path && peek.open : remembered;+ const onOpenChange = useCallback((value: boolean) => (full ? setPeek({ path, open: value }) : setRemembered(value)), [full, path]);return (- <SidebarProvider defaultOpen={defaultOpen} style={style}>+ <SidebarProvider open={open} onOpenChange={onOpenChange} persistOpen={!full} style={style}>+ <Suspense fallback={null}>+ <PathWatcher onPath={setPath} />+ </Suspense>{children}</SidebarProvider>);}+/** The first stop for keyboard users: jumps past the sidebar to the page (WCAG 2.4.1). */+function SkipLink() {+ return (+ <a+ href="#content"+ onClick={(e) => {+ // Focus the page without adding #content to the URL (Settings reads its hash for deep links).+ const main = document.getElementById("content");+ if (!main) return;+ e.preventDefault();+ main.focus();+ }}+ className="sr-only rounded-md bg-background px-3 py-2 text-[13px] font-medium shadow-strong focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-50 focus:outline-2 focus:outline-ring"+ >+ Skip to content+ </a>+ );+}+/** 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 />- <JobNotifications />- </SidebarShell>+ <CommandPaletteProvider>+ <SidebarShell style={{ "--sidebar-width": "15.5rem", "--sidebar-width-icon": "3.25rem" } as React.CSSProperties}>+ <SkipLink />+ <AppSidebar />+ <SidebarInset+ id="content"+ tabIndex={-1}+ className="min-h-svh min-w-0 outline-none md:m-0 md:mt-2 md:rounded-none md:rounded-tl-xl md:border-t-[0.5px] md:border-l-[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>+ <CommandPalette />+ <JobNotifications />+ </SidebarShell>+ </CommandPaletteProvider>);}@@ -307,6 +241,43 @@ function useMoreBelow<T extends HTMLElement>() {return ref;}+/** "Search ⌘K": opens the palette (the keycaps only where there's a keyboard). */+function SearchRow() {+ const palette = useCommandPalette();+ const { isMobile, setOpenMobile } = useSidebar();+ const mod = useModKey();+ return (+ <SidebarMenuItem>+ <SidebarMenuButton+ tooltip={`Search (${mod} K)`}+ className="h-8 text-[13px]"+ aria-keyshortcuts="Meta+K Control+K"+ aria-haspopup="dialog"+ onClick={() => {+ if (isMobile) setOpenMobile(false);+ palette.setOpen(true);+ }}+ >+ <Search />+ <span>Search</span>+ <span className="ml-auto flex gap-0.5 group-data-[collapsible=icon]:hidden [@media(hover:none)]:hidden">+ <Kbd>{mod}</Kbd>+ <Kbd>K</Kbd>+ </span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+}++/** The GitHub mark (lucide has no brand icons). */+function GitHubMark() {+ return (+ <svg viewBox="0 0 16 16" aria-hidden fill="currentColor">+ <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8Z" />+ </svg>+ );+}+export function AppSidebar() {const { resolvedTheme, setTheme } = useTheme();const { isMobile, setOpenMobile } = useSidebar();@@ -334,96 +305,92 @@ export function AppSidebar() {return (<><Sidebar variant="inset" collapsible="icon">- <SidebarHeader className="pt-3" onClick={closeOnLink}>- <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- ref={content}- onClick={closeOnLink}- className="scrollbar-none fade-bottom group-data-[collapsible=icon]:overflow-y-auto"- >- {NAV.map((group, i) => {- const id = groupId(group.label);- return (- <Fragment key={id}>- {/* Icon mode hides the group labels: a hairline keeps the groups apart. */}- {i > 0 && <SidebarSeparator className="my-1 hidden group-data-[collapsible=icon]:block" />}- <NavGroup group={group} open={!group.collapsible || !closed.includes(id)} onToggle={() => toggle(id)} />- </Fragment>- );- })}- </SidebarContent>- <SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>- <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 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>+ {/* The whole sidebar is the app's navigation landmark (the page is the one main landmark). */}+ <nav aria-label="Main" className="flex min-h-0 w-full flex-1 flex-col">+ <SidebarHeader className="pt-3" onClick={closeOnLink}>+ <div className="flex h-9 items-center justify-between gap-2 px-1 group-data-[collapsible=icon]:justify-center">+ <IntentLink href="/" eager 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>+ </IntentLink>+ {isMobile ? (+ <Button variant="ghost" size="icon-sm" className="text-muted-foreground" onClick={() => setOpenMobile(false)} aria-label="Close menu">+ <X />+ </Button>+ ) : (+ <SidebarTrigger className="text-muted-foreground" />+ )}+ </div>+ <SidebarMenu>+ <SearchRow />+ <SidebarMenuItem>+ <SidebarMenuButton asChild tooltip="New creation" className="h-8 text-[13px] has-[[data-pending]]:bg-sidebar-accent">+ <IntentLink href="/" eager>+ <Plus />+ <NavLabel>New creation</NavLabel>+ </IntentLink>+ </SidebarMenuButton>+ </SidebarMenuItem>+ </SidebarMenu>+ </SidebarHeader>+ <SidebarContent ref={content} onClick={closeOnLink} className="scrollbar-none fade-bottom group-data-[collapsible=icon]:overflow-y-auto">+ {NAV.map((group, i) => {+ const id = groupId(group.label);+ return (+ <Fragment key={id}>+ {/* Icon mode hides the group labels: a hairline keeps the groups apart. */}+ {i > 0 && <SidebarSeparator className="my-1 hidden group-data-[collapsible=icon]:block" />}+ <NavGroup group={group} open={!group.collapsible || !closed.includes(id)} onToggle={() => toggle(id)} />+ </Fragment>+ );+ })}+ </SidebarContent>+ <SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>+ <IntentLink+ 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-muted-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>+ )}+ </IntentLink>+ <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="Source code 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="Source code on GitHub">+ <GitHubMark />+ <span className="sr-only">Source code on GitHub</span>+ </a>+ </SidebarMenuButton>+ </SidebarMenuItem>+ </SidebarMenu>+ </SidebarFooter>+ </nav><SidebarRail /></Sidebar><SidebarStateScript />diff --git a/src/components/command-palette.tsx b/src/components/command-palette.tsxnew file mode 100644index 00000000..a0a1acf6--- /dev/null+++ b/src/components/command-palette.tsx@@ -0,0 +1,265 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { Bell, Clapperboard, Cpu, Film, KeyRound, LayoutGrid, Loader2, Plus, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";+import { useRouter } from "next/navigation";+import { createContext, lazy, Suspense, useCallback, useContext, useDeferredValue, useEffect, useMemo, useState } from "react";+import { NAV } from "@/components/nav-items";+import { MediaThumb } from "@/components/studio/result-media";+import { CommandDialog, CommandEmpty, CommandGroup, CommandItem, CommandList } from "@/components/ui/command";+import { Kbd } from "@/components/ui/kbd";+import { Command as CommandPrimitive } from "cmdk";+import { useEngineMode, useGenerations } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { indexEntries, KIND_LABELS, rankPalette, type PaletteEntry, type PaletteIndex, type PaletteKind } from "@/lib/command-search";+import { useModKey } from "@/lib/keys";+import { userTitle } from "@/lib/library";+import { cn } from "@/lib/utils";++// The viewer is only needed once a recent creation is opened from the palette.+const Viewer = lazy(() => import("@/components/studio/viewer").then((m) => ({ default: m.Viewer })));++interface PaletteState {+ open: boolean;+ setOpen: (open: boolean | ((open: boolean) => boolean)) => void;+}++const PaletteContext = createContext<PaletteState>({ open: false, setOpen: () => {} });++/** Opens and closes the ⌘K palette from anywhere in the app frame (the sidebar's Search row, the phone header, ⌘K). */+export const useCommandPalette = () => useContext(PaletteContext);++export function CommandPaletteProvider({ children }: { children: React.ReactNode }) {+ const [open, setOpen] = useState(false);+ const value = useMemo(() => ({ open, setOpen }), [open]);+ return <PaletteContext.Provider value={value}>{children}</PaletteContext.Provider>;+}++/** Settings sections the palette jumps to (ids in settings-form.tsx). */+const SETTINGS: { id: string; label: string; icon: LucideIcon; keywords: string }[] = [+ { id: "cloud", label: "API keys", icon: KeyRound, keywords: "fal replicate higgsfield paid cloud connect" },+ { id: "comfyui", label: "ComfyUI server", icon: Server, keywords: "open source gpu url connect local" },+ { id: "engine", label: "Engine mode", icon: Cpu, keywords: "open source cloud both" },+ { id: "enhance", label: "Prompt enhancement", icon: Sparkles, keywords: "claude ollama enhancer llm" },+ { id: "notifications", label: "Notifications", icon: Bell, keywords: "browser done alerts" },+ { id: "security", label: "Password and API tokens", icon: ShieldCheck, keywords: "security sign in mcp token" },+ { id: "demo", label: "Demo mode", icon: Settings2, keywords: "placeholder free try" },+];++const PAGES: (PaletteEntry & { icon: LucideIcon })[] = NAV.flatMap((g) =>+ g.items.map((i) => ({ key: `page:${i.href}`, kind: "page" as const, label: i.label, hint: g.label, href: i.href, keywords: i.keywords, icon: i.icon })),+);+const SETTING_ENTRIES: (PaletteEntry & { icon: LucideIcon })[] = SETTINGS.map((s) => ({+ key: `setting:${s.id}`,+ kind: "setting",+ label: s.label,+ hint: "Settings",+ href: `/settings#${s.id}`,+ keywords: s.keywords,+ icon: s.icon,+}));+// Icons as elements made once (a component picked during render would remount on every keystroke).+const iconEl = (Icon: LucideIcon) => <Icon className="text-muted-foreground" />;+const ICONS = new Map<string, React.ReactNode>([...PAGES, ...SETTING_ENTRIES].map((e) => [e.key, iconEl(e.icon)]));+const KIND_ICONS: Partial<Record<PaletteKind, React.ReactNode>> = { app: iconEl(LayoutGrid), motion: iconEl(Film), effect: iconEl(Wand2), model: iconEl(Clapperboard) };++function useDebounced<T>(value: T, ms: number): T {+ const [v, setV] = useState(value);+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms);+ return () => clearTimeout(t);+ }, [value, ms]);+ return v;+}++// The hints are marked as shortcuts so CommandItem drops its check mark, which would share the row's free space with them.+function Row({ entry, onPick }: { entry: PaletteEntry; onPick: (e: PaletteEntry) => void }) {+ return (+ <CommandItem value={entry.key} onSelect={() => onPick(entry)} className="h-9 gap-2.5 text-[14px]">+ {ICONS.get(entry.key) ?? KIND_ICONS[entry.kind] ?? KIND_ICONS.app}+ <span className="min-w-0 truncate">{entry.label}</span>+ {entry.hint && <span data-slot="command-shortcut" className="ml-auto shrink-0 truncate pl-2 text-[12px] text-muted-foreground max-sm:max-w-[40%]">{entry.hint}</span>}+ </CommandItem>+ );+}++function RecentRow({ g, onOpen }: { g: Generation; onOpen: (g: Generation) => void }) {+ const title = userTitle(g);+ return (+ <CommandItem value={`recent:${g.id}`} onSelect={() => onOpen(g)} className="h-11 gap-2.5 text-[14px]">+ <span className="relative size-8 shrink-0 overflow-hidden rounded-md bg-muted">{g.outputs[0] && <MediaThumb output={g.outputs[0]} g={g} />}</span>+ <span className="min-w-0 truncate">{title}</span>+ <span data-slot="command-shortcut" className="ml-auto shrink-0 pl-2 text-[12px] text-muted-foreground">{g.modelName}</span>+ </CommandItem>+ );+}++function Hints() {+ const mod = useModKey();+ return (+ <div className="flex items-center gap-3 border-t px-3 py-2 text-[12px] text-muted-foreground [@media(hover:none)]:hidden">+ <span className="flex items-center gap-1">+ <Kbd>↑</Kbd>+ <Kbd>↓</Kbd> to move+ </span>+ <span className="flex items-center gap-1">+ <Kbd>↵</Kbd> to open+ </span>+ <span className="flex items-center gap-1">+ <Kbd>Esc</Kbd> to close+ </span>+ <span className="ml-auto flex items-center gap-1">+ <Kbd>{mod}</Kbd>+ <Kbd>K</Kbd>+ </span>+ </div>+ );+}++/** What the palette lists and searches; mounted only while it's open. */+function PaletteBody({ onPick, onOpenRecent }: { onPick: (e: PaletteEntry) => void; onOpenRecent: (g: Generation) => void }) {+ const [q, setQ] = useState("");+ const query = useDeferredValue(q);+ const dq = useDebounced(q.trim(), 200);+ const mode = useEngineMode();+ // The apps, motions, effects and models load on first open (and stay for the session).+ const index = useQuery({+ queryKey: ["palette-index"],+ queryFn: async () => (await fetch("/api/palette")).json() as Promise<PaletteIndex>,+ staleTime: Infinity,+ });+ const recent = useGenerations({ q: dq || undefined, limit: 5, statuses: ["succeeded"] }, { keepPrevious: true });+ const entries = useMemo(() => [...PAGES, ...SETTING_ENTRIES, ...(index.data ? indexEntries(index.data, mode) : [])], [index.data, mode]);+ const groups = useMemo(() => rankPalette(entries, query), [entries, query]);+ const recentItems = (recent.data ?? []).filter((g) => g.outputs[0]);+ const searching = !!query.trim();+ // cmdk keeps no selection once the rows change (shouldFilter is off): every new query starts on its+ // best match, so Enter opens it; arrows move from there.+ const best = searching ? (groups[0]?.entries[0]?.key ?? (recentItems[0] ? `recent:${recentItems[0].id}` : "")) : "new";+ const [moved, setMoved] = useState<{ query: string; value: string } | null>(null);+ const selected = moved?.query === query ? moved.value : best;++ return (+ <CommandPrimitive shouldFilter={false} loop value={selected} onValueChange={(value) => setMoved({ query, value })} label="Search Fuobe" className="flex flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground">+ <div className="flex items-center gap-2 border-b px-3">+ <CommandPrimitive.Input+ value={q}+ onValueChange={setQ}+ autoFocus+ placeholder="Search pages, apps, motions, effects, models…"+ aria-label="Search Fuobe"+ className="h-12 min-w-0 flex-1 bg-transparent text-[15px] outline-none placeholder:text-subtle-foreground"+ />+ {index.isLoading && searching && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" aria-label="Loading the catalog" />}+ </div>+ <CommandList className="max-h-[min(60vh,440px)] p-1.5">+ {searching ? (+ <>+ <CommandEmpty className="py-10 text-center text-[13px] text-muted-foreground">+ {index.isLoading ? "Looking through apps, motions and models…" : `Nothing matches “${query.trim()}”.`}+ </CommandEmpty>+ {groups.map((g) => (+ <CommandGroup key={g.kind} heading={g.label}>+ {g.entries.map((e) => (+ <Row key={e.key} entry={e} onPick={onPick} />+ ))}+ </CommandGroup>+ ))}+ {recentItems.length > 0 && (+ <CommandGroup heading={KIND_LABELS.recent}>+ {recentItems.map((g) => (+ <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />+ ))}+ </CommandGroup>+ )}+ </>+ ) : (+ <>+ <CommandGroup>+ {/* Enter on an empty query keeps what ⌘K always did: a new creation. */}+ <CommandItem value="new" onSelect={() => onPick({ key: "new", kind: "page", label: "New creation", href: "/" })} className="h-9 gap-2.5 text-[14px]">+ <Plus className="text-muted-foreground" />+ New creation+ <span data-slot="command-shortcut" className="ml-auto text-[12px] text-muted-foreground">Home</span>+ </CommandItem>+ </CommandGroup>+ {recentItems.length > 0 && (+ <CommandGroup heading={KIND_LABELS.recent}>+ {recentItems.map((g) => (+ <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />+ ))}+ </CommandGroup>+ )}+ <CommandGroup heading={KIND_LABELS.page}>+ {PAGES.map((e) => (+ <Row key={e.key} entry={e} onPick={onPick} />+ ))}+ </CommandGroup>+ <CommandGroup heading={KIND_LABELS.setting}>+ {SETTING_ENTRIES.map((e) => (+ <Row key={e.key} entry={e} onPick={onPick} />+ ))}+ </CommandGroup>+ </>+ )}+ </CommandList>+ <Hints />+ </CommandPrimitive>+ );+}++/**+ * The ⌘K / Ctrl+K palette: every page, settings section, app, camera motion, effect and model, and+ * your recent creations, with a forgiving search (src/lib/command-search.ts). Rendered once, in the+ * app frame.+ */+export function CommandPalette() {+ const { open, setOpen } = useCommandPalette();+ const router = useRouter();+ const [viewing, setViewing] = useState<Generation | null>(null);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "k") {+ e.preventDefault();+ setOpen((o) => !o);+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [setOpen]);++ const pick = useCallback(+ (e: PaletteEntry) => {+ setOpen(false);+ router.push(e.href);+ },+ [router, setOpen],+ );+ const openRecent = useCallback(+ (g: Generation) => {+ setOpen(false);+ setViewing(g);+ },+ [setOpen],+ );++ return (+ <>+ <CommandDialog+ open={open}+ onOpenChange={setOpen}+ title="Search Fuobe"+ description="Go to a page, an app, a camera motion, an effect, a model, a settings section or a recent creation."+ className={cn("top-[8vh] gap-0 p-0 sm:top-[14vh] sm:max-w-xl")}+ >+ <PaletteBody onPick={pick} onOpenRecent={openRecent} />+ </CommandDialog>+ {viewing && (+ <Suspense fallback={null}>+ <Viewer generation={viewing} index={0} onClose={() => setViewing(null)} />+ </Suspense>+ )}+ </>+ );+}diff --git a/src/components/empty-state.tsx b/src/components/empty-state.tsxindex 3c0f5c3c..ab479792 100644--- a/src/components/empty-state.tsx+++ b/src/components/empty-state.tsx@@ -4,7 +4,7 @@ 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 { PhoneBar } from "@/components/phone-bar";import { Button } from "@/components/ui/button";/** A calm full-page state (Liner style): serif headline, one muted line, one or two actions. */@@ -21,9 +21,7 @@ export function PageState({}) {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>+ <PhoneBar className="bg-transparent backdrop-blur-none" /><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" />diff --git a/src/components/global-shortcuts.tsx b/src/components/global-shortcuts.tsxdeleted file mode 100644index b03ab8a4..00000000--- a/src/components/global-shortcuts.tsx+++ /dev/null@@ -1,20 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useEffect } from "react";--/** ⌘K / Ctrl+K → new creation. */-export function GlobalShortcuts() {- const router = useRouter();- useEffect(() => {- const onKey = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {- e.preventDefault();- router.push("/");- }- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [router]);- return null;-}diff --git a/src/components/intent-link.tsx b/src/components/intent-link.tsxnew file mode 100644index 00000000..289f8235--- /dev/null+++ b/src/components/intent-link.tsx@@ -0,0 +1,62 @@+"use client";++import { Loader2 } from "lucide-react";+import Link, { useLinkStatus } from "next/link";+import { useState } from "react";+import { cn } from "@/lib/utils";++/**+ * A Link that prefetches on intent: nothing while it merely sits on screen, then the usual prefetch+ * once the pointer is over it, a finger touches it or it gets keyboard focus (the "hover-triggered+ * prefetch" of Next's prefetching guide). `eager` rows prefetch as soon as they're on screen, like a+ * plain Link: the few routes most visits go to next. A page full of these no longer fetches every+ * route behind it on a cold visit.+ */+export function IntentLink({+ eager,+ onMouseEnter,+ onTouchStart,+ onFocus,+ ...props+}: React.ComponentProps<typeof Link> & { eager?: boolean }) {+ const [intent, setIntent] = useState(false);+ return (+ <Link+ {...props}+ prefetch={eager || intent ? null : false}+ onMouseEnter={(e) => {+ setIntent(true);+ onMouseEnter?.(e);+ }}+ onTouchStart={(e) => {+ setIntent(true);+ onTouchStart?.(e);+ }}+ onFocus={(e) => {+ setIntent(true);+ onFocus?.(e);+ }}+ />+ );+}++/**+ * Click feedback on a card while its page loads (useLinkStatus: the moment between the click and the+ * new route). Put it inside a positioned Link; it takes no space and only shows when the route is slow+ * (the fade starts after 120 ms), so fast navigations don't flash.+ */+export function CardPending({ className }: { className?: string }) {+ const { pending } = useLinkStatus();+ if (!pending) return null;+ return (+ <span+ aria-hidden+ className={cn(+ "pointer-events-none absolute inset-0 grid animate-pending-in place-items-center rounded-[inherit] bg-black/25 text-white",+ className,+ )}+ >+ <Loader2 className="size-5 animate-spin" />+ </span>+ );+}diff --git a/src/components/nav-items.ts b/src/components/nav-items.tsnew file mode 100644index 00000000..b84b2930--- /dev/null+++ b/src/components/nav-items.ts@@ -0,0 +1,135 @@+import {+ AtSign,+ AudioLines,+ Boxes,+ Box,+ Brush,+ Camera,+ Clapperboard,+ Crop,+ FastForward,+ Film,+ GalleryHorizontal,+ Home,+ ImageIcon,+ Images,+ Layers,+ Layers2,+ LayoutGrid,+ Library,+ ListChecks,+ Megaphone,+ MessageCircle,+ Mic2,+ Network,+ PersonStanding,+ Presentation,+ Scissors,+ Settings,+ Shapes,+ Shirt,+ SlidersHorizontal,+ Smartphone,+ Sparkles,+ Star,+ Swords,+ Target,+ TrendingUp,+ Tv,+ UserRoundCog,+ Video,+ Wand2,+ Workflow,+ ZoomIn,+ type LucideIcon,+} from "lucide-react";++export interface NavItem {+ href: string;+ label: string;+ icon: LucideIcon;+ /** Shorter label for compact groups (the full one is the tooltip). */+ short?: string;+ /** Prefetched as soon as it's on screen (the rows most visits start from); the others wait for a hover or touch. */+ eager?: boolean;+ /** More words the ⌘K palette matches ("tts" finds Audio). */+ keywords?: string;+}++export interface NavGroupDef {+ label: string;+ items: NavItem[];+ /** Can be folded away; the choice is remembered (Studios and Engine start folded, see DEFAULT_NAV_CLOSED). */+ collapsible?: boolean;+ /** Two small items per row. */+ compact?: boolean;+}++/** The sidebar, and the destinations of the ⌘K palette. Add a destination with one line in the right group. */+export const NAV: NavGroupDef[] = [+ {+ label: "Create",+ items: [+ { href: "/", label: "Home", icon: Home, eager: true, keywords: "start new creation" },+ { href: "/assist", label: "Assist", icon: MessageCircle, eager: true, keywords: "agent chat plan" },+ { href: "/image", label: "Image", icon: ImageIcon, eager: true, keywords: "text to image picture photo" },+ { href: "/video", label: "Video", icon: Video, eager: true, keywords: "text to video image to video animate" },+ { href: "/edit", label: "Edit", icon: Wand2, keywords: "edit image change" },+ { href: "/layers", label: "Layers", icon: Layers2, keywords: "layered psd split" },+ { href: "/inpaint", label: "Inpaint", icon: Brush, keywords: "mask fill remove" },+ { href: "/color-grade", label: "Color grading", icon: SlidersHorizontal, keywords: "grade lut colour" },+ { href: "/motions", label: "Camera motions", icon: Film, keywords: "camera moves presets" },+ { href: "/effects", label: "Effects", icon: Sparkles, keywords: "vfx presets" },+ { href: "/storyboard", label: "Storyboard", icon: GalleryHorizontal, keywords: "frames story" },+ { href: "/canvas", label: "Canvas", icon: Network, keywords: "nodes flow workflow" },+ { href: "/apps", label: "Apps", icon: LayoutGrid, keywords: "one-click tools" },+ ],+ },+ {+ label: "Library",+ items: [+ { href: "/library", label: "All creations", icon: Library, eager: true, keywords: "library history results" },+ { href: "/library?tab=favorites", label: "Favorites", icon: Star, keywords: "starred liked" },+ ],+ },+ {+ label: "Studios",+ items: [+ { href: "/cinema", label: "Cinema Studio", icon: Clapperboard, keywords: "film director shots" },+ { href: "/shorts", label: "Shorts Studio", icon: Smartphone, keywords: "vertical reels tiktok" },+ { href: "/mixed-media", label: "Mixed Media", icon: Shapes, keywords: "collage" },+ { href: "/marketing", label: "Marketing Studio", icon: Megaphone, keywords: "ugc product ads" },+ { href: "/ads", label: "Ads Studio", icon: Target, keywords: "brand campaign" },+ { href: "/moodboards", label: "Moodboards", icon: Images, keywords: "style references" },+ { href: "/photodump", label: "Photodump", icon: Camera, keywords: "photo pack character" },+ { href: "/fashion-factory", label: "Fashion Factory", icon: Shirt, keywords: "outfits try-on lookbook" },+ { href: "/character-sheet", label: "Character Sheet", icon: UserRoundCog, keywords: "turnaround" },+ { href: "/faceless", label: "Faceless Studio", icon: Tv, keywords: "youtube channel episodes" },+ { href: "/explainer", label: "Explainer", icon: Presentation, keywords: "slides pdf video" },+ { href: "/lipsync", label: "Lipsync & avatars", icon: Mic2, keywords: "talking avatar" },+ { href: "/motion-control", label: "Motion control", icon: PersonStanding, keywords: "pose dance transfer" },+ { href: "/video-edit", label: "Edit video", icon: Scissors, keywords: "video edit restyle" },+ { href: "/extend", label: "Extend video", icon: FastForward, keywords: "longer continue" },+ { href: "/reframe", label: "Reframe", icon: Crop, keywords: "aspect ratio outpaint" },+ { href: "/video-tools", label: "Video tools", icon: Layers, keywords: "join trim matte depth captions" },+ { href: "/elements", label: "Elements", icon: AtSign, keywords: "characters places props" },+ { href: "/upscale", label: "Upscale", icon: ZoomIn, keywords: "enhance resolution 4k" },+ { href: "/audio", label: "Audio", icon: AudioLines, keywords: "voice tts music sfx dub transcribe" },+ { href: "/katana", label: "Katana", icon: Swords, keywords: "cut edit clips" },+ { href: "/image-to-3d", label: "Image to 3D", icon: Box, keywords: "3d mesh glb" },+ { href: "/virality", label: "Virality predictor", icon: TrendingUp, keywords: "hook score" },+ ],+ collapsible: true,+ },+ {+ label: "Engine",+ items: [+ { href: "/models", label: "Models", icon: Boxes, keywords: "catalog prices" },+ { href: "/workflows", label: "ComfyUI workflows", short: "Workflows", icon: Workflow, keywords: "open source graphs" },+ { href: "/settings", label: "Settings", icon: Settings, keywords: "keys preferences" },+ { href: "/status", label: "Project status", short: "Status", icon: ListChecks, keywords: "parity progress" },+ ],+ collapsible: true,+ compact: true,+ },+];diff --git a/src/components/page-shell.tsx b/src/components/page-shell.tsxindex b841b356..ace1029b 100644--- a/src/components/page-shell.tsx+++ b/src/components/page-shell.tsx@@ -1,13 +1,11 @@-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneBar } from "@/components/phone-bar";import { cn } from "@/lib/utils";/** Scrollable page body for non-studio pages (galleries, settings, library). */export function PageShell({ children, wide }: { children: React.ReactNode; wide?: boolean }) {return (<div className="flex min-h-svh min-w-0 flex-col">- <div className="sticky top-0 z-20 flex h-12 items-center bg-background/85 px-3 backdrop-blur md:hidden">- <SidebarTrigger />- </div>+ <PhoneBar /><div className={cn("mx-auto w-full min-w-0 flex-1 px-4 pt-4 pb-16 sm:px-8 md:pt-12", wide ? "max-w-[1400px]" : "max-w-[1200px]")}>{children}</div></div>);diff --git a/src/components/phone-bar.tsx b/src/components/phone-bar.tsxnew file mode 100644index 00000000..c66baf6d--- /dev/null+++ b/src/components/phone-bar.tsx@@ -0,0 +1,31 @@+"use client";++import { Search } from "lucide-react";+import { IntentLink } from "@/components/intent-link";+import { useCommandPalette } from "@/components/command-palette";+import { Button } from "@/components/ui/button";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { cn } from "@/lib/utils";++/** Opens the ⌘K palette: the way to search on a phone, where there's no keyboard shortcut. */+export function SearchButton({ className }: { className?: string }) {+ const palette = useCommandPalette();+ return (+ <Button variant="ghost" size="icon-sm" className={cn("text-muted-foreground", className)} aria-label="Search" aria-haspopup="dialog" onClick={() => palette.setOpen(true)}>+ <Search />+ </Button>+ );+}++/** The phone header of gallery and settings pages: the menu, the wordmark (home) and search. Hidden from md up, where the sidebar shows. */+export function PhoneBar({ className }: { className?: string }) {+ return (+ <div className={cn("sticky top-0 z-20 flex h-12 items-center gap-1.5 bg-background/85 px-3 backdrop-blur md:hidden", className)}>+ <SidebarTrigger />+ <IntentLink href="/" eager className="rounded-md px-1 font-heading text-[20px] leading-none outline-none focus-visible:ring-2 focus-visible:ring-ring">+ Fuobe+ </IntentLink>+ <SearchButton className="ml-auto" />+ </div>+ );+}diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsxindex f952f172..2fd4a961 100644--- a/src/components/ui/command.tsx+++ b/src/components/ui/command.tsx@@ -48,10 +48,6 @@ function CommandDialog({}) {return (<Dialog {...props}>- <DialogHeader className="sr-only">- <DialogTitle>{title}</DialogTitle>- <DialogDescription>{description}</DialogDescription>- </DialogHeader><DialogContentclassName={cn("top-1/3 translate-y-0 overflow-hidden rounded-xl! p-0",@@ -59,6 +55,11 @@ function CommandDialog({)}showCloseButton={showCloseButton}>+ {/* Inside the content: outside it, the hidden title sat in the page, closed, outside every landmark. */}+ <DialogHeader className="sr-only">+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>{children}</DialogContent></Dialog>diff --git a/src/components/ui/sidebar.tsx b/src/components/ui/sidebar.tsxindex 6cb2cfe6..a4d9a7e9 100644--- a/src/components/ui/sidebar.tsx+++ b/src/components/ui/sidebar.tsx@@ -22,7 +22,7 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip"-import { PanelLeftIcon } from "lucide-react"+import { MenuIcon, PanelLeftIcon } from "lucide-react"const SIDEBAR_COOKIE_NAME = "sidebar_state"const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7@@ -56,6 +56,7 @@ function SidebarProvider({defaultOpen = true,open: openProp,onOpenChange: setOpenProp,+ persistOpen = true,className,style,children,@@ -64,6 +65,8 @@ function SidebarProvider({defaultOpen?: booleanopen?: booleanonOpenChange?: (open: boolean) => void+ /** Remember the expanded/collapsed choice in the cookie (off while a page decides it for itself). */+ persistOpen?: boolean}) {const isMobile = useIsMobile()const [openMobile, setOpenMobile] = React.useState(false)@@ -82,9 +85,9 @@ function SidebarProvider({}// This sets the cookie to keep the sidebar state.- document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`+ if (persistOpen) document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`},- [setOpenProp, open]+ [setOpenProp, open, persistOpen])// Helper to toggle the sidebar.@@ -270,7 +273,9 @@ function SidebarTrigger({}}{...props}>- <PanelLeftIcon />+ {/* Phones get the familiar menu glyph (the sidebar is a drawer there), wider screens the panel. */}+ <MenuIcon className="md:hidden" />+ <PanelLeftIcon className="max-md:hidden" /><span className="sr-only">Toggle Sidebar</span></Button>)diff --git a/src/lib/command-search.ts b/src/lib/command-search.tsnew file mode 100644index 00000000..001d791a--- /dev/null+++ b/src/lib/command-search.ts@@ -0,0 +1,191 @@+/**+ * The ⌘K palette's search (pure, so it's testable): a forgiving word match, and the matches grouped+ * by kind, best first. The palette (src/components/command-palette.tsx) renders what this returns.+ */++export type PaletteKind = "page" | "setting" | "app" | "motion" | "effect" | "model" | "recent";++export interface PaletteEntry {+ /** Unique in the palette. */+ key: string;+ kind: PaletteKind;+ label: string;+ /** Shown next to the label: a category, a vendor, the group a page is in. */+ hint?: string;+ href: string;+ /** More words that find it, worth less than the label. */+ keywords?: string;+}++/** Group headings, in the order groups take when their best matches tie. */+export const KIND_LABELS: Record<PaletteKind, string> = {+ page: "Go to",+ setting: "Settings",+ app: "Apps",+ motion: "Camera motions",+ effect: "Effects",+ model: "Models",+ recent: "Recent creations",+};+const KIND_ORDER = Object.keys(KIND_LABELS) as PaletteKind[];++/** Pages and settings are where people mostly go: they win close calls against a preset of the same name. */+const KIND_BONUS: Partial<Record<PaletteKind, number>> = { page: 8, setting: 4 };++/** Lower case, no accents, punctuation as spaces ("Lipsync & avatars" → "lipsync avatars"). */+export function normalize(s: string): string {+ return s+ .normalize("NFKD")+ .replace(/[̀-ͯ]/g, "")+ .toLowerCase()+ .replace(/[^a-z0-9.+#]+/g, " ")+ .trim();+}++/**+ * How well one query word matches a (normalized) text, 0 for no match: the whole text (100), its+ * start (80, or 70 when the text's spaces are ignored: "faceswap"), the start of a later word (60),+ * anywhere inside (40), then the word's letters in order (fuzzy, 10–30: more when they start words+ * or follow each other). A one-letter word only matches the start of a word.+ */+export function wordScore(word: string, text: string): number {+ if (!word || !text) return 0;+ if (text === word) return 100;+ if (text.startsWith(word)) return 80;+ if (text.replace(/ /g, "").startsWith(word)) return 70;+ if (text.includes(` ${word}`)) return 60;+ if (word.length < 2) return 0;+ if (text.includes(word)) return 40;+ return fuzzy(word, text);+}++/**+ * The letters of `word` in order in `text`: a typo or an abbreviation ("cinma" finds "cinema", "bg"+ * finds "background"). Two letters must start at the start of a word.+ */+function fuzzy(word: string, text: string): number {+ let at = -1;+ let first = -1;+ let bonus = 0;+ for (const ch of word) {+ const next = text.indexOf(ch, at + 1);+ if (next < 0) return 0;+ if (first < 0) {+ if (word.length < 3 && next > 0 && text[next - 1] !== " ") return 0;+ first = next;+ }+ if (next === at + 1) bonus += 2;+ if (next === 0 || text[next - 1] === " ") bonus += 3;+ at = next;+ }+ // Letters scattered over a long stretch are a weak match.+ const spread = at - first + 1;+ if (spread > word.length * 3) return 0;+ return Math.min(30, 10 + bonus);+}++/**+ * The entry's score for a query (0 = leave it out): every query word must match the label or the+ * keywords. Label matches count in full, keyword matches at half; pages and settings get a small+ * bonus, and a shorter label wins a tie ("Video" before "Video tools").+ */+export function entryScore(query: string, e: PaletteEntry): number {+ const words = normalize(query).split(" ").filter(Boolean);+ if (!words.length) return 0;+ const label = normalize(e.label);+ const extra = normalize(`${e.hint ?? ""} ${e.keywords ?? ""}`);+ let total = 0;+ for (const w of words) {+ const s = Math.max(wordScore(w, label), wordScore(w, extra) / 2);+ if (!s) return 0;+ total += s;+ }+ // The whole query reading as the label's start beats the same words matched one by one.+ const q = words.join(" ");+ if (words.length > 1 && label.startsWith(q)) total += 20;+ return total / words.length + (KIND_BONUS[e.kind] ?? 0) - label.length / 100;+}++export interface PaletteGroup {+ kind: PaletteKind;+ label: string;+ entries: PaletteEntry[];+}++/** How many matches each group shows. */+export const GROUP_LIMIT: Record<PaletteKind, number> = { page: 6, setting: 4, app: 5, motion: 4, effect: 4, model: 5, recent: 5 };++/** Matches far weaker than the best one are noise next to it ("lip" finds Lipsync, not "virality predictor"). */+const KEEP_FROM_BEST = 0.35;++/**+ * The matches for a query, grouped by kind: each group best first and cut to its limit, the groups+ * ordered by their best match (KIND_ORDER on a tie). Matches much weaker than the best are left out,+ * so letters-in-order guesses only show when nothing matches better. An empty query matches+ * nothing; the palette shows its own starting list then.+ */+export function rankPalette(entries: PaletteEntry[], query: string, limits: Record<PaletteKind, number> = GROUP_LIMIT): PaletteGroup[] {+ if (!normalize(query)) return [];+ const scored = entries.map((e) => ({ e, s: entryScore(query, e) })).filter((x) => x.s > 0);+ const floor = Math.max(0, ...scored.map((x) => x.s)) * KEEP_FROM_BEST;+ const byKind = new Map<PaletteKind, { e: PaletteEntry; s: number }[]>();+ for (const x of scored) {+ if (x.s < floor) continue;+ const list = byKind.get(x.e.kind) ?? [];+ list.push(x);+ byKind.set(x.e.kind, list);+ }+ return [...byKind.entries()]+ .map(([kind, list]) => {+ list.sort((a, b) => b.s - a.s);+ return { kind, label: KIND_LABELS[kind], best: list[0].s, entries: list.slice(0, limits[kind]).map((x) => x.e) };+ })+ .sort((a, b) => b.best - a.best || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind))+ .map(({ kind, label, entries }) => ({ kind, label, entries }));+}++/** The slim catalog the palette loads on first open (GET /api/palette). */+export interface PaletteIndex {+ apps: PalettePreset[];+ motions: PalettePreset[];+ effects: PalettePreset[];+ models: PaletteModel[];+}++export interface PalettePreset {+ id: string;+ name: string;+ category: string;+ /** Has a cloud / an open-source route. */+ cloud: boolean;+ open: boolean;+}++export interface PaletteModel {+ id: string;+ name: string;+ vendor: string;+ engine: "cloud" | "open";+ /** The studio that runs it (with ?model=), or the Models page. */+ href: string;+ /** What it does ("Text to image, Edit"). */+ ops: string;+}++/**+ * The palette's entries from the index, for one engine mode: with one engine locked in Settings, a+ * preset needs a route on that engine and a model must be on it, as in the galleries and pickers.+ */+export function indexEntries(index: PaletteIndex, mode: "both" | "cloud" | "open"): PaletteEntry[] {+ const runs = (p: PalettePreset) => mode === "both" || p[mode];+ const presets = (list: PalettePreset[], kind: "app" | "motion" | "effect", href: (id: string) => string) =>+ list.filter(runs).map((p): PaletteEntry => ({ key: `${kind}:${p.id}`, kind, label: p.name, hint: p.category, href: href(p.id) }));+ return [+ ...presets(index.apps, "app", (id) => `/apps/${id}`),+ ...presets(index.motions, "motion", (id) => `/video?preset=${id}`),+ ...presets(index.effects, "effect", (id) => `/video?preset=${id}`),+ ...index.models+ .filter((m) => mode === "both" || m.engine === mode)+ .map((m): PaletteEntry => ({ key: `model:${m.id}`, kind: "model", label: m.name, hint: m.vendor, href: m.href, keywords: `${m.ops} ${m.engine === "open" ? "open source free" : "cloud"}` })),+ ];+}diff --git a/src/lib/keys.ts b/src/lib/keys.tsnew file mode 100644index 00000000..95eaa344--- /dev/null+++ b/src/lib/keys.ts@@ -0,0 +1,21 @@+import { useSyncExternalStore } from "react";++/** Apple keyboards say ⌘ where everyone else says Ctrl. */+export function isApplePlatform(platform: string): boolean {+ return /Mac|iPhone|iPad|iPod/.test(platform);+}++/** The modifier key's name for this browser: "⌘" on Apple devices, "Ctrl" elsewhere (and on the server). */+export function modKey(): "⌘" | "Ctrl" {+ return typeof navigator !== "undefined" && isApplePlatform(navigator.platform) ? "⌘" : "Ctrl";+}++const noop = () => () => {};++/**+ * The modifier key's name, after hydration: the server and the first client render say "Ctrl", so a+ * keycap never makes the HTML and the first render disagree.+ */+export function useModKey(): "⌘" | "Ctrl" {+ return useSyncExternalStore(noop, modKey, () => "Ctrl");+}diff --git a/src/lib/nav.ts b/src/lib/nav.tsindex 3b4e556b..ef894354 100644--- a/src/lib/nav.ts+++ b/src/lib/nav.ts@@ -2,6 +2,11 @@/** Group labels the user collapsed, in localStorage. */export const NAV_CLOSED_KEY = "fuobe:nav-closed";+/**+ * Folded until the user opens them (nothing remembered yet): the sidebar starts short, with Create+ * and Library in view. ⌘K reaches everything in the folded groups too.+ */+export const DEFAULT_NAV_CLOSED: readonly string[] = ["studios", "engine"];/** Written by the shadcn SidebarProvider ("true" / "false"). */export const SIDEBAR_COOKIE = "sidebar_state";@@ -31,13 +36,16 @@ export function navActive(href: string, pathname: string, search: URLSearchParam});}-/** Read the collapsed groups (ids) from storage; tolerant of anything unexpected. */+/**+ * Read the collapsed groups (ids) from storage; tolerant of anything unexpected. Nothing stored (or+ * nothing readable) means the defaults; a stored list, even an empty one, is the user's own choice.+ */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") : [];+ const v = raw == null ? null : JSON.parse(raw);+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [...DEFAULT_NAV_CLOSED];} catch {- return [];+ return [...DEFAULT_NAV_CLOSED];}}@@ -45,9 +53,22 @@ export function sidebarOpenFromCookie(cookie: string): boolean {return !new RegExp(`(?:^|;\\s*)${SIDEBAR_COOKIE}=false(?:;|$)`).test(cookie);}+/**+ * Full-screen studios: a project open in Cinema, Canvas or Layers, and Assist (with its own rail of+ * chats). They have a sidebar of their own, so the app sidebar folds to its icon rail while one is+ * open, without touching the remembered choice, and comes back on the way out.+ */+const FULL_SCREEN = /^\/(?:(?:cinema|canvas|layers)\/[^/]+\/?|assist(?:\/.*)?)$/;++export function isFullScreenStudio(pathname: string): boolean {+ return FULL_SCREEN.test(pathname);+}+/*** 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.+ * paint: the collapsed rail (the cookie, or a full-screen studio) and the folded groups+ * (localStorage). The server renders the default folds (DEFAULT_NAV_CLOSED); a remembered list+ * opens or folds every foldable group to match. 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){}})()`;+export const SIDEBAR_STATE_SCRIPT = `(function(){try{var d=document;if(/(?:^|;\\s*)${SIDEBAR_COOKIE}=false(?:;|$)/.test(d.cookie)||${FULL_SCREEN}.test(location.pathname)){var s=d.querySelector('[data-slot="sidebar"]');if(s){s.setAttribute("data-state","collapsed");s.setAttribute("data-collapsible","icon")}}var r=localStorage.getItem("${NAV_CLOSED_KEY}");if(r===null)return;var c=JSON.parse(r);if(!Array.isArray(c))return;d.querySelectorAll("[data-nav-group]").forEach(function(e){var b=e.querySelector("[data-nav-toggle]");if(!b)return;var o=c.indexOf(e.getAttribute("data-nav-group"))<0?"true":"false";e.setAttribute("data-open",o);b.setAttribute("aria-expanded",o)})}catch(e){}})()`;diff --git a/src/lib/palette-index.ts b/src/lib/palette-index.tsnew file mode 100644index 00000000..c514f10e--- /dev/null+++ b/src/lib/palette-index.ts@@ -0,0 +1,78 @@+/**+ * The slim catalog behind the ⌘K palette (GET /api/palette): names, categories and where each item+ * opens. Built on the server from the catalog, so the palette never ships prompt templates or routes.+ */+import { APPS, EFFECTS, MODELS, MOTIONS } from "@/lib/catalog";+import { OPERATION_LABELS, type ModelDef, type Preset } from "@/lib/catalog/types";+import type { PaletteIndex, PaletteModel, PalettePreset } from "@/lib/command-search";+import type { StudioConfig } from "@/components/studio/studio-context";+import {+ AUDIO_STUDIO,+ DIALOGUE_STUDIO,+ EDIT_STUDIO,+ EXTEND_STUDIO,+ FOLEY_STUDIO,+ IMAGE_STUDIO,+ INPAINT_STUDIO,+ LIPSYNC_STUDIO,+ MOTION_CONTROL_STUDIO,+ MUSIC_STUDIO,+ REFRAME_STUDIO,+ SFX_STUDIO,+ TRANSCRIBE_STUDIO,+ UPSCALE_STUDIO,+ VIDEO_EDIT_STUDIO,+ VIDEO_STUDIO,+ VIDEO_UPSCALE_STUDIO,+ VOICE_CHANGE_STUDIO,+} from "@/lib/studios";++/** Studios a model opens in (with ?model=), first match wins: the studio's picker lists its operation and kind. */+const MODEL_STUDIOS: [string, StudioConfig][] = [+ ["/image", IMAGE_STUDIO],+ ["/video", VIDEO_STUDIO],+ ["/edit", EDIT_STUDIO],+ ["/inpaint", INPAINT_STUDIO],+ ["/lipsync", LIPSYNC_STUDIO],+ ["/motion-control", MOTION_CONTROL_STUDIO],+ ["/video-edit", VIDEO_EDIT_STUDIO],+ ["/extend", EXTEND_STUDIO],+ ["/reframe", REFRAME_STUDIO],+ ["/upscale", UPSCALE_STUDIO],+ ["/upscale/video", VIDEO_UPSCALE_STUDIO],+ ["/audio", AUDIO_STUDIO],+ ["/audio/dialogue", DIALOGUE_STUDIO],+ ["/audio/voice-change", VOICE_CHANGE_STUDIO],+ ["/audio/transcribe", TRANSCRIBE_STUDIO],+ ["/audio/sfx", SFX_STUDIO],+ ["/audio/music", MUSIC_STUDIO],+ ["/audio/video", FOLEY_STUDIO],+];++/** Where a model opens: the first studio that offers it, else its row on the Models page. */+export function modelHref(m: ModelDef): string {+ const ops = new Set(m.routes.map((r) => r.op));+ const hit = MODEL_STUDIOS.find(([, c]) => c.kind === m.kind && (c.pickerOps ?? c.ops).some((op) => ops.has(op)));+ return hit ? `${hit[0]}?model=${encodeURIComponent(m.id)}` : `/models?q=${encodeURIComponent(m.name)}`;+}++const preset = (p: Preset): PalettePreset => ({ id: p.id, name: p.name, category: p.category, cloud: !!p.cloud, open: !!p.open });++const model = (m: ModelDef): PaletteModel => ({+ id: m.id,+ name: m.name,+ vendor: m.vendor,+ engine: m.engine,+ href: modelHref(m),+ ops: [...new Set(m.routes.map((r) => OPERATION_LABELS[r.op] ?? r.op))].join(", "),+});++export function paletteIndex(): PaletteIndex {+ return {+ apps: APPS.map(preset),+ motions: MOTIONS.map(preset),+ effects: EFFECTS.map(preset),+ // Chain helpers (hidden) aren't offered anywhere, so the palette leaves them out too.+ models: MODELS.filter((m) => !m.hidden).map(model),+ };+}diff --git a/tests/command-palette.test.ts b/tests/command-palette.test.tsnew file mode 100644index 00000000..27f0250f--- /dev/null+++ b/tests/command-palette.test.ts@@ -0,0 +1,140 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { NAV } from "@/components/nav-items";+import { APPS, EFFECTS, getModel, MODELS, MOTIONS } from "@/lib/catalog";+import { entryScore, indexEntries, normalize, rankPalette, wordScore, type PaletteEntry } from "@/lib/command-search";+import { modelHref, paletteIndex } from "@/lib/palette-index";+import { hubModePaths, studioRoutes } from "./e2e/_routes.mjs";++const page = (label: string, href: string, keywords?: string): PaletteEntry => ({ key: `page:${href}`, kind: "page", label, href, keywords });+const PAGES = NAV.flatMap((g) => g.items.map((i) => page(i.label, i.href, i.keywords)));+const index = paletteIndex();+const ALL = [...PAGES, ...indexEntries(index, "both")];+const top = (q: string, entries = ALL) => rankPalette(entries, q).flatMap((g) => g.entries.map((e) => e.label));++describe("palette word match", () => {+ it("normalizes case, accents and punctuation", () => {+ expect(normalize(" Lipsync & Avatars ")).toBe("lipsync avatars");+ expect(normalize("Café — Crème")).toBe("cafe creme");+ expect(normalize("FLUX.2 [klein]")).toBe("flux.2 klein");+ });++ it("ranks whole > start > word start > inside > letters in order", () => {+ const scores = [wordScore("video", "video"), wordScore("vid", "video tools"), wordScore("tools", "video tools"), wordScore("deo", "video"), wordScore("vdo", "video")];+ expect(scores).toEqual([...scores].sort((a, b) => b - a));+ expect(new Set(scores).size).toBe(scores.length);+ expect(scores.at(-1)).toBeGreaterThan(0);+ });++ it("forgives a missing space and a typo, but not noise", () => {+ expect(wordScore("faceswap", "face swap")).toBeGreaterThan(0);+ expect(wordScore("cinma", "cinema studio")).toBeGreaterThan(0);+ expect(wordScore("zq", "cinema studio")).toBe(0);+ // Letters strewn across a long label are no match.+ expect(wordScore("cso", "cinema studio of something")).toBe(0);+ // One letter only matches the start of a word.+ expect(wordScore("s", "cinema studio")).toBeGreaterThan(0);+ expect(wordScore("t", "cinema studio")).toBe(0);+ });++ it("needs every word, from the label or (worth less) the keywords", () => {+ const audio = page("Audio", "/audio", "voice tts music");+ expect(entryScore("tts", audio)).toBeGreaterThan(0);+ expect(entryScore("audio", audio)).toBeGreaterThan(entryScore("tts", audio));+ expect(entryScore("audio guitar", audio)).toBe(0);+ expect(entryScore("", audio)).toBe(0);+ });+});++describe("palette ranking", () => {+ it("puts the page first when a page and presets share a word", () => {+ expect(top("video")[0]).toBe("Video");+ expect(top("cinema")[0]).toBe("Cinema Studio");+ expect(top("settings")[0]).toBe("Settings");+ expect(top("upscale")[0]).toBe("Upscale");+ });++ it("finds a page by a keyword and with a typo", () => {+ expect(top("tts")).toContain("Audio");+ expect(top("cinma")[0]).toBe("Cinema Studio");+ expect(top("libary")).toContain("All creations");+ });++ it("finds apps, motions, effects and models by name", () => {+ const app = APPS.find((a) => a.id === "app-packshot")!;+ expect(top(app.name)).toContain(app.name);+ const motion = MOTIONS[0];+ const groups = rankPalette(ALL, motion.name);+ expect(groups.find((g) => g.kind === "motion")?.entries.map((e) => e.label)).toContain(motion.name);+ const model = MODELS.find((m) => !m.hidden && m.engine === "cloud")!;+ expect(rankPalette(ALL, model.name).find((g) => g.kind === "model")?.entries.map((e) => e.label)).toContain(model.name);+ });++ it("orders groups by their best match and caps each group", () => {+ const groups = rankPalette(ALL, "zoom");+ for (const g of groups) expect(g.entries.length).toBeLessThanOrEqual({ page: 6, setting: 4, app: 5, motion: 4, effect: 4, model: 5, recent: 5 }[g.kind]);+ const best = groups.map((g) => entryScore("zoom", g.entries[0]));+ expect(best).toEqual([...best].sort((a, b) => b - a));+ });++ it("matches nothing on an empty query (the palette shows its own start list)", () => {+ expect(rankPalette(ALL, "")).toEqual([]);+ expect(rankPalette(ALL, " ")).toEqual([]);+ });+});++describe("palette index", () => {+ const routes = (() => {+ const root = path.resolve(__dirname, "..");+ const { routes, patterns } = studioRoutes(root);+ return { paths: new Set([...routes, ...hubModePaths(root)]), patterns };+ })();+ const pathOf = (href: string) => href.split("?")[0];++ it("lists every app, motion, effect and offered model, slim", () => {+ expect(index.apps).toHaveLength(APPS.length);+ expect(index.motions).toHaveLength(MOTIONS.length);+ expect(index.effects).toHaveLength(EFFECTS.length);+ expect(index.models).toHaveLength(MODELS.filter((m) => !m.hidden).length);+ // No prompt templates, routes or LoRA URLs: the whole thing stays small.+ expect(JSON.stringify(index).length).toBeLessThan(160_000);+ expect(Object.keys(index.apps[0]).sort()).toEqual(["category", "cloud", "id", "name", "open"]);+ });++ it("opens every model somewhere that exists, in a studio of its kind when there is one", () => {+ for (const m of index.models) {+ const p = pathOf(m.href);+ expect(routes.paths.has(p) || p === "/models", `${m.id} → ${m.href}`).toBe(true);+ }+ expect(modelHref(getModel("nano-banana-pro")!)).toBe("/image?model=nano-banana-pro");+ expect(modelHref(getModel("seedance-2-5")!)).toBe("/video?model=seedance-2-5");+ expect(modelHref(getModel("oss-qwen-edit")!)).toMatch(/^\/(edit|image)\?model=oss-qwen-edit$/);+ });++ it("opens every page and settings section the palette lists", () => {+ for (const p of PAGES) expect(routes.paths.has(pathOf(p.href)), p.href).toBe(true);+ const form = fs.readFileSync(path.resolve(__dirname, "../src/components/settings-form.tsx"), "utf8");+ const palette = fs.readFileSync(path.resolve(__dirname, "../src/components/command-palette.tsx"), "utf8");+ const ids = [...palette.matchAll(/\{ id: "([a-z-]+)", label:/g)].map((m) => m[1]);+ expect(ids.length).toBeGreaterThan(4);+ for (const id of ids) expect(form, `settings section #${id}`).toContain(`id="${id}"`);+ });++ it("leaves out what a locked engine can't run", () => {+ const open = indexEntries(index, "open");+ const cloud = indexEntries(index, "cloud");+ expect(open.filter((e) => e.kind === "model").every((e) => e.keywords?.includes("open source"))).toBe(true);+ expect(cloud.filter((e) => e.kind === "model").every((e) => e.keywords?.includes("cloud"))).toBe(true);+ const openApps = new Set(open.filter((e) => e.kind === "app").map((e) => e.key));+ for (const a of index.apps) expect(openApps.has(`app:${a.id}`)).toBe(a.open);+ expect(indexEntries(index, "both").length).toBeGreaterThan(open.length);+ });++ it("links presets the way their galleries do", () => {+ const entries = indexEntries(index, "both");+ expect(entries.find((e) => e.kind === "app")?.href).toMatch(/^\/apps\/app-/);+ expect(entries.find((e) => e.kind === "motion")?.href).toMatch(/^\/video\?preset=/);+ expect(entries.find((e) => e.kind === "effect")?.href).toMatch(/^\/video\?preset=/);+ });+});diff --git a/tests/e2e/shell.mjs b/tests/e2e/shell.mjsindex 39167897..6c7043de 100644--- a/tests/e2e/shell.mjs+++ b/tests/e2e/shell.mjs@@ -1,10 +1,16 @@// App-shell checks in a real browser (the app must be running; demo mode is fine).// Usage: node tests/e2e/shell.mjs [appUrl] (pnpm test:e2e:shell). Exits 1 on the first failure.//-// 1. Phone: the sidebar drawer closes when a link in it is tapped (nav item, New creation, footer).-// 2. A collapsed sidebar group still shows the page you're on.-// 3. Deep links into Settings (/settings#comfyui) scroll to the section after a client navigation.-// 4. Galleries: "Show more" pressed from the keyboard moves focus to the first new card.+// 1. Phone: the sidebar drawer closes when a link in it is tapped (nav item, New creation, footer),+// and its Search row opens the ⌘K palette.+// 2. A first visit folds Studios and Engine, with Library right after Create; a collapsed group+// still shows the page you're on.+// 3. Landmarks: "Skip to content" is the first Tab stop, one <main>, the sidebar is <nav "Main">.+// 4. ⌘K / Ctrl+K opens the palette; a typo still finds a page and Enter opens it.+// 5. Full-screen studios (Assist, an open Cinema project…) fold the app sidebar to its rail without+// changing the remembered state.+// 6. Deep links into Settings (/settings#comfyui) scroll to the section after a client navigation.+// 7. Galleries: "Show more" pressed from the keyboard moves focus to the first new card.import assert from "node:assert/strict";import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";@@ -19,7 +25,7 @@ try {for (const [from, link, to] of [["/models", /^Effects$/, "/effects"],["/effects", /^New creation/, "/"],- ["/", /^Settings$/, "/settings"],+ ["/", /^Favorites$/, "/library"],// The footer's engine status links to Settings too.["/models", /^Cloud models/, "/settings"],]) {@@ -32,6 +38,53 @@ try {await page.waitForURL((u) => new URL(u).pathname === to, { timeout: 20_000 });await drawer.waitFor({ state: "detached", timeout: 5_000 });}+ step("phone: Search in the drawer opens the palette");+ await openRoute(page, `${app}/models`);+ await page.getByRole("button", { name: "Toggle Sidebar" }).first().tap();+ await page.locator('[data-mobile="true"]').getByRole("button", { name: /^Search/ }).tap();+ await page.getByRole("dialog", { name: "Search Fuobe" }).waitFor();+ await page.locator('[data-mobile="true"]').waitFor({ state: "detached", timeout: 5_000 });+ await ctx.close();+ }+ {+ const ctx = await browser.newContext(DESKTOP);+ const page = await ctx.newPage();+ step("a first visit folds Studios and Engine, and Library follows Create");+ await openRoute(page, `${app}/image`);+ const groups = await page.locator("[data-nav-group]").evaluateAll((els) => els.map((e) => [e.getAttribute("data-nav-group"), e.getAttribute("data-open")]));+ assert.deepEqual(groups, [["create", "true"], ["library", "true"], ["studios", "false"], ["engine", "false"]]);++ step("Skip to content is the first Tab stop; one <main>; the sidebar is a navigation landmark");+ await page.keyboard.press("Tab");+ assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Skip to content");+ await page.keyboard.press("Enter");+ assert.equal(await page.evaluate(() => document.activeElement?.id), "content");+ assert.equal(await page.locator("main").count(), 1, "one <main>");+ assert.ok((await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Video" }).count()) > 0, "sidebar links are inside <nav aria-label=Main>");++ step("⌘K / Ctrl+K opens the palette; “cinma” finds Cinema Studio; Enter opens it");+ await page.keyboard.press("ControlOrMeta+k");+ const dialog = page.getByRole("dialog", { name: "Search Fuobe" });+ await dialog.waitFor();+ await page.keyboard.type("cinma");+ await dialog.getByRole("option", { name: /^Cinema Studio/ }).first().waitFor();+ await page.keyboard.press("Enter");+ await page.waitForURL((u) => new URL(u).pathname === "/cinema", { timeout: 20_000 });+ await dialog.waitFor({ state: "detached" });+ await ctx.close();+ }+ {+ const ctx = await browser.newContext(DESKTOP);+ const page = await ctx.newPage();+ step("full-screen studios fold the app sidebar to its rail, and it comes back on the way out");+ const sidebar = page.locator('[data-slot="sidebar"]').first();+ await openRoute(page, `${app}/assist`);+ assert.equal(await sidebar.getAttribute("data-state"), "collapsed", "folded on Assist");+ await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Image", exact: true }).click();+ await page.waitForURL((u) => new URL(u).pathname === "/image");+ await page.waitForFunction(() => document.querySelector('[data-slot="sidebar"]')?.getAttribute("data-state") === "expanded");+ const cookies = await ctx.cookies();+ assert.ok(!cookies.some((c) => c.name === "sidebar_state" && c.value === "false"), "the remembered state is untouched");await ctx.close();}{diff --git a/tests/nav.test.ts b/tests/nav.test.tsindex 2ffca1bc..a7e0e891 100644--- a/tests/nav.test.ts+++ b/tests/nav.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";-import { groupId, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";+import { NAV } from "@/components/nav-items";+import { DEFAULT_NAV_CLOSED, groupId, isFullScreenStudio, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";const q = (s = "") => new URLSearchParams(s);const LIBRARY = ["/library", "/library?tab=favorites"];@@ -39,10 +40,36 @@ describe("remembered sidebar state", () => {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"]);+ // The user opened every group: that choice is kept, not replaced by the defaults.+ expect(parseClosed("[]")).toEqual([]);+ });++ it("folds Studios and Engine until the user chooses (nothing stored, or nothing readable)", () => {+ expect(parseClosed(null)).toEqual(["studios", "engine"]);+ expect(parseClosed(undefined)).toEqual(["studios", "engine"]);+ expect(parseClosed("not json")).toEqual(["studios", "engine"]);+ expect(parseClosed('{"a":1}')).toEqual(["studios", "engine"]);+ // A fresh copy each time: a caller adding to it can't change the defaults.+ parseClosed(null).push("create");+ expect(parseClosed(null)).toEqual(["studios", "engine"]);+ });++ it("only folds groups that can fold, and keeps Create and Library in view", () => {+ const foldable = NAV.filter((g) => g.collapsible).map((g) => groupId(g.label));+ for (const id of DEFAULT_NAV_CLOSED) expect(foldable).toContain(id);+ expect(NAV.map((g) => g.label).slice(0, 2)).toEqual(["Create", "Library"]);+ // The always-open part of the sidebar is short: Create and Library hold 15 rows, not 46.+ const open = NAV.filter((g) => !DEFAULT_NAV_CLOSED.includes(groupId(g.label))).flatMap((g) => g.items);+ expect(open.length).toBeLessThanOrEqual(15);+ });++ it("prefetches only the rows most visits go to next", () => {+ const eager = NAV.flatMap((g) => g.items.filter((i) => i.eager).map((i) => i.href));+ expect(eager).toEqual(["/", "/assist", "/image", "/video", "/library"]);+ // Every destination is unique (the palette and the sidebar key rows by href).+ const hrefs = NAV.flatMap((g) => g.items.map((i) => i.href));+ expect(new Set(hrefs).size).toBe(hrefs.length);});it("uses stable group ids", () => {@@ -56,20 +83,50 @@ describe("remembered sidebar state", () => {expect(SIDEBAR_STATE_SCRIPT).toContain("fuobe:nav-closed");});- it("applies the cookie and the collapsed groups to the DOM", () => {+ /** Runs the pre-paint script against a fake DOM with the given cookie, path and stored folds. */+ function runScript(cookie: string, pathname: string, stored: string | null) {const attrs = new Map<string, Record<string, string>>();- const el = (key: string) => ({+ const el = (key: string, toggle = true) => ({setAttribute: (k: string, v: string) => attrs.set(key, { ...attrs.get(key), [k]: v }),- querySelector: (s: string) => (s === "[data-nav-toggle]" ? el(`${key}/toggle`) : null),+ getAttribute: (k: string) => (k === "data-nav-group" ? key : null),+ querySelector: (s: string) => (s === "[data-nav-toggle]" && 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),+ cookie,+ querySelector: (s: string) => (s === '[data-slot="sidebar"]' ? el("sidebar") : null),+ // Create and Library can't fold (no toggle); Studios and Engine can.+ querySelectorAll: (s: string) => (s === "[data-nav-group]" ? [el("create", false), el("library", false), el("studios"), el("engine")] : []),};- const localStorage = { getItem: () => '["studios","gone"]' };- new Function("document", "localStorage", SIDEBAR_STATE_SCRIPT)(document, localStorage);+ const localStorage = { getItem: () => stored };+ new Function("document", "localStorage", "location", SIDEBAR_STATE_SCRIPT)(document, localStorage, { pathname });+ return attrs;+ }++ it("applies the cookie and the remembered folds to the DOM", () => {+ const attrs = runScript("x=1; sidebar_state=false", "/image", '["studios","gone"]');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" });+ // Engine was opened by the user: the server's default fold is undone before paint.+ expect(attrs.get("engine")).toEqual({ "data-open": "true" });+ expect(attrs.get("engine/toggle")).toEqual({ "aria-expanded": "true" });+ expect(attrs.has("create")).toBe(false);+ });++ it("leaves the server's default folds alone when nothing is remembered", () => {+ const attrs = runScript("", "/image", null);+ expect([...attrs.keys()]).toEqual([]);+ });++ it("folds the sidebar to its rail on a full-screen studio, whatever the cookie says", () => {+ expect(runScript("sidebar_state=true", "/cinema/abc", null).get("sidebar")).toEqual({ "data-state": "collapsed", "data-collapsible": "icon" });+ expect(runScript("sidebar_state=true", "/cinema", null).get("sidebar")).toBeUndefined();+ });+});++describe("full-screen studios", () => {+ it("are an open Cinema, Canvas or Layers project, and Assist", () => {+ for (const p of ["/cinema/abc", "/canvas/x1", "/layers/l-2/", "/assist", "/assist/memory", "/assist/projects/p1"]) expect(isFullScreenStudio(p)).toBe(true);+ for (const p of ["/", "/cinema", "/canvas", "/layers", "/assistant", "/apps/app-packshot", "/cinema/a/b", "/library"]) expect(isFullScreenStudio(p)).toBe(false);});});