# Web browser

A browser window: tabs that open, close and load, an address bar with suggestions, bookmarks, downloads, a main menu, and History and Settings pages.

A whole app screen built only from this system's components and token utilities; the layout is Tailwind.

## App.tsx

```tsx
/* A browser window: tabs that open, close and load; back, forward and reload; an address bar with
 * suggestions; bookmarks; downloads; a main menu; History and Settings pages. All state lives here,
 * the pieces are in toolbar.tsx and pages.tsx.
 *
 * Keyboard: Ctrl/⌘+L focuses the address bar. A real browser keeps Ctrl/⌘+T, W and Tab for itself,
 * so the window also answers to Alt+T (new tab), Alt+W (close), Alt+Shift+T (reopen), Alt+1…9
 * (switch), Alt+Y (history); Ctrl+T, W and Tab still work where the host lets them through.
 * In the tab strip, arrows move between tabs and Delete closes the focused one (the Tabs' own).
 *
 * The layout: closable pill tabs in a header row over the toolbar, the bookmarks bar and the page.
 * The first icon of every row (a tab's favicon, Back, the first bookmark) stands on one line, 14px
 * from the window's edge. On a phone no strip: a tab-count button opens the open tabs as a sheet. */
import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { Progress, ScrollArea, Spinner, Tabs, Tooltip, Button } from "@fndn/react";
import { Plus } from "@phosphor-icons/react";
import { BOOKMARKS, CLI_DOWNLOAD, ENGINES, HISTORY, HOME, SETTINGS, VISITS, resolve, siteOf, type Visit } from "./data";
import { Favicon, Page, type Settings } from "./pages";
import { AddressBar, BookmarksBar, BrowserMenu, Downloads, NavButtons, TabSwitcher, suggestionsFor, useDownloads } from "./toolbar";

type Tab = {
  id: string;
  /** The tab's own history: back and forward move `at` along it. */
  stack: string[];
  at: number;
  loading: boolean;
  /** The page on screen: the previous one stays until the next has loaded. */
  page: string;
};

const urlOf = (tab: Tab) => tab.stack[tab.at] ?? HOME;
const now = () => new Date().toTimeString().slice(0, 5);
let seq = 3;

export default function App() {
  const [tabs, setTabs] = useState<Tab[]>([
    { id: "t1", stack: ["harbor.dev/docs/getting-started"], at: 0, loading: false, page: "harbor.dev/docs/getting-started" },
    { id: "t2", stack: ["status.harbor.dev"], at: 0, loading: false, page: "status.harbor.dev" },
    { id: "t3", stack: ["fieldnotes.app/northwind/q4-planning"], at: 0, loading: false, page: "fieldnotes.app/northwind/q4-planning" },
  ]);
  const [active, setActive] = useState("t1");
  const [closed, setClosed] = useState<Tab[]>([]);
  const [settings, setSettings] = useState<Settings>({ bookmarksBar: true, askWhereToSave: false, zoom: "100%", engine: ENGINES[0]!.value });
  const [bookmarks, setBookmarks] = useState(BOOKMARKS);
  const [visits, setVisits] = useState<Visit[]>(VISITS);
  const [downloads, setDownloads] = useDownloads();
  const [downloadsOpen, setDownloadsOpen] = useState(false);
  const [switcherOpen, setSwitcherOpen] = useState(false);
  const root = useRef<HTMLDivElement>(null);
  const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
  useEffect(() => () => timers.current.forEach(clearTimeout), []);

  const tab = tabs.find((t) => t.id === active) ?? tabs[0]!;
  const url = urlOf(tab);
  const set = (patch: Partial<Settings>) => setSettings((s) => ({ ...s, ...patch }));
  const update = (id: string, change: (t: Tab) => Tab) => setTabs((all) => all.map((t) => (t.id === id ? change(t) : t)));

  /* a site "loads" for a moment (a spinner in its tab, a progress bar over the page; the previous
   * page stays until then); the browser's own pages (ui://) show at once */
  const local = (u: string) => u.startsWith("ui://");
  const load = (id: string, to: string) => {
    clearTimeout(timers.current.get(id));
    if (local(to)) return update(id, (t) => ({ ...t, loading: false, page: to }));
    update(id, (t) => ({ ...t, loading: true }));
    timers.current.set(id, setTimeout(() => update(id, (t) => ({ ...t, loading: false, page: urlOf(t) })), 450 + Math.random() * 500));
  };
  const navigate = (text: string) => {
    const to = resolve(text, settings.engine);
    update(tab.id, (t) => ({ ...t, stack: [...t.stack.slice(0, t.at + 1), to], at: t.at + 1 }));
    if (!local(to)) setVisits((v) => [{ url: to, time: now(), day: "today" }, ...v]);
    load(tab.id, to);
  };
  const step = (by: number) => {
    const at = Math.max(0, Math.min(tab.stack.length - 1, tab.at + by));
    update(tab.id, (t) => ({ ...t, at }));
    load(tab.id, tab.stack[at] ?? HOME);
  };
  const reload = () => load(tab.id, url);
  const stop = () => { clearTimeout(timers.current.get(tab.id)); update(tab.id, (t) => ({ ...t, loading: false, page: urlOf(t) })); };

  /* the address bar takes focus after the panel that holds it has rendered */
  const [focusTick, setFocusTick] = useState(0);
  const focusAddress = () => setFocusTick((n) => n + 1);
  useEffect(() => {
    if (!focusTick) return;
    const input = root.current?.querySelector<HTMLInputElement>("[data-slot=tabs-content]:not([hidden]) [data-slot=combobox-input]");
    input?.focus();
    input?.select();
  }, [focusTick]);

  /* a shortcut or Delete that removes the focused panel or tab hands focus to the window, so the
   * next shortcut still reaches it */
  const first = useRef(true);
  useEffect(() => {
    if (first.current) { first.current = false; return; }
    if (document.activeElement === document.body) root.current?.focus({ preventScroll: true });
  }, [tab.id, tabs.length]);

  const open = (to = HOME) => {
    const id = `t${++seq}`;
    setTabs((all) => [...all, { id, stack: [to], at: 0, loading: false, page: "" }]);
    setActive(id);
    load(id, to);
    if (to === HOME) focusAddress();
  };
  /* closing the last tab leaves a new tab page, as a window that stays open would. The Tabs have
   * already selected the neighbour (onValueChange) when they ask to close */
  const close = (id: string) => {
    const i = tabs.findIndex((t) => t.id === id);
    const gone = tabs[i];
    if (!gone) return;
    setClosed((c) => [gone, ...c]);
    const rest = tabs.filter((t) => t.id !== id);
    if (rest.length === 0) {
      const fresh = { id: `t${++seq}`, stack: [HOME], at: 0, loading: false, page: HOME };
      setTabs([fresh]);
      setActive(fresh.id);
      return;
    }
    setTabs(rest);
    if (id === active) setActive((rest[i] ?? rest[i - 1])!.id);
  };
  const reopen = (id = closed[0]?.id) => {
    const t = closed.find((c) => c.id === id);
    if (!t) return;
    setClosed((c) => c.filter((x) => x.id !== id));
    setTabs((all) => [...all, { ...t, page: "" }]);
    setActive(t.id);
    load(t.id, urlOf(t));
  };
  /* the browser's own pages open once: a second request switches to the open tab */
  const openPage = (to: string) => {
    const there = tabs.find((t) => urlOf(t) === to);
    if (there) setActive(there.id); else open(to);
  };

  const menu = (value: string) => {
    if (value === "new-tab") open();
    else if (value === "reopen") reopen();
    else if (value === "history") openPage(HISTORY);
    else if (value === "settings") openPage(SETTINGS);
    else if (value === "downloads") setDownloadsOpen(true);
    else if (value.startsWith("closed:")) reopen(value.slice(7));
    else if (value.startsWith("open:")) navigate(value.slice(5));
  };

  const shortcuts = (e: KeyboardEvent) => {
    const mod = e.ctrlKey || e.metaKey;
    const alt = e.altKey && !mod;
    const key = e.code;
    const run = (action: () => void) => { e.preventDefault(); action(); };
    if (mod && key === "KeyL") return run(focusAddress);
    if ((alt || mod) && !e.shiftKey && key === "KeyT") return run(() => open());
    if (alt && e.shiftKey && key === "KeyT") return run(() => reopen());
    if ((alt || mod) && key === "KeyW") return run(() => close(tab.id));
    if (alt && key === "KeyY") return run(() => openPage(HISTORY));
    if (alt && key === "KeyJ") return run(() => setDownloadsOpen(true));
    const digit = /^Digit[1-9]$/.test(key) ? Number(key.slice(5)) : /^[1-9]$/.test(e.key) ? Number(e.key) : 0;
    if (alt && digit) {
      const to = digit === 9 ? tabs[tabs.length - 1] : tabs[digit - 1];
      return to && run(() => setActive(to.id));
    }
    if (e.ctrlKey && key === "Tab") {
      const i = tabs.findIndex((t) => t.id === tab.id);
      return run(() => setActive(tabs[(i + (e.shiftKey ? -1 : 1) + tabs.length) % tabs.length]!.id));
    }
  };
  /* a middle click closes a tab, as in every browser */
  const auxClose = (e: MouseEvent) => {
    const trigger = (e.target as HTMLElement).closest<HTMLElement>("[data-slot=tabs-trigger]");
    if (e.button === 1 && trigger?.dataset.value) { e.preventDefault(); close(trigger.dataset.value); }
  };
  /* the Download link on the Getting started page: the toolbar's ring shows it arriving */
  const download = () => setDownloads((l) => [{ id: `dl${++seq}`, received: 0, ...CLI_DOWNLOAD }, ...l]);

  const site = siteOf(url);
  const bookmarked = bookmarks.some((b) => b.url === url);
  const zoom = parseInt(settings.zoom, 10) / 100;

  const tabInfo = tabs.map((t) => ({ id: t.id, url: urlOf(t), loading: t.loading }));
  /* the toolbar, the bookmarks bar and the page: the selected tab's panel, under the strip's line */
  const body = (
    <div className="flex h-full min-h-0 flex-col">
      <div className="flex items-center gap-0.5 px-2 py-1.5">
        <NavButtons canBack={tab.at > 0} canForward={tab.at < tab.stack.length - 1} loading={tab.loading} back={() => step(-1)} forward={() => step(1)} reload={reload} stop={stop} />
        <AddressBar
          url={url} secure={site.secure} bookmarked={bookmarked} go={navigate} suggestions={suggestionsFor(url, visits)} engine={settings.engine}
          onBookmark={(on) => setBookmarks((b) => (on ? [...b, { url, label: site.title.split(/ [·—:] /)[0]! }] : b.filter((x) => x.url !== url)))}
        />
        <Downloads list={downloads} open={downloadsOpen} onOpenChange={setDownloadsOpen}
          onCancel={(id) => setDownloads((l) => l.filter((d) => d.id !== id))} onClear={() => setDownloads((l) => l.filter((d) => d.received < d.size))} />
        <TabSwitcher tabs={tabInfo} active={tab.id} open={switcherOpen} onOpenChange={setSwitcherOpen}
          select={(id) => { setActive(id); setSwitcherOpen(false); }} close={close} newTab={() => { setSwitcherOpen(false); open(); }} />
        <BrowserMenu closed={closed.map((t) => ({ id: t.id, url: urlOf(t) }))} bookmarks={bookmarks} bookmarksBar={settings.bookmarksBar} zoom={settings.zoom}
          onSelect={menu} onBookmarksBar={(on) => set({ bookmarksBar: on })} onZoom={(z) => set({ zoom: z })} />
      </div>
      {/* shown or hidden, the bar opens or closes its row (instant from the keyboard) */}
      <div className={`grid kbd-instant motion-size-reveal max-sm:hidden ${settings.bookmarksBar ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}>
        <div className="min-h-0 overflow-hidden"><BookmarksBar bookmarks={bookmarks} go={navigate} /></div>
      </div>
      <div className="relative flex min-h-0 flex-1 flex-col border-t border-line">
        {tab.loading && <Progress className="absolute inset-x-0 top-0 z-1" size="sm" tone="accent" ariaLabel={`Loading ${site.title}`} />}
        <ScrollArea key={tab.page} className="min-h-0 flex-1" aria-label={siteOf(tab.page).title}>
          <div style={{ zoom }}>
            {tab.page && <Page url={tab.page} go={navigate} reload={reload} download={download} settings={settings} set={set} visits={visits} clearHistory={() => setVisits([])} />}
          </div>
        </ScrollArea>
      </div>
    </div>
  );

  return (
    <div ref={root} data-showcase="web-browser" tabIndex={-1} onKeyDown={shortcuts} onAuxClick={auxClose} className="flex h-full flex-col overflow-hidden bg-surface outline-none">
      <Tabs
        variant="pill"
        closable
        fill
        inHeader
        aria-label="Tabs"
        value={tab.id}
        onValueChange={setActive}
        onClose={close}
        closeLabel="Close tab"
        /* a phone shows no strip: the tab-count button in the toolbar opens the tabs as a sheet. The
         * header's 6px start inset puts the first favicon 14px from the edge, as Back and the first
         * bookmark */
        headerClass="h-9 gap-0.5 border-b border-line ps-1.5 pe-2 max-sm:hidden"
        end={
          <Tooltip content="New tab" shortcut="Alt+T">
            <Button variant="ghost" size="sm" square muted aria-label="New tab" icon={<Plus data-slot="icon" weight="bold" />} onClick={() => open()} className="shrink-0" />
          </Tooltip>
        }
        items={tabs.map((t) => ({
          value: t.id,
          label: siteOf(urlOf(t)).title,
          icon: t.loading ? <Spinner decorative /> : <Favicon url={urlOf(t)} />,
          content: t.id === tab.id ? body : null,
        }))}
      />
    </div>
  );
}
```

## data.ts

```tsx
/* The browser's data: the sites it can show, the bookmarks bar, the history and the downloads.
 * A page is addressed by its URL without the scheme, as the address bar shows it. */

export type Site = {
  url: string;
  title: string;
  /** Favicon: two letters on a coloured square (an Avatar), or an internal page's icon. */
  mark: string;
  color: string;
  /** Served over https: the address bar shows a lock. */
  secure: boolean;
};

export const HOME = "ui://newtab";
export const HISTORY = "ui://history";
export const SETTINGS = "ui://settings";

export const SITES: Site[] = [
  { url: HOME, title: "New tab", mark: "", color: "", secure: true },
  { url: HISTORY, title: "History", mark: "", color: "", secure: true },
  { url: SETTINGS, title: "Settings", mark: "", color: "", secure: true },
  { url: "harbor.dev/docs/getting-started", title: "Getting started · Harbor Docs", mark: "H", color: "oklch(0.55 0.17 255)", secure: true },
  { url: "harbor.dev/docs/preview-deploys", title: "Preview deploys · Harbor Docs", mark: "H", color: "oklch(0.55 0.17 255)", secure: true },
  { url: "harbor.dev/blog/harbor-2-4", title: "Harbor 2.4: preview deploys for every pull request", mark: "H", color: "oklch(0.55 0.17 255)", secure: true },
  { url: "status.harbor.dev", title: "Harbor Status", mark: "S", color: "oklch(0.6 0.15 150)", secure: true },
  { url: "fieldnotes.app/northwind/q4-planning", title: "Q4 planning — Fieldnotes", mark: "F", color: "oklch(0.62 0.16 45)", secure: true },
  { url: "intranet.local/wiki/on-call", title: "On-call rotation · Wiki", mark: "W", color: "oklch(0.5 0.02 260)", secure: false },
];

/** A known site, a search (titled by its query), or an unknown domain (titled by its address). */
export function siteOf(url: string): Site {
  const known = SITES.find((s) => s.url === url);
  if (known) return known;
  const search = searchQuery(url);
  const title = search ? `${search.q} — ${search.engine}` : url;
  return { url, title, mark: (search?.engine ?? url).slice(0, 1).toUpperCase(), color: "oklch(0.55 0.02 260)", secure: true };
}

export const ENGINES = [
  { value: "duckduckgo", label: "DuckDuckGo", prefix: "duckduckgo.com/?q=" },
  { value: "startpage", label: "Startpage", prefix: "startpage.com/search?q=" },
  { value: "kagi", label: "Kagi", prefix: "kagi.com/search?q=" },
];

/** What the address bar does with typed text: a known page, a domain, or a search. */
export function resolve(text: string, engine: string): string {
  const t = text.trim().replace(/^https?:\/\//, "");
  if (SITES.some((s) => s.url === t) || /^[^\s]+\.[a-z]{2,}(\/\S*)?$/i.test(t)) return t;
  const prefix = ENGINES.find((e) => e.value === engine)?.prefix ?? ENGINES[0]!.prefix;
  return prefix + encodeURIComponent(t);
}

/** The query of a search URL, or null. */
export const searchQuery = (url: string) => {
  const engine = ENGINES.find((e) => url.startsWith(e.prefix));
  return engine ? { engine: engine.label, q: decodeURIComponent(url.slice(engine.prefix.length)) } : null;
};

export type Bookmark = { url: string; label: string };
export const BOOKMARKS: Bookmark[] = [
  { url: "harbor.dev/docs/getting-started", label: "Harbor Docs" },
  { url: "status.harbor.dev", label: "Status" },
  { url: "fieldnotes.app/northwind/q4-planning", label: "Q4 planning" },
];
/** The "Reading list" folder of the bookmarks bar. */
export const READING: Bookmark[] = [
  { url: "harbor.dev/blog/harbor-2-4", label: "Harbor 2.4 release notes" },
  { url: "harbor.dev/docs/preview-deploys", label: "Preview deploys" },
  { url: "intranet.local/wiki/on-call", label: "On-call rotation" },
];

export type Visit = { url: string; time: string; day: "today" | "yesterday" | "week" };
export const VISITS: Visit[] = [
  { url: "status.harbor.dev", time: "09:42", day: "today" },
  { url: "harbor.dev/docs/preview-deploys", time: "09:31", day: "today" },
  { url: "harbor.dev/docs/getting-started", time: "09:28", day: "today" },
  { url: "fieldnotes.app/northwind/q4-planning", time: "08:55", day: "today" },
  { url: "intranet.local/wiki/on-call", time: "17:20", day: "yesterday" },
  { url: "harbor.dev/blog/harbor-2-4", time: "16:04", day: "yesterday" },
  { url: "duckduckgo.com/?q=harbor%20preview%20deploys%20github%20actions", time: "15:58", day: "yesterday" },
  { url: "fieldnotes.app/northwind/q4-planning", time: "Mon 11:12", day: "week" },
];

export type Download = { id: string; name: string; size: number; received: number; kind: "pdf" | "archive" | "file" };
/* every seeded download has finished: nothing runs (or spins) until the user starts one */
export const DOWNLOADS: Download[] = [
  { id: "invoice", name: "invoice-2026-10.pdf", size: 0.2, received: 0.2, kind: "pdf" },
  { id: "assets", name: "brand-assets-v3.zip", size: 148, received: 148, kind: "archive" },
];
/** What the Download link on the Getting started page fetches. */
export const CLI_DOWNLOAD = { name: "harbor-cli-2.4.0-linux-x64.tar.gz", size: 20.3, kind: "archive" } as const;
```

## pages.tsx

```tsx
/* What the browser shows in its page area: a few simple sites, the new tab page, search results,
 * and the browser's own History and Settings pages. Every page is plain layout around the
 * system's components; links are real anchors that navigate inside the window. */
import { useState, type MouseEvent, type ReactNode } from "react";
import {
  Alert, Avatar, Button, Card, CardBody, CardDescription, CardHeader, CardTitle, CodeBlock, EmptyState,
  InputGroup, Link as UiLink, PageHeader, SegmentedControl, Select, StatusPill, Switch, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, Tag,
} from "@fndn/react";
import { ClockCounterClockwise, DownloadSimple, Gear, MagnifyingGlass, Browsers, Trash } from "@phosphor-icons/react";
import { BOOKMARKS, ENGINES, HISTORY, HOME, SETTINGS, SITES, searchQuery, siteOf, type Visit } from "./data";

export type Settings = { bookmarksBar: boolean; askWhereToSave: boolean; zoom: string; engine: string };
type Go = (url: string) => void;

/** The page's icon: the browser's own pages get a glyph, sites a lettered mark (14px in a tab). */
export function Favicon({ url, size = 16 }: { url: string; size?: 14 | 16 | 24 }) {
  if (url === HISTORY) return <ClockCounterClockwise data-slot="icon" weight="bold" aria-hidden />;
  if (url === SETTINGS) return <Gear data-slot="icon" weight="bold" aria-hidden />;
  if (url === HOME) return <Browsers data-slot="icon" weight="bold" aria-hidden />;
  const site = siteOf(url);
  return <Avatar shape="square" size={size} initials={site.mark} color={site.color} />;
}

/** A link that navigates inside the window. */
function Link({ to, go, children }: { to: string; go: Go; children: ReactNode }) {
  const click = (e: MouseEvent) => {
    e.preventDefault();
    go(to);
  };
  return <UiLink href={`https://${to}`} onClick={click}>{children}</UiLink>;
}

const Prose = ({ children }: { children: ReactNode }) => (
  /* a web page keeps its own direction, whatever the browser's interface uses (an English page stays
   * left to right in a right-to-left browser): the content decides */
  <article dir="auto" className="mx-auto flex max-w-[680px] flex-col gap-4 px-6 py-10 text-md leading-relaxed text-ink-2 max-sm:px-4 max-sm:py-6">{children}</article>
);
const H1 = ({ children }: { children: ReactNode }) => <h1 className="text-xl font-semibold text-ink">{children}</h1>;

function NewTab({ go, engine }: { go: Go; engine: string }) {
  const [q, setQ] = useState("");
  const name = ENGINES.find((e) => e.value === engine)?.label;
  return (
    <div className="mx-auto flex max-w-[560px] flex-col items-center gap-6 px-4 pt-[12vh] pb-10">
      <h1 className="text-xl font-semibold text-ink">Good morning</h1>
      <form className="w-full" onSubmit={(e) => { e.preventDefault(); if (q.trim()) go(q); }}>
        <InputGroup size="lg" aria-label={`Search with ${name}`} placeholder={`Search with ${name} or type a URL`} value={q} onChange={(e) => setQ(e.target.value)} start={<MagnifyingGlass data-slot="icon" weight="bold" />} enterKeyHint="go" />
      </form>
      {/* Chrome's shortcut tiles: the site's mark on a round field over its name (which wraps) */}
      <nav aria-label="Shortcuts" className="flex flex-wrap justify-center gap-1">
        {BOOKMARKS.map((b) => (
          <a key={b.url} href={`https://${b.url}`} onClick={(e) => { e.preventDefault(); go(b.url); }}
            className="flex w-24 flex-col items-center gap-2 rounded-card px-1 pt-3 pb-2 text-center text-xs text-ink-2 [overflow-wrap:anywhere] hover:bg-hover hover:text-ink motion-colors-fast motion-transform-press [:root:not([data-fndn-input=keyboard])_&:active]:scale-press">
            <span className="grid size-12 place-items-center rounded-full bg-field"><Favicon url={b.url} size={24} /></span>
            {b.label}
          </a>
        ))}
      </nav>
    </div>
  );
}

function SearchResults({ engine, q, go }: { engine: string; q: string; go: Go }) {
  const words = q.toLowerCase().split(/\s+/).filter(Boolean);
  const hits = SITES.filter((s) => !s.url.startsWith("ui://") && words.some((w) => s.title.toLowerCase().includes(w) || s.url.includes(w)));
  return (
    <Prose>
      <p className="text-sm text-ink-2">{engine} · results for <span className="text-ink">“{q}”</span></p>
      {hits.length === 0 && <EmptyState icon="magnifying-glass" title="No results" hint="Try fewer or different words." />}
      {hits.map((s) => (
        <div key={s.url} className="flex flex-col gap-0.5">
          <span className="flex items-center gap-2 text-sm text-ink-2"><Favicon url={s.url} />{s.url}</span>
          <Link to={s.url} go={go}><span className="text-lg">{s.title}</span></Link>
        </div>
      ))}
    </Prose>
  );
}

function DocsPage({ go, download }: { go: Go; download: () => void }) {
  return (
    <Prose>
      <Tag tone="blue" className="self-start">Docs</Tag>
      <H1>Getting started</H1>
      <p>Harbor deploys every push to a fresh URL. Install the CLI, link a project, and your next commit ships to a preview.</p>
      <CodeBlock variant="command" value="npm install --global @harbor/cli" />
      <p>
        No npm? <UiLink href="https://harbor.dev/download/harbor-cli-2.4.0-linux-x64.tar.gz" onClick={(e: MouseEvent) => { e.preventDefault(); download(); }}>
          <DownloadSimple data-slot="icon" weight="bold" aria-hidden className="me-1 inline align-[-2px]" />Download the CLI for Linux</UiLink> (20.3&nbsp;MB).
      </p>
      <p>Then run <code className="font-mono text-sm text-ink">harbor link</code> in your repository and follow the prompts.</p>
      <Alert tone="accent" title="Preview deploys are on by default">Turn them off per branch in the project settings.</Alert>
      <p>Next: <Link to="harbor.dev/docs/preview-deploys" go={go}>Preview deploys</Link> · <Link to="status.harbor.dev" go={go}>Service status</Link></p>
    </Prose>
  );
}

const SERVICES: [string, "green" | "orange"][] = [["Deploys", "green"], ["Builds", "green"], ["Edge network", "green"], ["Logs", "orange"]];
function StatusPage() {
  return (
    <Prose>
      <H1>Harbor Status</H1>
      <Alert tone="orange" title="Degraded: log search">Log search is slower than usual in eu-west. Deploys are not affected. Updated 09:40 UTC.</Alert>
      <Card>
        {SERVICES.map(([name, tone]) => (
          <CardBody key={name} className="flex items-center justify-between gap-4 border-b border-line-soft last:border-0">
            <span className="text-ink">{name}</span>
            <StatusPill tone={tone}>{tone === "green" ? "Operational" : "Degraded"}</StatusPill>
          </CardBody>
        ))}
      </Card>
    </Prose>
  );
}

function Article({ url, go }: { url: string; go: Go }) {
  const site = siteOf(url);
  return (
    <Prose>
      <p className="text-sm text-ink-2">{url.split("/")[0]}</p>
      <H1>{site.title}</H1>
      <p>Every pull request now gets its own preview URL, posted as a comment on the pull request and torn down when it merges. Reviewers click through the change instead of reading about it.</p>
      <p>Previews share the production build cache, so most of them are live in under a minute. Read <Link to="harbor.dev/docs/preview-deploys" go={go}>the guide</Link> to set protection rules and environment variables per branch.</p>
    </Prose>
  );
}

function Unreachable({ url, reload }: { url: string; reload: () => void }) {
  return (
    <div className="mx-auto flex max-w-[480px] flex-col items-start gap-4 px-6 pt-[12vh]">
      <EmptyState size="block" icon="file" title="This site can’t be reached" hint={`${url.split("/")[0]} took too long to respond. Check the address, or try again.`} />
      <Button variant="outline" size="sm" onClick={reload}>Try again</Button>
    </div>
  );
}

const DAYS = [{ value: "all", label: "All time" }, { value: "today", label: "Today" }, { value: "yesterday", label: "Yesterday" }, { value: "week", label: "Earlier this week" }];
function HistoryPage({ visits, go, clear }: { visits: Visit[]; go: Go; clear: () => void }) {
  const [q, setQ] = useState("");
  const [day, setDay] = useState("all");
  const shown = visits.filter((v) => (day === "all" || v.day === day) && `${siteOf(v.url).title} ${v.url}`.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="mx-auto flex max-w-[860px] flex-col gap-4 px-6 py-8 max-sm:px-4">
      <PageHeader
        title="History"
        actions={<Button size="sm" variant="secondary" icon={<Trash data-slot="icon" weight="bold" />} onClick={clear} disabled={!visits.length}>Clear browsing data</Button>}
      />
      <div className="flex flex-wrap gap-2">
        <InputGroup className="min-w-[200px] flex-1" aria-label="Search history" placeholder="Search history" value={q} onChange={(e) => setQ(e.target.value)} start={<MagnifyingGlass data-slot="icon" weight="bold" />} />
        <Select className="w-44" aria-label="When" items={DAYS} value={day} onValueChange={(v) => setDay(v ?? "all")} />
      </div>
      {shown.length === 0 ? (
        <EmptyState size="block" icon="magnifying-glass" title={visits.length ? "No pages match" : "Your history is empty"} hint={visits.length ? "Try another word or time range." : "Pages you visit appear here."} />
      ) : (
        <Table aria-label="Visited pages">
          <TableHeader>
            <TableRow><TableHead>Page</TableHead><TableHead numeric>Visited</TableHead></TableRow>
          </TableHeader>
          <TableBody>
            {shown.map((v, i) => (
              <TableRow key={`${v.url}-${i}`}>
                <TableCell>
                  <span className="flex min-w-0 items-center gap-2">
                    <Favicon url={v.url} />
                    <Link to={v.url} go={go}>{siteOf(v.url).title}</Link>
                    <span className="truncate text-ink-2 max-sm:hidden" title={v.url}>{v.url.split("/")[0]}</span>
                  </span>
                </TableCell>
                <TableCell numeric className="whitespace-nowrap">{v.time}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  );
}

/** One setting: its name and hint at the start, its control at the end (under them when narrow). */
const Row = ({ title, hint, children }: { title: string; hint: string; children: ReactNode }) => (
  <CardBody className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 border-b border-line-soft last:border-0">
    <div className="flex min-w-[200px] flex-1 flex-col gap-0.5"><span className="text-ink">{title}</span><span className="text-sm text-ink-2">{hint}</span></div>
    {children}
  </CardBody>
);

function SettingsPage({ settings, set }: { settings: Settings; set: (patch: Partial<Settings>) => void }) {
  return (
    <div className="mx-auto flex max-w-[720px] flex-col gap-4 px-6 py-8 max-sm:px-4">
      <PageHeader title="Settings" />
      <Card>
        <CardHeader><CardTitle>Appearance</CardTitle><CardDescription>How pages look in this window.</CardDescription></CardHeader>
        <Row title="Show bookmarks bar" hint="Your bookmarks under the address bar.">
          <Switch label="Show bookmarks bar" checked={settings.bookmarksBar} onCheckedChange={(v) => set({ bookmarksBar: v })} />
        </Row>
        <Row title="Page zoom" hint="Text and images on every site.">
          <SegmentedControl size="sm" aria-label="Page zoom" options={["90%", "100%", "125%"]} value={settings.zoom} onValueChange={(v) => set({ zoom: v })} />
        </Row>
      </Card>
      <Card>
        <CardHeader><CardTitle>Search and downloads</CardTitle></CardHeader>
        <Row title="Search engine" hint="Used by the address bar.">
          <Select className="w-44" aria-label="Search engine" items={ENGINES} value={settings.engine} onValueChange={(v) => v && set({ engine: v })} />
        </Row>
        <Row title="Ask where to save each file" hint="Otherwise files go to Downloads.">
          <Switch label="Ask where to save each file" checked={settings.askWhereToSave} onCheckedChange={(v) => set({ askWhereToSave: v })} />
        </Row>
      </Card>
    </div>
  );
}

/** The page area's content for a URL. */
export function Page(props: { url: string; go: Go; reload: () => void; download: () => void; settings: Settings; set: (patch: Partial<Settings>) => void; visits: Visit[]; clearHistory: () => void }) {
  const { url, go, settings } = props;
  const search = searchQuery(url);
  if (url === HOME) return <NewTab go={go} engine={settings.engine} />;
  if (url === HISTORY) return <HistoryPage visits={props.visits} go={go} clear={props.clearHistory} />;
  if (url === SETTINGS) return <SettingsPage settings={settings} set={props.set} />;
  if (search) return <SearchResults engine={search.engine} q={search.q} go={go} />;
  if (url === "harbor.dev/docs/getting-started") return <DocsPage go={go} download={props.download} />;
  if (url === "status.harbor.dev") return <StatusPage />;
  if (SITES.some((s) => s.url === url)) return <Article url={url} go={go} />;
  return <Unreachable url={url} reload={props.reload} />;
}
```

## toolbar.tsx

```tsx
/* The browser's chrome under the tab strip: navigation buttons, the address bar (site information,
 * suggestions, bookmark star), downloads, the main menu, and the bookmarks bar. */
import { useEffect, useState, type KeyboardEvent, type ReactNode } from "react";
import {
  Button, Combobox, Drawer, Menu, Popover, Progress, ProgressRing, Separator, Toggle, Tooltip, type MenuEntry,
} from "@fndn/react";
import {
  ArrowClockwise, ArrowLeft, ArrowRight, BookmarkSimple, Browsers, ClockCounterClockwise, DotsThreeVertical, DownloadSimple,
  File, FilePdf, FolderOpen, Gear, Globe, Lock, MagnifyingGlass, Package, Plus, Star, Warning, X,
} from "@phosphor-icons/react";
import { DOWNLOADS, ENGINES, HOME, READING, SITES, resolve, searchQuery, siteOf, type Bookmark, type Download, type Visit } from "./data";
import { Favicon } from "./pages";

/** A square icon button with its name in a tooltip. */
export function IconButton({ label, shortcut, icon, ...rest }: { label: string; shortcut?: string; icon: ReactNode; onClick?: () => void; disabled?: boolean; className?: string }) {
  return (
    <Tooltip content={label} shortcut={shortcut}>
      <Button variant="ghost" size="sm" square muted aria-label={label} icon={icon} {...rest} />
    </Tooltip>
  );
}

/** The site information button at the start of the address bar: a lock, a warning, or the browser's
 * own mark on its pages. Always there, so the address never moves when the page changes. */
function SiteInfo({ url, secure }: { url: string; secure: boolean }) {
  const internal = url.startsWith("ui://");
  const Glyph = internal ? Browsers : secure ? Lock : Warning;
  const [label, text] = internal
    ? ["This is a browser page", "Settings, history and the new tab page belong to the browser, not to a website."]
    : secure
      ? ["Connection is secure", "Your information, like passwords or card numbers, is private when it is sent to this site."]
      : ["Not secure", "Don’t enter passwords or card numbers on this site: they could be read by others on the network."];
  return (
    <Popover
      title={internal ? "Browser" : url.split("/")[0]}
      placement="bottom-start"
      trigger={<Button variant="ghost" size="xs" shape="rounded" square muted aria-label="View site information" icon={<Glyph data-slot="icon" weight="bold" />} />}
    >
      <div className="flex w-[260px] max-w-full flex-col gap-2 text-sm text-ink-2">
        <span className="flex items-center gap-2 text-ink"><Glyph data-slot="icon" weight="bold" />{label}</span>
        <p>{text}</p>
      </div>
    </Popover>
  );
}

/** The suggestions for what was typed, Chrome's order: pages whose address starts with it (Enter
 * goes there), then a search for it, then pages that merely contain it (in the address or the
 * title). With nothing typed, every page. Each row leads with what it is (the site's favicon, a
 * globe for an address not visited yet, a magnifier for the search), and the typed part of the
 * address stays in ink while the rest dims (highlightMatch). */
function suggestionItems(typed: string, pages: string[], engine: string) {
  const row = (u: string) => {
    const title = siteOf(u).title;
    return { value: u, label: u, icon: <Favicon url={u} size={14} />, meta: title === u ? undefined : title, keywords: [title] };
  };
  const q = typed.trim();
  if (!q) return pages.map(row);
  const lower = q.toLowerCase();
  const prefix = pages.filter((u) => u.toLowerCase().startsWith(lower));
  const typedUrl = resolve(q, engine);
  const domain = !searchQuery(typedUrl) && !pages.includes(typedUrl) ? [{ value: typedUrl, label: typedUrl, icon: <Globe data-slot="icon" weight="bold" />, keywords: [q] }] : [];
  const name = ENGINES.find((e) => e.value === engine)?.label ?? ENGINES[0]!.label;
  const search = { value: `search:${q}`, label: `Search ${name} for “${q}”`, icon: <MagnifyingGlass data-slot="icon" weight="bold" />, keywords: [q] };
  return [...prefix.map(row), ...domain, search, ...pages.filter((u) => !prefix.includes(u)).map(row)];
}

export function AddressBar({ url, secure, bookmarked, onBookmark, suggestions, go, engine }: {
  url: string; secure: boolean; bookmarked: boolean; onBookmark: (on: boolean) => void; suggestions: string[]; go: (text: string) => void; engine: string;
}) {
  /* what the user typed (not the label a selection writes into the field) */
  const [typed, setTyped] = useState("");
  const items = suggestionItems(typed, suggestions, engine);
  const choose = (v: string | null) => {
    setTyped("");
    if (!v) return;
    const prefix = ENGINES.find((e) => e.value === engine)?.prefix ?? ENGINES[0]!.prefix;
    go(v.startsWith("search:") ? prefix + encodeURIComponent(v.slice(7)) : v);
  };
  /* Enter with no row highlighted (the list closed): go to the text, or search for it */
  const enter = (e: KeyboardEvent) => {
    const input = e.target as HTMLInputElement;
    if (e.key !== "Enter" || input.tagName !== "INPUT" || !input.value.trim()) return;
    if (!document.querySelector("[data-slot=combobox-content][data-state=open] [data-slot=combobox-item][data-highlighted]")) { setTyped(""); go(input.value); }
  };
  const internal = url.startsWith("ui://");
  return (
    <div className="flex min-w-0 flex-1" onKeyDown={enter} onInput={(e) => setTyped((e.target as HTMLInputElement).value)}>
      <Combobox
        className="min-w-0 flex-1"
        size="sm"
        variant="subtle"
        caret={false}
        highlightMatch
        aria-label="Address and search bar"
        placeholder="Search or type a URL"
        items={items}
        value={url === HOME ? null : url}
        onValueChange={choose}
        onOpenChange={(open) => { if (!open) setTyped(""); }}
        start={url === HOME
          ? <span className="grid size-6 place-items-center"><MagnifyingGlass data-slot="icon" weight="bold" aria-hidden /></span>
          : <SiteInfo url={url} secure={secure} />}
        end={!internal && (
          <Toggle variant="ghost" size="xs" shape="rounded" square muted tooltip={bookmarked ? "Remove bookmark" : "Bookmark this tab"}
            pressed={bookmarked} onPressedChange={onBookmark} icon={<Star data-slot="icon" weight={bookmarked ? "fill" : "bold"} />} />
        )}
      />
    </div>
  );
}

const ICON = { pdf: FilePdf, archive: Package, file: File };
const mb = (n: number) => (n < 1 ? `${Math.round(n * 1000)} KB` : `${n.toFixed(1)} MB`);

/** Downloads keep receiving while the window is open: STEP megabytes every half second. */
const STEP = 0.5;
export function useDownloads() {
  const [list, setList] = useState<Download[]>(DOWNLOADS);
  const active = list.some((d) => d.received < d.size);
  useEffect(() => {
    if (!active) return;
    const timer = setInterval(() => setList((all) => all.map((d) => (d.received < d.size ? { ...d, received: Math.min(d.size, d.received + STEP) } : d))), 500);
    return () => clearInterval(timer);
  }, [active]);
  return [list, setList] as const;
}

export function Downloads({ list, onCancel, onClear, open, onOpenChange }: {
  list: Download[]; onCancel: (id: string) => void; onClear: () => void; open: boolean; onOpenChange: (open: boolean) => void;
}) {
  const running = list.find((d) => d.received < d.size);
  const icon = running
    ? <ProgressRing size="sm" tone="accent" progress={running.received / running.size} label={`Downloading ${running.name}`}><DownloadSimple data-slot="icon" weight="bold" /></ProgressRing>
    : <DownloadSimple data-slot="icon" weight="bold" />;
  return (
    <Popover
      open={open}
      onOpenChange={onOpenChange}
      title="Downloads"
      placement="bottom-end"
      trigger={<Tooltip content="Downloads"><Button variant="ghost" size="sm" square muted aria-label="Downloads" icon={icon} /></Tooltip>}
    >
      <div className="flex w-[300px] max-w-full flex-col gap-3">
        {list.length === 0 && <p className="text-sm text-ink-2">Files you download appear here.</p>}
        {list.map((d) => {
          const Glyph = ICON[d.kind];
          const done = d.received >= d.size;
          return (
            <div key={d.id} className="flex items-start gap-3">
              <Glyph className="mt-0.5 size-5 shrink-0 text-ink-3" weight="bold" aria-hidden />
              <div className="flex min-w-0 flex-1 flex-col gap-1">
                <span className="text-sm text-ink [overflow-wrap:anywhere]">{d.name}</span>
                {!done && <Progress size="sm" tone="accent" value={d.received} max={d.size} ariaLabel={`Downloading ${d.name}`} />}
                <span className="text-xs text-ink-2 tabular-nums">
                  {done ? `${mb(d.size)} · Done` : `${mb(d.received)} of ${mb(d.size)} · ${Math.ceil(((d.size - d.received) / STEP) * 0.5)} s left`}
                </span>
              </div>
              {done
                ? <IconButton label="Show in folder" icon={<FolderOpen data-slot="icon" weight="bold" />} />
                : <IconButton label="Cancel download" icon={<X data-slot="icon" weight="bold" />} onClick={() => onCancel(d.id)} />}
            </div>
          );
        })}
        {list.length > 0 && <Button size="sm" variant="outline" className="self-start" onClick={onClear}>Clear list</Button>}
      </div>
    </Popover>
  );
}

export function BrowserMenu({ closed, bookmarks, bookmarksBar, zoom, onSelect, onBookmarksBar, onZoom }: {
  closed: { id: string; url: string }[]; bookmarks: Bookmark[]; bookmarksBar: boolean; zoom: string;
  onSelect: (value: string) => void; onBookmarksBar: (on: boolean) => void; onZoom: (zoom: string) => void;
}) {
  const items: MenuEntry[] = [
    { value: "new-tab", label: "New tab", meta: "Alt+T", icon: <Plus data-slot="icon" weight="bold" /> },
    { value: "reopen", label: "Reopen closed tab", meta: "Alt+Shift+T", disabled: closed.length === 0 },
    { type: "separator" },
    {
      type: "submenu", label: "History", icon: <ClockCounterClockwise data-slot="icon" weight="bold" />, items: [
        { value: "history", label: "Show full history", meta: "Alt+Y" },
        { type: "separator" },
        {
          type: "group", label: "Recently closed",
          items: closed.length ? closed.slice(0, 5).map((t) => ({ value: `closed:${t.id}`, label: siteOf(t.url).title })) : [{ value: "none", label: "No closed tabs", disabled: true }],
        },
      ],
    },
    { value: "downloads", label: "Downloads", meta: "Alt+J", icon: <DownloadSimple data-slot="icon" weight="bold" /> },
    {
      type: "submenu", label: "Bookmarks", icon: <BookmarkSimple data-slot="icon" weight="bold" />, items: [
        { type: "checkbox", value: "bookmarks-bar", label: "Show bookmarks bar", checked: bookmarksBar },
        { type: "separator" },
        ...bookmarks.map((b) => ({ value: `open:${b.url}`, label: b.label })),
      ],
    },
    { type: "separator" },
    { type: "radio-group", name: "zoom", label: "Zoom", value: zoom, items: ["90%", "100%", "125%"].map((v) => ({ value: v, label: v })) },
    { type: "separator" },
    { value: "settings", label: "Settings", icon: <Gear data-slot="icon" weight="bold" /> },
  ];
  return (
    <Menu items={items} placement="bottom-end" onSelect={onSelect} onCheckedChange={(_, on) => onBookmarksBar(on)} onRadioChange={(_, v) => onZoom(v)}>
      <Tooltip content="Customize and control">
        <Button variant="ghost" size="sm" square muted aria-label="Main menu" icon={<DotsThreeVertical data-slot="icon" weight="bold" />} />
      </Tooltip>
    </Menu>
  );
}

/** The bookmarks under the address bar, and the Reading list folder. The row keeps 4px above and
 * 6px below the buttons: it scrolls sideways (and sits in a clipped reveal), so the focus ring
 * (2px at a 2px offset) must fit inside it. The folder's glyph takes a favicon's 16px box, so every
 * bookmark's label starts the same way. */
export function BookmarksBar({ bookmarks, go }: { bookmarks: Bookmark[]; go: (url: string) => void }) {
  return (
    <nav aria-label="Bookmarks" className="flex min-w-0 items-center gap-0.5 overflow-x-auto overscroll-x-contain px-2 pt-1 pb-1.5 [scrollbar-width:none]">
      {bookmarks.map((b) => (
        <Button key={b.url} variant="ghost" size="xs" icon={<Favicon url={b.url} />} onClick={() => go(b.url)} className="shrink-0">{b.label}</Button>
      ))}
      <Separator orientation="vertical" decorative className="mx-1 h-4 self-center" />
      <Menu items={READING.map((b) => ({ value: b.url, label: b.label }))} onSelect={go}>
        <Button variant="ghost" size="xs" className="shrink-0" icon={<span className="grid size-4 place-items-center"><FolderOpen className="size-4" weight="bold" aria-hidden /></span>}>Reading list</Button>
      </Menu>
    </nav>
  );
}

export function NavButtons({ canBack, canForward, loading, back, forward, reload, stop }: {
  canBack: boolean; canForward: boolean; loading: boolean; back: () => void; forward: () => void; reload: () => void; stop: () => void;
}) {
  return (
    <>
      <IconButton label="Back" icon={<ArrowLeft data-slot="icon" weight="bold" />} onClick={back} disabled={!canBack} />
      <IconButton label="Forward" icon={<ArrowRight data-slot="icon" weight="bold" />} onClick={forward} disabled={!canForward} className="max-sm:hidden" />
      {loading
        ? <IconButton label="Stop loading" icon={<X data-slot="icon" weight="bold" />} onClick={stop} />
        : <IconButton label="Reload" icon={<ArrowClockwise data-slot="icon" weight="bold" />} onClick={reload} />}
    </>
  );
}

/** Every page the address bar can suggest: the sites, the history, and the current page. */
export const suggestionsFor = (url: string, visits: Visit[]) =>
  [...new Set([...(url === HOME ? [] : [url]), ...SITES.filter((s) => !s.url.startsWith("ui://")).map((s) => s.url), ...visits.map((v) => v.url)])];

/** On a phone: the tab-count button beside the address bar, and the open tabs as a sheet of cards
 * (Chrome and Safari on a phone show no tab strip). A card selects its tab; its × closes it. */
export function TabSwitcher({ tabs, active, open, onOpenChange, select, close, newTab }: {
  tabs: { id: string; url: string; loading: boolean }[]; active: string; open: boolean; onOpenChange: (open: boolean) => void;
  select: (id: string) => void; close: (id: string) => void; newTab: () => void;
}) {
  const count = tabs.length;
  const label = `${count} open ${count === 1 ? "tab" : "tabs"}`;
  return (
    <Drawer
      className="sm:hidden"
      open={open}
      onOpenChange={onOpenChange}
      title={label}
      footer={<Button size="sm" variant="primary" icon={<Plus data-slot="icon" weight="bold" />} onClick={newTab}>New tab</Button>}
      trigger={
        <Button variant="ghost" size="sm" square muted aria-label={`${label}, switch tabs`}
          icon={<span aria-hidden className="grid size-4 place-items-center rounded-[4px] border-[1.5px] border-current text-[10px] font-semibold leading-none tabular-nums">{count > 99 ? ":D" /* as Chrome does */ : count}</span>} />
      }
    >
      <ul className="grid grid-cols-2 gap-3 pb-1" aria-label="Open tabs">
        {tabs.map((t) => {
          const site = siteOf(t.url);
          const current = t.id === active;
          return (
            <li key={t.id} className={`relative flex min-w-0 flex-col overflow-hidden rounded-card bg-surface shadow-card ${current ? "outline-2 outline-accent" : ""}`}>
              <div className="flex min-w-0 items-center gap-1.5 py-1 ps-2 pe-1">
                <span className="grid size-4 shrink-0 place-items-center text-ink-2"><Favicon url={t.url} size={14} /></span>
                <button type="button" onClick={() => select(t.id)} aria-current={current ? "page" : undefined}
                  className="min-w-0 flex-1 truncate text-start text-xs text-ink after:absolute after:inset-0 after:content-['']" title={site.title}>
                  {site.title}
                </button>
                <Button variant="ghost" size="xs" shape="rounded" square muted aria-label={`Close ${site.title}`} className="relative z-1" icon={<X data-slot="icon" weight="bold" />} onClick={() => close(t.id)} />
              </div>
              <span className="truncate border-t border-line-soft bg-inset px-2 pt-2 pb-6 text-xs text-ink-2" title={t.url}>{t.url.split("/")[0]}</span>
            </li>
          );
        })}
      </ul>
    </Drawer>
  );
}
```
