The app's frame
Its sidebar, a screen's top bar with the light and dark switch
This recipe draws AppFrame arrangement="sidebar"; the others (agent/layout-chooser.md) take the same slots. Your page fits another? Change the one prop:
rail(places: few, body: long; Trail draws it assidebar):AppFrameRaila few top places.top-nav(places: few, fields: many):AppFrameRaila few places, across the top.global-bar(places: many, fields: many):AppFramePanelits header a bar across the window: search, switchers, the account.focus(subject: document, body: long):AppFrameTriggerthe way back, in the navigation control’s place;AppFramePanelone task.
The free AppFrame draws sidebar for every id; the other three are Pro: ArrangedAppFrame, ArrangedAppFrameRail, ArrangedAppFramePanel, ArrangedAppFrameTrigger (@/components/goop/patterns/app-frame-arrangements) in place of the parts below, same props.
Copy both files below whole (src/screens/frame.tsx, src/screens/router.ts) and swap the pages for yours; every screen recipe imports ScreenFrame and ScreenTopBar from the frame: one frame, one navigation. A phone holds five pages or fewer in a tab bar at the foot (phoneNav). Each row is a plain link; the router marks the page (a record's, /issues/FW-121, marks the page it belongs to). It is yours, about 20 lines: the route is the path after the #, so any host serves it, links open in new tabs and from the back button, and code moves with go(path); on your framework's router keep its three names (useRoute, hrefOf, go). The pages hold every screen recipe's (/board, /schedule, /visits, /chat…): keep only your app's. With a sign-in (docs/screen-account.md), <FrameAccount account={<SignedInMenu />}> puts the person's menu at the sidebar's foot; a screen's own account wins. App.tsx (docs/screen-app.md) mounts <Toaster /> once.
Which sidebar
Each prop (off unless given; none: the plain list) arranges the sidebar in a shape of docs/recipe-sidebars.md. Pick by the product and give them once round every screen (<FrameShape value={{ search: true }}>), so the sidebar never changes between screens:
| The product | The shape | ScreenFrame's props | | --- | --- | --- | | One person, one workspace, a handful of pages | A tool for one person | search (the app's name over it), the person at the foot (FrameAccount) | | Teams or projects, each with its own pages | A team's workspace | sections, variant: 'item' (a team's mark and name fold its rows), counts | | A person in several workspaces or accounts | A team's workspace | switcher (your store holds the current one) | | Many pages or records to reach by name | A team's workspace | search (narrows the rows as you type; Enter opens the first) | | Many settings or places in a few areas | An admin console | sections (each folds from its heading; defaultOpen: false on a seldom used one), counts | | A dense app (a dashboard, a board, an editor) needing the width | A compact rail | collapsible="rail" (opens as icons under a 1440 px window, wide from 1440; collapsible opens wide), with switcher | | Something waits on someone (unread, invites, open items) | any | counts by route, { '/inbox': 3 } |
The search narrows the sidebar alone (the CommandPalette finds commands and records app-wide). The rail draws no search field; the switcher shows its tile, each row its icon, its words in a tooltip; the toggle or Cmd/Ctrl B widens it. The rail and each fold survive reloads (local storage frame:sidebar, frame:sidebar:<label>); a search leaving no row says "No page matches".
Show the code329 lines
// src/screens/frame.tsx: the frame every screen sits in, its sidebar and top bar
import { createContext, type ReactNode, useContext, useState } from 'react';
import { AppFrame, AppFrameRail, AppFrameTrigger } from '@/components/goop/patterns/app-frame';
import { ColorModeToggle } from '@/components/ui/goop/color-mode-toggle';
import { SearchInput } from '@/components/ui/goop/search-input';
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarHeader,
SidebarHeaderRow,
SidebarRailToggle,
SidebarTitle,
useSidebar,
} from '@/components/ui/goop/sidebar';
import {
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
type SidebarGroupVariant,
SidebarMenu,
SidebarMenuItem,
} from '@/components/ui/goop/sidebar-group';
import { SidebarMenuBadge, SidebarMenuButton } from '@/components/ui/goop/sidebar-menu-button';
import { TabBar, TabBarItem } from '@/components/ui/goop/tab-bar';
import { TopBar, TopBarGroup, TopBarRow, TopBarTitle } from '@/components/ui/goop/top-bar';
import {
WorkspaceSwitcher,
WorkspaceSwitcherAction,
WorkspaceSwitcherContent,
WorkspaceSwitcherItem,
WorkspaceSwitcherLabel,
WorkspaceSwitcherTrigger,
} from '@/components/ui/goop/workspace-switcher';
import { Glyph, type IconName } from '@/lib/goop/trail/glyph';
import { SAMPLE_BRAND } from '@/lib/goop/trail/sample-brand';
import { go, hrefOf, useRoute } from './router';
// ---- the app's pages: swap them for yours
const NAVIGATION = [
{ words: 'Overview', path: '/', icon: 'home' },
{ words: 'Inbox', path: '/inbox', icon: 'inbox' },
{ words: 'Issues', path: '/issues', icon: 'circle-dot' },
{ words: 'Work', path: '/board', icon: 'columns-3' },
{ words: 'Schedule', path: '/schedule', icon: 'calendar' },
{ words: 'Visits', path: '/visits', icon: 'calendar-plus' },
{ words: 'Assistant', path: '/chat', icon: 'message' },
{ words: 'Settings', path: '/settings', icon: 'settings' },
] as const;
// ---- the frame
/** A row of the sidebar: a page of yours, its route and its pack icon. */
export type FrameRow = { words: string; path: string; icon: IconName };
/**
* A folding section under the pages: `variant: 'default'` a few places under a heading that folds them (an admin
* console's areas, your favourites); `variant: 'item'` a team's or a project's own section, its `mark` before its name.
* Open unless `defaultOpen: false`.
*/
export type FrameSection = {
label: string;
variant?: SidebarGroupVariant;
mark?: IconName;
defaultOpen?: boolean;
rows: readonly FrameRow[];
};
/** The workspaces a person belongs to, at the sidebar's head: your store holds the current one (`value`). */
export type FrameSwitcher = {
workspaces: readonly { id: string; name: string }[];
value: string;
onValueChange: (id: string) => void;
/** "Create workspace" at the menu's end, your own step; left out, no such row. */
onCreate?: () => void;
};
/** Whether the app's pages hold a route: a link to one from elsewhere (the account menu's Settings) asks first. */
export const hasPage = (path: string): boolean => NAVIGATION.some((page: FrameRow) => page.path === path);
/** The signed-in person's menu every frame under it draws at the sidebar's foot: given once, in App.tsx. */
const AccountSlot = createContext<ReactNode>(null);
/** Gives every screen's frame under it the signed-in person's menu: `<FrameAccount account={<SignedInMenu />}>`. */
export function FrameAccount({ account, children }: { account: ReactNode; children: ReactNode }) {
return <AccountSlot value={account}>{children}</AccountSlot>;
}
/** The sidebar's arrangement for every frame under it (App.tsx); a screen's own props win. */
export const FrameShape = createContext<Arrangement>({});
/** The row a route belongs to, the longest that holds it: `/issues/FW-121` is under Issues; none outside them all. */
function pageOf(route: string, rows: readonly FrameRow[]): string | undefined {
const holding = rows.filter((page) =>
page.path === '/' ? route === '/' : route === page.path || route.startsWith(`${page.path}/`),
);
return holding.sort((a, b) => b.path.length - a.path.length)[0]?.path;
}
// sidebar props (the same on every screen): switcher, search, sections, collapsible, counts (docs/recipe-sidebars.md)
/** The sidebar's arrangement: what `ScreenFrame` takes beside the screen ("Which sidebar" picks it). */
type Arrangement = {
/** The workspace switcher at the sidebar's head, for a person in several workspaces or accounts. */
switcher?: FrameSwitcher;
/** A field under the head that narrows the sidebar's rows as you type; Enter opens the first left. */
search?: boolean;
/** Folding sections under the pages: an admin console's areas, a team's or a project's rows. */
sections?: readonly FrameSection[];
/** The rail toggle at the head's end: the sidebar folds to its icons (`"rail"`: it opens folded). */
collapsible?: boolean | 'rail';
/** A row's count by its route (`{ '/inbox': 3 }`), where something waits on the person. */
counts?: Readonly<Partial<Record<string, number>>>;
};
/**
* The frame every screen sits in: the navigation in its rail, the screen's template (or AppFramePanel) beside it;
* `more`, a screen's own sidebar group under the pages (an inbox's queues); `account`, the signed-in person's menu at
* the sidebar's foot (FrameAccount's when not given); `scroll="panel"` keeps a reply box pinned; `switcher`,
* `search`, `sections`, `collapsible` and `counts` arrange the sidebar ("Which sidebar", above).
* The page marked is the route's; `current` names it only for a route under none of the pages.
*/
export function ScreenFrame({
current,
more,
account,
scroll,
children,
...own
}: Arrangement & {
current?: string;
more?: ReactNode;
account?: ReactNode;
scroll?: 'page' | 'panel';
children: ReactNode;
}) {
const { collapsible = false, ...arrangement } = { ...useContext(FrameShape), ...own };
const rows = [...NAVIGATION, ...(arrangement.sections ?? []).flatMap((section) => section.rows)];
const here = pageOf(useRoute(), rows) ?? current;
const given = useContext(AccountSlot);
const foot = account ?? given;
const rail = collapsible ? { storageKey: FRAME_KEY, defaultOpen: collapsible !== 'rail' || roomy() } : {};
const phone = NAVIGATION.length < 1 || NAVIGATION.length > 5 ? undefined : (
<TabBar value={here} aria-label="Pages">
{NAVIGATION.map((page: FrameRow) => (
<TabBarItem key={page.path} value={page.path} icon={page.icon} href={hrefOf(page.path)}>
{page.words}
</TabBarItem>
))}
</TabBar>
);
return (
<AppFrame arrangement="sidebar" scroll={scroll} phoneNav={phone}>
<AppFrameRail>
<Sidebar aria-label="Main" {...rail}>
<FrameColumn here={here} more={more} collapsible={collapsible !== false} {...arrangement} />
{foot ? <SidebarFooter>{foot}</SidebarFooter> : null}
</Sidebar>
</AppFrameRail>
{children}
</AppFrame>
);
}
/** Where the sidebar keeps the person's choices across screens and reloads: the rail, and each section's fold. */
const FRAME_KEY = 'frame:sidebar';
/** A window wide enough for the whole sidebar beside a dense page: from 1440 px a rail opens wide, below it folded. */
const roomy = (): boolean => typeof window !== 'undefined' && window.innerWidth >= 1440;
/** A section's kept fold, under the frame's key and its label: folded (`true`), open (`false`), or none kept. */
function keptFold(label: string): boolean | undefined {
try {
const kept = localStorage.getItem(`${FRAME_KEY}:${label}`);
return kept === null ? undefined : kept === 'folded';
} catch {
return undefined; // a server, or a browser that refuses storage: the section's own default
}
}
/** Keeps a section's fold; a browser that refuses storage keeps it for this screen. */
function keepFold(label: string, folded: boolean): void {
try {
localStorage.setItem(`${FRAME_KEY}:${label}`, folded ? 'folded' : 'open');
} catch {
// a private window or a full quota: nothing kept
}
}
/** The sidebar's head (when it has one) and its column of rows, the search narrowing them while the sidebar is wide. */
function FrameColumn({
here,
more,
switcher,
search = false,
sections = [],
collapsible,
counts,
}: Omit<Arrangement, 'collapsible'> & { here?: string; more?: ReactNode; collapsible: boolean }) {
const { collapsed } = useSidebar();
const [query, setQuery] = useState('');
const [folded, setFolded] = useState<Readonly<Record<string, boolean>>>(() =>
Object.fromEntries(
sections.flatMap((section) => {
const kept = keptFold(section.label);
return kept === undefined ? [] : [[section.label, kept]];
}),
),
);
const narrow = search && !collapsed ? query.trim().toLowerCase() : '';
const kept = (list: readonly FrameRow[]) => list.filter((page) => page.words.toLowerCase().includes(narrow));
const pages = kept(NAVIGATION);
const shown = sections.map((section) => ({ ...section, rows: kept(section.rows) }));
const first = [...pages, ...shown.flatMap((section) => section.rows)][0];
const row = (page: FrameRow) => (
<SidebarMenuItem key={page.path}>
<SidebarMenuButton href={hrefOf(page.path)} icon={page.icon} size="sm" isActive={page.path === here}>
{page.words}
{counts?.[page.path] ? <SidebarMenuBadge>{counts[page.path]}</SidebarMenuBadge> : null}
</SidebarMenuButton>
</SidebarMenuItem>
);
const now = switcher?.workspaces.find((one) => one.id === switcher.value);
const head =
switcher || search || collapsible ? (
<SidebarHeader>
<SidebarHeaderRow>
{switcher ? (
<WorkspaceSwitcher value={switcher.value} onValueChange={switcher.onValueChange}>
<WorkspaceSwitcherTrigger name={now?.name ?? ''} />
<WorkspaceSwitcherContent>
<WorkspaceSwitcherLabel />
{switcher.workspaces.map((one) => (
<WorkspaceSwitcherItem key={one.id} value={one.id} name={one.name} />
))}
{switcher.onCreate ? <WorkspaceSwitcherAction onSelect={switcher.onCreate} /> : null}
</WorkspaceSwitcherContent>
</WorkspaceSwitcher>
) : (
<SidebarTitle>{SAMPLE_BRAND.name}</SidebarTitle>
)}
{collapsible ? <SidebarRailToggle /> : null}
</SidebarHeaderRow>
{search && !collapsed ? (
<div className="pt-1">
<SearchInput
size="sm"
label="Find a page"
placeholder="Find a page"
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter' && first) go(first.path);
if (event.key === 'Escape') setQuery('');
}}
/>
</div>
) : null}
</SidebarHeader>
) : null;
return (
<>
{head}
<SidebarContent>
{narrow && !first ? (
<p role="status" className="ps-2.5 text-base text-muted-foreground">
No page matches
</p>
) : null}
{pages.length > 0 ? (
<SidebarGroup>
<SidebarGroupContent>
<SidebarMenu>{pages.map(row)}</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
) : null}
{shown.length > 0 ? (
<>
{shown.map((section) =>
section.rows.length > 0 ? (
<SidebarGroup
key={section.label}
collapsible
variant={section.variant ?? 'default'}
// while the search narrows, every section that keeps a row is open
open={narrow ? true : !(folded[section.label] ?? section.defaultOpen === false)}
onOpenChange={(open) => {
keepFold(section.label, !open);
setFolded((all) => ({ ...all, [section.label]: !open }));
}}
>
<SidebarGroupLabel
mark={
section.mark ? <Glyph icon={section.mark} box={{ w: 14, h: 14 }} aria-hidden="true" /> : undefined
}
>
{section.label}
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>{section.rows.map(row)}</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
) : null,
)}
{more}
</>
) : (
more
)}
</SidebarContent>
</>
);
}
/** A screen's top bar, for its template's or its panel's `header`: the navigation's button, the title, the switch. */
export function ScreenTopBar({ title }: { title: ReactNode }) {
return (
<TopBar role="banner">
<TopBarRow>
<TopBarGroup>
<AppFrameTrigger />
<TopBarTitle>{title}</TopBarTitle>
</TopBarGroup>
<TopBarGroup align="end">
<ColorModeToggle />
</TopBarGroup>
</TopBarRow>
</TopBar>
);
}Show the code31 lines
// src/screens/router.ts: the app's router, the route after the `#`
import { useSyncExternalStore } from 'react';
/** The route the app opens on: an address with no `#`, or `#/`, shows it. */
const HOME = '/';
/** The route now: the path after the `#`. */
function routeNow(): string {
const path = window.location.hash.replace(/^#/, '');
return path === '' || path === '/' ? HOME : path;
}
function onRouteChange(listener: () => void): () => void {
window.addEventListener('hashchange', listener);
return () => window.removeEventListener('hashchange', listener);
}
/** The route the app shows (`/`, `/inbox`, `/issues/FW-121`); a component reading it renders again when it moves. */
export function useRoute(): string {
return useSyncExternalStore(onRouteChange, routeNow, () => HOME);
}
/** A route as a link's `href` (`#/inbox`). */
export function hrefOf(path: string): string {
return `#${path}`;
}
/** Moves to a route from code (a row pressed, a record made); the back button comes back. */
export function go(path: string): void {
window.location.hash = path;
}