Skip to content
On this page Rail labels, search slot, badges and More

Layout

AppShell

Application layout with a module rail, a navigation panel, a mobile header and a bottom navigation, independent of any router.

<script lang="ts">
  import { AppShellLayout, SiteHeader, type NavModule } from "@codeatlasdev/ui";
  import { goto } from "$app/navigation"; // or any router
  import { page } from "$app/state";

  let { children } = $props();

  const modules: NavModule[] = [/* id, label, icon, basePath, items */];
</script>

<AppShellLayout {modules} pathname={page.url.pathname} onNavigate={(path) => goto(path)}>
  {#snippet header()}<SiteHeader />{/snippet}
  {@render children()}
</AppShellLayout>

The shell never imports a router. You pass the current pathname and handle onNavigate, so it works with SvelteKit, Astro, or plain state. onNavigate fires when the user switches module from the rail or the bottom navigation. Panel items are plain <a href> links, so a client-side router takes them over like any other link. Put it only on application routes, never on marketing pages. The panel is skipped for a module with fewer than two destinations, since it would only repeat the rail icon and the page title. Below 900px the rail and panel disappear and the mobile header plus bottom navigation take over. See the templates for complete applications built on it.

SiteHeader is also the top bar of a public page (outside the shell, with no panel toggle). Its trailing snippet holds the actions at the end of the bar and keeps the bar to one row. Below 600px a NavigationMenu placed directly in trailing is hidden, because three links never fit beside a locale switcher and a call to action at 390px; the LocaleSwitcher already shows its short code there. Give phones the same links in a menu of your own (an IconButton that opens a Drawer), shown only below 600px.

The rail magnifies the module icon under the pointer, like a dock. Only the glyph grows, never the button, so the hover background cannot cover the active neighbour. The effect follows the motion scale: it is off with motion: { scale: 0 } in the theme and under prefers-reduced-motion.

#165

Anatomy

Rail (52px), panel (200px by default) and the main content area.

Reference #165 · Pick in the gallery

Code
svelte
<div class="shell-diagram" role="img" aria-label="App shell anatomy: rail, panel and main content">
  <div class="shell-rail">
    <span class="shell-label">Rail<br />52px</span>
    <div class="rail-icons">
      {#each [0, 1, 2, 3] as i}
        <div class="rail-icon" class:rail-icon--active={i === 1}></div>
      {/each}
    </div>
  </div>
  <div class="shell-panel">
    <span class="shell-label">Panel<br />200px</span>
    <div class="panel-items">
      {#each ['Dashboard', 'Users', 'Reports', 'Settings'] as item, i}
        <div class="panel-item" class:panel-item--active={i === 0}>{item}</div>
      {/each}
    </div>
  </div>
  <div class="shell-main">
    <span class="shell-label">Main content</span>
    <div class="main-topbar"></div>
    <div class="content-block"></div>
    <div class="content-block content-block--short"></div>
    <div class="content-block"></div>
  </div>
</div>

<style>
  .shell-diagram {
    display: flex;
    width: 100%;
    height: 280px;
    border-radius: var(--ca-radius-lg);
    overflow: hidden;
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .shell-label {
    font-size: 10px;
    font-weight: 600;
    color: var(--ca-text-hint);
    text-transform: uppercase;
    letter-spacing: 0.06em;
    line-height: 1.3;
    text-align: center;
  }
  .shell-rail {
    width: 52px;
    flex-shrink: 0;
    box-shadow: inset -1px 0 0 var(--ca-outline-subtle);
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 0;
    gap: 16px;
  }
  .rail-icons { display: flex; flex-direction: column; gap: 8px; align-items: center; }
  .rail-icon { width: 32px; height: 32px; border-radius: var(--ca-radius-md); background: var(--ca-action-hover); }
  .rail-icon--active {
    background: color-mix(in oklch, var(--ca-brand-main) 20%, transparent);
    box-shadow: inset 3px 0 0 var(--ca-brand-main);
  }
  .shell-panel {
    width: 200px;
    flex-shrink: 0;
    box-shadow: inset -1px 0 0 var(--ca-outline-subtle);
    display: flex;
    flex-direction: column;
    padding: 12px 8px;
    gap: 12px;
  }
  .panel-items { display: flex; flex-direction: column; gap: 4px; }
  .panel-item {
    padding: 6px 10px;
    border-radius: var(--ca-radius-sm);
    font-size: var(--ca-font-size-caption);
    color: var(--ca-text-secondary);
  }
  .panel-item--active {
    background: color-mix(in oklch, var(--ca-brand-main) 12%, transparent);
    color: var(--ca-brand-text);
    font-weight: 600;
  }
  .shell-main { flex: 1; display: flex; flex-direction: column; padding: 12px; gap: 8px; overflow: hidden; min-width: 0; }
  .main-topbar { height: 40px; border-radius: var(--ca-radius-md); background: var(--ca-action-hover); flex-shrink: 0; }
  .content-block { height: 48px; border-radius: var(--ca-radius-md); background: var(--ca-action-hover); }
  .content-block--short { height: 32px; width: 60%; }

  @media (max-width: 599.98px) {
    .shell-panel { display: none; }
  }
</style>
#166

Live shell

The real component inside a fixed-height frame. The pathname lives in local state; click the rail and panel to navigate.

Dashboard

Dashboard

/app/dashboard

Revenue
$118k
↑+23.4%
Users
24.8k
↑+8.1%

Click a rail icon or a panel item. The demo keeps the pathname in local state.

Reference #166 · Pick in the gallery

Code
svelte
<script lang="ts">
  import { AppShellLayout, PageShell, KpiCard, KpiGrid, Card, type NavModule } from '@codeatlasdev/ui';
  import { LayoutDashboard, Users, BarChart3, Settings, CreditCard, Activity } from '@lucide/svelte';

  const modules: NavModule[] = [
    {
      id: 'app',
      label: 'App',
      icon: LayoutDashboard,
      basePath: '/app',
      items: [
        { id: 'dashboard', label: 'Dashboard', icon: LayoutDashboard, path: '/app/dashboard' },
        { id: 'users', label: 'Users', icon: Users, path: '/app/users' },
        { id: 'reports', label: 'Reports', icon: BarChart3, path: '/app/reports' },
      ],
    },
    {
      id: 'account',
      label: 'Account',
      icon: Settings,
      basePath: '/account',
      items: [
        { id: 'billing', label: 'Billing', icon: CreditCard, path: '/account/billing' },
        { id: 'activity', label: 'Activity', icon: Activity, path: '/account/activity' },
        { id: 'settings', label: 'Settings', icon: Settings, path: '/account/settings' },
      ],
    },
  ];

  // The shell is router-agnostic: the app owns the URL and feeds it back in.
  let pathname = $state('/app/dashboard');

  // Panel items are plain <a href> links, exactly what a client router intercepts. With no router
  // in this demo, do the same: take over in-stage link clicks and feed the path back in.
  function intercept(e: MouseEvent) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = (e.target as Element).closest('a[href^="/"]');
    if (!a) return;
    e.preventDefault();
    pathname = a.getAttribute('href')!;
  }

  const titles: Record<string, string> = {
    '/app/dashboard': 'Dashboard',
    '/app/users': 'Users',
    '/app/reports': 'Reports',
    '/account/billing': 'Billing',
    '/account/activity': 'Activity',
    '/account/settings': 'Settings',
  };
</script>

<!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
<div class="stage" onclick={intercept}>
  <AppShellLayout {modules} {pathname} onNavigate={(path) => (pathname = path)} persistPanel={false} mainId={null} skipLink={false}>
    <PageShell title={titles[pathname] ?? 'Page'} description={pathname}>
      <KpiGrid>
        <KpiCard title="Revenue" value="$118k" trend={23.4} />
        <KpiCard title="Users" value="24.8k" trend={8.1} />
      </KpiGrid>
      <Card full>
        <p class="hint">Click a rail icon or a panel item. The demo keeps the pathname in local state.</p>
      </Card>
    </PageShell>
  </AppShellLayout>
</div>

<style>
  /* The shell sizes itself with --ca-vh and pins its sidebar and bottom nav with position: fixed.
     Overriding --ca-vh and creating a containing block (contain: layout) frames it inside the demo. */
  .stage {
    --ca-vh: 440px;
    position: relative;
    width: 100%;
    height: 440px;
    contain: layout paint;
    overflow: hidden;
    border-radius: var(--ca-radius-lg);
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .hint {
    margin: 0;
    color: var(--ca-text-secondary);
    font-size: var(--ca-font-size-body2);
  }
</style>
#480

Panel width

panelWidth={280} with resizablePanel: drag the edge or focus it and use the arrow keys.

Quarterly revenue forecast and planning

Wider panel

Drag the panel edge, or focus it and use the arrow keys.

The panel starts at 280px and holds between 160px and 480px.

Reference #480 · Pick in the gallery

Code
svelte
<script lang="ts">
  import { AppShellLayout, PageShell, Card, type NavModule } from '@codeatlasdev/ui';
  import { Folder } from '@lucide/svelte';

  const modules: NavModule[] = [
    {
      id: 'projects',
      label: 'Projects',
      icon: Folder,
      basePath: '/projects',
      items: [
        { id: 'a', label: 'Quarterly revenue forecast and planning', icon: Folder, path: '/projects/revenue' },
        { id: 'b', label: 'Customer onboarding experience redesign', icon: Folder, path: '/projects/onboarding' },
        { id: 'c', label: 'Infrastructure cost review', icon: Folder, path: '/projects/infra' },
      ],
    },
    { id: 'other', label: 'Other', icon: Folder, basePath: '/other', items: [] },
  ];

  let pathname = $state('/projects/revenue');

  function intercept(e: MouseEvent) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = (e.target as Element).closest('a[href^="/"]');
    if (!a) return;
    e.preventDefault();
    pathname = a.getAttribute('href')!;
  }
</script>

<!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
<div class="stage" onclick={intercept}>
  <AppShellLayout {modules} {pathname} panelWidth={280} resizablePanel persistPanel={false} mainId={null} skipLink={false}>
    <PageShell title="Wider panel" description="Drag the panel edge, or focus it and use the arrow keys.">
      <Card full>
        <p class="hint">The panel starts at 280px and holds between 160px and 480px.</p>
      </Card>
    </PageShell>
  </AppShellLayout>
</div>

<style>
  .stage {
    --ca-vh: 360px;
    position: relative;
    width: 100%;
    height: 360px;
    contain: layout paint;
    overflow: hidden;
    border-radius: var(--ca-radius-lg);
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .hint {
    margin: 0;
    color: var(--ca-text-secondary);
    font-size: var(--ca-font-size-body2);
  }
</style>
#601

Short panel

collapseShortPanel: a module with two destinations shows only the rail.

Profile

Profile

A two-item module needs no panel: the rail is enough.

With collapseShortPanel the content takes the width a two-link panel would waste.

Reference #601 · Pick in the gallery

Code
svelte
<script lang="ts">
  import { AppShellLayout, PageShell, Card, type NavModule } from '@codeatlasdev/ui';
  import { Settings, User, CreditCard } from '@lucide/svelte';

  const modules: NavModule[] = [
    {
      id: 'settings',
      label: 'Settings',
      icon: Settings,
      basePath: '/settings',
      items: [
        { id: 'profile', label: 'Profile', icon: User, path: '/settings/profile' },
        { id: 'billing', label: 'Billing', icon: CreditCard, path: '/settings/billing' },
      ],
    },
  ];

  let pathname = $state('/settings/profile');

  function intercept(e: MouseEvent) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = (e.target as Element).closest('a[href^="/"]');
    if (!a) return;
    e.preventDefault();
    pathname = a.getAttribute('href')!;
  }
</script>

<!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
<div class="stage" onclick={intercept}>
  <AppShellLayout {modules} {pathname} collapseShortPanel persistPanel={false} mainId={null} skipLink={false}>
    <PageShell title="Profile" description="A two-item module needs no panel: the rail is enough.">
      <Card full>
        <p class="hint">With collapseShortPanel the content takes the width a two-link panel would waste.</p>
      </Card>
    </PageShell>
  </AppShellLayout>
</div>

<style>
  .stage {
    --ca-vh: 320px;
    position: relative;
    width: 100%;
    height: 320px;
    contain: layout paint;
    overflow: hidden;
    border-radius: var(--ca-radius-lg);
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .hint {
    margin: 0;
    color: var(--ca-text-secondary);
    font-size: var(--ca-font-size-body2);
  }
</style>

Props

PropTypeDefaultDescription
modulesNavModule[]–Navigation modules. Each has id, label, icon, basePath, optional pathPrefixes and items (NavItem or NavSection). Prefixes match whole path segments and the longest one wins, so a module at `basePath: "/"` only gets the pages no other module claims.
pathnamestring–Current location. Decides the active module and item. An item is active on its `path` and below it; when several match (`/items` and `/items/a` on `/items/a`) the most specific one wins, whatever the order, and its label is the mobile header title. An item at `path: "/"` is active on `/` only.
onNavigate(path: string) => void–Called with the first path of the module when the rail or the bottom navigation switches module. Panel items are links and do not call it.
defaultModulenumber0Module index used when the URL matches no module and none was stored.
persistPanelbooleantrueKeeps the shell across page loads: panel open or closed, selected module and expanded sections (localStorage), panel scroll (sessionStorage). Restored before the first paint. Turn it off for demos and embeds that must always start from the defaults.
panelWidthnumber200Width of the navigation panel in px, for lists with long labels. Held between 160 and 480. The content offset and the open and close animation follow it, so nothing misaligns. Prefer it to overriding `--ca-panel-width`, which the layout does not read.
resizablePanelbooleanfalseAdds a drag handle on the panel's trailing edge. It is a keyboard-operable separator: Arrow keys move it by 8px, Shift by 32px, Home and End jump to the bounds. With `persistPanel` the chosen width is kept like the open state and restored before the first paint; `panelWidth` is the width used until the user picks one.
collapseShortPanelbooleanfalseCollapses the panel to the rail for a module with 2 destinations or fewer, so a short list does not reserve a 200px column. A module with a single destination never shows a panel either way; with three or more it stays open.
reorderComponent–Pass the exported `NavReorder` to enable `onReorder` on sections and modules. Opt-in so the drag engine is only bundled by apps that reorder.
itemMenuComponent–Pass the exported `NavItemMenu` to render `NavItem.actions` as a "…" menu. Opt-in so the dropdown menu is only bundled by apps that use it.
filterModules(module: NavModule) => boolean–Hides modules the user may not see (role, plan, flag). Rail, panel, bottom navigation and the active-module logic all use the filtered list, so a hidden module never shifts the indexes. Return `true` to keep one.
railLabelsbooleanfalseShows each module's label as a caption under its rail icon. The button's accessible name is the same with or without it.
railTopSnippet–Control between the brand and the modules in the rail, such as a search or ⌘K trigger that opens a `CommandPalette`.
bottomNavPrimarynumber5Most tabs on the mobile bottom navigation. With more modules, the first `bottomNavPrimary - 1` stay and the last tab is More, a dialog with the rest, so no module is ever unreachable. The More tab is current when the active module is inside it.
moreSheetComponent–Replaces the built-in More dialog. Pass the exported `NavMoreSheet` for a full `Sheet` with swipe to dismiss and an exit animation. Opt-in because `Sheet` adds about 10 kB gzip to the shell; the built-in dialog costs about 1 kB.
bottomNavOverflowSnippet–Extra content in the More dialog under the modules: search, account, sign out.
stageSnippet<[{ hidden: boolean }]>–A persistent background layer (map, canvas, video, 3D) rendered once, full-bleed under the content, beside the rail and above the bottom navigation. It survives route changes. The snippet gets `{ hidden }`: pause rendering while it is true. Content passes pointer events through; mark panels with `class="ca-stage-panel"`.
stageVisiblebooleantrue`false` hides the stage (`visibility: hidden`, `inert`) and passes `hidden: true` to it, without unmounting: for a full-page route that covers it. A page outside the component can set `data-ca-stage="hidden"` on `<html>` for the same effect.
headerSnippet–Desktop header rendered above the page content. Hidden below 900px.
brandSnippet–Logo shown at the top of the rail and in the mobile header.
railBottomSnippet–Items pinned to the bottom of the rail, such as an avatar or notifications.
mobileHeaderActionsSnippet–Controls at the trailing edge of the mobile header. Use it for anything that must stay reachable below 900px.
mobileTitleSnippet–Replaces the plain page title in the mobile header, for example a tappable title that opens a sheet.
mainIdstring | null'main'`id` of the content region, which is the page `<main tabindex="-1">` landmark and the skip link target. Pass `null` when your page renders its own `<main id="main" tabindex="-1">`: the region becomes a plain `div`.
skipLinkbooleantrueRenders the SkipLink. Turn it off when the shell is embedded in a page that already has one.
childrenSnippet–Page content.

Rail labels, search slot, badges and More

railLabels adds a caption under each rail icon. railTop is a slot above the modules for a search trigger: render a Button that opens your CommandPalette (see CommandPalette). Below 900px the bottom navigation holds up to bottomNavPrimary tabs (5 by default). With more modules it keeps bottomNavPrimary - 1 and adds a More tab that opens a dialog with the rest plus whatever bottomNavOverflow renders (an account row, sign out): no module is hidden. The built-in dialog is a native <dialog> (focus trap, Escape and focus restore come from the browser) and adds about 1 kB gzip. For swipe to dismiss and an exit animation pass moreSheet={NavMoreSheet}, which swaps in a full Sheet (opt-in like reorder and itemMenu, because Sheet adds about 10 kB gzip).

A module can carry a marker on its rail icon and tab:

Field What it does
badge A number (capped at 99+) or 'dot'. 0 and unset draw nothing.
badgeLabel The text a screen reader gets. The button is named "<label>, <badgeLabel>". Without it a number reads "Inbox, 12 unread" and a dot reads "Inbox, New". Set it for anything that is not “unread” ("3 tasks pending") and translate it yourself.

The marker itself is decorative; the count is never announced separately from the button. When any module inside the More sheet has a badge, the More tab shows a dot.

filterModules is for role-based navigation: keep one module list and filter it. Because the shell resolves the active module, the panel and the bottom navigation against the filtered list, hiding an earlier module cannot make the wrong rail icon active. When the URL belongs to a hidden module, the first visible module is selected.

#530

Labels, search slot, badges and More

railLabels, railTop, module badges, bottomNavOverflow and filterModules. Narrow the viewport below 900px to see the More sheet.

All

Labeled rail

/inbox/all

Captions under the icons, a search trigger on top, badges with names, and a More sheet below 900px. The role filter hides Settings.

Reference #530 · Pick in the gallery

Code
svelte
<script lang="ts">
  import { AppShellLayout, Button, PageShell, Card, type NavModule } from '@codeatlasdev/ui';
  import { Bell, Inbox, Map as MapIcon, Search, Settings, Users, Home } from '@lucide/svelte';

  // Role filter: the same list for everyone, filtered on the way in.
  let admin = $state(true);

  const modules: NavModule[] = [
    { id: 'inbox', label: 'Inbox', icon: Inbox, basePath: '/inbox', badge: 12, items: [
      { id: 'all', label: 'All', icon: Inbox, path: '/inbox/all' },
      { id: 'sent', label: 'Sent', icon: Inbox, path: '/inbox/sent' },
    ] },
    { id: 'map', label: 'Map', icon: MapIcon, basePath: '/map', badge: 'dot', badgeLabel: 'Search running', items: [
      { id: 'live', label: 'Live', icon: MapIcon, path: '/map/live' },
      { id: 'saved', label: 'Saved', icon: MapIcon, path: '/map/saved' },
    ] },
    { id: 'people', label: 'People', icon: Users, basePath: '/people', badge: 3, badgeLabel: '3 tasks pending', items: [
      { id: 'dir', label: 'Directory', icon: Users, path: '/people/dir' },
    ] },
    { id: 'alerts', label: 'Alerts', icon: Bell, basePath: '/alerts', items: [
      { id: 'rules', label: 'Rules', icon: Bell, path: '/alerts/rules' },
    ] },
    { id: 'search', label: 'Search', icon: Search, basePath: '/search', items: [
      { id: 'saved', label: 'Saved', icon: Search, path: '/search/saved' },
    ] },
    { id: 'home', label: 'Home', icon: Home, basePath: '/home', items: [
      { id: 'start', label: 'Start', icon: Home, path: '/home/start' },
    ] },
    { id: 'settings', label: 'Settings', icon: Settings, basePath: '/settings', items: [
      { id: 'gen', label: 'General', icon: Settings, path: '/settings/gen' },
    ] },
  ];

  let pathname = $state('/inbox/all');

  function intercept(e: MouseEvent) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = (e.target as Element).closest('a[href^="/"]');
    if (!a) return;
    e.preventDefault();
    pathname = a.getAttribute('href')!;
  }
</script>

<!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
<div class="stage" onclick={intercept}>
  <AppShellLayout {modules} filterModules={(m) => admin || m.id !== 'settings'} {pathname} onNavigate={(path) => (pathname = path)} railLabels persistPanel={false} mainId={null} skipLink={false}>
    {#snippet railTop()}
      <Button variant="ghost" size="sm" aria-label="Search, command K">
        {#snippet leading()}<Search size={16} />{/snippet}
      </Button>
    {/snippet}
    {#snippet bottomNavOverflow()}
      <Button variant="outlined" fullWidth>Account</Button>
    {/snippet}
    <PageShell title="Labeled rail" description={pathname}>
      <Card full>
        <p class="hint">Captions under the icons, a search trigger on top, badges with names, and a More sheet below 900px. The role filter hides Settings.</p>
        <Button variant="outlined" onclick={() => (admin = !admin)}>{admin ? 'Hide Settings (member)' : 'Show Settings (admin)'}</Button>
      </Card>
    </PageShell>
  </AppShellLayout>
</div>

<style>
  .stage {
    --ca-vh: 440px;
    position: relative;
    width: 100%;
    height: 440px;
    contain: layout paint;
    overflow: hidden;
    border-radius: var(--ca-radius-lg);
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .hint {
    margin: 0 0 var(--ca-space-3);
    color: var(--ca-text-secondary);
    font-size: var(--ca-font-size-body2);
  }
</style>

A stage behind the pages

Map-first products keep one live map behind every screen: the camera, the WebGL context and the selection must survive navigation. Pass the layer as the stage snippet. The shell renders it once, outside the page content, so a route change never remounts it.

<AppShellLayout {modules} {pathname} {onNavigate} {stage}>
  {@render children()}
</AppShellLayout>

{#snippet stage({ hidden })}
  <MapView paused={hidden} />
{/snippet}
Behavior How
Placement Full-bleed in the content region: right of the rail and panel, under the headers, above the bottom navigation and the home-indicator inset. No offsets to write.
Pointer events The content region is click-through. Empty areas reach the stage; give each panel class="ca-stage-panel" (or pointer-events: auto) to keep it interactive.
Background With a stage the shell paints nothing behind the content, so the stage shows.
Hide and pause stageVisible={false}, or data-ca-stage="hidden" on <html>. The stage turns visibility: hidden and inert, stays mounted and receives { hidden: true }: stop rendering there.
Insets --ca-shell-inset-top, -right, -bottom and -left on the shell hold what the chrome covers (desktop: rail plus panel on the left; below 900px: the mobile header on top and the bottom navigation plus safe area at the bottom). Use them for a map’s padding or a floating panel.
#531

Stage

A draggable stand-in for a map. Navigate with the panel: the mount count stays at 1 and the camera stays where you left it.

Leads

Floating over the stage

/field/leads

Stage mounted 0 time(s). Navigate the panel: the count stays at 1. Drag the stage behind this card; empty areas pass clicks through.

Reference #531 · Pick in the gallery

Code
svelte
<script lang="ts">
  import { untrack } from 'svelte';
  import { AppShellLayout, Button, Card, PageShell, type NavModule } from '@codeatlasdev/ui';
  import { Compass, Layers, Map as MapIcon } from '@lucide/svelte';

  const modules: NavModule[] = [
    {
      id: 'field',
      label: 'Field',
      icon: MapIcon,
      basePath: '/field',
      items: [
        { id: 'leads', label: 'Leads', icon: Layers, path: '/field/leads' },
        { id: 'routes', label: 'Routes', icon: Compass, path: '/field/routes' },
        { id: 'report', label: 'Report', icon: MapIcon, path: '/field/report' },
      ],
    },
  ];

  // A stand-in for a map: its camera is state that a remount would lose.
  let x = $state(0);
  let y = $state(0);
  let drag: { px: number; py: number } | null = null;

  let pathname = $state('/field/leads');
  let stageVisible = $state(true);
  // Counted in the stage itself: it must stay at 1 while the pages change.
  let mounts = $state(0);

  function intercept(e: MouseEvent) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = (e.target as Element).closest('a[href^="/"]');
    if (!a) return;
    e.preventDefault();
    pathname = a.getAttribute('href')!;
  }
</script>

{#snippet stage(s: { hidden: boolean })}
  <div
    class="map"
    class:map--paused={s.hidden}
    role="presentation"
    style="--x:{x}px;--y:{y}px"
    {@attach () => untrack(() => { mounts += 1; })}
    onpointerdown={(e) => { drag = { px: e.clientX - x, py: e.clientY - y }; (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); }}
    onpointermove={(e) => { if (drag) { x = e.clientX - drag.px; y = e.clientY - drag.py; } }}
    onpointerup={() => (drag = null)}
  >
    <span class="pin">Camera {Math.round(x)}, {Math.round(y)}</span>
  </div>
{/snippet}

<!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
<div class="frame" onclick={intercept}>
  <AppShellLayout {modules} {pathname} onNavigate={(path) => (pathname = path)} {stage} {stageVisible} persistPanel={false} mainId={null} skipLink={false}>
    <PageShell title="Floating over the stage" description={pathname}>
      <div class="ca-stage-panel panel">
        <Card full>
          <p class="hint">Stage mounted {mounts} time(s). Navigate the panel: the count stays at 1. Drag the stage behind this card; empty areas pass clicks through.</p>
          <Button variant="outlined" onclick={() => (stageVisible = !stageVisible)}>{stageVisible ? 'Hide and pause stage' : 'Show stage'}</Button>
        </Card>
      </div>
    </PageShell>
  </AppShellLayout>
</div>

<style>
  .frame {
    --ca-vh: 440px;
    position: relative;
    width: 100%;
    height: 440px;
    contain: layout paint;
    overflow: hidden;
    border-radius: var(--ca-radius-lg);
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .panel { max-width: 22rem; }
  .map {
    position: absolute;
    inset: 0;
    cursor: grab;
    background:
      linear-gradient(var(--ca-outline-subtle) 1px, transparent 1px) var(--x) var(--y) / 48px 48px,
      linear-gradient(90deg, var(--ca-outline-subtle) 1px, transparent 1px) var(--x) var(--y) / 48px 48px,
      color-mix(in oklab, var(--ca-brand-main) 10%, var(--ca-surface-base));
    touch-action: none;
  }
  .map--paused { cursor: default; }
  .pin {
    position: absolute;
    right: var(--ca-space-3);
    bottom: var(--ca-space-3);
    padding: var(--ca-space-1) var(--ca-space-2);
    border-radius: var(--ca-radius-pill);
    background: var(--ca-brand-fill);
    color: var(--ca-brand-contrast);
    font-size: var(--ca-font-size-caption);
  }
  .hint {
    margin: 0 0 var(--ca-space-3);
    color: var(--ca-text-secondary);
    font-size: var(--ca-font-size-body2);
  }
</style>

Matching the page background to a nested preset

<html> paints the page preset’s surface, so a public screen wrapped in its own preset would leave the overscroll area and the mobile toolbar in the wrong color. Use <ThemeIsland preset scheme document> (ThemeIsland, from the theme work in #352): it mirrors the island’s preset and scheme onto <html> while it is mounted, so the root background follows with no copied color.

Resizing the panel

The panel is 200px by default. For lists with long names pass panelWidth (px, held between 160 and 480): the content offset and the open and close animation follow it, so the page never misaligns. Add resizablePanel to let people choose: a handle sits on the panel’s trailing edge and is a keyboard-operable separator (role="separator" with aria-valuenow, aria-valuemin and aria-valuemax). Arrow keys move it by 8px, Shift by 32px, Home and End jump to the bounds. While the pointer holds the edge the panel follows it with no spring in between. With persistPanel the width is stored with the open state and restored before the first paint; panelWidth is the width used until the user picks one. A stored width is ignored when resizablePanel is off, so the prop stays the contract.

Rich panel items

A NavItem takes more than an icon and a label:

Field What it does
color A decorative dot before the label, any CSS color. The icon stays.
leading A snippet that replaces the icon (a color swatch, an avatar, an emoji). Decorative: the label is the name.
count A neutral total after the label (1.2k above 999). The link’s name carries the exact number, never “unread”. 0 renders.
badge Unread-style count: announced “N unread”, capped at 99+. Use count for a plain total.
actions A snippet of DropdownMenuItems. The row gets a “…” button named Actions for <label>, a sibling of the link, shown on hover and focus. Needs itemMenu={NavItemMenu} on the shell.

Reordering is per list: set onReorder on a NavSection (or on the NavModule for the items that sit outside any section) and pass reorder={NavReorder} to AppShellLayout. Each row gets a grip that works with the mouse, touch (press and hold) and the keyboard (Space lifts, arrows move, Enter drops, Escape cancels), and every step is announced. It is the same useDnd engine as drag and drop. The shell never reorders items for you: commit the move in your state and the new order flows back in. onReorder is not called when the drop lands where it started.

NavReorder and NavItemMenu are opt-in on purpose: the drag engine and the dropdown menu are only bundled by apps that import them, so a shell without per-item menus or reordering stays small.

<script lang="ts">
  import { AppShellLayout, DropdownMenuItem, NavItemMenu, NavReorder, type NavModule, type NavReorderEvent } from "@codeatlasdev/ui";

  type Row = { id: string; name: string; color: string; count: number };
  let rows = $state<Row[]>([]);
  function archive() {}

  function reorder(e: NavReorderEvent) {
    const next = rows.slice();
    next.splice(e.to, 0, ...next.splice(e.from, 1));
    rows = next;
  }
</script>

{#snippet menu()}
  <DropdownMenuItem onclick={archive}>{#snippet children()}Archive{/snippet}</DropdownMenuItem>
{/snippet}

<!-- items: rows.map((r) => ({ id: r.id, label: r.name, icon: Folder, path: `/p/${r.id}`, color: r.color, count: r.count, actions: menu })) -->
<!-- <AppShellLayout {modules} {pathname} reorder={NavReorder} itemMenu={NavItemMenu}> -->
#481

Color, count, actions and reorder

Each row has a color dot, a neutral count and a … menu; drag a row by its grip.

Design system

Workspaces

/projects/design

Open the … menu of a row, or drag a row by its grip.

Reference #481 · Pick in the gallery

Code
svelte
<script lang="ts">
  import {
    AppShellLayout,
    DropdownMenuItem,
    NavItemMenu,
    NavReorder,
    PageShell,
    Card,
    type NavModule,
    type NavReorderEvent,
  } from '@codeatlasdev/ui';
  import { Folder } from '@lucide/svelte';

  type Row = { id: string; name: string; color: string; count: number };
  let rows = $state<Row[]>([
    { id: 'design', name: 'Design system', color: '#e11d48', count: 42 },
    { id: 'web', name: 'Marketing site', color: '#2563eb', count: 1280 },
    { id: 'mobile', name: 'Mobile app', color: '#16a34a', count: 0 },
  ]);
  let log = $state('Open the … menu of a row, or drag a row by its grip.');

  function reorder(e: NavReorderEvent) {
    const next = rows.slice();
    const [moved] = next.splice(e.from, 1);
    next.splice(e.to, 0, moved);
    rows = next;
    log = `Moved ${moved.name} to position ${e.to + 1}.`;
  }

  const modules: NavModule[] = $derived([
    {
      id: 'projects',
      label: 'Projects',
      icon: Folder,
      basePath: '/projects',
      items: [
        {
          label: 'Workspaces',
          collapsible: false,
          onReorder: reorder,
          items: rows.map((r) => ({
            id: r.id,
            label: r.name,
            icon: Folder,
            path: `/projects/${r.id}`,
            color: r.color,
            count: r.count,
            actions: menu,
          })),
        },
      ],
    },
    { id: 'other', label: 'Other', icon: Folder, basePath: '/other', items: [] },
  ]);

  let pathname = $state('/projects/design');
  function intercept(e: MouseEvent) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = (e.target as Element).closest('a[href^="/"]');
    if (!a) return;
    e.preventDefault();
    pathname = a.getAttribute('href')!;
  }
</script>

{#snippet menu()}
  <DropdownMenuItem onclick={() => (log = 'Favorite')}>{#snippet children()}Favorite{/snippet}</DropdownMenuItem>
  <DropdownMenuItem onclick={() => (log = 'Archive')} variant="destructive">{#snippet children()}Archive{/snippet}</DropdownMenuItem>
{/snippet}

<!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
<div class="stage" onclick={intercept}>
  <AppShellLayout {modules} {pathname} reorder={NavReorder} itemMenu={NavItemMenu} persistPanel={false} mainId={null} skipLink={false}>
    <PageShell title="Workspaces" description={pathname}>
      <Card full>
        <p class="hint">{log}</p>
      </Card>
    </PageShell>
  </AppShellLayout>
</div>

<style>
  .stage {
    --ca-vh: 360px;
    position: relative;
    width: 100%;
    height: 360px;
    contain: layout paint;
    overflow: hidden;
    border-radius: var(--ca-radius-lg);
    box-shadow: inset 0 0 0 1px var(--ca-outline-subtle);
  }
  .hint {
    margin: 0;
    color: var(--ca-text-secondary);
    font-size: var(--ca-font-size-body2);
  }
</style>

State across page loads

On a multi-page site (Astro, a full reload) every link loads a new document, so a shell that only keeps state in memory reopens at its defaults: the panel, the module, the expanded groups and the panel scroll are all lost. With persistPanel (the default) the shell keeps them and puts them back before the first paint, the same way the theme script does.

What Where Key
Panel open or closed, selected module, dragged panel width, section open map localStorage ca-shell
Panel scroll, per module sessionStorage ca-shell-scroll

An inline script emitted right after the sidebar reads those keys and sets data-ca-panel="open|closed" and data-ca-module="<id>" on <html> before anything paints, so a panel the user closed is laid out closed from the first frame instead of flashing open. Stored values are validated and discarded when malformed. A section’s last open or closed choice wins over defaultOpen, but the section that holds the current page always opens. The module comes from the URL when modules matches it, and from the stored choice otherwise.

Render the shell on the server so the first paint is not blank: the inline script and the markup travel together. A client-only mount gets the same restore on hydration, and a page whose CSP blocks inline scripts too. Keep id stable on each NavModule (it is the stored module key) and each section label unique within a module (it is the stored section key).

Building blocks for a custom panel

AppShellLayout renders the panel for you. Rail, Panel, BottomNav and MobileHeader are exported too, and two of them are the pieces to reuse when you lay out your own navigation: PanelNavItem is the row the panel draws for one NavItem (icon or leading, color dot, label, count, unread badge, new dot, the actions menu and the active pip), and SectionGroup is a titled group of items that collapses.

<script lang="ts">
  import { PanelNavItem, SectionGroup, type NavSection } from "@codeatlasdev/ui";

  const section: NavSection = { label: "Reports", collapsible: true, items };
</script>

<SectionGroup {section} {pathname} />
<PanelNavItem item={items[0]} isActive={pathname === items[0].path} href={items[0].path} />

PanelNavItem renders a row with a plain <a> inside it (aria-current="page" when active); the actions button and the grip are siblings of the link, because a link cannot contain controls. SectionGroup opens itself when it holds the current page, and inside an AppShellLayout with persistPanel it stores its open state under the section label; a bare SectionGroup keeps nothing.

PanelNavItem props

PropTypeDefaultDescription
itemNavItem–The destination: `id`, `label`, `icon`, `path`, and optional `badge`, `count`, `color`, `leading`, `actions`, `isNew`, `shortcut`, `description`. Required.
isActiveboolean–Marks the row as the current page (`aria-current="page"`, active pip). Required.
hrefstring–Link target. Required.
gripbooleanfalseAdds the drag grip. Set it when the list the row sits in is reorderable (`NavSection.onReorder`).
describedbystring–`id` of the node that describes the keyboard drag (`dnd.instructionsId`), set on the grip.
classstring''Extra class names.

SectionGroup props

PropTypeDefaultDescription
sectionNavSection–`label`, `items`, and optional `collapsible` (default `true`), `defaultOpen` (default `true`) and `onReorder` (makes the items reorderable). Required.
pathnamestring–Current location, used to mark the active item and to keep the group holding it open. Required.
classstring''Extra class names.