Skip to content

App shell

A collapsible sidebar on the paper and one raised sheet: a range, a chart, tabbed lists and plan meters, with an org switcher and ⌘K.

1152 lines · React · Tailwind 4

Install

$ bunx shadcn@latest add @blocco/app-shell

Code

blocks/free/app-shell.tsx1152 lines
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
  IconBuilding,
  IconChartBar,
  IconCreditCard,
  IconKey,
  IconLayoutGrid,
  IconLink,
  IconSettings,
  IconUsers,
  IconWorld,
  type Icon,
} from "@tabler/icons-react";
import { Avatar } from "@/registry/blocco/ui/avatar";
import { Button } from "@/registry/blocco/ui/button";
import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/registry/blocco/ui/command";
import {
  ArrowDown,
  ArrowUp,
  Check,
  ChevronsUpDown,
  Lightbulb,
  MenuIcon,
  PanelLeftClose,
  PanelLeftOpen,
  Plus,
  Search,
  TriangleAlert,
  X,
  Globe,
} from "@/registry/blocco/ui/icons";
import { Kbd, Shortcut } from "@/registry/blocco/ui/kbd";
import { Menu, MenuHeader, MenuItem, MenuSeparator } from "@/registry/blocco/ui/menu";
import { PageHeader } from "@/registry/blocco/ui/misc";
import { Segmented } from "@/registry/blocco/ui/segmented";
import { PanelTabs } from "@/registry/blocco/ui/tabs";
import { useToast } from "@/registry/blocco/ui/toast";
import { Tooltip, TooltipGroup } from "@/registry/blocco/ui/tooltip";
import { cn } from "@/registry/blocco/ui/cn";

/* ------------------------------------------------------------------ data */

type Range = "24h" | "7d" | "30d";
const RANGES = [
  { id: "24h", label: "24h" },
  { id: "7d", label: "7d" },
  { id: "30d", label: "30d" },
] as const;

type Point = { label: string; clicks: number };

const MONTH_DAYS = Array.from({ length: 30 }, (_, i) => {
  const d = new Date(Date.UTC(2026, 9, 18 + i));
  return d.toLocaleDateString("en", { month: "short", day: "numeric", timeZone: "UTC" });
});
/** The last week, and the 23 days before it with a weekly rhythm and a steady climb. */
const WEEK = [318, 402, 466, 521, 498, 642, 781];
const DAILY: Point[] = MONTH_DAYS.map((label, i) => ({
  label,
  clicks:
    i >= 23
      ? WEEK[i - 23]
      : Math.round(
          250 + i * 9 + Math.sin(((i + 2) * 2 * Math.PI) / 7) * 80 + (((i * 37) % 11) - 5) * 14,
        ),
}));
const HOURLY: Point[] = [
  38, 29, 22, 18, 16, 19, 31, 52, 78, 96, 110, 118, 121, 113, 126, 131, 117, 102, 88, 79, 66, 58,
  49, 42,
].map((clicks, i) => ({ label: `${String(i).padStart(2, "0")}:00`, clicks }));

const SERIES = { "24h": HOURLY, "7d": DAILY.slice(-7), "30d": DAILY } satisfies Record<
  Range,
  Point[]
>;

const FIGURES = {
  "24h": { links: 31, clicksDelta: 6, linksDelta: 3, country: "United States", source: "Direct" },
  "7d": { links: 58, clicksDelta: 12, linksDelta: -4, country: "Germany", source: "Direct" },
  "30d": { links: 96, clicksDelta: 21, linksDelta: 9, country: "Germany", source: "google.com" },
} satisfies Record<
  Range,
  { links: number; clicksDelta: number; linksDelta: number; country: string; source: string }
>;
const SCALE = { "24h": 0.14, "7d": 1, "30d": 4.1 } satisfies Record<Range, number>;

const LINKS = [
  { slug: "spring", title: "Spring launch", clicks: 412 },
  { slug: "docs", title: "Docs home", clicks: 388 },
  { slug: "pricing", title: "Pricing page", clicks: 301 },
  { slug: "news", title: "Newsletter signup", clicks: 246 },
  { slug: "app", title: "App download", clicks: 187 },
  { slug: "menu", title: "Menu", clicks: 121 },
];

const ATTENTION = [
  { slug: "promo", title: "Summer promo", note: "62% fewer clicks" },
  { slug: "webinar", title: "Webinar signup", note: "54% fewer clicks" },
  { slug: "old-docs", title: "Old docs", note: "No clicks in 30 days" },
  { slug: "beta", title: "Beta invite", note: "No clicks in 30 days" },
];

const CLICKS = [
  { slug: "spring", source: "Direct", country: "de", ago: "2m" },
  { slug: "docs", source: "t.co", country: "us", ago: "9m" },
  { slug: "spring", source: "google.com", country: "pt", ago: "31m" },
  { slug: "pricing", source: "linkedin.com", country: "gb", ago: "1h" },
  { slug: "news", source: "instagram.com", country: "gr", ago: "3h" },
  { slug: "app", source: "Direct", country: "au", ago: "5h" },
  { slug: "docs", source: "google.com", country: "ca", ago: "1d" },
  { slug: "menu", source: "facebook.com", country: "it", ago: "2d" },
];

const TEAM = [
  { who: "Ada Lovelace", slug: "spring", ago: "2d" },
  { who: "Grace Hopper", slug: "webinar", ago: "3d" },
  { who: "Alan Turing", slug: "beta", ago: "5d" },
  { who: "Katherine Johnson", slug: "menu", ago: "1w" },
  { who: "Ada Lovelace", slug: "docs", ago: "2w" },
];

const BEFORE = {
  "24h": "the day before",
  "7d": "last week",
  "30d": "the 30 days before",
} satisfies Record<Range, string>;

type Tone = "up" | "down" | "first" | "warn";
const TONES = {
  up: { icon: ArrowUp, tile: "bg-mint/15 text-mint" },
  down: { icon: ArrowDown, tile: "bg-danger/15 text-danger" },
  first: { icon: Lightbulb, tile: "bg-accent/15 text-accent" },
  warn: { icon: TriangleAlert, tile: "bg-butter/15 text-butter" },
} satisfies Record<Tone, { icon: Icon; tile: string }>;

const METERS = [
  { label: "Links", count: 184, limit: 3000 },
  { label: "Clicks this month", count: 7908, limit: 500000 },
  { label: "Custom domains", count: 2, limit: 3 },
  { label: "Members", count: 8, limit: 10 },
];

const pages = [
  { id: "dashboard", label: "Dashboard", icon: IconLayoutGrid },
  { id: "analytics", label: "Analytics", icon: IconChartBar },
  { id: "links", label: "Links", icon: IconLink },
  { id: "domains", label: "Domains", icon: IconWorld },
  { id: "members", label: "Members", icon: IconUsers },
  { id: "organization", label: "Organization", icon: IconBuilding },
  { id: "api", label: "API", icon: IconKey },
  { id: "billing", label: "Billing", icon: IconCreditCard },
  { id: "settings", label: "Settings", icon: IconSettings },
] as const;
type PageId = (typeof pages)[number]["id"];

const orgs = [
  { id: "acme", name: "Acme Studio", detail: "Pro, 8 members" },
  { id: "north", name: "Northwind", detail: "Hobby, 2 members" },
];

const USER = { name: "Ada Lovelace", email: "ada@acme.test" };

/* --------------------------------------------------------------- helpers */

/** 1,284 is "1.3k" from a thousand up, as the real dashboard says it. */
function compact(n: number) {
  if (n < 1000) return String(n);
  const k = Math.round(n / 100) / 10;
  return `${k}k`;
}
const exact = (n: number) => n.toLocaleString("en");

/** Every label up to eight; past that, five evenly spaced, ends included. */
function evenTicks(count: number): number[] {
  if (count <= 8) return Array.from({ length: count }, (_, i) => i);
  return [0, 1, 2, 3, 4].map((i) => Math.round((i * (count - 1)) / 4));
}

/** The top of the y scale: the max rounded up to an even, round number. */
function yTop(max: number) {
  const raw = Math.max(2, max) / 4;
  const pow = 10 ** Math.floor(Math.log10(raw));
  const step = ([1, 2, 2.5, 5, 10].find((s) => s * pow >= raw) ?? 10) * pow;
  const top = Math.ceil(Math.max(2, max) / step) * step;
  return top % 2 === 0 ? top : top + 1;
}

/** A monotone cubic through the points: it never overshoots, so it never dips below zero. */
function monotonePath(pts: [number, number][]) {
  const n = pts.length;
  const dx = (i: number) => pts[i + 1][0] - pts[i][0];
  const slope = (i: number) => (pts[i + 1][1] - pts[i][1]) / dx(i);
  const m = pts.map((_, i) =>
    i === 0
      ? slope(0)
      : i === n - 1
        ? slope(n - 2)
        : slope(i - 1) * slope(i) <= 0
          ? 0
          : (slope(i - 1) + slope(i)) / 2,
  );
  let d = `M${pts[0][0]},${pts[0][1]}`;
  for (let i = 0; i < n - 1; i++) {
    const h = dx(i) / 3;
    d += ` C${pts[i][0] + h},${pts[i][1] + m[i] * h} ${pts[i + 1][0] - h},${pts[i + 1][1] - m[i + 1] * h} ${pts[i + 1][0]},${pts[i + 1][1]}`;
  }
  return d;
}

/** Fades in from a soft blur when it mounts, so a new key crossfades without CSS of its own. */
const FADE_IN =
  "transition-[opacity,filter] duration-200 ease-out starting:opacity-0 starting:blur-[4px]";

/* ----------------------------------------------------------------- flags */

/** Round flags, drawn inline (circle-flags, MIT): the pages stay self-contained. */
const FLAGS = {
  pt: `<path fill="#6da544" d="M0 512h167l37.9-260.3L167 0H0z"/><path fill="#d80027" d="M512 0H167v512h345z"/><circle cx="167" cy="256" r="89" fill="#ffda44"/><path fill="#d80027" d="M116.9 211.5V267a50 50 0 1 0 100.1 0v-55.6H117z"/><path fill="#eee" d="M167 283.8c-9.2 0-16.7-7.5-16.7-16.7V245h33.4v22c0 9.2-7.5 16.7-16.7 16.7z"/>`,
  ca: `<path fill="#d80027" d="M0 0v512h144l112-64 112 64h144V0H368L256 64 144 0Z"/><path fill="#eee" d="M144 0h224v512H144Z"/><path fill="#d80027" d="m301 289 44-22-22-11v-22l-45 22 23-44h-23l-22-34-22 33h-23l23 45-45-22v22l-22 11 45 22-12 23h45v33h22v-33h45z"/>`,
  au: `<path fill="#0052b4" d="M0 0h512v512H0z"/><path fill="#eee" d="m154 300 14 30 32-8-14 30 25 20-32 7 1 33-26-21-26 21 1-33-33-7 26-20-14-30 32 8zm222-27h47l-38 27 15-44 14 44zm7-162 7 15 16-4-7 15 12 10-15 3v17l-13-11-13 11v-17l-15-3 12-10-7-15 16 4zm57 67 7 15 16-4-7 15 12 10-15 3v16l-13-10-13 11v-17l-15-3 12-10-7-15 16 4zm-122 22 7 15 16-4-7 15 12 10-15 3v16l-13-10-13 11v-17l-15-3 12-10-7-15 16 4zm65 156 7 15 16-4-7 15 12 10-15 3v17l-13-11-13 11v-17l-15-3 12-10-7-15 16 4zM0 0v32l32 32L0 96v160h32l32-32 32 32h32v-83l83 83h45l-8-16 8-15v-14l-83-83h83V96l-32-32 32-32V0H96L64 32 32 0Z"/><path fill="#d80027" d="M32 0v32H0v64h32v160h64V96h160V32H96V0Zm96 128 128 128v-31l-97-97z"/>`,
  gr: `<path fill="#0052b4" d="M0 0h99l29 32 28-32h356v57l-32 28 32 29v57l-32 28 32 29v57l-32 28 32 28v57l-32 29 32 28v57H0v-57l32-28-32-29v-56l32-29-32-28V171l32-29-32-28Z"/><path fill="#eee" d="M99 0v114H0v57h99v114H0v57h512v-57H156V171h100v-57H156V0Zm157 57v57h256V57Zm0 114v57h256v-57ZM0 398v57h512v-57z"/>`,
  us: `<path fill="#eee" d="M256 0h256v64l-32 32 32 32v64l-32 32 32 32v64l-32 32 32 32v64l-256 32L0 448v-64l32-32-32-32v-64z"/><path fill="#d80027" d="M224 64h288v64H224Zm0 128h288v64H256ZM0 320h512v64H0Zm0 128h512v64H0Z"/><path fill="#0052b4" d="M0 0h256v256H0Z"/><path fill="#eee" d="m187 243 57-41h-70l57 41-22-67zm-81 0 57-41H93l57 41-22-67zm-81 0 57-41H12l57 41-22-67zm162-81 57-41h-70l57 41-22-67zm-81 0 57-41H93l57 41-22-67zm-81 0 57-41H12l57 41-22-67Zm162-82 57-41h-70l57 41-22-67Zm-81 0 57-41H93l57 41-22-67zm-81 0 57-41H12l57 41-22-67Z"/>`,
  de: `<path fill="#ffda44" d="m0 345 256.7-25.5L512 345v167H0z"/><path fill="#d80027" d="m0 167 255-23 257 23v178H0z"/><path fill="#333" d="M0 0h512v167H0z"/>`,
  gb: `<path fill="#eee" d="m0 0 8 22-8 23v23l32 54-32 54v32l32 48-32 48v32l32 54-32 54v68l22-8 23 8h23l54-32 54 32h32l48-32 48 32h32l54-32 54 32h68l-8-22 8-23v-23l-32-54 32-54v-32l-32-48 32-48v-32l-32-54 32-54V0l-22 8-23-8h-23l-54 32-54-32h-32l-48 32-48-32h-32l-54 32L68 0H0z"/><path fill="#0052b4" d="M336 0v108L444 0Zm176 68L404 176h108zM0 176h108L0 68ZM68 0l108 108V0Zm108 512V404L68 512ZM0 444l108-108H0Zm512-108H404l108 108Zm-68 176L336 404v108z"/><path fill="#d80027" d="M0 0v45l131 131h45L0 0zm208 0v208H0v96h208v208h96V304h208v-96H304V0h-96zm259 0L336 131v45L512 0h-45zM176 336 0 512h45l131-131v-45zm160 0 176 176v-45L381 336h-45z"/>`,
  it: `<path fill="#eee" d="M167 0h178l25.9 252.3L345 512H167l-29.8-253.4z"/><path fill="#6da544" d="M0 0h167v512H0z"/><path fill="#d80027" d="M345 0h167v512H345z"/>`,
} satisfies Record<string, string>;

type CountryCode = keyof typeof FLAGS;
const isCountry = (code: string): code is CountryCode => Object.hasOwn(FLAGS, code);

function Flag({ code }: { code: string }) {
  if (!isCountry(code))
    return <Globe aria-hidden size={16} stroke={1.75} className="shrink-0 text-muted" />;
  return (
    <svg
      aria-hidden
      viewBox="0 0 512 512"
      className="size-4 shrink-0 overflow-hidden rounded-full smooth-shadow-ring-xs"
      dangerouslySetInnerHTML={{ __html: FLAGS[code] }}
    />
  );
}

const COUNTRY_NAME = {
  de: "Germany",
  us: "United States",
  pt: "Portugal",
  gb: "United Kingdom",
  gr: "Greece",
  au: "Australia",
  ca: "Canada",
  it: "Italy",
} satisfies Record<CountryCode, string>;

const countryName = (code: string) => (isCountry(code) ? COUNTRY_NAME[code] : undefined);

/* ----------------------------------------------------------------- chart */

const PAD_L = 20;
const PAD_R = 27;
const LABEL_W = 30;

/** One hue, a faint fill, three hairlines labelled on the right, a dashed guide and a small tip on hover. */
function AreaChart({ data, height = 180 }: { data: Point[]; height?: number }) {
  const wrap = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);
  const [hover, setHover] = useState<number | null>(null);

  useLayoutEffect(() => {
    const el = wrap.current;
    if (!el) return;
    setWidth(el.clientWidth);
    const ro = new ResizeObserver(() => setWidth(el.clientWidth));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const top = yTop(Math.max(1, ...data.map((d) => d.clicks)));
  const zero = height - 24;
  const plotTop = 8;
  const y = (v: number) => zero - (v / top) * (zero - plotTop);
  const x = (i: number) => PAD_L + (i / (data.length - 1)) * (width - PAD_L - PAD_R);
  const pts = useMemo(
    () => data.map((d, i): [number, number] => [x(i), y(d.clicks)]),
    // eslint-disable-next-line react-hooks/exhaustive-deps -- x and y are pure in these
    [data, width, height, top],
  );
  const line = width > 0 ? monotonePath(pts) : "";
  const ticks = evenTicks(data.length);

  const onMove = (e: React.PointerEvent<HTMLDivElement>) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const t = (e.clientX - rect.left - PAD_L) / (width - PAD_L - PAD_R);
    setHover(Math.min(data.length - 1, Math.max(0, Math.round(t * (data.length - 1)))));
  };
  const point = hover === null || width === 0 ? null : data[hover];

  return (
    <div
      ref={wrap}
      className="relative touch-pan-y select-none"
      style={{ height }}
      onPointerMove={onMove}
      onPointerLeave={() => setHover(null)}
    >
      {width > 0 && (
        <svg
          width={width}
          height={height}
          role="img"
          aria-label={`Clicks, ${data[0].label} to ${data[data.length - 1].label}`}
          className="block"
        >
          {[0, top / 2, top].map((v) => (
            <g key={v}>
              <line x1={0} x2={width - LABEL_W} y1={y(v)} y2={y(v)} className="stroke-border/70" />
              <text x={width} y={y(v)} dy="0.35em" textAnchor="end" className="fill-muted text-2xs">
                {compact(v)}
              </text>
            </g>
          ))}
          <path
            d={`${line} L${pts[pts.length - 1][0]},${zero} L${pts[0][0]},${zero} Z`}
            className="fill-chart/14"
          />
          <path d={line} className="fill-none stroke-chart" strokeWidth={2} />
          {hover !== null && (
            <line
              x1={pts[hover][0]}
              x2={pts[hover][0]}
              y1={plotTop}
              y2={zero}
              strokeDasharray="3 3"
              className="stroke-placeholder"
            />
          )}
          {ticks.map((i) => (
            <text
              key={i}
              x={pts[i][0]}
              y={height - 6}
              textAnchor="middle"
              className="fill-muted text-2xs"
            >
              {data[i].label}
            </text>
          ))}
        </svg>
      )}
      {point && hover !== null && (
        <div
          className="pointer-events-none absolute top-2 z-10"
          style={{
            left: pts[hover][0],
            transform: `translateX(${pts[hover][0] > width / 2 ? "calc(-100% - 12px)" : "12px"})`,
          }}
        >
          <div className="rounded-lg bg-surface-2 px-2.5 py-1.5 whitespace-nowrap smooth-shadow-ring-lg">
            <div className="text-xs text-muted">{point.label}</div>
            <div className="tnum text-sm font-semibold">
              {exact(point.clicks)}{" "}
              <span className="text-xs font-normal text-muted">
                {point.clicks === 1 ? "click" : "clicks"}
              </span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/** The change beside a figure: an arrow and the size of the move. The arrow carries the direction. */
function Delta({ pct }: { pct: number }) {
  const up = pct > 0;
  const Arrow = up ? ArrowUp : ArrowDown;
  return (
    <span
      className={cn(
        "tnum inline-flex items-center gap-0.5 text-xs font-medium",
        pct === 0 ? "text-muted" : up ? "text-accent-2" : "text-danger",
      )}
    >
      {pct !== 0 && <Arrow aria-hidden size={12} stroke={2.25} />}
      <span className="sr-only">{pct === 0 ? "No change" : up ? "Up" : "Down"}</span>
      {Math.abs(pct)}%
    </span>
  );
}

function StatsChart({
  figures,
  children,
}: {
  figures: { label: string; value: ReactNode; delta?: number }[];
  children: ReactNode;
}) {
  return (
    <div className="rounded-xl bg-surface smooth-shadow-ring-xs">
      <dl className="flex flex-wrap gap-1 p-1.5">
        {figures.map((f) => (
          <div
            key={f.label}
            className="flex min-w-[40%] flex-1 flex-col gap-0.5 px-2.5 py-2 sm:min-w-0"
          >
            <dt className="truncate text-xs text-muted">{f.label}</dt>
            <dd className="tnum flex min-w-0 items-baseline gap-2 text-xl leading-tight font-semibold tracking-tight">
              <span className="truncate">{f.value}</span>
              {f.delta !== undefined && <Delta pct={f.delta} />}
            </dd>
          </div>
        ))}
      </dl>
      <div className="px-4 pt-1 pb-3">{children}</div>
    </div>
  );
}

/* ------------------------------------------------------------- the lists */

/** Ranked bars with the label inside: one shared scale, the count in its own column. */
function BarList({ items }: { items: { key: string; label: ReactNode; clicks: number }[] }) {
  const max = Math.max(1, ...items.map((i) => i.clicks));
  return (
    <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-0.5 text-sm">
      {items.map((item) => (
        <div key={item.key} className="group contents">
          <div className="relative flex h-[30px] min-w-0 items-center gap-2 px-2">
            <span
              aria-hidden
              className="pointer-events-none absolute inset-y-0 left-0 rounded-md bg-chart/10 transition-colors duration-150 ease-out [@media(hover:hover)]:group-hover:bg-chart/20"
              style={{ width: item.clicks ? `${Math.max(2, (item.clicks / max) * 100)}%` : 0 }}
            />
            <span className="relative min-w-0 truncate">{item.label}</span>
          </div>
          <span className="tnum pr-1 text-right">{exact(item.clicks)}</span>
        </div>
      ))}
    </div>
  );
}

const ROW =
  "flex h-8 items-center justify-between gap-3 text-sm [&+&]:shadow-[inset_0_1px_0_var(--border)]";

function Slug({ children }: { children: string }) {
  return <span className="font-mono text-[13px]">/{children}</span>;
}

function RecentClicks() {
  return (
    <ul className="flex flex-col">
      {CLICKS.map((c) => (
        <li
          key={`${c.slug}-${c.ago}`}
          className="grid h-8 grid-cols-[minmax(0,7.5rem)_minmax(0,1fr)_auto_1.75rem] items-center gap-2.5 text-sm [&+&]:shadow-[inset_0_1px_0_var(--border)]"
        >
          <span className="truncate">
            <Slug>{c.slug}</Slug>
          </span>
          <span className="truncate text-muted">{c.source}</span>
          <Tooltip content={countryName(c.country)}>
            <span className="flex">
              <Flag code={c.country} />
              <span className="sr-only">{countryName(c.country)}</span>
            </span>
          </Tooltip>
          <time className="tnum text-right text-xs text-muted">{c.ago}</time>
        </li>
      ))}
    </ul>
  );
}

function TeamActivity() {
  return (
    <ul className="flex flex-col">
      {TEAM.map((t) => (
        <li key={`${t.who}-${t.slug}`} className={ROW}>
          <span className="min-w-0 truncate">
            <span className="font-medium">{t.who}</span>
            <span className="text-muted"> created </span>
            <Slug>{t.slug}</Slug>
          </span>
          <span className="tnum shrink-0 text-xs text-muted">{t.ago}</span>
        </li>
      ))}
    </ul>
  );
}

function Attention() {
  return (
    <ul className="flex flex-col">
      {ATTENTION.map((l) => (
        <li key={l.slug} className={ROW}>
          <span className="min-w-0 truncate">
            <Slug>{l.slug}</Slug>
            <span className="text-muted"> {l.title}</span>
          </span>
          <span className="tnum shrink-0 text-xs text-muted">{l.note}</span>
        </li>
      ))}
    </ul>
  );
}

function Changed({ range }: { range: Range }) {
  const before = BEFORE[range];
  const rows: { tone: Tone; title: ReactNode; detail: string }[] = [
    { tone: "up", title: `Germany is up 34% on ${before}`, detail: `428 clicks, 319 ${before}` },
    {
      tone: "first",
      title: (
        <>
          <Slug>spring</Slug> got its first clicks from{" "}
          <span className="font-mono">news.ycombinator.com</span>
        </>
      ),
      detail: "38 since Friday",
    },
    {
      tone: "down",
      title: (
        <>
          <Slug>promo</Slug> fell 62%
        </>
      ),
      detail: `241 clicks ${before}`,
    },
    {
      tone: "warn",
      title: (
        <>
          <span className="font-mono">go.acme.test</span> is waiting for DNS
        </>
      ),
      detail: "Add its DNS record to finish setup.",
    },
  ];
  return (
    <ul aria-label="What changed" className="flex flex-col gap-3">
      {rows.map((r, i) => {
        const { icon: Glyph, tile } = TONES[r.tone];
        return (
          <li key={i} className="flex items-center gap-3">
            <span className={cn("grid size-8 shrink-0 place-items-center rounded-lg", tile)}>
              <Glyph size={16} stroke={1.75} aria-hidden />
            </span>
            <span className="flex min-w-0 flex-col">
              <span className="text-sm text-pretty [overflow-wrap:anywhere]">{r.title}</span>
              <span className="tnum text-xs text-pretty text-muted">{r.detail}</span>
            </span>
          </li>
        );
      })}
    </ul>
  );
}

function MeterRow({ label, count, limit }: (typeof METERS)[number]) {
  const share = count / limit;
  const fill = share >= 1 ? "bg-danger" : share >= 0.8 ? "bg-butter" : "bg-accent";
  return (
    <li className="flex flex-col gap-1.5">
      <div className="flex items-baseline justify-between gap-3 text-sm">
        <span>{label}</span>
        <span className="tnum text-muted">
          {exact(count)} of {exact(limit)}
        </span>
      </div>
      <div
        role="meter"
        aria-label={label}
        aria-valuemin={0}
        aria-valuemax={limit}
        aria-valuenow={count}
        className="h-1 overflow-hidden rounded-full bg-surface-2"
      >
        <div
          className={cn("h-full rounded-full", fill)}
          style={{ width: `${Math.min(100, Math.max(2, share * 100))}%` }}
        />
      </div>
    </li>
  );
}

/* ------------------------------------------------------------- dashboard */

function Dashboard({ onNewLink, onPage }: { onNewLink: () => void; onPage: (id: PageId) => void }) {
  const [range, setRange] = useState<Range>("7d");
  const data = SERIES[range];
  const f = FIGURES[range];
  const total = data.reduce((sum, d) => sum + d.clicks, 0);
  const scale = SCALE[range];
  const topLinks = LINKS.map((l) => ({ ...l, clicks: Math.max(1, Math.round(l.clicks * scale)) }));

  return (
    <div>
      <PageHeader
        title="Dashboard"
        action={
          <div className="flex flex-wrap items-center gap-2">
            <div className="flex sm:order-last">
              <Button variant="primary" onClick={onNewLink}>
                <Plus size={15} aria-hidden /> New link
                <Kbd tone="primary" className="ml-0.5 max-sm:hidden">
                  C
                </Kbd>
              </Button>
            </div>
            <Segmented label="Range" items={RANGES} value={range} onChange={setRange} />
          </div>
        }
      />

      <div className="flex flex-col gap-6">
        <StatsChart
          figures={[
            { label: "Clicks", value: compact(total), delta: f.clicksDelta },
            { label: "Links clicked", value: f.links, delta: f.linksDelta },
            { label: "Top country", value: f.country },
            { label: "Top source", value: f.source },
          ]}
        >
          {/* Keyed on the range: a new one crossfades in instead of morphing between two sets of days. */}
          <div key={range} className={FADE_IN}>
            <AreaChart data={data} />
          </div>
        </StatsChart>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <PanelTabs
            end={
              <button
                type="button"
                onClick={() => onPage("links")}
                className="cursor-pointer [@media(hover:hover)]:hover:text-text"
              >
                All links
              </button>
            }
            tabs={[
              {
                value: "top",
                label: "Top links",
                panel: (
                  <div key={range} className={FADE_IN}>
                    <BarList
                      items={topLinks.map((l) => ({
                        key: l.slug,
                        clicks: l.clicks,
                        label: (
                          <>
                            <Slug>{l.slug}</Slug>
                            <span className="text-muted"> {l.title}</span>
                          </>
                        ),
                      }))}
                    />
                  </div>
                ),
              },
              {
                value: "attention",
                label: "Needs attention",
                count: ATTENTION.length,
                panel: <Attention />,
              },
            ]}
          />
          <PanelTabs
            tabs={[
              { value: "clicks", label: "Recent clicks", panel: <RecentClicks /> },
              { value: "team", label: "Team activity", panel: <TeamActivity /> },
            ]}
          />
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <PanelTabs
            className="h-full"
            tabs={[{ value: "changed", label: "What changed", panel: <Changed range={range} /> }]}
          />
          <PanelTabs
            className="h-full"
            end="Pro"
            tabs={[
              {
                value: "plan",
                label: "Your plan",
                panel: (
                  <ul aria-label="Your plan" className="flex flex-col gap-3.5">
                    {METERS.map((m) => (
                      <MeterRow key={m.label} {...m} />
                    ))}
                  </ul>
                ),
              },
            ]}
          />
        </div>
      </div>
    </div>
  );
}

/* --------------------------------------------------------------- sidebar */

/** A placeholder mark: two overlapping rounds. Swap in your own. */
function LogoMark({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 18" aria-hidden="true" className={cn("h-[0.9em] w-auto", className)}>
      <circle cx="8" cy="9" r="7" fill="currentColor" />
      <circle cx="16" cy="9" r="7" className="fill-accent" opacity="0.9" />
    </svg>
  );
}

function Logo() {
  return (
    <span className="inline-flex items-center gap-[0.4em] font-bold tracking-tight">
      <LogoMark />
      acme
    </span>
  );
}

/** Hidden in the rail but still laid out, so nothing beside it moves while the sidebar folds. */
const fade = (collapsed: boolean) =>
  cn("whitespace-nowrap transition-opacity duration-150", collapsed && "opacity-0");

const foldKey = <Shortcut keys={["["]} tone="tooltip" />;

function OrgSwitcher({
  org,
  onChange,
  collapsed,
  phone,
}: {
  org: string;
  onChange: (id: string) => void;
  collapsed: boolean;
  phone?: boolean;
}) {
  const toast = useToast();
  const current = orgs.find((o) => o.id === org) ?? orgs[0];
  return (
    <Menu
      label="Switch organization"
      trigger={
        <div
          className={cn(
            "flex w-full min-w-9 items-center gap-2.5 rounded-lg px-1.5 text-sm select-none",
            phone
              ? "h-11 rounded-[10px] bg-surface px-2 smooth-shadow-ring-xs"
              : "h-10 [@media(hover:hover)]:hover:bg-surface-2",
          )}
        >
          <span
            aria-hidden
            className="grid size-6 shrink-0 place-items-center rounded-md bg-accent text-xs font-bold text-bg"
          >
            {current.name[0]}
          </span>
          <span className={cn("min-w-0 flex-1 truncate text-left font-semibold", fade(collapsed))}>
            {current.name}
          </span>
          <ChevronsUpDown size={14} className={cn("shrink-0 text-muted", fade(collapsed))} />
        </div>
      }
    >
      <MenuHeader title="Switch organization" />
      {orgs.map((o) => (
        <MenuItem key={o.id} onClick={() => onChange(o.id)}>
          <span className="w-4 shrink-0">
            {o.id === org && <Check size={13} className="text-accent" />}
          </span>
          <span className="flex min-w-0 flex-col">
            <span className="truncate">{o.name}</span>
            <span className="text-xs text-muted">{o.detail}</span>
          </span>
        </MenuItem>
      ))}
      <MenuSeparator />
      <MenuItem onClick={() => toast("Organization created")}>
        <Plus size={14} className="text-muted" />
        New organization
      </MenuItem>
    </Menu>
  );
}

function NavItem({
  id,
  label,
  icon: Glyph,
  on,
  collapsed,
  phone,
  onPage,
}: {
  id: PageId;
  label: string;
  icon: Icon;
  on: boolean;
  collapsed: boolean;
  phone?: boolean;
  onPage: (id: PageId) => void;
}) {
  const button = (
    <button
      type="button"
      aria-current={on ? "page" : undefined}
      onClick={() => onPage(id)}
      className={cn(
        "flex h-9 w-full min-w-9 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-sm transition-[background-color,color] focus-visible:outline-2 focus-visible:outline-accent [&_svg]:shrink-0",
        phone && "h-[42px] gap-3 text-[15px]",
        on
          ? "bg-surface font-medium text-text smooth-shadow-ring-xs [&_svg]:text-accent"
          : "text-muted [@media(hover:hover)]:hover:bg-surface/50 [@media(hover:hover)]:hover:text-text",
      )}
    >
      <Glyph size={phone ? 18 : 16} stroke={1.75} aria-hidden />
      <span className={fade(collapsed)}>{label}</span>
    </button>
  );
  return collapsed ? (
    <Tooltip grouped side="right" content={label}>
      {button}
    </Tooltip>
  ) : (
    button
  );
}

function SidebarTop({ collapsed, onToggle }: { collapsed: boolean; onToggle: () => void }) {
  return (
    <div className="flex h-14 items-center gap-1 px-3">
      {collapsed ? (
        <Tooltip
          grouped
          side="right"
          content={<span className="flex items-center gap-2">Expand sidebar {foldKey}</span>}
        >
          <button
            type="button"
            onClick={onToggle}
            aria-label="Expand sidebar"
            className="group/mark relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-lg [@media(hover:hover)]:hover:bg-surface-2"
          >
            <LogoMark className="h-[18px] transition-[opacity,scale,filter] duration-200 ease-out group-hover/mark:scale-25 group-hover/mark:opacity-0 group-hover/mark:blur-[4px] group-focus-visible/mark:scale-25 group-focus-visible/mark:opacity-0" />
            <PanelLeftOpen
              size={18}
              className="absolute scale-25 text-muted opacity-0 blur-[4px] transition-[opacity,scale,filter] duration-200 ease-out group-hover/mark:scale-100 group-hover/mark:opacity-100 group-hover/mark:blur-none group-focus-visible/mark:scale-100 group-focus-visible/mark:opacity-100 group-focus-visible/mark:blur-none"
            />
          </button>
        </Tooltip>
      ) : (
        <span aria-label="Acme" className="grid size-9 shrink-0 place-items-center rounded-lg">
          <LogoMark className="h-[18px]" />
        </span>
      )}
      <div inert={collapsed} className={cn("ml-auto", fade(collapsed))}>
        <Tooltip
          grouped
          side="right"
          content={<span className="flex items-center gap-2">Collapse sidebar {foldKey}</span>}
        >
          <button
            type="button"
            onClick={onToggle}
            aria-label="Collapse sidebar"
            className="grid size-8 cursor-pointer place-items-center rounded-md text-muted transition-[background-color,color,scale] duration-200 ease-out active:scale-[0.96] [@media(hover:hover)]:hover:bg-surface-2 [@media(hover:hover)]:hover:text-text"
          >
            <PanelLeftClose size={16} />
          </button>
        </Tooltip>
      </div>
    </div>
  );
}

function Sidebar({
  page,
  onPage,
  org,
  onOrg,
  collapsed = false,
  onToggle,
  onSearch,
  phone = false,
}: {
  page: PageId;
  onPage: (id: PageId) => void;
  org: string;
  onOrg: (id: string) => void;
  collapsed?: boolean;
  onToggle?: () => void;
  onSearch: () => void;
  phone?: boolean;
}) {
  return (
    <div className={cn("flex h-full flex-col overflow-hidden", phone ? "overflow-y-auto" : "w-60")}>
      {phone ? (
        <div className="flex h-12 shrink-0 items-center px-5 pt-1 text-base">
          <Logo />
        </div>
      ) : (
        <SidebarTop collapsed={collapsed} onToggle={onToggle ?? (() => {})} />
      )}

      <div className="px-3 py-2">
        <OrgSwitcher org={org} onChange={onOrg} collapsed={collapsed} phone={phone} />
      </div>

      <nav aria-label="Main" className="flex flex-col gap-0.5 px-3 py-2">
        {pages.map((p) => (
          <NavItem
            key={p.id}
            id={p.id}
            label={p.label}
            icon={p.icon}
            on={p.id === page}
            collapsed={collapsed}
            phone={phone}
            onPage={onPage}
          />
        ))}
      </nav>

      <div className="mt-auto">
        {phone ? (
          <div className="px-3 py-3">
            <div className="flex min-h-12 items-center gap-2.5 rounded-[10px] px-2 py-1.5">
              <Avatar name={USER.name} size={28} />
              <span className="flex min-w-0 flex-1 flex-col leading-tight">
                <span className="truncate text-sm font-semibold">{USER.name}</span>
                <span className="truncate text-xs text-muted">{USER.email}</span>
              </span>
            </div>
          </div>
        ) : (
          <div className="flex items-center gap-0.5 px-3 py-3">
            <div className="flex min-w-9 flex-1 items-center gap-2.5 rounded-lg px-1 py-1.5">
              <Avatar name={USER.name} size={28} />
              <span
                className={cn("min-w-0 flex-1 truncate text-sm font-semibold", fade(collapsed))}
              >
                {USER.name}
              </span>
            </div>
            <Tooltip grouped content="Search and commands">
              <button
                type="button"
                inert={collapsed}
                onClick={onSearch}
                aria-label="Search and commands"
                className={cn(
                  "shrink-0 cursor-pointer rounded-md p-0.5 transition-[scale,opacity] duration-200 ease-out active:scale-[0.96] [@media(hover:hover)]:hover:[&_kbd]:text-text",
                  fade(collapsed),
                )}
              >
                <Shortcut keys={["mod", "K"]} className="gap-0.5" />
              </button>
            </Tooltip>
          </div>
        )}
      </div>
    </div>
  );
}

/* ----------------------------------------------------------------- shell */

/** An app frame in rdyrct's layout: nav on the paper, one raised sheet for the page, an org switcher and ⌘K. */
export default function AppShell() {
  const toast = useToast();
  const [page, setPage] = useState<PageId>("dashboard");
  const [org, setOrg] = useState("acme");
  const [collapsed, setCollapsed] = useState(false);
  const [drawer, setDrawer] = useState(false);
  const [palette, setPalette] = useState(false);
  const title = pages.find((p) => p.id === page)?.label ?? "Dashboard";

  const newLink = () => toast("Link created");

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setPalette((open) => !open);
        return;
      }
      if (e.key === "Escape") setDrawer(false);
      const el = e.target instanceof HTMLElement ? e.target : null;
      const typing = !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
      if (typing || e.metaKey || e.ctrlKey || e.altKey || palette) return;
      if (e.key === "[") setCollapsed((c) => !c);
      if (e.key.toLowerCase() === "c" && page === "dashboard") {
        e.preventDefault();
        toast("Link created");
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [palette, page, toast]);

  const go = (id: PageId) => {
    setPage(id);
    setDrawer(false);
    setPalette(false);
  };
  const search = () => {
    setDrawer(false);
    setPalette(true);
  };

  return (
    <section className="flex h-[720px] max-h-dvh w-full overflow-hidden bg-bg text-text max-md:flex-col">
      <TooltipGroup>
        <aside
          className={cn(
            "hidden shrink-0 overflow-hidden transition-[width] duration-200 ease-out md:block",
            collapsed ? "w-[52px]" : "w-60",
          )}
        >
          <Sidebar
            page={page}
            onPage={go}
            org={org}
            onOrg={setOrg}
            collapsed={collapsed}
            onToggle={() => setCollapsed((c) => !c)}
            onSearch={search}
          />
        </aside>
      </TooltipGroup>

      <header className="flex h-[52px] shrink-0 items-center gap-1.5 px-3 md:hidden">
        <button
          type="button"
          onClick={() => setDrawer((v) => !v)}
          aria-label="Menu"
          aria-expanded={drawer}
          className="grid size-10 cursor-pointer place-items-center rounded-lg text-text transition-[scale] duration-200 ease-out active:scale-[0.96]"
        >
          {drawer ? <X size={20} /> : <MenuIcon size={20} />}
        </button>
        <span className="text-base">
          <Logo />
        </span>
        <button
          type="button"
          onClick={search}
          aria-label="Search and commands"
          className="ml-auto grid size-10 cursor-pointer place-items-center rounded-lg text-muted transition-[scale] duration-200 ease-out active:scale-[0.96]"
        >
          <Search size={20} />
        </button>
      </header>

      <div
        className={cn("fixed inset-0 z-30 md:hidden", drawer ? "visible" : "invisible delay-200")}
      >
        <button
          type="button"
          tabIndex={-1}
          aria-label="Close menu"
          onClick={() => setDrawer(false)}
          className={cn(
            "absolute inset-0 cursor-default bg-[rgb(23_21_31/0.32)] transition-opacity duration-200 dark:bg-black/50",
            drawer ? "opacity-100" : "opacity-0",
          )}
        />
        <aside
          role="dialog"
          aria-label="Menu"
          className={cn(
            "absolute top-1.5 bottom-1.5 left-1.5 w-[min(300px,calc(100vw-3.5rem))] overflow-hidden rounded-[26px] bg-bg pt-2 smooth-shadow-ring-xl transition-[translate,opacity] duration-200 ease-out",
            drawer ? "translate-x-0 opacity-100" : "-translate-x-6 opacity-0",
          )}
        >
          <Sidebar page={page} onPage={go} org={org} onOrg={setOrg} onSearch={search} phone />
        </aside>
      </div>

      <main className="mx-1.5 mb-1.5 flex min-h-0 min-w-0 flex-1 flex-col rounded-[22px] bg-surface smooth-shadow-ring-sm md:my-2 md:mr-2 md:ml-2 md:rounded-[14px]">
        <div className="flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-4 py-6 md:my-2 md:mr-1 md:py-6 md:pr-9 md:pl-10">
          <div className="mx-auto w-full max-w-5xl flex-1">
            {page === "dashboard" ? (
              <Dashboard onNewLink={newLink} onPage={go} />
            ) : (
              <PageHeader title={title} sub="This page is not part of the demo." />
            )}
          </div>
        </div>
      </main>

      <CommandDialog open={palette} onOpenChange={setPalette} label="Search and jump">
        <CommandInput placeholder="Search links, pages and actions" />
        <CommandList>
          <CommandEmpty>Nothing matches.</CommandEmpty>
          <CommandGroup heading="Pages">
            {pages.map(({ id, label, icon: Glyph }) => (
              <CommandItem key={id} value={`page ${label}`} onSelect={() => go(id)}>
                <Glyph size={16} stroke={1.75} className="text-muted" aria-hidden />
                {label}
              </CommandItem>
            ))}
          </CommandGroup>
          <CommandGroup heading="Links">
            {LINKS.map((l) => (
              <CommandItem
                key={l.slug}
                value={`link ${l.title} ${l.slug}`}
                onSelect={() => {
                  setPalette(false);
                  toast("Opened link", "info", { code: `/${l.slug}` });
                }}
              >
                <span className="flex-1 truncate">{l.title}</span>
                <span className="font-mono text-xs text-muted">/{l.slug}</span>
              </CommandItem>
            ))}
          </CommandGroup>
          <CommandGroup heading="Actions">
            <CommandItem
              value="action new link"
              onSelect={() => {
                setPalette(false);
                newLink();
              }}
            >
              <Plus size={16} className="text-muted" aria-hidden />
              New link
            </CommandItem>
          </CommandGroup>
        </CommandList>
      </CommandDialog>
    </section>
  );
}