Put every page in the Control room shell: rail, bars, workspace, router links, keys, head, error and pending states
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- The root route renders the document as its shell component and an AppShell around every page: from 70 rem a rail (wordmark, Asks, Today with the decider's count, For agents, the projects with the current one first and its sections under it, the session and Keys), main and an optional inspector, each pane scrolling on its own; from 40 rem a top bar with Menu (the rail as a sheet), the project switcher and the session; below it a 44 px top bar (Back on subject pages) and a bottom bar of Asks, Today, Projects and More. - Workspace is the one component every page renders (crumbs, title, status, meta, state, count, primary command, toolbar, facts, variant); PageShell is now a thin adapter over it, so every page sits in the shell unchanged in content until its group rewrites it. Facts render as the inspector and, below the shell's width, inline after the head (a disclosure on lists, a sheet on code pages). - AppLink is the router's Link with intent preloading, over paths built whole; with no router around it (a view's own test) it draws a plain anchor with the same href. The rail, bars, crumbs, section row and session use it; a test fences the shell's sources against plain anchors. - A $project layout route reads nothing and lets the shell find the project; a route's staticData.rail fills the rail's slot, kept mounted across sibling routes because the rail never unmounts. - The router preloads on intent (50 ms), keeps preloads 30 s and loads 10 s, shows PendingPage after 300 ms, and draws RouteError (ink, Unplug, Reload, never red) and NotFoundPage inside the shell; main and the inspector scroll back to their tops on a new page. - Keys: one listener; ? opens the keys dialog with the On/Off switch (kept in localStorage through Result.try, on by default); j/k, J/K, 1-9 and Escape through useListKeys, useFileKeys, useNumberedCommand (facts numbered first) and useEscapeClears; no key acts in a field or with a modifier. - pageHead gives every route its title and the Open Graph metas; the root carries a default description. The selection helper keeps a list's selected row in the search (?ask=, ?decision=) with replace and no scroll reset. - The project's tabs become a section row that scrolls sideways and reads Policy for /people; the footer's repeated commands are gone; Reading and Unreachable move to features/shared/pending.tsx with 64 px skeleton rows. - Overlays (Base UI dialog, sheet, combobox switcher) load after hydration in their own chunk, so no first load carries them; the kit dialog's backdrop drops its blur. - Tests: test/render.tsx (renderAt: a view inside a memory router), shell.test.tsx, keys.test.tsx, head.test.ts, nav.test.tsx rewritten for the section row, root.test.tsx gains the router's defaults, shared.test.tsx loses the header and footer cases to shell.test.tsx. - Sizes: web entry 709,159 of 818,000, JavaScript 3,683,491 of 4,075,000; no limit changed. - ASSUMPTION confirmed: TanStack Router 1.170.41 renders a memory-history router to static markup after router.load().
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
54 files+3891 added−405 removed
- tests:+753 added−91 removed
- other:+3138 added−314 removed
Provenance
- Commit
ddbd51e- Tree
9878222- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
512af5a
54 files changed+3891 added−405 removed
modified:apps/web/src/components/ui/dialog.tsx+1 added-1 removed
29 unmodified lines30313233343435363738118 unmodified linesExpand all29 unmodified lines return ( <DialogPrimitive.Backdrop data-slot="dialog-overlay" className={cn( "data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0 fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs", "data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0 fixed inset-0 isolate z-50 bg-[color-mix(in_oklch,var(--foreground)_22%,transparent)] duration-100", className )} {...props} />118 unmodified linesExpand alladded:apps/web/src/components/ui/sheet.tsx+85 added
1+"use client";2+3+/**4+ * A sheet: Base UI's dialog drawn against an edge of the screen. It slides5+ * in over 200 ms (none under reduced motion, which the stylesheet's switch6+ * turns off), traps focus while open, and closes on Escape, a press outside7+ * or its Close button. The page behind dims in ink, without blur.8+ */9+import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";10+import { cva } from "class-variance-authority";11+import { cn } from "cn";12+import { XIcon } from "lucide-react";13+import type * as React from "react";14+15+import { Button } from "@/components/ui/button";16+17+function Sheet({ ...props }: DialogPrimitive.Root.Props) {18+ return <DialogPrimitive.Root data-slot="sheet" {...props} />;19+}20+21+function SheetTrigger({ ...props }: DialogPrimitive.Trigger.Props) {22+ return <DialogPrimitive.Trigger data-slot="sheet-trigger" {...props} />;23+}24+25+function SheetClose({ ...props }: DialogPrimitive.Close.Props) {26+ return <DialogPrimitive.Close data-slot="sheet-close" {...props} />;27+}28+29+const sheetVariants = cva(30+ "bg-background text-foreground border-rule fixed z-50 flex flex-col overflow-hidden shadow-[0_8px_32px_-8px_color-mix(in_oklch,var(--foreground)_28%,transparent)] transition-transform duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] outline-none",31+ {32+ variants: {33+ side: {34+ bottom:35+ "inset-x-0 bottom-0 max-h-[85dvh] border-t pb-[env(safe-area-inset-bottom)] data-ending-style:translate-y-full data-starting-style:translate-y-full",36+ full: "inset-0 pb-[env(safe-area-inset-bottom)] data-ending-style:translate-y-full data-starting-style:translate-y-full",37+ left: "inset-y-0 left-0 w-[min(20rem,calc(100vw-3rem))] border-r data-ending-style:-translate-x-full data-starting-style:-translate-x-full",38+ right:39+ "inset-y-0 right-0 w-[min(22rem,calc(100vw-3rem))] border-l data-ending-style:translate-x-full data-starting-style:translate-x-full",40+ },41+ },42+ defaultVariants: { side: "left" },43+ }44+);45+46+function SheetContent({47+ className,48+ children,49+ side = "left",50+ title,51+ ...props52+}: DialogPrimitive.Popup.Props & {53+ readonly side?: "bottom" | "full" | "left" | "right";54+ /** The sheet's name, drawn in its head beside Close. */55+ readonly title: React.ReactNode;56+}) {57+ return (58+ <DialogPrimitive.Portal data-slot="sheet-portal">59+ <DialogPrimitive.Backdrop60+ className="fixed inset-0 z-50 bg-[color-mix(in_oklch,var(--foreground)_22%,transparent)] transition-opacity duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0"61+ data-slot="sheet-overlay"62+ />63+ <DialogPrimitive.Popup64+ className={cn(sheetVariants({ side }), className)}65+ data-slot="sheet-content"66+ {...props}67+ >68+ <div className="border-rule flex h-12 shrink-0 items-center justify-between gap-3 border-b pr-2 pl-4">69+ <DialogPrimitive.Title className="text-ui font-semibold">70+ {title}71+ </DialogPrimitive.Title>72+ <DialogPrimitive.Close render={<Button size="sm" variant="ghost" />}>73+ <XIcon aria-hidden="true" />74+ Close75+ </DialogPrimitive.Close>76+ </div>77+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">78+ {children}79+ </div>80+ </DialogPrimitive.Popup>81+ </DialogPrimitive.Portal>82+ );83+}84+85+export { Sheet, SheetClose, SheetContent, SheetTrigger };modified:apps/web/src/features/auth/session-slot.tsx+51 added-21 removed
1 /**2- * The header's session slot: who is signed in, with sign-out,3- * or a link to sign in that comes back to this page. Signing in is only4- * for deciders (PRODUCT.md), so the slot stays one quiet line: the handle5- * in ink, the action in the nav's muted text.2+ * The session, wherever the shell shows it (the rail's foot, the tablet's3+ * top bar, the phone's More sheet): who is signed in, with sign-out, or a4+ * link to sign in that comes back to this page. Signing in is only for5+ * deciders (PRODUCT.md), so the slot stays quiet: the handle in ink, the6+ * action in muted text.7 *7- * `SessionView` draws it from props; `SessionSlot` (no props: the root8- * route renders it) wires it to `whoAtom` and the location.8+ * `SessionView` draws it from props; `SessionSlot` wires it to `whoAtom`9+ * and the location. Sign-in is a server route, so its link is a plain10+ * anchor that loads the document; the handle's page is the router's.11 */12 import { useAtomValue } from "@effect/atom-react";13 import type { Handle } from "@repo/protocol/ids";14 import { useLocation } from "@tanstack/react-router";15 import { Option } from "effect";16 import { AsyncResult } from "effect/reactivity";17+import { LogIn } from "lucide-react";18 16-import { HandleLink } from "../shared/handle.tsx";19+import { AppLink } from "../shared/link.tsx";20+import { personPath } from "../shared/paths.ts";21 import { whoAtom } from "./who.ts";22 23 /**24 * Where sign-in comes back to: the page the reader is on, without its8 unmodified lines33 /** Sign-in, coming back to `here` afterwards. */34 export const signInHref = (here: string) =>35 `/auth/signin?${new URLSearchParams({ return: here }).toString()}`;36 33-/** The nav's own action style: muted text, ink on hover. */37+/** The session's own action style: muted text, ink on hover. */38 const ACTION =35- "text-muted-foreground hover:text-foreground cursor-pointer text-sm no-underline transition-colors duration-150";39+ "text-muted-foreground hover:text-foreground text-ui inline-flex cursor-pointer items-center gap-1.5 no-underline transition-colors duration-150";40 41+/**42+ * Where the slot sits: `rail` stacks the handle over its action in the43+ * rail's foot and the More sheet; `bar` keeps both on the top bar's line.44+ */45+export type SessionLayout = "bar" | "rail";46+47 export const SessionView = ({48 handle,49 here,50+ layout = "bar",51 }: {52 readonly handle: Option.Option<Handle>;53 readonly here: string;54+ readonly layout?: SessionLayout;55 }) =>56 Option.match(handle, {57 onNone: () => (58 <a className={ACTION} href={signInHref(here)}>59+ <LogIn aria-hidden="true" className="size-4" strokeWidth={1.75} />60 Sign in61 </a>62 ),63 onSome: (signedIn) => (64+ <div65+ className={66+ layout === "rail"67+ ? "flex min-w-0 flex-col gap-0.5"68+ : "flex min-w-0 items-center gap-3"69+ }51- <div className="flex items-center gap-3">52- <p className="flex min-w-0 items-baseline gap-1">53- <span className="text-muted-foreground sr-only shrink-0 sm:not-sr-only">70+ >71+ <p className="text-ui flex min-w-0 items-baseline gap-1">72+ <span className="text-muted-foreground sr-only shrink-0">73 Signed in as74 </span>56- {/* The header's row never shrinks below its content, so a long57- handle is capped (a quarter of a phone's width) for `truncate`58- to take hold and keep "Sign out" on screen; its title is whole. */}59- <span60- className="max-w-[25vw] min-w-0 truncate sm:max-w-xs"75+ {/* A long handle is cut short for the line it shares; its title76+ is whole. */}77+ <AppLink78+ className="decoration-rule hover:decoration-foreground max-w-[12rem] min-w-0 truncate font-medium underline-offset-4 hover:underline"79 title={signedIn}80+ to={personPath(signedIn)}81 >63- <HandleLink handle={signedIn} />64- </span>82+ {signedIn}83+ </AppLink>84 </p>66- <span aria-hidden className="bg-rule h-4 w-px" />85 <form action="/auth/signout" className="flex" method="post">86 <button className={ACTION} type="submit">87 Sign out88 </button>1 unmodified line90 </div>91 ),92 });93 76-export const SessionSlot = () => {94+export const SessionSlot = ({95+ layout = "bar",96+}: {97+ readonly layout?: SessionLayout;98+}) => {99 const here = useLocation({ select: hereOf });100 const who = useAtomValue(whoAtom);101 102 return (103 <SessionView104 handle={AsyncResult.isSuccess(who) ? who.value : Option.none()}105 here={here}106+ layout={layout}107 />108 );109 };110+111+/** Whether someone is signed in, as far as this browser knows yet. */112+export const useSignedIn = (): boolean => {113+ const who = useAtomValue(whoAtom);114+115+ return AsyncResult.isSuccess(who) && Option.isSome(who.value);116+};deleted:apps/web/src/features/front/reading.tsx-47 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/** * What a page shows while its reads are on their way, and when the platform * did not answer: the page's own title over rows that hold its place, or a * plain sentence. Neither is a refusal: a refusal is the platform's answer, * and these are the absence of one. */import { CloudOff } from "lucide-react";
import { Skeleton } from "../../components/ui/skeleton.tsx";import { PageShell } from "../shared/layout.tsx";
const ROWS = ["first", "second", "third"] as const;
/** Rows that hold a list's place while the platform answers. */export const ReadingRows = () => ( <div aria-busy="true" className="flex flex-col"> <output className="sr-only">Reading from the platform</output> {ROWS.map((row) => ( <div className="border-rule flex flex-col gap-2 border-t py-4" key={row}> <Skeleton className="h-4 w-40" /> <Skeleton className="h-5 w-full max-w-[60ch]" /> <Skeleton className="h-4 w-56" /> </div> ))} </div>);
export const Reading = ({ title }: { readonly title: string }) => ( <PageShell title={title}> <ReadingRows /> </PageShell>);
export const Unreachable = ({ title }: { readonly title: string }) => ( <PageShell title={title}> <p className="flex items-start gap-2" role="alert"> <CloudOff aria-hidden="true" className="text-muted-foreground mt-1 size-4 shrink-0" /> <span> The platform did not answer. Reload the page to ask again; git and the CLI reach it directly. </span> </p> </PageShell>);modified:apps/web/src/features/project/project-nav.tsx+19 added-47 removed
1 /**2- * The tabs every project page shares: Overview, Code, Landings, Refs,3- * People, Ledger and Env shape (the glossary's word). The page being read is marked `aria-current`; a4- * page under none of them (a proposal) marks none.2+ * A project's section row: Asks, Code, Landings, Refs, Policy, Ledger and3+ * Env shape, one line under the page's head where the rail is not drawn4+ * (below 1120 px; from there the rail lists them). The line scrolls5+ * sideways inside itself and never wraps, so it never pushes the page6+ * sideways. The page being read is marked `aria-current` and underlined in7+ * ink; a page under none of them (a proposal) marks none.8 *6- * Each tab is a plain `<a>` drawn as a ghost button (`buttonVariants`), as7- * every link between the web's pages is a plain link: a page loads whole8- * from its own route, and a view renders without a router around it, as9- * its tests render it. Base UI's `Button` rendered as `<a>` would give each10- * link `role="button"`, which a nav of pages must not have.9+ * Its links are the router's (`AppLink`), so moving between sections never10+ * reloads the page.11 */12 import type { ProjectName } from "@repo/protocol/ids";13 import type { ReactNode } from "react";14 15-import { buttonVariants } from "@/components/ui/button";15+import { AppLink } from "../shared/link.tsx";16+import { projectSections } from "../shared/shell/sections.ts";17+import type { ProjectTab } from "../shared/shell/sections.ts";18 17-import { envPath, ledgerPath } from "../shared/paths.ts";19+export type { ProjectTab } from "../shared/shell/sections.ts";20 19-/** Which of a project's pages is being read. */20-export type ProjectTab =21- | "code"22- | "env"23- | "landings"24- | "ledger"25- | "overview"26- | "people"27- | "refs";28-29-/** Each tab: its label and its page's address, in the order the nav shows them. */30-const tabs = (project: ProjectName) =>31- [32- { href: `/${project}`, label: "Overview", tab: "overview" },33- { href: `/${project}/tree/main`, label: "Code", tab: "code" },34- { href: `/${project}/commits/main`, label: "Landings", tab: "landings" },35- { href: `/${project}/refs`, label: "Refs", tab: "refs" },36- { href: `/${project}/people`, label: "People", tab: "people" },37- { href: ledgerPath(project), label: "Ledger", tab: "ledger" },38- { href: envPath(project), label: "Env shape", tab: "env" },39- ] as const satisfies readonly {40- readonly href: string;41- readonly label: string;42- readonly tab: ProjectTab;43- }[];44-21 export const ProjectNav = ({22 current,23 project,24 }: {1 unmodified line26 readonly project: ProjectName;27 }): ReactNode => (28 <nav29 aria-label={project}54- className="border-rule -mt-2 flex flex-wrap gap-1 border-b pb-2"30+ className="border-rule shell:hidden -mt-2 flex [scrollbar-width:none] overflow-x-auto overscroll-x-contain border-b"31 >56- {tabs(project).map(({ href, label, tab }) => (57- <a32+ {projectSections(project).map(({ label, tab, to }) => (33+ <AppLink34+ activeOptions={{ exact: true, includeSearch: false }}35 aria-current={tab === current ? "page" : undefined}59- className={buttonVariants({60- className:61- "text-muted-foreground aria-[current=page]:bg-muted aria-[current=page]:text-foreground no-underline",62- size: "sm",63- variant: "ghost",64- })}65- href={href}36+ className="text-ui text-muted-foreground hover:text-foreground aria-[current=page]:border-foreground aria-[current=page]:text-foreground -mb-px flex h-10 shrink-0 items-center border-b-2 border-transparent px-3 whitespace-nowrap no-underline transition-colors duration-[120ms] first:pl-0 focus-visible:outline-offset-[-2px] aria-[current=page]:font-semibold"37 key={tab}38+ to={to}39 >40 {label}69- </a>41+ </AppLink>42 ))}43 </nav>44 );modified:apps/web/src/features/project/project-page.tsx+1 added-1 removed
14 unmodified lines15 import type { ProjectName } from "@repo/protocol/ids";16 import type { DateTime } from "effect";17 18 import { EntriesTable, ReadmeSection } from "../code/tree-view.tsx";19-import { ReadingRows } from "../front/reading.tsx";19 import { SignedInProposeLink } from "../propose/propose-link.tsx";20 import { ID, SECTION } from "../shared/classes.ts";21 import { CommandLine } from "../shared/command.tsx";22 import { EmptyState } from "../shared/empty.tsx";23 import { PageShell } from "../shared/layout.tsx";24 import { askPath } from "../shared/paths.ts";25+import { ReadingRows } from "../shared/pending.tsx";26 import { PostureBadge } from "../shared/posture.tsx";27 import { When } from "../shared/time.tsx";28 import { AskFields, AskStanding } from "./asks.tsx";29 import { LandingList } from "./landings.tsx";240 unmodified linesadded:apps/web/src/features/shared/shell/app-shell.tsx+87 added
1+/**2+ * The shell every page sits in: the rail (where you are), main (what is3+ * waiting) and, when a page has typed facts, the inspector (the thing in4+ * hand), on one paper ground parted by hairlines. From 1120 px the three5+ * are columns, each scrolling on its own; below it a top bar holds the way6+ * around, and on a phone a bottom bar holds the sections. The page's own7+ * panes come from its `Workspace`.8+ *9+ * The shell owns the overlays (the rail as a sheet, More, Projects, the10+ * keys dialog), loaded once the page is up and closed whenever the reader11+ * moves, and the keyboard's one listener.12+ */13+import { useHydrated, useLocation } from "@tanstack/react-router";14+import { Suspense, useCallback, useMemo, useState } from "react";15+import type { ReactNode } from "react";16+17+import { KeysProvider } from "../keys.tsx";18+import { SkipLink } from "../layout.tsx";19+import { BottomBar } from "./bottom-bar.tsx";20+import { ShellContext, ShellReadsContext } from "./context.ts";21+import type { Overlay, ShellReads } from "./context.ts";22+import { LazyOverlays } from "./lazy-overlays.ts";23+import { Rail } from "./rail.tsx";24+import { TopBar } from "./top-bar.tsx";25+26+export const AppShell = ({27+ children,28+ projects,29+ todayCount,30+}: ShellReads & { readonly children: ReactNode }) => {31+ const pathname = useLocation({ select: (location) => location.pathname });32+ const hydrated = useHydrated();33+34+ // An overlay belongs to the address it opened on: a link inside it moves35+ // the reader on, and it is gone from the next page.36+ const [opened, setOpened] = useState<{37+ readonly at: string;38+ readonly overlay: Overlay;39+ }>();40+41+ const overlay = opened?.at === pathname ? opened.overlay : undefined;42+43+ const open = useCallback(44+ (next: Overlay) => {45+ setOpened({ at: pathname, overlay: next });46+ },47+ [pathname]48+ );49+50+ const close = useCallback(() => {51+ setOpened(undefined);52+ }, []);53+54+ const openDialog = useCallback(() => {55+ open("keys");56+ }, [open]);57+58+ const shell = useMemo(() => ({ open }), [open]);59+60+ const reads = useMemo(61+ () => ({ projects, todayCount }),62+ [projects, todayCount]63+ );64+65+ return (66+ <ShellContext value={shell}>67+ <ShellReadsContext value={reads}>68+ <KeysProvider openDialog={openDialog}>69+ <SkipLink />70+ <div className="shell:h-dvh shell:overflow-hidden tablet:pb-0 flex min-h-dvh pb-[calc(3.5rem+env(safe-area-inset-bottom))]">71+ <Rail />72+ <div className="shell:flex-row flex min-w-0 flex-1 flex-col">73+ <TopBar />74+ {children}75+ </div>76+ </div>77+ <BottomBar />78+ {hydrated && LazyOverlays !== undefined ? (79+ <Suspense fallback={null}>80+ <LazyOverlays onClose={close} overlay={overlay} />81+ </Suspense>82+ ) : null}83+ </KeysProvider>84+ </ShellReadsContext>85+ </ShellContext>86+ );87+};added:apps/web/src/features/shared/shell/bottom-bar.tsx+73 added
1+/**2+ * The phone's bottom bar, fixed above the home indicator: Asks, Today,3+ * Projects (the switcher, as a sheet) and More (For agents, the project's4+ * sections, the keys and the session), each a mark over its word. The5+ * current page's item is ink at 600 with a rule on its top edge; the rest6+ * are muted.7+ */8+import { CalendarCheck, Ellipsis, Folders, List } from "lucide-react";9+import type { LucideIcon } from "lucide-react";10+11+import { AppLink } from "../link.tsx";12+import { useShell } from "./context.ts";13+import type { Overlay } from "./context.ts";14+15+const ITEM =16+ "text-label text-muted-foreground hover:text-foreground before:bg-foreground relative flex h-14 cursor-pointer flex-col items-center justify-center gap-1 no-underline transition-colors duration-[120ms] before:absolute before:inset-x-4 before:-top-px before:h-0.5 before:opacity-0 focus-visible:outline-offset-[-2px] aria-[current=page]:font-semibold aria-[current=page]:text-foreground aria-[current=page]:before:opacity-100";17+18+const MARK = "size-5";19+20+const LINKS = [21+ { icon: List, label: "Asks", to: "/" },22+ { icon: CalendarCheck, label: "Today", to: "/today" },23+] as const satisfies readonly {24+ readonly icon: LucideIcon;25+ readonly label: string;26+ readonly to: string;27+}[];28+29+const SHEETS = [30+ { icon: Folders, label: "Projects", overlay: "projects" },31+ { icon: Ellipsis, label: "More", overlay: "more" },32+] as const satisfies readonly {33+ readonly icon: LucideIcon;34+ readonly label: string;35+ readonly overlay: Overlay;36+}[];37+38+export const BottomBar = () => {39+ const { open } = useShell();40+41+ return (42+ <nav43+ aria-label="Sections"44+ className="border-rule bg-background tablet:hidden fixed inset-x-0 bottom-0 z-30 grid grid-cols-4 border-t pb-[env(safe-area-inset-bottom)]"45+ >46+ {LINKS.map(({ icon: Icon, label, to }) => (47+ <AppLink48+ activeOptions={{ exact: true, includeSearch: false }}49+ className={ITEM}50+ key={to}51+ to={to}52+ >53+ <Icon aria-hidden="true" className={MARK} strokeWidth={1.75} />54+ {label}55+ </AppLink>56+ ))}57+ {SHEETS.map(({ icon: Icon, label, overlay }) => (58+ <button59+ aria-haspopup="dialog"60+ className={ITEM}61+ key={overlay}62+ onClick={() => {63+ open(overlay);64+ }}65+ type="button"66+ >67+ <Icon aria-hidden="true" className={MARK} strokeWidth={1.75} />68+ {label}69+ </button>70+ ))}71+ </nav>72+ );73+};added:apps/web/src/features/shared/shell/context-bar.tsx+148 added
1+/**2+ * Main's context bar, 44 px, on the same line as the rail's wordmark: the3+ * trail to the page on the left (the project first, ids in mono, each a4+ * link but the last), and on the right what the page is in a word (its5+ * state, or a list's count) and its one command to copy. From the shell's6+ * width it stays at the top of main while main scrolls.7+ */8+import { Effect } from "effect";9+import { Check, Copy } from "lucide-react";10+import { useState } from "react";11+import type { ReactNode } from "react";12+13+import { Button } from "../../../components/ui/button.tsx";14+import { useNumberedCommand } from "../keys.tsx";15+import { AppLink } from "../link.tsx";16+import type { Crumb } from "./sections.ts";17+18+/** The trail to the page, as a breadcrumb: each step a link but the page itself. */19+export const Breadcrumb = ({20+ crumbs,21+}: {22+ readonly crumbs: readonly Crumb[];23+}) => (24+ <nav aria-label="Breadcrumb" className="min-w-0">25+ <ol className="text-ui flex min-w-0 items-center gap-1.5">26+ {crumbs.map(({ label, mono = false, to }, index) => {27+ const last = index === crumbs.length - 1;28+ const face = mono ? "text-mono font-mono" : "";29+30+ return (31+ <li32+ className="flex min-w-0 items-center gap-1.5"33+ key={`${index}:${label}`}34+ >35+ {index === 0 ? null : (36+ <span aria-hidden="true" className="text-muted-foreground">37+ /38+ </span>39+ )}40+ {last || to === undefined ? (41+ <span42+ aria-current={last ? "page" : undefined}43+ className={`min-w-0 truncate ${last ? "text-foreground font-medium" : "text-muted-foreground"} ${face}`}44+ title={label}45+ >46+ {label}47+ </span>48+ ) : (49+ <AppLink50+ activeOptions={{ exact: true, includeSearch: false }}51+ className={`text-muted-foreground hover:text-foreground max-w-[14rem] min-w-0 truncate no-underline transition-colors duration-[120ms] ${face}`}52+ title={label}53+ to={to}54+ >55+ {label}56+ </AppLink>57+ )}58+ </li>59+ );60+ })}61+ </ol>62+ </nav>63+);64+65+/** Copy `command`, then show it copied for two seconds. */66+const copyFor = (command: string, shown: (copied: boolean) => void) =>67+ Effect.tryPromise(() => navigator.clipboard.writeText(command)).pipe(68+ Effect.andThen(69+ Effect.sync(() => {70+ shown(true);71+ })72+ ),73+ Effect.andThen(Effect.sleep("2 seconds")),74+ Effect.andThen(75+ Effect.sync(() => {76+ shown(false);77+ })78+ ),79+ Effect.ignore80+ );81+82+/**83+ * The page's one command, as a copy button: the command itself is the84+ * button's text for a screen reader and a crawler, and its number (when the85+ * single keys are on) is in its title.86+ */87+export const CopyCommand = ({ command }: { readonly command: string }) => {88+ const [copied, setCopied] = useState(false);89+ const number = useNumberedCommand(command);90+91+ return (92+ <Button93+ onClick={() => {94+ Effect.runFork(copyFor(command, setCopied));95+ }}96+ size="sm"97+ title={98+ number === undefined99+ ? `Copy: ${command}`100+ : `Copy (${number}): ${command}`101+ }102+ variant="outline"103+ >104+ {copied ? (105+ <Check aria-hidden="true" strokeWidth={1.75} />106+ ) : (107+ <Copy aria-hidden="true" strokeWidth={1.75} />108+ )}109+ <span aria-hidden="true">{copied ? "Copied" : "Copy"}</span>110+ <code className="sr-only">111+ {copied ? `Copied ${command}` : `Copy ${command}`}112+ </code>113+ </Button>114+ );115+};116+117+export const ContextBar = ({118+ count,119+ crumbs,120+ end,121+ primaryCommand,122+ state,123+}: {124+ readonly count?: string | undefined;125+ readonly crumbs: readonly Crumb[];126+ /** Anything else the page's bar holds at its end (the code pages' Facts button). */127+ readonly end?: ReactNode;128+ readonly primaryCommand?: string | undefined;129+ readonly state?: ReactNode;130+}) => (131+ <div className="border-rule bg-background tablet:px-5 shell:sticky shell:top-0 shell:px-6 z-20 flex h-11 shrink-0 items-center gap-3 border-b px-4">132+ <Breadcrumb crumbs={crumbs} />133+ <div className="ml-auto flex shrink-0 items-center gap-3">134+ {count === undefined ? null : (135+ <p className="text-ui text-muted-foreground truncate tabular-nums">136+ {count}137+ </p>138+ )}139+ {state === undefined ? null : (140+ <div className="text-ui flex items-center">{state}</div>141+ )}142+ {primaryCommand === undefined ? null : (143+ <CopyCommand command={primaryCommand} />144+ )}145+ {end}146+ </div>147+ </div>148+);added:apps/web/src/features/shared/shell/context.ts+66 added
1+/**2+ * What the shell lends the parts inside it: a way to open its overlays (the3+ * rail as a sheet, the phone's More and Projects sheets, the keys dialog),4+ * the project the address is in, and what the root route read for the rail5+ * (the list of projects, the count on Today). The shell's parts are views:6+ * the root route wires the reads (`src/routes/__root.tsx`).7+ */8+import type { ProjectListing } from "@repo/protocol/domain/front-page";9+import { ProjectName } from "@repo/protocol/ids";10+import { useMatch } from "@tanstack/react-router";11+import { Schema } from "effect";12+import { createContext, useContext } from "react";13+import type { ReactNode } from "react";14+15+/** One of the shell's overlays. */16+export type Overlay = "keys" | "menu" | "more" | "projects";17+18+export interface Shell {19+ readonly open: (overlay: Overlay) => void;20+}21+22+export const ShellContext = createContext<Shell>({23+ open: () => {24+ // Outside the shell (a view's own test) there is nothing to open.25+ },26+});27+28+/** The shell's overlays, from inside it. */29+export const useShell = (): Shell => useContext(ShellContext);30+31+const isProjectName = Schema.is(ProjectName);32+33+/**34+ * The project the address is in: the `$project` route's name, when it is35+ * one a project could have. None on the site's own pages, and none for a36+ * name no project may take (the page says so itself).37+ */38+export const useCurrentProject = (): ProjectName | undefined =>39+ useMatch({40+ from: "/$project",41+ select: ({ params }) =>42+ isProjectName(params.project) ? params.project : undefined,43+ shouldThrow: false,44+ });45+46+/** What the root route read for the rail. */47+export interface ShellReads {48+ /** Every listed project, once the list has arrived in the browser; nothing before. */49+ readonly projects?: readonly ProjectListing[] | undefined;50+ /** Today's count, drawn at the end of its row (`RailCount`); nothing for a reader who decides nothing. */51+ readonly todayCount?: ReactNode;52+}53+54+export const ShellReadsContext = createContext<ShellReads>({});55+56+/**57+ * Every listed project, once the list has arrived: the server renders the58+ * rail without them (the current project's name comes from the address),59+ * and nothing on a page waits on the list.60+ */61+export const useProjectList = (): readonly ProjectListing[] | undefined =>62+ useContext(ShellReadsContext).projects;63+64+/** Today's count for the rail, when there is one. */65+export const useTodayCount = (): ReactNode =>66+ useContext(ShellReadsContext).todayCount;added:apps/web/src/features/shared/shell/facts-sheet.tsx+31 added
12345678910111213141516171819202122232425262728293031/** * A code page's facts as a sheet from the right, where the code keeps the * width (below 1440 px). Loaded once the page is up, and mounted closed so * it slides in when the Facts button opens it. */import type { ReactNode } from "react";
import { Sheet, SheetContent } from "../../../components/ui/sheet.tsx";import { CommandSlotProvider } from "../keys.tsx";
const FactsSheet = ({ content, heading, onOpenChange, open,}: { readonly content: ReactNode; readonly heading: string; readonly onOpenChange: (open: boolean) => void; readonly open: boolean;}) => ( <Sheet onOpenChange={onOpenChange} open={open}> <SheetContent side="right" title={heading}> <CommandSlotProvider slot="facts"> <div className="flex flex-col p-4">{content}</div> </CommandSlotProvider> </SheetContent> </Sheet>);
export default FactsSheet;added:apps/web/src/features/shared/shell/lazy-overlays.ts+15 added
1+/**2+ * The shell's overlays (`overlays.tsx`) and a code page's facts sheet3+ * (`facts-sheet.tsx`), fetched once the page is up: the Worker never4+ * renders one (an overlay opens on a press), and no page's first load5+ * carries their dialog, sheet and combobox code.6+ */7+import { lazy } from "react";8+9+export const LazyOverlays = import.meta.env.SSR10+ ? undefined11+ : lazy(() => import("./overlays.tsx"));12+13+export const LazyFactsSheet = import.meta.env.SSR14+ ? undefined15+ : lazy(() => import("./facts-sheet.tsx"));added:apps/web/src/features/shared/shell/overlays.tsx+259 added
1+/**2+ * The shell's overlays, loaded once the page is up, so no page's first load3+ * carries them: the rail as a sheet (Menu, below the shell's width), the4+ * phone's More and Projects sheets, and the keys dialog. Each opens on a5+ * press, slides in over 200 ms, traps focus, and closes on Escape, a press6+ * outside or Close; following a link inside closes it too (the shell's open7+ * overlay belongs to the address it opened on).8+ */9+import { Brand } from "@repo/brand";10+import { useRouter } from "@tanstack/react-router";11+import { Bot, Keyboard } from "lucide-react";12+import { useRef } from "react";13+import type { RefObject } from "react";14+15+import {16+ Combobox,17+ ComboboxEmpty,18+ ComboboxInput,19+ ComboboxItem,20+ ComboboxList,21+} from "../../../components/ui/combobox.tsx";22+import {23+ Dialog,24+ DialogContent,25+ DialogDescription,26+ DialogHeader,27+ DialogTitle,28+} from "../../../components/ui/dialog.tsx";29+import { Sheet, SheetContent } from "../../../components/ui/sheet.tsx";30+import { SessionSlot } from "../../auth/session-slot.tsx";31+import { KeysHelp, useKeys } from "../keys.tsx";32+import { AppLink } from "../link.tsx";33+import { useCurrentProject, useProjectList, useShell } from "./context.ts";34+import type { Overlay } from "./context.ts";35+import {36+ PostureMark,37+ ProjectSectionList,38+ RAIL_ROW,39+ RailContent,40+ RailFoot,41+} from "./rail.tsx";42+43+export interface OverlayProps {44+ /** The overlay open now; none when all are closed. */45+ readonly overlay: Overlay | undefined;46+ readonly onClose: () => void;47+}48+49+/** A sheet's or dialog's open state, as the shell holds it. */50+const openState = (open: boolean, onClose: () => void) => ({51+ onOpenChange: (next: boolean) => {52+ if (!next) {53+ onClose();54+ }55+ },56+ open,57+});58+59+/** Whether the screen is at least a tablet's width, read when an overlay opens. */60+const atLeastTablet = () => globalThis.matchMedia("(min-width: 40rem)").matches;61+62+/**63+ * Every project, with a typed filter: choosing one opens its asks. The64+ * names, their posture and their open asks come from the list the rail65+ * reads.66+ */67+const ProjectSwitcher = ({68+ input,69+ onChosen,70+}: {71+ /** The filter, which takes focus when the sheet opens. */72+ readonly input: RefObject<HTMLInputElement | null>;73+ readonly onChosen: () => void;74+}) => {75+ const listed = useProjectList();76+ const current = useCurrentProject();77+ const router = useRouter();78+ const names = (listed ?? []).map(({ project }) => project);79+80+ return (81+ <Combobox82+ autoHighlight83+ inline84+ items={names}85+ onValueChange={(name) => {86+ if (name !== null) {87+ onChosen();88+ router.history.push(`/${name}`);89+ }90+ }}91+ open92+ value={current ?? null}93+ >94+ <div className="border-rule border-b p-3">95+ <ComboboxInput96+ aria-label="Find a project"97+ className="w-full"98+ placeholder="Find a project"99+ ref={input}100+ showTrigger={false}101+ />102+ </div>103+ {listed === undefined ? (104+ <p className="text-ui text-muted-foreground p-4">105+ Reading the projects…106+ </p>107+ ) : (108+ <>109+ <ComboboxEmpty className="p-4">110+ No project by that name.111+ </ComboboxEmpty>112+ <ComboboxList className="max-h-none p-1">113+ {(name: string) => {114+ const listing = listed.find(({ project }) => project === name);115+116+ return (117+ <ComboboxItem className="h-10 gap-3" key={name} value={name}>118+ <span className="min-w-0 truncate font-medium">{name}</span>119+ {listing === undefined ? null : (120+ <>121+ <span className="text-muted-foreground text-label ml-auto tabular-nums">122+ {listing.openAsks} open123+ </span>124+ <PostureMark posture={listing.posture} />125+ </>126+ )}127+ </ComboboxItem>128+ );129+ }}130+ </ComboboxList>131+ </>132+ )}133+ </Combobox>134+ );135+};136+137+/** The phone's More: For agents, the project's sections, the keys, the session. */138+const More = () => {139+ const project = useCurrentProject();140+ const listed = useProjectList();141+ const { open } = useShell();142+143+ return (144+ <div className="flex flex-col gap-2 px-2 py-2">145+ <AppLink146+ activeOptions={{ exact: true }}147+ className={RAIL_ROW}148+ to="/agents"149+ >150+ <Bot151+ aria-hidden="true"152+ className="text-muted-foreground size-4"153+ strokeWidth={1.75}154+ />155+ For agents156+ </AppLink>157+ {project === undefined ? null : (158+ <div className="flex flex-col gap-1">159+ <h2 className="text-label text-muted-foreground px-2 pt-3 pb-1">160+ {project}161+ </h2>162+ <ProjectSectionList163+ openAsks={164+ listed?.find((listing) => listing.project === project)?.openAsks165+ }166+ project={project}167+ />168+ </div>169+ )}170+ <button171+ className={`${RAIL_ROW} w-full cursor-pointer`}172+ onClick={() => {173+ open("keys");174+ }}175+ type="button"176+ >177+ <Keyboard178+ aria-hidden="true"179+ className="text-muted-foreground size-4"180+ strokeWidth={1.75}181+ />182+ Keys183+ </button>184+ <div className="border-rule mt-1 border-t px-2 pt-3 pb-1">185+ <SessionSlot layout="rail" />186+ </div>187+ </div>188+ );189+};190+191+const KeysDialog = ({192+ onClose,193+ open,194+}: {195+ readonly onClose: () => void;196+ readonly open: boolean;197+}) => {198+ const keys = useKeys();199+200+ return (201+ <Dialog {...openState(open, onClose)}>202+ <DialogContent className="sm:max-w-md">203+ <DialogHeader>204+ <DialogTitle>Keys</DialogTitle>205+ <DialogDescription>206+ Every key has a twin you can click: rows are links, files are rows207+ of the tree, and commands have their copy buttons.208+ </DialogDescription>209+ </DialogHeader>210+ <KeysHelp211+ on={keys?.on ?? true}212+ onChange={(on) => {213+ keys?.setOn(on);214+ }}215+ />216+ </DialogContent>217+ </Dialog>218+ );219+};220+221+/**222+ * Every overlay the shell has, each closed until the shell opens it. They223+ * stay mounted once loaded, so each one slides in from closed.224+ */225+const ShellOverlays = ({ onClose, overlay }: OverlayProps) => {226+ const filter = useRef<HTMLInputElement>(null);227+228+ return (229+ <>230+ <Sheet {...openState(overlay === "menu", onClose)}>231+ <SheetContent side="left" title={Brand.name}>232+ <div className="flex min-h-full flex-col">233+ <div className="flex-1">234+ <RailContent />235+ </div>236+ <RailFoot />237+ </div>238+ </SheetContent>239+ </Sheet>240+ <Sheet {...openState(overlay === "more", onClose)}>241+ <SheetContent side="bottom" title="More">242+ <More />243+ </SheetContent>244+ </Sheet>245+ <Sheet {...openState(overlay === "projects", onClose)}>246+ <SheetContent247+ initialFocus={filter}248+ side={overlay === "projects" && atLeastTablet() ? "left" : "full"}249+ title="Projects"250+ >251+ <ProjectSwitcher input={filter} onChosen={onClose} />252+ </SheetContent>253+ </Sheet>254+ <KeysDialog onClose={onClose} open={overlay === "keys"} />255+ </>256+ );257+};258+259+export default ShellOverlays;added:apps/web/src/features/shared/shell/rail-slot.tsx+60 added
1+/**2+ * The rail's slot: room under the project's line for what a page keeps3+ * beside it while the reader moves between its siblings (the code pages'4+ * file tree). A route names the component that fills it in its5+ * `staticData.rail`; the shell draws the deepest one the address matches,6+ * on the server too. Sibling routes that name the same component keep one7+ * mounted instance as the reader moves between them, since the rail itself8+ * never leaves the page.9+ *10+ * ```tsx11+ * const CodeRail = () => <RailSlot label="Files"><ProjectTree /></RailSlot>;12+ *13+ * export const Route = createFileRoute("/$project/blob/$rev/$")({14+ * staticData: { rail: CodeRail },15+ * });16+ * ```17+ */18+import { useMatches } from "@tanstack/react-router";19+import { createElement } from "react";20+import type { ComponentType, ReactNode } from "react";21+22+declare module "@tanstack/react-router" {23+ interface StaticDataRouteOption {24+ /** What fills the rail's slot on this route's pages, and on its children's. */25+ readonly rail?: ComponentType;26+ }27+}28+29+/** The slot's frame: the rest of the rail's height, scrolling on its own. */30+export const RailSlot = ({31+ children,32+ label = "Files",33+}: {34+ readonly children: ReactNode;35+ /** What the slot holds, for a screen reader moving by region. */36+ readonly label?: string;37+}) => (38+ <section39+ aria-label={label}40+ className="border-rule flex min-h-0 flex-1 flex-col overflow-hidden border-t"41+ data-rail-slot=""42+ >43+ {children}44+ </section>45+);46+47+/** The component the deepest matched route puts in the slot, when one does. */48+export const useRailContent = (): ComponentType | undefined =>49+ useMatches({50+ select: (matches) =>51+ matches.findLast(({ staticData }) => staticData.rail !== undefined)52+ ?.staticData.rail,53+ });54+55+/** The slot's content for the address, or nothing. */56+export const RailSlotOutlet = (): ReactNode => {57+ const Content = useRailContent();58+59+ return Content === undefined ? null : createElement(Content);60+};added:apps/web/src/features/shared/shell/rail.tsx+413 added
1+/**2+ * The rail: where the reader is. Top to bottom, the wordmark; the site's3+ * sections (Asks, Today, For agents), each a word beside its mark; the4+ * projects, the current one first with its own sections under it; the5+ * rail's slot on pages that fill it (the code pages' tree); and the session6+ * with the Keys button at the foot.7+ *8+ * From the shell's width it is a column beside main; below it, the same9+ * content opens as a sheet from the top bar's Menu (`RailContent`). The10+ * current item is filled with the surface and set in ink at 600, never11+ * coloured; the router marks a link to the page being read12+ * `aria-current="page"`, and a section holding the page is marked13+ * `aria-current="true"`.14+ */15+import { Brand } from "@repo/brand";16+import type { ProjectListing } from "@repo/protocol/domain/front-page";17+import type { ProjectName } from "@repo/protocol/ids";18+import type { Posture } from "@repo/protocol/posture";19+import { useLocation } from "@tanstack/react-router";20+import {21+ Bot,22+ CalendarCheck,23+ ChevronDown,24+ Eye,25+ Folders,26+ Keyboard,27+ List,28+ LockKeyhole,29+ LockKeyholeOpen,30+ Menu,31+} from "lucide-react";32+import type { LucideIcon } from "lucide-react";33+import type { ReactNode } from "react";34+35+import { Button } from "../../../components/ui/button.tsx";36+import { Skeleton } from "../../../components/ui/skeleton.tsx";37+import { SessionSlot } from "../../auth/session-slot.tsx";38+import { postureLabel } from "../../project/posture-label.ts";39+import { AppLink } from "../link.tsx";40+import {41+ useCurrentProject,42+ useProjectList,43+ useShell,44+ useTodayCount,45+} from "./context.ts";46+import { RailSlotOutlet, useRailContent } from "./rail-slot.tsx";47+import { POSTURE_WORD, projectSections, sectionOf } from "./sections.ts";48+49+/** A row of the rail, before the fill that marks the current one. */50+const RAIL_BASE =51+ "text-ui text-foreground hover:bg-surface flex h-8 min-w-0 items-center gap-2.5 px-2 no-underline transition-colors duration-[120ms] focus-visible:outline-offset-[-2px] [&[aria-current]]:font-semibold [&[aria-current]>svg]:text-foreground";52+53+/** A row of the rail: a word (and its mark), 32 px, filled when current. */54+export const RAIL_ROW = `${RAIL_BASE} [&[aria-current]]:bg-surface`;55+56+/** A row's mark: 16 px at the marks' stroke, muted until the row is current. */57+const MARK = "text-muted-foreground size-4 shrink-0";58+59+/** At most this many projects in the rail; more open the switcher. */60+const SHOWN = 8;61+62+const SITE = [63+ { icon: List, label: "Asks", to: "/" },64+ { icon: CalendarCheck, label: "Today", to: "/today" },65+ { icon: Bot, label: "For agents", to: "/agents" },66+] as const satisfies readonly {67+ readonly icon: LucideIcon;68+ readonly label: string;69+ readonly to: string;70+}[];71+72+/** Only the page itself is current; its search (a filter, a selection) does not count. */73+const EXACT = { exact: true, includeSearch: false } as const;74+75+/** A count of things at a rail row's end, in tabular figures, with what it counts for a screen reader. */76+export const RailCount = ({77+ count,78+ of,79+}: {80+ readonly count: number;81+ readonly of: string;82+}) => (83+ <span className="text-muted-foreground ml-auto font-normal tabular-nums">84+ {count}85+ <span className="sr-only"> {of}</span>86+ </span>87+);88+89+/** Today's count, as the root route read it. */90+const TodayCount = () => useTodayCount() ?? null;91+92+/** The wordmark, home to the front page. */93+export const Wordmark = ({94+ className = "",95+}: {96+ readonly className?: string;97+}) => (98+ <AppLink99+ activeOptions={EXACT}100+ className={`text-want text-foreground font-semibold tracking-[-0.015em] no-underline ${className}`}101+ to="/"102+ >103+ {Brand.name}104+ </AppLink>105+);106+107+/** Asks, Today and For agents. */108+const SiteSections = () => (109+ <ul className="flex flex-col gap-px">110+ {SITE.map(({ icon: Icon, label, to }) => (111+ <li key={to}>112+ <AppLink activeOptions={EXACT} className={RAIL_ROW} to={to}>113+ <Icon aria-hidden="true" className={MARK} strokeWidth={1.75} />114+ {label}115+ {to === "/today" ? <TodayCount /> : null}116+ </AppLink>117+ </li>118+ ))}119+ </ul>120+);121+122+/** A posture's mark: a lock in the sealed role when something is kept sealed. */123+const POSTURE_MARK = {124+ open: { icon: LockKeyholeOpen, tone: "text-muted-foreground" },125+ openCore: { icon: LockKeyhole, tone: "text-sealed" },126+ openOnSchedule: { icon: LockKeyhole, tone: "text-sealed" },127+ openWithSealedEvidence: { icon: LockKeyhole, tone: "text-sealed" },128+ sourceAvailable: { icon: Eye, tone: "text-muted-foreground" },129+} as const satisfies Record<130+ Posture,131+ { readonly icon: LucideIcon; readonly tone: string }132+>;133+134+/** A project's posture at its row's end: the mark in its role, a short word muted, the full label as its title. */135+export const PostureMark = ({ posture }: { readonly posture: Posture }) => {136+ const { icon: Icon, tone } = POSTURE_MARK[posture];137+138+ return (139+ <span140+ className="text-label text-muted-foreground ml-auto flex shrink-0 items-center gap-1 font-normal"141+ data-posture={posture}142+ title={postureLabel(posture)}143+ >144+ <Icon145+ aria-hidden="true"146+ className={`size-3.5 ${tone}`}147+ strokeWidth={1.75}148+ />149+ {POSTURE_WORD[posture]}150+ <span className="sr-only">: {postureLabel(posture)}</span>151+ </span>152+ );153+};154+155+/** A project's row: its name, and its posture once the list has it. */156+/** The current project's row: in ink at 600, unfilled, so the page being read (a section under it) is the one filled row. */157+const PROJECT_ROW = RAIL_BASE;158+159+const ProjectRow = ({160+ current,161+ listing,162+ project,163+}: {164+ readonly current: boolean;165+ readonly listing: ProjectListing | undefined;166+ readonly project: string;167+}) => (168+ <AppLink169+ activeOptions={EXACT}170+ aria-current={current ? "true" : undefined}171+ className={PROJECT_ROW}172+ data-project={project}173+ to={`/${project}`}174+ >175+ <span className="min-w-0 truncate">{project}</span>176+ {listing === undefined ? null : <PostureMark posture={listing.posture} />}177+ </AppLink>178+);179+180+/** The current project's sections, indented under it, the open asks counted beside Asks. */181+export const ProjectSectionList = ({182+ openAsks,183+ project,184+}: {185+ readonly openAsks: number | undefined;186+ readonly project: ProjectName;187+}) => {188+ const section = useLocation({189+ select: ({ pathname }) => sectionOf(pathname),190+ });191+192+ return (193+ <ul194+ aria-label={`${project}'s sections`}195+ className="border-rule ml-4 flex flex-col gap-px border-l py-0.5 pl-1.5"196+ >197+ {projectSections(project).map(({ label, tab, to }) => (198+ <li key={tab}>199+ <AppLink200+ activeOptions={EXACT}201+ aria-current={section === tab ? "true" : undefined}202+ className={RAIL_ROW}203+ to={to}204+ >205+ {label}206+ {tab === "overview" && openAsks !== undefined ? (207+ <RailCount count={openAsks} of="open" />208+ ) : null}209+ </AppLink>210+ </li>211+ ))}212+ </ul>213+ );214+};215+216+/** The list's place while it is read: three rows of the rail's height. */217+const PLACEHOLDERS = ["w-24", "w-20", "w-28"] as const;218+219+const PlaceholderRows = () => (220+ <li aria-hidden="true" className="flex flex-col gap-px">221+ {PLACEHOLDERS.map((width) => (222+ <span className="flex h-8 items-center px-2" key={width}>223+ <Skeleton className={`h-2.5 ${width}`} />224+ </span>225+ ))}226+ </li>227+);228+229+/**230+ * The projects: the current one first, its sections under it, so the list231+ * arriving after the page moves nothing above it; then the others, up to232+ * eight in all, and the switcher for the rest.233+ */234+const Projects = () => {235+ const current = useCurrentProject();236+ const listed = useProjectList();237+ const { open } = useShell();238+239+ const listingOf = (project: string) =>240+ listed?.find((listing) => listing.project === project);241+242+ const others = (listed ?? []).filter(({ project }) => project !== current);243+ const room = SHOWN - (current === undefined ? 0 : 1);244+245+ return (246+ <div className="flex flex-col gap-1">247+ <h2 className="text-label text-muted-foreground px-2 pt-4 pb-1">248+ Projects249+ </h2>250+ <ul className="flex flex-col gap-px">251+ {current === undefined ? null : (252+ <li>253+ <ProjectRow254+ current255+ listing={listingOf(current)}256+ project={current}257+ />258+ <ProjectSectionList259+ openAsks={listingOf(current)?.openAsks}260+ project={current}261+ />262+ </li>263+ )}264+ {listed === undefined ? (265+ <PlaceholderRows />266+ ) : (267+ others.slice(0, room).map((listing) => (268+ <li key={listing.project}>269+ <ProjectRow270+ current={false}271+ listing={listing}272+ project={listing.project}273+ />274+ </li>275+ ))276+ )}277+ {listed !== undefined && others.length > room ? (278+ <li>279+ <button280+ className={`${RAIL_ROW} w-full cursor-pointer`}281+ onClick={() => {282+ open("projects");283+ }}284+ type="button"285+ >286+ <Folders aria-hidden="true" className={MARK} strokeWidth={1.75} />287+ All projects288+ <RailCount count={listed.length} of="projects" />289+ </button>290+ </li>291+ ) : null}292+ </ul>293+ </div>294+ );295+};296+297+/** The rail's foot: the session, and the Keys button that opens the `?` dialog. */298+export const RailFoot = () => {299+ const { open } = useShell();300+301+ return (302+ <div className="border-rule flex min-h-12 shrink-0 items-center justify-between gap-2 border-t py-1.5 pr-1.5 pl-3">303+ <SessionSlot layout="rail" />304+ <Button305+ className="text-muted-foreground shrink-0"306+ onClick={() => {307+ open("keys");308+ }}309+ size="sm"310+ variant="ghost"311+ >312+ <Keyboard aria-hidden="true" strokeWidth={1.75} />313+ Keys314+ </Button>315+ </div>316+ );317+};318+319+/** The rail's sections and projects: the column's middle, and the Menu sheet's body. */320+export const RailContent = (): ReactNode => (321+ <div className="flex flex-col gap-2 px-2 py-2">322+ <SiteSections />323+ <Projects />324+ </div>325+);326+327+/**328+ * The project's line in the code pages' rail: its name and the section329+ * being read, opening to the project's sections, so the tree below gets330+ * the height.331+ */332+const ProjectLine = ({ project }: { readonly project: ProjectName }) => {333+ const listed = useProjectList();334+335+ const section = useLocation({336+ select: ({ pathname }) => sectionOf(pathname),337+ });338+339+ const label = projectSections(project).find(340+ ({ tab }) => tab === section341+ )?.label;342+343+ return (344+ <details className="group border-rule border-t">345+ <summary className="text-ui hover:bg-surface flex h-10 cursor-pointer list-none items-center gap-2 px-4 transition-colors duration-[120ms] [&::-webkit-details-marker]:hidden">346+ <span className="min-w-0 truncate font-semibold">{project}</span>347+ {label === undefined ? null : (348+ <span className="text-muted-foreground truncate">{label}</span>349+ )}350+ <ChevronDown351+ aria-hidden="true"352+ className="text-muted-foreground ml-auto size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"353+ strokeWidth={1.75}354+ />355+ </summary>356+ <div className="px-2 pb-2">357+ <ProjectSectionList358+ openAsks={359+ listed?.find((listing) => listing.project === project)?.openAsks360+ }361+ project={project}362+ />363+ </div>364+ </details>365+ );366+};367+368+/**369+ * The rail as a column, from the shell's width. On a page that fills the370+ * slot (the code pages) it gives the slot the height: the site's sections371+ * and the projects fold into the wordmark row's Menu, and the project's372+ * sections into its line.373+ */374+export const Rail = () => {375+ const slotted = useRailContent() !== undefined;376+ const project = useCurrentProject();377+ const { open } = useShell();378+379+ return (380+ <nav381+ aria-label="Site"382+ className="border-rule bg-background shell:flex hidden h-dvh w-60 shrink-0 flex-col border-r"383+ >384+ <div className="border-rule flex h-11 shrink-0 items-center justify-between gap-2 border-b pr-1.5 pl-4">385+ <Wordmark />386+ {slotted ? (387+ <Button388+ className="text-muted-foreground"389+ onClick={() => {390+ open("menu");391+ }}392+ size="sm"393+ variant="ghost"394+ >395+ <Menu aria-hidden="true" strokeWidth={1.75} />396+ Menu397+ </Button>398+ ) : null}399+ </div>400+ {slotted ? (401+ <>402+ {project === undefined ? null : <ProjectLine project={project} />}403+ <RailSlotOutlet />404+ </>405+ ) : (406+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">407+ <RailContent />408+ </div>409+ )}410+ <RailFoot />411+ </nav>412+ );413+};added:apps/web/src/features/shared/shell/sections.ts+228 added
1+/**2+ * Where a reader can be: the site's sections, a project's, and the trail of3+ * crumbs from the site to the page at an address. The rail, the top bar,4+ * the bottom bar, the section row and the context bar all read them here,5+ * so one address names one place everywhere.6+ */7+import type { Posture } from "@repo/protocol/posture";8+import { Result } from "effect";9+10+/** Which of a project's pages is being read. */11+export type ProjectTab =12+ | "code"13+ | "env"14+ | "landings"15+ | "ledger"16+ | "overview"17+ | "people"18+ | "refs";19+20+/** One of a project's sections: its word, its page, and the tab it is. */21+export interface Section {22+ readonly label: string;23+ readonly tab: ProjectTab;24+ readonly to: string;25+}26+27+/**28+ * A project's sections (`project` as the address names it), in the order29+ * every list of them shows. The project's30+ * home is its asks; its `people` page is its policy (who decides, vouches,31+ * budgets), and reads so, at the address it has always had.32+ */33+export const projectSections = (project: string): readonly Section[] => [34+ { label: "Asks", tab: "overview", to: `/${project}` },35+ { label: "Code", tab: "code", to: `/${project}/tree/main` },36+ { label: "Landings", tab: "landings", to: `/${project}/commits/main` },37+ { label: "Refs", tab: "refs", to: `/${project}/refs` },38+ { label: "Policy", tab: "people", to: `/${project}/people` },39+ { label: "Ledger", tab: "ledger", to: `/${project}/ledger` },40+ { label: "Env shape", tab: "env", to: `/${project}/env` },41+];42+43+/** The first segment of each of a project's pages, by the section it sits in. */44+const SECTION_OF = {45+ answers: "overview",46+ asks: "overview",47+ blob: "code",48+ commit: "landings",49+ commits: "landings",50+ env: "env",51+ ledger: "ledger",52+ people: "people",53+ refs: "refs",54+ tree: "code",55+ why: "code",56+} as const satisfies Record<string, ProjectTab>;57+58+/** The site's own first segments: every other one names a project. */59+const SITE = new Set(["agents", "people", "today"]);60+61+/** `segment` decoded, or as it came when it does not decode. */62+const decoded = (segment: string) =>63+ Result.getOrElse(64+ Result.try(() => decodeURIComponent(segment)),65+ () => segment66+ );67+68+/** The address's segments, decoded. */69+const segmentsOf = (pathname: string) =>70+ pathname71+ .split("/")72+ .filter((segment) => segment !== "")73+ .map(decoded);74+75+/** The project an address is in, by its first segment; none on the site's own pages. */76+export const projectOf = (pathname: string): string | undefined => {77+ const [first] = segmentsOf(pathname);78+79+ return first === undefined || SITE.has(first) ? undefined : first;80+};81+82+/** The project section an address sits in; none for a page under none (a decision, a proposal). */83+export const sectionOf = (pathname: string): ProjectTab | undefined => {84+ const [first, second] = segmentsOf(pathname);85+86+ if (first === undefined || SITE.has(first)) {87+ return undefined;88+ }89+90+ return second === undefined91+ ? "overview"92+ : Object.entries(SECTION_OF).find(([segment]) => segment === second)?.[1];93+};94+95+/** One step of the trail to a page: its word, its page (none for the page itself), and whether it is an id. */96+export interface Crumb {97+ readonly label: string;98+ readonly mono?: boolean;99+ readonly to?: string;100+}101+102+const SECTION_LABEL = {103+ code: "Code",104+ env: "Env shape",105+ landings: "Landings",106+ ledger: "Ledger",107+ overview: "Asks",108+ people: "Policy",109+ refs: "Refs",110+} as const satisfies Record<ProjectTab, string>;111+112+/** A section's crumb, linked to its page when a page sits below it. */113+const sectionCrumb = (114+ project: string,115+ tab: ProjectTab,116+ below: boolean117+): Crumb => {118+ const label = SECTION_LABEL[tab];119+ const section = projectSections(project).find((each) => each.tab === tab);120+121+ return below && section !== undefined ? { label, to: section.to } : { label };122+};123+124+/** A project's crumb, then its section's. */125+const projectCrumbs = (126+ project: string,127+ tab: ProjectTab,128+ below: boolean129+): readonly Crumb[] => [130+ { label: project, to: `/${project}` },131+ sectionCrumb(project, tab, below),132+];133+134+/** A code page's trail: Code, then the path in hand (none at the root). */135+const pathCrumbs = (project: string, path: string): readonly Crumb[] =>136+ path === ""137+ ? projectCrumbs(project, "code", false)138+ : [...projectCrumbs(project, "code", true), { label: path, mono: true }];139+140+/** The site's own pages' trails, by first segment. */141+const SITE_CRUMBS = {142+ agents: () => [{ label: "For agents" }],143+ people: (handle: string | undefined) => [{ label: handle ?? "People" }],144+ today: () => [{ label: "Today" }],145+} as const satisfies Record<146+ string,147+ (second: string | undefined) => readonly Crumb[]148+>;149+150+/** A project's subject pages' trails (an ask, an answer, a commit, a path…), by second segment. */151+const SUBJECT_CRUMBS = {152+ answers: (project: string, ask: string) => [153+ ...projectCrumbs(project, "overview", true),154+ { label: ask, mono: true, to: `/${project}/asks/${ask}` },155+ { label: "Answer" },156+ ],157+ asks: (project: string, ask: string) => [158+ ...projectCrumbs(project, "overview", true),159+ { label: ask, mono: true },160+ ],161+ blob: (project: string, _rev: string, path: string) =>162+ pathCrumbs(project, path),163+ commit: (project: string, sha: string) => [164+ ...projectCrumbs(project, "landings", true),165+ { label: sha.slice(0, 7), mono: true },166+ ],167+ decisions: (project: string, decision: string) => [168+ { label: project, to: `/${project}` },169+ { label: "Today", to: "/today" },170+ { label: decision, mono: true },171+ ],172+ proposals: (project: string, proposal: string) => [173+ ...projectCrumbs(project, "overview", true),174+ proposal === "new" ? { label: "Propose" } : { label: proposal, mono: true },175+ ],176+ tree: (project: string, _rev: string, path: string) =>177+ pathCrumbs(project, path),178+ why: (project: string, _rev: string, path: string) =>179+ pathCrumbs(project, path),180+} as const satisfies Record<181+ string,182+ (project: string, third: string, rest: string) => readonly Crumb[]183+>;184+185+/**186+ * The trail from the site to the page at `pathname`: the project first, then187+ * its section, then the thing in hand (an ask, a commit, a path), each a188+ * link but the last. A page that knows better gives `Workspace` its own.189+ */190+export const crumbsFor = (pathname: string): readonly Crumb[] => {191+ const [first, second, third, ...rest] = segmentsOf(pathname);192+193+ if (first === undefined) {194+ return [{ label: "Asks" }];195+ }196+197+ const site = Object.entries(SITE_CRUMBS).find(([name]) => name === first);198+199+ if (site !== undefined) {200+ return site[1](second);201+ }202+203+ const subject = Object.entries(SUBJECT_CRUMBS).find(204+ ([name]) => name === second205+ );206+207+ if (subject !== undefined && third !== undefined) {208+ return subject[1](first, third, rest.join("/"));209+ }210+211+ const tab = sectionOf(pathname);212+213+ return tab === undefined214+ ? [215+ { label: first, to: `/${first}` },216+ { label: rest.at(-1) ?? third ?? second ?? first },217+ ]218+ : projectCrumbs(first, tab, false);219+};220+221+/** A posture in one short word for the rail, beside its mark; the full label is its title. */222+export const POSTURE_WORD = {223+ open: "Open",224+ openCore: "Core",225+ openOnSchedule: "Scheduled",226+ openWithSealedEvidence: "Sealed",227+ sourceAvailable: "Source",228+} as const satisfies Record<Posture, string>;added:apps/web/src/features/shared/shell/selection.ts+111 added
1+/**2+ * A list's selected row, kept in the address's search (`?ask=format-ordinal`,3+ * `?decision=dec-000001`), so the server renders the row selected with its4+ * facts in the inspector, and a link to them can be shared. Selecting5+ * replaces the history entry and keeps every pane's scroll; `Escape` clears6+ * it (`useEscapeClears`).7+ *8+ * A route whose list selects keeps the param out of its loader: `loaderDeps`9+ * leaves it out, so a selection never reads the list again, and10+ * `shouldReload: reloadOnEnter` keeps a list from reading again on every11+ * selection once it is stale.12+ *13+ * ```tsx14+ * const { selected, select } = useSelection("ask");15+ * const { focused } = useListKeys(ids, select);16+ * <Workspace facts={selected === undefined ? <ProjectFacts /> : <AskFacts ask={selected} />} factsKey={selected} … />17+ * ```18+ */19+import {20+ defaultStringifySearch,21+ useLocation,22+ useRouter,23+} from "@tanstack/react-router";24+import { Effect, Option, Schema } from "effect";25+import { useCallback } from "react";26+27+import { useEscapeClears } from "../keys.tsx";28+29+/** The search params a list selects by. */30+export type SelectionParam = "ask" | "decision";31+32+/** A selection as an address's search carries it. */33+const Selection = Schema.Struct({34+ ask: Schema.optionalKey(Schema.String),35+ decision: Schema.optionalKey(Schema.String),36+});37+38+const decodeSelection = Schema.decodeUnknownOption(Selection);39+40+/**41+ * `searchStr` (`?filter=…&ask=…`) with `param` set to `id`, or without it,42+ * each value written as the router writes it.43+ */44+export const searchWith = (45+ searchStr: string,46+ param: SelectionParam,47+ id?: string48+): string => {49+ const params = new URLSearchParams(searchStr);50+51+ params.delete(param);52+53+ if (id !== undefined) {54+ params.set(55+ param,56+ new URLSearchParams(defaultStringifySearch({ [param]: id })).get(param) ??57+ id58+ );59+ }60+61+ const next = params.toString();62+63+ return next === "" ? "" : `?${next}`;64+};65+66+export const useSelection = (param: SelectionParam) => {67+ const router = useRouter();68+ const { pathname, search, searchStr } = useLocation();69+70+ const selected = Option.getOrUndefined(71+ Option.flatMapNullishOr(decodeSelection(search), (read) => read[param])72+ );73+74+ const move = useCallback(75+ (id?: string) => {76+ Effect.runFork(77+ Effect.tryPromise(() =>78+ router.navigate({79+ href: `${pathname}${searchWith(searchStr, param, id)}`,80+ replace: true,81+ resetScroll: false,82+ })83+ ).pipe(Effect.ignore)84+ );85+ },86+ [param, pathname, router, searchStr]87+ );88+89+ const select = useCallback(90+ (id: string) => {91+ move(id);92+ },93+ [move]94+ );95+96+ const clear = useCallback(() => {97+ move();98+ }, [move]);99+100+ useEscapeClears(clear);101+102+ return { clear, select, selected };103+};104+105+/**106+ * A route's `shouldReload` for a list that selects: read the list when the107+ * reader comes to it (or a link to it is preloaded), not again on each108+ * selection; its atoms keep it live.109+ */110+export const reloadOnEnter = ({ cause }: { readonly cause: string }) =>111+ cause !== "stay";added:apps/web/src/features/shared/shell/top-bar.tsx+88 added
1+/**2+ * The top bar, below the shell's width, where the rail is not drawn. On a3+ * tablet (48 px): Menu (the rail as a sheet), the wordmark, the current4+ * project as a switcher, and the session at the end. On a phone (44 px):5+ * Back to the page above on a subject page (an ask, an answer, a commit),6+ * else the wordmark, then the project's switcher; the bottom bar holds the7+ * rest.8+ */9+import { useLocation } from "@tanstack/react-router";10+import { ChevronLeft, ChevronsUpDown, Menu } from "lucide-react";11+12+import { Button } from "../../../components/ui/button.tsx";13+import { SessionSlot } from "../../auth/session-slot.tsx";14+import { AppLink } from "../link.tsx";15+import { useCurrentProject, useShell } from "./context.ts";16+import { Wordmark } from "./rail.tsx";17+import { crumbsFor } from "./sections.ts";18+19+/** The page above a subject page (its crumb before last), when the address is one. */20+const parentOf = (pathname: string) => {21+ const crumbs = crumbsFor(pathname);22+ const parent = crumbs.at(-2);23+24+ return crumbs.length >= 3 && parent?.to !== undefined25+ ? { label: parent.label, to: parent.to }26+ : undefined;27+};28+29+export const TopBar = () => {30+ const { open } = useShell();31+ const project = useCurrentProject();32+ const parent = useLocation({ select: ({ pathname }) => parentOf(pathname) });33+34+ return (35+ <header className="border-rule bg-background tablet:h-12 tablet:px-3 shell:hidden sticky top-0 z-30 flex h-11 shrink-0 items-center gap-1 border-b px-2">36+ <Button37+ className="tablet:inline-flex hidden"38+ onClick={() => {39+ open("menu");40+ }}41+ size="sm"42+ variant="ghost"43+ >44+ <Menu aria-hidden="true" strokeWidth={1.75} />45+ Menu46+ </Button>47+ {parent === undefined ? (48+ <Wordmark className="px-2" />49+ ) : (50+ <>51+ <AppLink52+ className="text-ui hover:bg-surface tablet:hidden flex h-8 min-w-0 items-center gap-1 pr-2 pl-1 no-underline"53+ to={parent.to}54+ >55+ <ChevronLeft56+ aria-hidden="true"57+ className="size-4 shrink-0"58+ strokeWidth={1.75}59+ />60+ <span className="min-w-0 truncate">{parent.label}</span>61+ </AppLink>62+ <Wordmark className="tablet:inline hidden px-2" />63+ </>64+ )}65+ {project === undefined ? null : (66+ <Button67+ aria-label={`Project: ${project}. Switch project`}68+ className="text-ui ml-1 max-w-[45vw] min-w-0 font-semibold"69+ onClick={() => {70+ open("projects");71+ }}72+ size="sm"73+ variant="outline"74+ >75+ <span className="min-w-0 truncate">{project}</span>76+ <ChevronsUpDown77+ aria-hidden="true"78+ className="text-muted-foreground"79+ strokeWidth={1.75}80+ />81+ </Button>82+ )}83+ <div className="tablet:flex ml-auto hidden min-w-0 items-center">84+ <SessionSlot />85+ </div>86+ </header>87+ );88+};added:apps/web/src/features/shared/shell/workspace.tsx+316 added
1+/**2+ * One page's panes: main (the context bar, the page's head, its toolbar and3+ * its content) and, when the page has typed facts, the inspector, both4+ * rendered in one pass on the server. Every page renders one `Workspace`.5+ *6+ * From the shell's width main scrolls on its own and the inspector is a7+ * column of its own scroll on the right, its heading announcing what it8+ * describes as it changes. Below it, the facts sit in one slot after the9+ * page's head: open on a subject's page, a disclosure on a list's (whose10+ * summary keeps one fact in sight). Code pages keep the width for the code:11+ * the inspector is a column from 1440 px and a sheet below, behind a Facts12+ * button in the context bar.13+ *14+ * Rows and the head stop at 56 rem, left-aligned; prose at 70 ch is the15+ * page's; code takes the whole pane.16+ */17+import { useHydrated, useLocation, useRouter } from "@tanstack/react-router";18+import { Predicate } from "effect";19+import { ChevronDown, PanelRight } from "lucide-react";20+import { Suspense, useState } from "react";21+import type { ReactNode } from "react";22+23+import { Button } from "../../../components/ui/button.tsx";24+import { CommandSlotProvider } from "../keys.tsx";25+import { ContextBar } from "./context-bar.tsx";26+import { LazyFactsSheet } from "./lazy-overlays.ts";27+import { crumbsFor } from "./sections.ts";28+import type { Crumb } from "./sections.ts";29+30+export interface WorkspaceProps {31+ /** The trail to the page; the address's when left out. */32+ readonly crumbs?: readonly Crumb[];33+ /** The page head's title: the headline, or a title when it runs long. */34+ readonly title: ReactNode;35+ /** A status line under the title. */36+ readonly status?: ReactNode;37+ /** A 14 px muted line under the status: kind, asker, age. */38+ readonly meta?: ReactNode;39+ /** The subject's state in a word and a mark, at the context bar's end. */40+ readonly state?: ReactNode;41+ /** A list's count, at the context bar's end ("10 open asks, 8 open to take"). */42+ readonly count?: string;43+ /** The page's one command, copied from the context bar. */44+ readonly primaryCommand?: string;45+ /** Filters, view toggles, sort: a bar that stays under the context bar. */46+ readonly toolbar?: ReactNode;47+ /** The inspector's fact blocks; inline below the shell's width. */48+ readonly facts?: ReactNode;49+ /** What the facts describe: "This ask", "Selected ask", "How a change lands here". */50+ readonly factsHeading?: string;51+ /** The one fact a list keeps in sight below the shell's width (its posture). */52+ readonly factsSummary?: ReactNode;53+ /** The facts' subject (a selected row's id): a new one settles in. */54+ readonly factsKey?: string;55+ /** A document (the default), a list, or code. */56+ readonly variant?: "code" | "document" | "list";57+ /** Main's content. */58+ readonly children: ReactNode;59+}60+61+/** Main's side padding at each width. */62+export const GUTTER = "px-4 tablet:px-5 shell:px-6";63+64+/** How wide rows and the head run: 56 rem, from the left. */65+export const MEASURE = "max-w-[56rem]";66+67+/** Past this many characters a title is set a step down, to stay within three lines. */68+const LONG_TITLE = 80;69+70+const PageHead = ({71+ meta,72+ status,73+ title,74+}: Pick<WorkspaceProps, "meta" | "status" | "title">) => (75+ <div className="flex flex-col gap-4 pt-6 pb-6">76+ <h177+ className={`text-balance break-words ${78+ Predicate.isString(title) && title.length > LONG_TITLE79+ ? "text-title"80+ : "text-headline"81+ }`}82+ >83+ {title}84+ </h1>85+ {status === undefined ? null : <div>{status}</div>}86+ {meta === undefined ? null : (87+ <div className="text-ui text-muted-foreground">{meta}</div>88+ )}89+ </div>90+);91+92+/** The inspector's heading row: names what the facts describe, and announces it when it changes. */93+const FactsHeading = ({ heading }: { readonly heading: string }) => (94+ <div95+ aria-live="polite"96+ className="border-rule bg-background sticky top-0 z-10 flex h-11 shrink-0 items-center border-b px-4"97+ >98+ <h2 className="text-ui font-semibold">{heading}</h2>99+ </div>100+);101+102+/** The facts settling in when their subject changes: 120 ms of opacity, nothing that moves. */103+const Settling = ({104+ children,105+ id,106+}: {107+ readonly children: ReactNode;108+ readonly id: string | undefined;109+}) => (110+ <div className="animate-in fade-in-0 flex flex-col duration-[120ms]" key={id}>111+ {children}112+ </div>113+);114+115+/** The facts in main, after the head, below the shell's width. */116+const InlineFacts = ({117+ facts,118+ heading,119+ list,120+ summary,121+}: {122+ readonly facts: ReactNode;123+ readonly heading: string;124+ readonly list: boolean;125+ readonly summary: ReactNode;126+}) =>127+ list ? (128+ <details129+ className={`group border-rule shell:hidden mb-6 border-y ${MEASURE}`}130+ data-facts="inline"131+ >132+ <summary className="text-ui hover:bg-surface flex min-h-11 cursor-pointer list-none items-center gap-3 py-2 transition-colors duration-[120ms] [&::-webkit-details-marker]:hidden">133+ <span className="font-semibold">{heading}</span>134+ {summary === undefined ? null : (135+ <span className="text-muted-foreground min-w-0 flex-1 truncate">136+ {summary}137+ </span>138+ )}139+ <ChevronDown140+ aria-hidden="true"141+ className="text-muted-foreground ml-auto size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"142+ strokeWidth={1.75}143+ />144+ </summary>145+ <div className="flex flex-col pb-4">{facts}</div>146+ </details>147+ ) : (148+ <section149+ aria-label={heading}150+ className={`border-rule shell:hidden mb-6 border-y py-4 ${MEASURE}`}151+ data-facts="inline"152+ >153+ <h2 className="text-ui mb-2 font-semibold">{heading}</h2>154+ <div className="flex flex-col">{facts}</div>155+ </section>156+ );157+158+/** A code page's Facts button, and its facts as a sheet from the right. */159+const FactsSheet = ({160+ facts,161+ heading,162+}: {163+ readonly facts: ReactNode;164+ readonly heading: string;165+}) => {166+ const [open, setOpen] = useState(false);167+ const hydrated = useHydrated();168+169+ return (170+ <>171+ <Button172+ aria-haspopup="dialog"173+ className="codefacts:hidden"174+ onClick={() => {175+ setOpen(true);176+ }}177+ size="sm"178+ variant="outline"179+ >180+ <PanelRight aria-hidden="true" strokeWidth={1.75} />181+ Facts182+ </Button>183+ {hydrated && LazyFactsSheet !== undefined ? (184+ <Suspense fallback={null}>185+ <LazyFactsSheet186+ content={facts}187+ heading={heading}188+ onOpenChange={setOpen}189+ open={open}190+ />191+ </Suspense>192+ ) : null}193+ </>194+ );195+};196+197+const WorkspaceView = ({198+ children,199+ count,200+ crumbs,201+ facts,202+ factsHeading = "Facts",203+ factsKey,204+ factsSummary,205+ meta,206+ primaryCommand,207+ state,208+ status,209+ title,210+ toolbar,211+ pathname,212+ variant = "document",213+}: WorkspaceProps & {214+ /** The address, for the default trail; none outside a router. */215+ readonly pathname: string;216+}) => {217+ const hasFacts = facts !== undefined && facts !== null;218+ const code = variant === "code";219+220+ return (221+ <>222+ <main223+ className="shell:h-dvh shell:overflow-y-auto flex min-w-0 flex-1 flex-col outline-none"224+ data-scroll-restoration-id="main"225+ data-variant={variant}226+ id="main"227+ tabIndex={-1}228+ >229+ <CommandSlotProvider slot="main">230+ <ContextBar231+ count={count}232+ crumbs={crumbs ?? crumbsFor(pathname)}233+ end={234+ code && hasFacts ? (235+ // The sheet belongs to the page it opened on.236+ <FactsSheet237+ facts={facts}238+ heading={factsHeading}239+ key={pathname}240+ />241+ ) : undefined242+ }243+ primaryCommand={primaryCommand}244+ state={state}245+ />246+ <div className={`${GUTTER} ${code ? "" : MEASURE}`}>247+ <PageHead meta={meta} status={status} title={title} />248+ </div>249+ {hasFacts && !code ? (250+ <CommandSlotProvider slot="facts">251+ <div className={GUTTER}>252+ <InlineFacts253+ facts={facts}254+ heading={factsHeading}255+ list={variant === "list"}256+ summary={factsSummary}257+ />258+ </div>259+ </CommandSlotProvider>260+ ) : null}261+ {toolbar === undefined ? null : (262+ <div263+ className={`border-rule bg-background tablet:top-[2.9375rem] shell:top-[2.6875rem] sticky top-[2.6875rem] z-10 flex h-10 shrink-0 items-center gap-3 border-y ${GUTTER}`}264+ data-toolbar=""265+ >266+ {toolbar}267+ </div>268+ )}269+ <div270+ className={`flex flex-1 flex-col gap-8 pb-16 ${271+ code ? "" : `${GUTTER} ${MEASURE}`272+ } ${toolbar === undefined ? "" : "pt-6"}`}273+ >274+ {children}275+ </div>276+ </CommandSlotProvider>277+ </main>278+ {hasFacts ? (279+ <aside280+ aria-label="Facts"281+ className={`border-rule bg-background h-dvh w-[19rem] shrink-0 flex-col overflow-y-auto overscroll-contain border-l ${282+ code ? "codefacts:flex hidden" : "shell:flex hidden"283+ }`}284+ data-facts="inspector"285+ id="facts"286+ >287+ <CommandSlotProvider slot="facts">288+ <FactsHeading heading={factsHeading} />289+ <div className="flex flex-col px-4 py-4">290+ <Settling id={factsKey}>{facts}</Settling>291+ </div>292+ </CommandSlotProvider>293+ </aside>294+ ) : null}295+ </>296+ );297+};298+299+const AtAddress = (props: WorkspaceProps) => (300+ <WorkspaceView301+ {...props}302+ pathname={useLocation({ select: (location) => location.pathname })}303+ />304+);305+306+/**307+ * A page's panes. Inside the router its trail defaults to its address's; a308+ * view rendered alone (its own test) draws the same panes with the trail309+ * it is given.310+ */311+export const Workspace = (props: WorkspaceProps) =>312+ Predicate.isNotNullish(useRouter({ warn: false })) ? (313+ <AtAddress {...props} />314+ ) : (315+ <WorkspaceView {...props} pathname="" />316+ );modified:apps/web/src/features/shared/head.ts+33 added
4 unmodified lines5 import { Brand } from "@repo/brand";6 7 /** A page's `<title>`: the page, then the product. */8 export const pageTitle = (title: string) => `${title} · ${Brand.name}`;9+10+/**11+ * A page's head: its `<title>`, and what a shared link unfurls with (the12+ * description and the Open Graph title, description and type; no image).13+ * The router keeps one meta per name or Open Graph property, the last a14+ * route gives, so a page's replace the root's, and a page with no15+ * description of its own unfurls with the root's.16+ *17+ * ```ts18+ * head: ({ params }) => pageHead({ title: `${params.ask} · ${params.project}`, description: want }),19+ * ```20+ */21+export const pageHead = ({22+ description,23+ title,24+ type = "website",25+}: {26+ readonly description?: string;27+ readonly title: string;28+ readonly type?: "article" | "website";29+}) => ({30+ meta: [31+ { title: pageTitle(title) },32+ { content: title, property: "og:title" },33+ { content: type, property: "og:type" },34+ ...(description === undefined35+ ? []36+ : [37+ { content: description, name: "description" },38+ { content: description, property: "og:description" },39+ ]),40+ ],41+});added:apps/web/src/features/shared/keys.tsx+616 added
1+/**2+ * The keyboard's single keys, one listener for the whole shell:3+ *4+ * - `?` opens the keys dialog, which lists them and holds the switch;5+ * - `j` / `k` move through the page's list (its rows, `useListKeys`), and at6+ * the shell's width select the row, so the inspector follows; `Enter`7+ * opens the focused row, as a link does;8+ * - `J` / `K` move between the page's files (`useFileKeys`);9+ * - `1` to `9` copy the page's numbered commands, the inspector's first10+ * (`useNumberedCommand`);11+ * - `Escape` clears the selection (a sheet or a dialog closes itself).12+ *13+ * No key acts while focus is in a text field, a combobox or the tree's14+ * search, or with Ctrl, Alt or Meta held. Every key has a twin a pointer15+ * reaches: rows are links, files are the tree's rows, commands have their16+ * copy buttons. The switch turns every key but `?` off (WCAG 2.2 SC 2.1.4)17+ * and is the viewer's own: kept in this browser's storage, on until turned18+ * off, and on whenever the storage cannot be read.19+ */20+import { Effect, Option, Result } from "effect";21+import {22+ createContext,23+ useCallback,24+ useContext,25+ useEffect,26+ useId,27+ useMemo,28+ useRef,29+ useState,30+} from "react";31+import type { ReactNode } from "react";32+33+import { Kbd } from "../../components/ui/kbd.tsx";34+35+/** A key pressed, as the listener reads it. */36+export interface KeyPress {37+ readonly altKey: boolean;38+ readonly ctrlKey: boolean;39+ /** Whether focus is in a text field, a combobox or a search. */40+ readonly inField: boolean;41+ readonly key: string;42+ readonly metaKey: boolean;43+}44+45+/** What a key asks for. */46+export type KeyIntent =47+ | { readonly index: number; readonly kind: "copy" }48+ | {49+ readonly kind:50+ | "clear"51+ | "keys"52+ | "next"53+ | "nextFile"54+ | "previous"55+ | "previousFile";56+ };57+58+const MOVES = {59+ J: "nextFile",60+ K: "previousFile",61+ j: "next",62+ k: "previous",63+} as const satisfies Record<string, KeyIntent["kind"]>;64+65+const DIGIT = /^[1-9]$/u;66+67+/** The shell's width, from which the rail and the inspector are columns. */68+const SHELL_WIDTH = "(min-width: 70rem)";69+70+/**71+ * What `press` asks for, with the single keys `on` or off; nothing for a72+ * press in a text field, with a modifier held, or with no meaning here.73+ */74+export const intentOf = (75+ press: KeyPress,76+ on: boolean77+): KeyIntent | undefined => {78+ if (press.inField || press.altKey || press.ctrlKey || press.metaKey) {79+ return undefined;80+ }81+82+ if (press.key === "?") {83+ return { kind: "keys" };84+ }85+86+ if (press.key === "Escape") {87+ return { kind: "clear" };88+ }89+90+ if (!on) {91+ return undefined;92+ }93+94+ if (DIGIT.test(press.key)) {95+ return { index: Number(press.key), kind: "copy" };96+ }97+98+ const move = Object.entries(MOVES).find(([key]) => key === press.key);99+100+ return move === undefined ? undefined : { kind: move[1] };101+};102+103+/** Where the switch is kept, in the browser's storage. */104+const SWITCH = "keys.single";105+106+/** Whether the single keys are on: on unless `storage` says off, or cannot say. */107+export const readShortcuts = (storage?: Storage): boolean =>108+ storage === undefined ||109+ Result.getOrElse(110+ Result.try(() => storage.getItem(SWITCH) !== "off"),111+ () => true112+ );113+114+/** Keep the switch as `on` says; a storage that refuses keeps nothing. */115+export const writeShortcuts = (storage: Storage | undefined, on: boolean) => {116+ Result.try(() => storage?.setItem(SWITCH, on ? "on" : "off"));117+};118+119+/** The browser's storage, when there is one this page may use. */120+const localStorageOf = (): Storage | undefined =>121+ Result.getOrUndefined(Result.try(() => globalThis.localStorage));122+123+/** The keys and what each does, as the dialog lists them. */124+const KEYS = [125+ { does: "Show these keys", keys: ["?"] },126+ { does: "Next or previous row", keys: ["j", "k"] },127+ { does: "Open the focused row", keys: ["Enter"] },128+ { does: "Next or previous file", keys: ["J", "K"] },129+ { does: "Copy the page's numbered command", keys: ["1", "…", "9"] },130+ { does: "Close, or clear the selection", keys: ["Esc"] },131+] as const;132+133+/** The switch's two settings, each a button that says whether it is pressed. */134+const SETTINGS = [135+ { label: "On", on: true },136+ { label: "Off", on: false },137+] as const;138+139+/**140+ * The keys dialog's body: every key with what it does, and the switch. `?`141+ * opens it even with the switch off, so the switch is always in reach.142+ */143+export const KeysHelp = ({144+ on,145+ onChange,146+}: {147+ readonly on: boolean;148+ readonly onChange: (on: boolean) => void;149+}) => (150+ <div className="flex flex-col gap-5">151+ <dl className="text-ui grid grid-cols-[auto_1fr] gap-x-4 gap-y-2.5">152+ {KEYS.map(({ does, keys }) => (153+ <div className="contents" key={does}>154+ <dt className="flex items-center gap-1">155+ {keys.map((key) =>156+ key === "…" ? (157+ <span className="text-muted-foreground" key={key}>158+ to159+ </span>160+ ) : (161+ <Kbd className="text-foreground font-mono" key={key}>162+ {key}163+ </Kbd>164+ )165+ )}166+ </dt>167+ <dd>{does}</dd>168+ </div>169+ ))}170+ </dl>171+ <fieldset className="border-rule flex flex-wrap items-center justify-between gap-3 border-t pt-4">172+ <legend className="text-ui float-left font-medium">173+ Single-key shortcuts174+ </legend>175+ <div className="border-input flex border">176+ {SETTINGS.map(({ label, on: setting }) => (177+ <button178+ aria-pressed={on === setting}179+ className="text-ui aria-pressed:bg-foreground aria-pressed:text-background hover:bg-surface aria-pressed:hover:bg-foreground h-8 cursor-pointer px-3 font-medium transition-colors duration-150"180+ key={label}181+ onClick={() => {182+ onChange(setting);183+ }}184+ type="button"185+ >186+ {label}187+ </button>188+ ))}189+ </div>190+ </fieldset>191+ <p className="text-muted-foreground text-label">192+ Off, only ? acts. No key acts while you type in a field.193+ </p>194+ </div>195+);196+197+/** Which part of the page a command sits in: the inspector's are numbered first. */198+export type CommandSlot = "facts" | "main";199+200+const SlotContext = createContext<CommandSlot>("main");201+202+/** Commands under `slot` number as the inspector's or main's. */203+export const CommandSlotProvider = ({204+ children,205+ slot,206+}: {207+ readonly children: ReactNode;208+ readonly slot: CommandSlot;209+}) => <SlotContext value={slot}>{children}</SlotContext>;210+211+/** A list the page lets `j` and `k` move through. */212+interface ListRegistration {213+ readonly focus: (id: string) => void;214+ readonly read: () => {215+ readonly ids: readonly string[];216+ readonly onSelect: (id: string) => void;217+ };218+ focused?: string;219+}220+221+/** The files a page lets `J` and `K` move between. */222+interface FileRegistration {223+ readonly read: () => {224+ readonly onMove: (path: string) => void;225+ readonly paths: readonly string[];226+ };227+ at?: string;228+}229+230+interface Command {231+ readonly command: string;232+ readonly id: string;233+ readonly slot: CommandSlot;234+}235+236+/** What the page registers with the listener; one for the shell's life. */237+interface Registry {238+ readonly clearers: Set<() => void>;239+ readonly files: Set<FileRegistration>;240+ readonly lists: Set<ListRegistration>;241+ readonly register: (command: Command) => () => void;242+}243+244+/** What the keys show: whether they are on, the numbers, the last copy. */245+interface KeysState {246+ readonly copied: string | undefined;247+ readonly numbered: ReadonlyMap<string, number>;248+ readonly on: boolean;249+ readonly setOn: (on: boolean) => void;250+}251+252+const RegistryContext = createContext<Registry | undefined>(undefined);253+254+const StateContext = createContext<KeysState | undefined>(undefined);255+256+/** The keys' state, for the dialog. */257+export const useKeys = () => useContext(StateContext);258+259+/** `item` in `set` until the returned function takes it out. */260+const held = <A,>(set: Set<A>, item: A) => {261+ set.add(item);262+263+ return () => {264+ set.delete(item);265+ };266+};267+268+/** The last registered of `set`: the page's own, over any that left late. */269+const lastOf = <A,>(set: ReadonlySet<A>): A | undefined => [...set].at(-1);270+271+/** Whether `event` was pressed inside something that takes typing. */272+const inField = (event: KeyboardEvent) => {273+ const [target] = event.composedPath();274+275+ return (276+ target instanceof HTMLElement &&277+ (target.isContentEditable ||278+ target.closest(279+ "input, textarea, select, [role=combobox], [role=searchbox], [role=textbox], [data-keys-off]"280+ ) !== null)281+ );282+};283+284+/** Numbers commands 1 to 9: the inspector's first, each command once. */285+const numberOf = (286+ commands: readonly Command[]287+): ReadonlyMap<string, number> => {288+ const ordered = [289+ ...commands.filter(({ slot }) => slot === "facts"),290+ ...commands.filter(({ slot }) => slot === "main"),291+ ];292+293+ const unique = [...new Set(ordered.map(({ command }) => command))];294+295+ return new Map(296+ unique.slice(0, 9).map((command, index) => [command, index + 1])297+ );298+};299+300+/** Copy `command`, then mark it copied for two seconds. */301+const copyNumbered = (command: string, shown: (copied?: string) => void) =>302+ Effect.tryPromise(() => navigator.clipboard.writeText(command)).pipe(303+ Effect.andThen(304+ Effect.sync(() => {305+ shown(command);306+ })307+ ),308+ Effect.andThen(Effect.sleep("2 seconds")),309+ Effect.andThen(310+ Effect.sync(() => {311+ shown();312+ })313+ ),314+ Effect.ignore315+ );316+317+/** The row a key moved to: focused, scrolled to, and selected at the shell's width. */318+const moveTo = (list: ListRegistration, step: 1 | -1) => {319+ const { ids, onSelect } = list.read();320+ const at = list.focused === undefined ? -1 : ids.indexOf(list.focused);321+322+ const next =323+ ids[324+ Math.min(325+ Math.max(at === -1 && step === -1 ? 0 : at + step, 0),326+ ids.length - 1327+ )328+ ];329+330+ if (next === undefined) {331+ return;332+ }333+334+ list.focused = next;335+ list.focus(next);336+337+ const row = document.querySelector(`[data-list-key="${CSS.escape(next)}"]`);338+339+ if (row instanceof HTMLElement) {340+ row.focus({ preventScroll: true });341+ row.scrollIntoView({ block: "nearest" });342+ }343+344+ // The inspector is a column at the shell's width, so a move selects there.345+ if (globalThis.matchMedia(SHELL_WIDTH).matches) {346+ onSelect(next);347+ }348+};349+350+const moveFile = (files: FileRegistration, step: 1 | -1) => {351+ const { onMove, paths } = files.read();352+ const at = files.at === undefined ? -1 : paths.indexOf(files.at);353+ const next = paths[Math.min(Math.max(at + step, 0), paths.length - 1)];354+355+ if (next !== undefined) {356+ files.at = next;357+ onMove(next);358+ }359+};360+361+/** What the listener reads when a key is pressed. */362+interface Pressing {363+ readonly copy: (command: string) => void;364+ readonly numbered: ReadonlyMap<string, number>;365+ readonly on: boolean;366+ readonly openDialog: () => void;367+ readonly registry: Registry;368+}369+370+/** Do what `intent` asks; whether it did anything (so the browser does not too). */371+const act = (intent: KeyIntent, now: Pressing): boolean => {372+ const { registry } = now;373+374+ if (intent.kind === "keys") {375+ now.openDialog();376+377+ return true;378+ }379+380+ if (intent.kind === "clear") {381+ // An open sheet or dialog closes itself on Escape.382+ if (document.querySelector('[role="dialog"]') === null) {383+ lastOf(registry.clearers)?.();384+ }385+386+ return false;387+ }388+389+ if (intent.kind === "copy") {390+ const command = [...now.numbered].find(391+ ([, index]) => index === intent.index392+ )?.[0];393+394+ if (command !== undefined) {395+ now.copy(command);396+ }397+398+ return command !== undefined;399+ }400+401+ if (intent.kind === "next" || intent.kind === "previous") {402+ const list = lastOf(registry.lists);403+404+ if (list !== undefined) {405+ moveTo(list, intent.kind === "next" ? 1 : -1);406+ }407+408+ return list !== undefined;409+ }410+411+ const files = lastOf(registry.files);412+413+ if (files !== undefined) {414+ moveFile(files, intent.kind === "nextFile" ? 1 : -1);415+ }416+417+ return files !== undefined;418+};419+420+/**421+ * The shell's one listener and the state behind it. `openDialog` opens the422+ * keys dialog (the shell draws it).423+ */424+export const KeysProvider = ({425+ children,426+ openDialog,427+}: {428+ readonly children: ReactNode;429+ readonly openDialog: () => void;430+}) => {431+ // The server has no storage and renders the keys on; nothing it renders432+ // depends on them (a command's number comes once the page has run).433+ const [on, setOn] = useState(() => readShortcuts(localStorageOf()));434+ const [commands, setCommands] = useState<readonly Command[]>([]);435+ const [copied, setCopied] = useState<string>();436+437+ const registry = useMemo<Registry>(438+ () => ({439+ clearers: new Set(),440+ files: new Set(),441+ lists: new Set(),442+ register: (command) => {443+ setCommands((now) => [...now, command]);444+445+ return () => {446+ setCommands((now) => now.filter(({ id }) => id !== command.id));447+ };448+ },449+ }),450+ []451+ );452+453+ const turn = useCallback((next: boolean) => {454+ setOn(next);455+ writeShortcuts(localStorageOf(), next);456+ }, []);457+458+ const numbered = useMemo(() => numberOf(commands), [commands]);459+460+ // The listener reads the latest of these, kept here after each render.461+ const pressing = useRef<Pressing | null>(null);462+463+ useEffect(() => {464+ pressing.current = {465+ copy: (command) => {466+ Effect.runFork(copyNumbered(command, setCopied));467+ },468+ numbered,469+ on,470+ openDialog,471+ registry,472+ };473+ });474+475+ useEffect(() => {476+ const onKey = (event: KeyboardEvent) => {477+ const now = pressing.current;478+479+ if (now === null || event.defaultPrevented || event.repeat) {480+ return;481+ }482+483+ const intent = intentOf(484+ {485+ altKey: event.altKey,486+ ctrlKey: event.ctrlKey,487+ inField: inField(event),488+ key: event.key,489+ metaKey: event.metaKey,490+ },491+ now.on492+ );493+494+ if (intent !== undefined && act(intent, now)) {495+ event.preventDefault();496+ }497+ };498+499+ document.addEventListener("keydown", onKey);500+501+ return () => {502+ document.removeEventListener("keydown", onKey);503+ };504+ }, []);505+506+ const state = useMemo(507+ () => ({ copied, numbered, on, setOn: turn }),508+ [copied, numbered, on, turn]509+ );510+511+ return (512+ <RegistryContext value={registry}>513+ <StateContext value={state}>514+ {children}515+ <output aria-live="polite" className="sr-only">516+ {copied === undefined ? "" : `Copied: ${copied}`}517+ </output>518+ </StateContext>519+ </RegistryContext>520+ );521+};522+523+/** `value`, kept current in a ref after each render, for a handler to read later. */524+const useLatest = <A,>(value: A) => {525+ const latest = useRef(value);526+527+ useEffect(() => {528+ latest.current = value;529+ });530+531+ return latest;532+};533+534+/**535+ * Let `j` and `k` move through `ids` (the page's rows, in order); at the536+ * shell's width each move also selects the row (`onSelect`). Give each row's537+ * link `data-list-key={id}` so the move focuses it and `Enter` opens it.538+ * Returns the row the keys rest on, to draw as focused.539+ */540+export const useListKeys = (541+ ids: readonly string[],542+ onSelect: (id: string) => void543+): { readonly focused?: string } => {544+ const registry = useContext(RegistryContext);545+ const [focused, setFocused] = useState<string>();546+ const latest = useLatest({ ids, onSelect });547+548+ useEffect(549+ () =>550+ registry === undefined551+ ? undefined552+ : held(registry.lists, {553+ focus: setFocused,554+ read: () => latest.current,555+ }),556+ [latest, registry]557+ );558+559+ return focused === undefined ? {} : { focused };560+};561+562+/** Let `J` and `K` move between `paths` (the page's files, in order), each move calling `onMove`. */563+export const useFileKeys = (564+ paths: readonly string[],565+ onMove: (path: string) => void566+): void => {567+ const registry = useContext(RegistryContext);568+ const latest = useLatest({ onMove, paths });569+570+ useEffect(571+ () =>572+ registry === undefined573+ ? undefined574+ : held(registry.files, { read: () => latest.current }),575+ [latest, registry]576+ );577+};578+579+/**580+ * Number `command` among the page's commands: the digit that copies it, while581+ * the single keys are on, to show before it ("Copy (1)"); nothing when they582+ * are off or it is past the ninth.583+ */584+export const useNumberedCommand = (command: string): number | undefined => {585+ const registry = useContext(RegistryContext);586+ const state = useContext(StateContext);587+ const slot = useContext(SlotContext);588+ const id = useId();589+590+ useEffect(591+ () => registry?.register({ command, id, slot }),592+ [command, id, registry, slot]593+ );594+595+ return state?.on === true ? state.numbered.get(command) : undefined;596+};597+598+/** The command a number key copied in the last two seconds, to show as copied. */599+export const useCopiedCommand = (): Option.Option<string> =>600+ Option.fromUndefinedOr(useContext(StateContext)?.copied);601+602+/** Let `Escape` call `clear` while the caller is on the page (the selection's). */603+export const useEscapeClears = (clear: () => void): void => {604+ const registry = useContext(RegistryContext);605+ const latest = useLatest(clear);606+607+ useEffect(608+ () =>609+ registry === undefined610+ ? undefined611+ : held(registry.clearers, () => {612+ latest.current();613+ }),614+ [latest, registry]615+ );616+};modified:apps/web/src/features/shared/layout.tsx+15 added-99 removed
1 /**2- * The shell every page shares: the site header (front page, Today, Agents,3- * the session), one main region per page headed by its title over a double4- * rule, and the footer's ways in (plain git, the CLI, and the Agents page).5- * The root route composes them (`src/routes/__root.tsx`); a page renders6- * `PageShell`.2+ * What every page renders inside the shell (`shell/app-shell.tsx`):3+ * `PageShell`, a page with a title and no facts, drawn by the shell's4+ * `Workspace` (its context bar names the page from its address), for the5+ * pages that have not yet come to `Workspace` themselves; and the skip link6+ * the shell puts first, so a keyboard passes the rail to the page.7 */8-import { Brand } from "@repo/brand";8 import type { ReactNode } from "react";9 11-import { CommandLine } from "./command.tsx";10+import { Workspace } from "./shell/workspace.tsx";11 13-/** The content column every region lines up on. */14-const COLUMN = "mx-auto w-full max-w-6xl px-4 sm:px-6";15-12 export const PageShell = ({13 children,14 title,15 }: {16 readonly children: ReactNode;17 readonly title: string;22-}) => (23- <main className={`${COLUMN} flex-1 pt-6 pb-16 sm:pt-8`} id="main">24- <h1 className="border-rule-strong border-b-[3px] border-double pb-2 text-2xl font-semibold tracking-[-0.02em] text-balance">25- {title}26- </h1>27- <div className="mt-6 flex flex-col gap-8">{children}</div>28- </main>29-);18+}) => <Workspace title={title}>{children}</Workspace>;19 31-const NAV = [32- { href: "/", label: "Asks" },33- { href: "/today", label: "Today" },34- { href: "/agents", label: "Agents" },35-] as const;36-37-/** Whether `href` is the page at `pathname`, or the section it heads. */38-const isCurrent = (href: string, pathname: string) =>39- href === "/" ? pathname === "/" : pathname.startsWith(href);40-41-export const SiteHeader = ({42- pathname,43- session,44-}: {45- readonly pathname: string;46- readonly session: ReactNode;47-}) => (48- <header className="border-rule border-b">49- <a50- className="focus:bg-background sr-only focus:not-sr-only focus:absolute focus:top-2 focus:left-2 focus:z-50 focus:px-3 focus:py-2"51- href="#main"52- >53- Skip to content54- </a>20+/** The first stop of a keyboard on every page: straight to main, past the rail. */21+export const SkipLink = () => (22+ <a23+ className="bg-background text-ui sr-only z-50 px-3 py-2 font-medium focus:not-sr-only focus:fixed focus:top-2 focus:left-2"24+ href="#main"25+ >26+ Skip to content27+ </a>55- <div className={`${COLUMN} flex h-12 items-center gap-4 sm:gap-6`}>56- <a57- className="text-base font-bold tracking-[-0.02em] no-underline"58- href="/"59- >60- {Brand.name}61- </a>62- <nav aria-label="Main" className="flex h-full items-stretch gap-4">63- {NAV.map(({ href, label }) => (64- <a65- aria-current={isCurrent(href, pathname) ? "page" : undefined}66- className="text-muted-foreground hover:text-foreground aria-[current=page]:border-rule-strong aria-[current=page]:text-foreground flex items-center border-b-2 border-transparent pt-0.5 text-sm no-underline aria-[current=page]:font-medium"67- href={href}68- key={href}69- >70- {label}71- </a>72- ))}73- </nav>74- <div className="ml-auto flex min-w-0 items-center text-sm">{session}</div>75- </div>76- </header>28 );78-79-export const SiteFooter = ({80- platformUrl,81-}: {82- readonly platformUrl: string;83-}) => (84- <footer className="border-rule border-t">85- <div className={`${COLUMN} grid gap-6 py-8 sm:grid-cols-3`}>86- <section className="flex min-w-0 flex-col gap-2">87- <h2 className="text-muted-foreground text-label">88- Plain git: clone any project89- </h2>90- <CommandLine command={`git clone ${platformUrl}/<project>.git`} />91- </section>92- <section className="flex min-w-0 flex-col gap-2">93- <h2 className="text-muted-foreground text-label">94- Install the {Brand.cli} CLI95- </h2>96- <CommandLine command={`curl -fsSL ${platformUrl}/install.sh | sh`} />97- </section>98- <section className="flex min-w-0 flex-col gap-2">99- <h2 className="text-muted-foreground text-label">Connect an agent</h2>100- <p className="text-sm">101- <a102- className="decoration-rule underline hover:decoration-current"103- href="/agents"104- >105- MCP, the CLI, llms.txt and skills106- </a>107- , with the setup for each agent.108- </p>109- </section>110- </div>111- </footer>112-);added:apps/web/src/features/shared/link.tsx+90 added
1+/**2+ * The one link between the web's pages: the router's `Link`, so a click3+ * moves without reloading the document, and a hover or focus fetches the4+ * page's code and loader data first (the router's `defaultPreload` is5+ * "intent", `src/router.tsx`). The router marks the link to the page being6+ * read with `aria-current="page"` and `data-status="active"`.7+ *8+ * `to` is a path built whole, as `paths.ts` builds them (`askPath(project,9+ * ask)`), with its search as `search`; the router reads its params from it10+ * as it reads them from a typed address.11+ *12+ * A view rendered with no router around it (its own test, with13+ * `renderToStaticMarkup`) draws the same address as a plain anchor, so its14+ * markup reads the same either way; the shell's own test renders inside a15+ * router (`test/render.tsx`) and checks its links are the router's.16+ *17+ * Only pages the router serves take an `AppLink`. A server route (sign-in,18+ * a raw file, a `.md` twin, `llms.txt`) is a plain `<a>`, or the router would19+ * look for a page that is not there.20+ */21+import {22+ defaultStringifySearch,23+ Link,24+ useRouter,25+} from "@tanstack/react-router";26+import type { ActiveOptions, AnyRouter } from "@tanstack/react-router";27+import { Predicate } from "effect";28+import { createElement } from "react";29+import type { AnchorHTMLAttributes, ReactNode } from "react";30+31+/** An `AppLink`'s props: an anchor's, with the address as `to`. */32+export interface AppLinkProps extends Omit<33+ AnchorHTMLAttributes<HTMLAnchorElement>,34+ "href" | "target"35+> {36+ /** The path, built whole: `/datekit/ledger`. */37+ readonly to: string;38+ /** The address's search, each value a string. */39+ readonly search?: Readonly<Record<string, string>>;40+ /** The fragment, without its `#`. */41+ readonly hash?: string;42+ /** How the router decides the link leads to the page being read. */43+ readonly activeOptions?: ActiveOptions;44+ /** `false` keeps the router from fetching the page ahead of a click. */45+ readonly preload?: false;46+ /** Replace the history entry rather than push one (a selection). */47+ readonly replace?: boolean;48+ /** Keep each pane's scroll where it is (a selection in a list). */49+ readonly resetScroll?: boolean;50+}51+52+/** The address an `AppLink` names, as the router would write it. */53+export const hrefOf = ({54+ hash,55+ search,56+ to,57+}: Pick<AppLinkProps, "hash" | "search" | "to">): string =>58+ `${to}${59+ search === undefined || Object.keys(search).length === 060+ ? ""61+ : defaultStringifySearch(search)62+ }${hash === undefined ? "" : `#${hash}`}`;63+64+/**65+ * `Link` over any router, whose `to` is any path: the router reads a path66+ * built whole as it reads a typed address.67+ */68+const PathLink = Link<AnyRouter, string, string>;69+70+export const AppLink = (props: AppLinkProps): ReactNode => {71+ const router = useRouter({ warn: false });72+73+ if (Predicate.isNotNullish(router)) {74+ return <PathLink {...props} />;75+ }76+77+ // A router is always there in the app; only a view rendered alone has none.78+ const {79+ activeOptions: _active,80+ hash: _hash,81+ preload: _preload,82+ replace: _replace,83+ resetScroll: _reset,84+ search: _search,85+ to: _to,86+ ...anchor87+ } = props;88+89+ return createElement("a", { ...anchor, href: hrefOf(props) });90+};added:apps/web/src/features/shared/pending.tsx+154 added
1+/**2+ * What a page shows while its reads are on their way, when the platform3+ * did not answer, and when nothing is at an address, each inside the shell4+ * (the rail, the bars and the context bar stay):5+ *6+ * - `ReadingRows`: rows of a list's own height (64 px), each two hairline7+ * bars, with no shimmer; `Reading` is a page of them under its title;8+ * - `Unreachable`: the platform did not answer, said in ink with a way to9+ * ask again. It is not a refusal (a refusal is the platform's answer, and10+ * this is the absence of one), so it is never drawn in the refusal's red;11+ * - `PendingPage`, `RouteError` and `NotFoundPage`: the router's own pending,12+ * failure and missing pages (`src/router.tsx`).13+ */14+import type { ErrorComponentProps } from "@tanstack/react-router";15+import { useLocation } from "@tanstack/react-router";16+import { Unplug } from "lucide-react";17+18+import { Button } from "../../components/ui/button.tsx";19+import { Skeleton } from "../../components/ui/skeleton.tsx";20+import { PageShell } from "./layout.tsx";21+import { AppLink } from "./link.tsx";22+import { crumbsFor, projectOf } from "./shell/sections.ts";23+import { Workspace } from "./shell/workspace.tsx";24+25+const ROWS = ["first", "second", "third"] as const;26+27+/** Rows that hold a list's place while the platform answers: a row's height, two bars each. */28+export const ReadingRows = () => (29+ <div aria-busy="true" className="flex flex-col">30+ <output className="sr-only">Reading from the platform</output>31+ {ROWS.map((row) => (32+ <div33+ className="border-rule flex h-16 flex-col justify-center gap-2.5 border-t"34+ key={row}35+ >36+ <Skeleton className="h-3 w-full max-w-[28rem]" />37+ <Skeleton className="h-2.5 w-full max-w-[14rem]" />38+ </div>39+ ))}40+ </div>41+);42+43+export const Reading = ({ title }: { readonly title: string }) => (44+ <PageShell title={title}>45+ <ReadingRows />46+ </PageShell>47+);48+49+const reload = () => {50+ globalThis.location.reload();51+};52+53+/** The platform did not answer: in ink, with a way to ask again. */54+export const UnreachableNotice = () => (55+ <div56+ className="border-rule-strong flex max-w-[40rem] items-start gap-3 border p-4"57+ role="alert"58+ >59+ <Unplug60+ aria-hidden="true"61+ className="text-muted-foreground mt-0.5 size-5 shrink-0"62+ strokeWidth={1.75}63+ />64+ <div className="flex flex-col items-start gap-1.5">65+ <p className="font-semibold">The platform did not answer.</p>66+ <p className="text-ui text-muted-foreground">67+ Try again in a minute; nothing was changed. Git and the CLI reach it68+ directly.69+ </p>70+ <Button className="mt-2" onClick={reload} size="sm" variant="outline">71+ Reload72+ </Button>73+ </div>74+ </div>75+);76+77+export const Unreachable = ({ title }: { readonly title: string }) => (78+ <PageShell title={title}>79+ <UnreachableNotice />80+ </PageShell>81+);82+83+/** The page's name as its address gives it: the last step of its trail. */84+const useAddressTitle = () =>85+ useLocation({86+ select: ({ pathname }) => crumbsFor(pathname).at(-1)?.label ?? "",87+ });88+89+/**90+ * A page the router is still loading, after 300 ms: its name from the91+ * address over rows that hold its place, so a quick move never flashes and92+ * a slow one keeps the shell where it is.93+ */94+export const PendingPage = () => (95+ <PageShell title={useAddressTitle()}>96+ <ReadingRows />97+ </PageShell>98+);99+100+/**101+ * A page whose read failed on its way (the platform did not answer, or102+ * answered with nothing the page could read), inside the shell.103+ */104+export const RouteError = (_props: ErrorComponentProps) => (105+ <PageShell title={useAddressTitle()}>106+ <UnreachableNotice />107+ </PageShell>108+);109+110+/** An address no page serves: the trail up to what exists, and the ways onward. */111+export const NotFoundPage = () => {112+ const pathname = useLocation({ select: (location) => location.pathname });113+ const project = projectOf(pathname);114+115+ return (116+ <Workspace117+ crumbs={[118+ ...(project === undefined119+ ? []120+ : [{ label: project, to: `/${project}` }]),121+ { label: "No such page" },122+ ]}123+ title="No such page"124+ >125+ <p className="text-want">126+ Nothing is at{" "}127+ <code className="text-mono font-mono [overflow-wrap:anywhere]">128+ {pathname}129+ </code>130+ .131+ </p>132+ <ul className="text-ui flex flex-wrap gap-x-6 gap-y-2">133+ <li>134+ <AppLink135+ className="decoration-rule hover:decoration-foreground underline"136+ to="/"137+ >138+ Open asks139+ </AppLink>140+ </li>141+ {project === undefined ? null : (142+ <li>143+ <AppLink144+ className="decoration-rule hover:decoration-foreground underline"145+ to={`/${project}`}146+ >147+ {project}148+ </AppLink>149+ </li>150+ )}151+ </ul>152+ </Workspace>153+ );154+};modified:apps/web/src/routes/$project/answers/$ask.tsx+2 added-4 removed
15 unmodified lines16 import { watchAtom } from "../../../client/watch.ts";17 import { AnswerView } from "../../../features/answer/answer-page.tsx";18 import { NoSuchAsk } from "../../../features/ask/refused.tsx";19 import { CODE, LINK } from "../../../features/shared/classes.ts";20-import { pageTitle } from "../../../features/shared/head.ts";20+import { pageHead } from "../../../features/shared/head.ts";21 import { PageShell } from "../../../features/shared/layout.tsx";22 import { answerPath } from "../../../features/shared/paths.ts";23 import { notFoundFor } from "../../../features/shared/refusals.ts";24 import { serverClient } from "../../../server/client.ts";178 unmodified lines203 validateSearch: ({ head }: { readonly head?: unknown }) =>204 Predicate.isString(head) ? { head } : {},205 loaderDeps: ({ search }) => ({ head: search.head }),206 loader: ({ deps, params }) => answerPage({ data: { ...params, ...deps } }),207- head: ({ params }) => ({208- meta: [{ title: pageTitle(`Answer to ${params.ask}`) }],209- }),207+ head: ({ params }) => pageHead({ title: `Answer to ${params.ask}` }),208 component: AnswerPage,209 notFoundComponent: AnswerNotFound,210 });modified:apps/web/src/routes/$project/asks/$ask.tsx+6 added-10 removed
12 unmodified lines13 markdownAlternate,14 wantsMarkdown,15 } from "../../../features/ask/markdown.ts";16 import { NoSuchAsk } from "../../../features/ask/refused.tsx";17-import { pageTitle } from "../../../features/shared/head.ts";17+import { pageHead } from "../../../features/shared/head.ts";18 import { notFoundFor } from "../../../features/shared/refusals.ts";19 import { serverClient } from "../../../server/client.ts";20 import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";21 import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";130 unmodified lines152 export const Route = createFileRoute("/$project/asks/$ask")({153 // TanStack infers each option from the ones before it: the loader comes154 // first, so `head` reads its data.155 loader: ({ params }) => askPage({ data: params }),156- head: ({ loaderData }) => ({157- meta: [158- {159- title: pageTitle(160- loaderData === undefined ? "No such ask" : loaderData.ask.brief.want161- ),162- },163- ],164- }),156+ head: ({ loaderData }) =>157+ pageHead({158+ title:159+ loaderData === undefined ? "No such ask" : loaderData.ask.brief.want,160+ }),161 headers: askPageHeaders,162 component: AskPage,163 notFoundComponent: NoSuchAsk,164 server: {5 unmodified linesmodified:apps/web/src/routes/$project/blob/$rev/$.tsx+3 added-4 removed
15 unmodified lines16 NumberedLines,17 } from "../../../../features/code/blob-view.tsx";18 import { ClientFile } from "../../../../features/code/client-code.tsx";19 import { CodeNotFound } from "../../../../features/code/not-found.tsx";20-import { pageTitle } from "../../../../features/shared/head.ts";20+import { pageHead } from "../../../../features/shared/head.ts";21 import { notFoundFor } from "../../../../features/shared/refusals.ts";22 import { serverClient } from "../../../../server/client.ts";23 import { PathsTree } from "../../tree/-paths-tree.tsx";24 83 unmodified lines108 validateSearch: ({ plain }: { readonly plain?: unknown }) => ({109 plain: plain === 1 || plain === "1" ? (1 as const) : undefined,110 }),111 loader: ({ params }) => blobPage({ data: params }),112- head: ({ params: { _splat, project, rev } }) => ({113- meta: [{ title: pageTitle(`${_splat ?? project} at ${rev}`) }],114- }),112+ head: ({ params: { _splat, project, rev } }) =>113+ pageHead({ title: `${_splat ?? project} at ${rev}` }),114 component: BlobPage,115 notFoundComponent: CodeNotFound,116 });modified:apps/web/src/routes/$project/commit/$sha.tsx+3 added-4 removed
13 unmodified lines14 CommitView,15 } from "../../../features/code/commit-view.tsx";16 import { CodeNotFound } from "../../../features/code/not-found.tsx";17 import { diffAnchor } from "../../../features/code/paths.ts";18-import { pageTitle } from "../../../features/shared/head.ts";18+import { pageHead } from "../../../features/shared/head.ts";19 import { notFoundFor } from "../../../features/shared/refusals.ts";20 import { serverClient } from "../../../server/client.ts";21 22 // One commit and what it changed, read on the server: the browser then88 unmodified lines111 validateSearch: (search: { readonly style?: unknown }) => ({112 style: search.style === "split" ? ("split" as const) : undefined,113 }),114 loader: ({ params }) => commitPage({ data: params }),115- head: ({ params: { project, sha } }) => ({116- meta: [{ title: pageTitle(`${project}: commit ${sha.slice(0, 7)}`) }],117- }),115+ head: ({ params: { project, sha } }) =>116+ pageHead({ title: `${project}: commit ${sha.slice(0, 7)}` }),117 component: CommitPage,118 notFoundComponent: CodeNotFound,119 });modified:apps/web/src/routes/$project/commits/$rev.tsx+3 added-4 removed
13 unmodified lines14 } from "../../../features/code/address.ts";15 import { LOG_PAGE } from "../../../features/code/log-page.ts";16 import { LogView } from "../../../features/code/log-view.tsx";17 import { CodeNotFound } from "../../../features/code/not-found.tsx";18-import { pageTitle } from "../../../features/shared/head.ts";18+import { pageHead } from "../../../features/shared/head.ts";19 import { notFoundFor } from "../../../features/shared/refusals.ts";20 import { serverClient } from "../../../server/client.ts";21 22 // The log from a revision, a page at a time (`?from=` is where the page82 unmodified lines105 path: Predicate.isString(search.path) ? search.path : undefined,106 }),107 loaderDeps: ({ search }) => ({ from: search.from, path: search.path }),108 loader: ({ deps, params }) => logPage({ data: { ...params, ...deps } }),109- head: ({ params: { project, rev } }) => ({110- meta: [{ title: pageTitle(`${project}: commits on ${rev}`) }],111- }),109+ head: ({ params: { project, rev } }) =>110+ pageHead({ title: `${project}: commits on ${rev}` }),111 component: LogPage,112 notFoundComponent: CodeNotFound,113 });modified:apps/web/src/routes/$project/decisions/$decision.tsx+2 added-4 removed
16 unmodified lines17 import { FinishView } from "../../../features/finish/finish-view.tsx";18 import { isFinishDecision } from "../../../features/finish/patch.ts";19 import type { FinishDecision } from "../../../features/finish/patch.ts";20 import { EmptyState } from "../../../features/shared/empty.tsx";21-import { pageTitle } from "../../../features/shared/head.ts";21+import { pageHead } from "../../../features/shared/head.ts";22 import { PageShell } from "../../../features/shared/layout.tsx";23 import {24 DecidedNotice,25 FailureView,127 unmodified lines153 };154 155 export const Route = createFileRoute("/$project/decisions/$decision")({156 component: DecisionPage,157- head: ({ params }) => ({158- meta: [{ title: pageTitle(`Decision ${params.decision}`) }],159- }),157+ head: ({ params }) => pageHead({ title: `Decision ${params.decision}` }),158 ssr: false,159 });modified:apps/web/src/routes/$project/proposals/$proposal.tsx+3 added-4 removed
27 unmodified lines28 import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";29 import { ProposalFailure } from "../../../features/proposal/failure.tsx";30 import { ProposalView } from "../../../features/proposal/proposal-view.tsx";31 import { EmptyState } from "../../../features/shared/empty.tsx";32-import { pageTitle } from "../../../features/shared/head.ts";32+import { pageHead } from "../../../features/shared/head.ts";33 import { PageShell } from "../../../features/shared/layout.tsx";34 import { serverClient } from "../../../server/client.ts";35 36 // `/$project/proposals/$proposal`: one proposal and the platform's draft of161 unmodified lines198 };199 200 export const Route = createFileRoute("/$project/proposals/$proposal")({201 loader: ({ params }) => proposalPage({ data: params }),202- head: ({ params: { project, proposal } }) => ({203- meta: [{ title: pageTitle(`${project}: proposal ${proposal}`) }],204- }),202+ head: ({ params: { project, proposal } }) =>203+ pageHead({ title: `${project}: proposal ${proposal}` }),204 component: ProposalPage,205 notFoundComponent: Unknown,206 });modified:apps/web/src/routes/$project/proposals/new.tsx+3 added-4 removed
19 unmodified lines20 import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";21 import { ProposalFailure } from "../../../features/proposal/failure.tsx";22 import { ProposeView } from "../../../features/propose/propose-view.tsx";23 import type { About } from "../../../features/propose/propose-view.tsx";24-import { pageTitle } from "../../../features/shared/head.ts";24+import { pageHead } from "../../../features/shared/head.ts";25 import { PageShell } from "../../../features/shared/layout.tsx";26 27 // `/$project/proposals/new`: the propose form. Who is signed in and the28 // project's top folders are read in the browser (the server paints the115 unmodified lines144 about: Option.getOrUndefined(decodeText(search.about)),145 at: Option.getOrUndefined(decodeText(search.at)),146 line: Option.getOrUndefined(decodeLine(search.line)),147 }),148- head: ({ params: { project } }) => ({149- meta: [{ title: pageTitle(`${project}: propose an ask`) }],150- }),148+ head: ({ params: { project } }) =>149+ pageHead({ title: `${project}: propose an ask` }),150 });modified:apps/web/src/routes/$project/tree/$rev/$.tsx+5 added-10 removed
11 unmodified lines12 revisionOf,13 } from "../../../../features/code/address.ts";14 import { CodeNotFound } from "../../../../features/code/not-found.tsx";15 import { TreeView } from "../../../../features/code/tree-view.tsx";16-import { pageTitle } from "../../../../features/shared/head.ts";16+import { pageHead } from "../../../../features/shared/head.ts";17 import { notFoundFor } from "../../../../features/shared/refusals.ts";18 import { serverClient } from "../../../../server/client.ts";19 import { readFolderWithReadme } from "../../../../server/folder.ts";20 77 unmodified lines98 };99 100 export const Route = createFileRoute("/$project/tree/$rev/$")({101 loader: ({ params }) => treePage({ data: params }),102- head: ({ params: { _splat, project, rev } }) => ({103- meta: [104- {105- title: pageTitle(106- `${_splat === undefined || _splat === "" ? project : _splat} at ${rev}`107- ),108- },109- ],110- }),102+ head: ({ params: { _splat, project, rev } }) =>103+ pageHead({104+ title: `${_splat === undefined || _splat === "" ? project : _splat} at ${rev}`,105+ }),106 component: TreePage,107 notFoundComponent: CodeNotFound,108 });modified:apps/web/src/routes/$project/why/$rev/$.tsx+3 added-4 removed
10 unmodified lines11 repoPathOf,12 revisionOf,13 } from "../../../../features/code/address.ts";14 import { CodeNotFound } from "../../../../features/code/not-found.tsx";15-import { pageTitle } from "../../../../features/shared/head.ts";15+import { pageHead } from "../../../../features/shared/head.ts";16 import { notFoundFor } from "../../../../features/shared/refusals.ts";17 import { ClientWhy } from "../../../../features/why/client-why.tsx";18 import { WhyFallback, WhyLines } from "../../../../features/why/why-view.tsx";19 import { serverClient } from "../../../../server/client.ts";91 unmodified lines111 };112 113 export const Route = createFileRoute("/$project/why/$rev/$")({114 loader: ({ params }) => whyPage({ data: params }),115- head: ({ params: { _splat, project, rev } }) => ({116- meta: [{ title: pageTitle(`Why ${_splat ?? project} at ${rev}`) }],117- }),115+ head: ({ params: { _splat, project, rev } }) =>116+ pageHead({ title: `Why ${_splat ?? project} at ${rev}` }),117 component: WhyPage,118 notFoundComponent: CodeNotFound,119 });modified:apps/web/src/routes/$project/env.tsx+2 added-4 removed
14 unmodified lines15 import { envSchemaAtom } from "../../client/env.ts";16 import { watchAtom } from "../../client/watch.ts";17 import { EnvView, NothingLanded } from "../../features/env/env-page.tsx";18 import { UnknownProjectView } from "../../features/project/unknown-project.tsx";19-import { pageTitle } from "../../features/shared/head.ts";19+import { pageHead } from "../../features/shared/head.ts";20 import { serverClient } from "../../server/client.ts";21 22 // A project's env shape, as anyone may read it: never a value, and no form23 // (a value is set from a terminal only). The loader reads it on the server,99 unmodified lines123 };124 125 export const Route = createFileRoute("/$project/env")({126 loader: ({ params }) => envPage({ data: params.project }),127- head: ({ params }) => ({128- meta: [{ title: pageTitle(`Env shape of ${params.project}`) }],129- }),127+ head: ({ params }) => pageHead({ title: `Env shape of ${params.project}` }),128 component: EnvPage,129 notFoundComponent: Unknown,130 });modified:apps/web/src/routes/$project/index.tsx+3 added-3 removed
12 unmodified lines13 import { recentLandingsAtom } from "../../client/events.ts";14 import { projectsAtom } from "../../client/front.ts";15 import { asksAtom } from "../../client/project.ts";16 import { watchAtom } from "../../client/watch.ts";17-import { Unreachable } from "../../features/front/reading.tsx";17 import {18 ProjectReadingView,19 ProjectView,20 } from "../../features/project/project-page.tsx";21 import { UnknownProjectView } from "../../features/project/unknown-project.tsx";23-import { pageTitle } from "../../features/shared/head.ts";22+import { pageHead } from "../../features/shared/head.ts";23+import { Unreachable } from "../../features/shared/pending.tsx";24 import { serverClient } from "../../server/client.ts";25 import { readFolderWithReadme } from "../../server/folder.ts";26 27 // A project's page. The loader asks the platform, on the server, for the157 unmodified lines185 };186 187 export const Route = createFileRoute("/$project/")({188 component: ProjectPage,189- head: ({ params }) => ({ meta: [{ title: pageTitle(params.project) }] }),189+ head: ({ params }) => pageHead({ title: params.project }),190 loader: ({ params }) => projectPage({ data: params.project }),191 notFoundComponent: Unknown,192 });modified:apps/web/src/routes/$project/ledger.tsx+2 added-4 removed
14 unmodified lines15 import { ledgerAtom } from "../../client/ledger.ts";16 import { watchAtom } from "../../client/watch.ts";17 import { LedgerView } from "../../features/ledger/ledger-page.tsx";18 import { UnknownProjectView } from "../../features/project/unknown-project.tsx";19-import { pageTitle } from "../../features/shared/head.ts";19+import { pageHead } from "../../features/shared/head.ts";20 import { serverClient } from "../../server/client.ts";21 22 // A project's ledger, as anyone may read it. The loader reads it on the23 // server, so the page arrives whole and an address naming no project is a75 unmodified lines99 };100 101 export const Route = createFileRoute("/$project/ledger")({102 loader: ({ params }) => ledgerPage({ data: params.project }),103- head: ({ params }) => ({104- meta: [{ title: pageTitle(`Ledger of ${params.project}`) }],105- }),103+ head: ({ params }) => pageHead({ title: `Ledger of ${params.project}` }),104 component: LedgerPage,105 notFoundComponent: Unknown,106 });modified:apps/web/src/routes/$project/people.tsx+2 added-4 removed
16 unmodified lines17 import { policyAtom } from "../../client/policy.ts";18 import { watchAtom } from "../../client/watch.ts";19 import { PeopleView } from "../../features/project-people/people-view.tsx";20 import { UnknownProjectView } from "../../features/project/unknown-project.tsx";21-import { pageTitle } from "../../features/shared/head.ts";21+import { pageHead } from "../../features/shared/head.ts";22 import { serverClient } from "../../server/client.ts";23 24 // Who decides what in a project, who is vouched for, and who reads and25 // writes each layer: the evaluated policy at the landed commit beside the98 unmodified lines124 };125 126 export const Route = createFileRoute("/$project/people")({127 loader: ({ params }) => peoplePage({ data: params.project }),128- head: ({ params: { project } }) => ({129- meta: [{ title: pageTitle(`${project}: people`) }],130- }),128+ head: ({ params: { project } }) => pageHead({ title: `${project}: people` }),129 component: PeoplePage,130 notFoundComponent: Unknown,131 });modified:apps/web/src/routes/$project/refs.tsx+2 added-4 removed
7 unmodified lines8 import { offsetOf, projectOf } from "../../features/code/address.ts";9 import { CodeNotFound } from "../../features/code/not-found.tsx";10 import { packageParamOf } from "../../features/code/refs-param.ts";11 import { RefsView } from "../../features/code/refs-view.tsx";12-import { pageTitle } from "../../features/shared/head.ts";12+import { pageHead } from "../../features/shared/head.ts";13 import { notFoundFor } from "../../features/shared/refusals.ts";14 import { serverClient } from "../../server/client.ts";15 16 // Main, the tags and the forks, read on the server; `?from=` pages the40 unmodified lines57 from: Option.getOrUndefined(offsetOf(search.from)),58 package: Option.getOrUndefined(packageParamOf(search.package)),59 }),60 loader: ({ params }) => refsPage({ data: params.project }),61- head: ({ params: { project } }) => ({62- meta: [{ title: pageTitle(`${project}: refs`) }],63- }),61+ head: ({ params: { project } }) => pageHead({ title: `${project}: refs` }),62 component: RefsPage,63 notFoundComponent: CodeNotFound,64 });added:apps/web/src/routes/$project/route.tsx+13 added
1+import { createFileRoute, Outlet } from "@tanstack/react-router";2+3+// Every page of a project sits under this route. It reads nothing, so no4+// page waits on it: the shell finds the project here (`useCurrentProject`,5+// which reads this route's match) and draws the project's part of the rail6+// from the name in the address at once, its posture arriving later with the7+// list of projects without moving anything. A name no project could take8+// is left to the page, which says so. The rail itself is the root's, so9+// what a project's pages put in its slot (`staticData.rail`) stays mounted10+// as the reader moves between them.11+export const Route = createFileRoute("/$project")({12+ component: Outlet,13+});modified:apps/web/src/routes/people/$handle.tsx+3 added-3 removed
3 unmodified lines4 import { Effect, Option, Schema } from "effect";5 import { AsyncResult } from "effect/reactivity";6 7 import { creditsAtom } from "../../client/people.ts";8-import { Reading, Unreachable } from "../../features/front/reading.tsx";8 import {9 NoSuchPersonView,10 PersonView,11 } from "../../features/people/person-page.tsx";13-import { pageTitle } from "../../features/shared/head.ts";12+import { pageHead } from "../../features/shared/head.ts";13+import { Reading, Unreachable } from "../../features/shared/pending.tsx";14 15 // A person's page: their credit by project, area and role, read once by the16 // browser. An address whose last part cannot be a handle is a 404.17 19 unmodified lines37 };38 39 export const Route = createFileRoute("/people/$handle")({40 component: PersonPage,41- head: ({ params }) => ({ meta: [{ title: pageTitle(params.handle) }] }),41+ head: ({ params }) => pageHead({ title: params.handle }),42 // A 404 for an address that names no handle.43 loader: ({ params }) =>44 Effect.runPromise(45 Effect.asVoid(7 unmodified linesmodified:apps/web/src/routes/__root.tsx+67 added-16 removed
1+import { useAtomValue } from "@effect/atom-react";2 import { Brand } from "@repo/brand";3 import {4 createRootRoute,5 HeadContent,6 Outlet,7 Scripts,7- useLocation,8+ useHydrated,9 } from "@tanstack/react-router";10 import { createServerFn } from "@tanstack/react-start";11 import { env } from "cloudflare:workers";12+import { AsyncResult } from "effect/reactivity";13 import type { ReactNode } from "react";14 15 import monoFont from "../assets/fonts/jetbrains-mono-latin.woff2?url";16 import sansFont from "../assets/fonts/public-sans-latin.woff2?url";17+import { projectsAtom } from "../client/front.ts";18+import { todayAtom } from "../client/today.ts";19 import { TooltipProvider } from "../components/ui/tooltip.tsx";20 import { MANIFEST_PATH } from "../features/agents/manifest.ts";17-import { SessionSlot } from "../features/auth/session-slot.tsx";18-import { SiteFooter, SiteHeader } from "../features/shared/layout.tsx";21+import { useSignedIn } from "../features/auth/session-slot.tsx";22+import { AppShell } from "../features/shared/shell/app-shell.tsx";23+import { RailCount } from "../features/shared/shell/rail.tsx";24 import { themeColors } from "../features/shared/theme.ts";25 26 import styles from "../styles.css?url";27 23-// The shell every page shares: the document, the header with24-// the front page, Today and the session, each page's own <main> (from25-// `PageShell`), and the footer's two ways in. Pages read the site's facts26-// from this route's loader data (`getRouteApi("__root__").useLoaderData()`).28+// The document every page shares, and the shell inside it: the rail, the29+// bars, and each page's own panes (its `Workspace`). The document is the30+// route's shell component, so a failure in this route's own read still31+// draws inside a whole document. Pages read the site's facts from this32+// route's loader data (`getRouteApi("__root__").useLoaderData()`).33 34 /**35 * What every page may need from the Worker's env: where a browser reaches36 * the platform (its git remotes and the CLI's install line). Read on the28 unmodified lines65 <head>66 <HeadContent />67 <ThemeColors />68 </head>63- <body className="flex min-h-dvh flex-col">69+ <body>70 {children}71 <Scripts />72 </body>73 </html>74 );75 76+/** The decider's Today, read in the browser for the rail's count. */77+const railToday = todayAtom();78+79+const TodayWaiting = () => {80+ const today = useAtomValue(railToday);81+82+ if (!AsyncResult.isSuccess(today)) {83+ return null;84+ }85+86+ const waiting = today.value.decisions.length + today.value.overflow;87+88+ return waiting === 0 ? null : (89+ <RailCount count={waiting} of="decisions waiting" />90+ );91+};92+93+/**94+ * How many decisions wait on the signed-in decider, beside Today in the95+ * rail: read once the page is up and only for someone signed in, never on96+ * the server, so it never holds a page back.97+ */98+const TodayCount = () => {99+ const hydrated = useHydrated();100+ const signedIn = useSignedIn();101+102+ return hydrated && signedIn ? <TodayWaiting /> : null;103+};104+105 const Root = () => {71- const { platformUrl } = Route.useLoaderData();72- const { pathname } = useLocation();106+ // Read in the browser after the page is up; the rail draws without it first.107+ const listed = useAtomValue(projectsAtom);108 109 return (75- <Document>76- <TooltipProvider>77- <SiteHeader pathname={pathname} session={<SessionSlot />} />110+ <TooltipProvider>111+ <AppShell112+ projects={113+ AsyncResult.isSuccess(listed) ? listed.value.projects : undefined114+ }115+ todayCount={<TodayCount />}116+ >117 <Outlet />79- <SiteFooter platformUrl={platformUrl} />80- </TooltipProvider>81- </Document>118+ </AppShell>119+ </TooltipProvider>120 );121 };122 123+/**124+ * What a shared link to any page unfurls with until the page gives its own125+ * (`pageHead`): what the platform is, in a sentence.126+ */127+export const SITE_DESCRIPTION =128+ "A git platform where a project says what it wants as asks, anyone may answer, and a change lands on main only by passing a typed gate, with credit for every person involved.";129+130 /** The site's icon, drawn to scale (`public/icons/icon.svg`). */131 const ICON_PATH = "/icons/icon.svg";132 133 /**30 unmodified lines164 { charSet: "utf-8" },165 { content: "width=device-width, initial-scale=1", name: "viewport" },166 { content: "light dark", name: "color-scheme" },167 { title: Brand.name },168+ { content: SITE_DESCRIPTION, name: "description" },169+ { content: Brand.name, property: "og:title" },170+ { content: SITE_DESCRIPTION, property: "og:description" },171+ { content: "website", property: "og:type" },172+ { content: Brand.name, property: "og:site_name" },173 ],174 });175 176 export const Route = createRootRoute({177 component: Root,178 head: rootHead,179+ shellComponent: Document,180 loader: () => siteFacts(),181 // The facts are the stage's, fixed for the Worker's life: fetch them once.182 staleTime: Number.POSITIVE_INFINITY,183 });modified:apps/web/src/routes/agents.tsx+2 added-2 removed
5 unmodified lines6 } from "@tanstack/react-router";7 8 import { commands } from "../features/agents/catalog.ts";9 import { AgentSetupView } from "../features/agents/setup-page.tsx";10-import { pageTitle } from "../features/shared/head.ts";10+import { pageHead } from "../features/shared/head.ts";11 import { PageShell } from "../features/shared/layout.tsx";12 13 // `/agents`: how each agent connects, drawn from `@repo/agent-kit`'s14 // `agentSetup` for this stage's platform and the web's own origin (the17 unmodified lines32 };33 34 export const Route = createFileRoute("/agents")({35 component: AgentsPage,36- head: () => ({ meta: [{ title: pageTitle("Agents") }] }),36+ head: () => pageHead({ title: "Agents" }),37 });modified:apps/web/src/routes/index.tsx+3 added-3 removed
4 unmodified lines5 6 import { frontPageAtom, projectsAtom } from "../client/front.ts";7 import { readFilter } from "../features/front/filter.ts";8 import { FrontPageView } from "../features/front/front-page.tsx";9-import { Reading, Unreachable } from "../features/front/reading.tsx";10-import { pageTitle } from "../features/shared/head.ts";9+import { pageHead } from "../features/shared/head.ts";10+import { Reading, Unreachable } from "../features/shared/pending.tsx";11 12 // The front page: every open ask, read once, filtered here by the address's13 // `?kind=` and `?reserved=` (each decoded with its schema; one that does not14 // decode is dropped). The whole list is read, so the filter offers every28 unmodified lines43 };44 45 export const Route = createFileRoute("/")({46 component: FrontPage,47- head: () => ({ meta: [{ title: pageTitle(TITLE) }] }),47+ head: () => pageHead({ title: TITLE }),48 validateSearch: readFilter,49 });modified:apps/web/src/routes/today.tsx+2 added-2 removed
3 unmodified lines4 import { DateTime, Option, Schema } from "effect";5 6 import { decideAtom } from "../client/decide.ts";7 import { todayAtom } from "../client/today.ts";8-import { pageTitle } from "../features/shared/head.ts";8+import { pageHead } from "../features/shared/head.ts";9 import { PageShell } from "../features/shared/layout.tsx";10 import { TodayView } from "../features/today/today-page.tsx";11 12 // `/today`: the signed-in decider's decisions across their projects, or in20 unmodified lines33 };34 35 export const Route = createFileRoute("/today")({36 component: TodayPage,37- head: () => ({ meta: [{ title: pageTitle("Today") }] }),37+ head: () => pageHead({ title: "Today" }),38 ssr: false,39 validateSearch: (search: {40 readonly project?: unknown;41 }): { readonly project?: ProjectName } =>5 unmodified linesmodified:apps/web/src/router.tsx+30 added-1 removed
1 import { createRouter } from "@tanstack/react-router";2 3+import {4+ NotFoundPage,5+ PendingPage,6+ RouteError,7+} from "./features/shared/pending.tsx";8 import { routeTree } from "./routeTree.gen.ts";9 5-/** TanStack Start's router, over the route tree the Vite plugin generates. */10+/**11+ * TanStack Start's router, over the route tree the Vite plugin generates.12+ *13+ * - A link (`AppLink`) fetches its page's code and loader data once a14+ * pointer rests on it for 50 ms (the router's own delay, stated) or it15+ * takes focus, and what it read stays fresh for 30 s, so a click soon16+ * after reads nothing again. A page left and come back to within 10 s is17+ * drawn from what it read; later, it is drawn so and read again behind18+ * it. A page's own reads stay live through its atoms either way.19+ * - A page that takes longer than 300 ms to load shows `PendingPage` in the20+ * shell; a quicker one never flashes it.21+ * - A failed read draws `RouteError` and an address no page serves draws22+ * `NotFoundPage`, both inside the shell, never the router's own.23+ * - Each new page's main pane (and its inspector) starts at its top; going24+ * back returns each to where it was.25+ */26 export const getRouter = () =>27 createRouter({28+ defaultErrorComponent: RouteError,29+ defaultNotFoundComponent: NotFoundPage,30+ defaultPendingComponent: PendingPage,31+ defaultPendingMs: 300,32+ defaultPreload: "intent",33+ defaultPreloadDelay: 50,34+ defaultPreloadStaleTime: 30_000,35+ defaultStaleTime: 10_000,36 routeTree,37 scrollRestoration: true,38+ scrollToTopSelectors: ["#main", "#facts"],39 });40 41 declare module "@tanstack/react-router" {42 interface Register {3 unmodified linesmodified:apps/web/src/styles.css+14 added
228 unmodified lines229 --popover: oklch(0.235 0.009 258);230 }231 }232 233+/*234+ The shell's widths, by name: a phone below `tablet`; from `tablet` a top235+ bar with the rail as a sheet; from `diffsplit` a diff may go side by236+ side; from `shell` (1120 px, so the 110% zoom of a 1280 frame keeps it)237+ the rail and the inspector are columns; from `codefacts` code pages keep238+ the inspector open beside the code.239+*/240+@theme {241+ --breakpoint-tablet: 40rem;242+ --breakpoint-diffsplit: 48rem;243+ --breakpoint-shell: 70rem;244+ --breakpoint-codefacts: 90rem;245+}246+247 @theme inline {248 --font-sans:249 "Public Sans", "Public Sans Fallback", ui-sans-serif, system-ui,250 -apple-system, "Segoe UI", sans-serif;272 unmodified linesadded:apps/web/test/head.test.ts+65 added
1+/**2+ * What a page puts in the document's head: its title, and the description3+ * a shared link unfurls with (`description` and the Open Graph trio). The4+ * router keeps one meta per name (or Open Graph property), the last a route5+ * gives, so each one here has a name of its own and a page's replace the6+ * root's.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { Brand } from "@repo/brand";10+11+import { pageHead } from "../src/features/shared/head.ts";12+import { rootHead } from "../src/routes/__root.tsx";13+14+/** Each meta's key as the router dedupes it: its `name`, else its `property`. */15+const keyOf = (meta: Readonly<Record<string, string>>) =>16+ meta.name ?? meta.property ?? (meta.title === undefined ? "" : "title");17+18+/** The metas of `head` as `key: content` pairs (the title as `title`). */19+const metasOf = (head: {20+ readonly meta: readonly Readonly<Record<string, string>>[];21+}) =>22+ Object.fromEntries(23+ head.meta.map((meta) => [keyOf(meta), meta.content ?? meta.title])24+ );25+26+describe(pageHead, () => {27+ it("titles the page, then the product, and gives one meta per name for the unfurl", () => {28+ const head = pageHead({29+ description: "Format a date as an ordinal, in English.",30+ title: "format-ordinal · datekit",31+ });32+33+ expect(metasOf(head)).toStrictEqual({34+ description: "Format a date as an ordinal, in English.",35+ "og:description": "Format a date as an ordinal, in English.",36+ "og:title": "format-ordinal · datekit",37+ "og:type": "website",38+ title: `format-ordinal · datekit · ${Brand.name}`,39+ });40+ expect(head.meta.map(keyOf)).toStrictEqual([41+ ...new Set(head.meta.map(keyOf)),42+ ]);43+ });44+45+ it("names an article as one, and leaves the root's description in place when it has none", () => {46+ const head = pageHead({ title: "Ledger", type: "article" });47+48+ expect(metasOf(head)).toStrictEqual({49+ "og:title": "Ledger",50+ "og:type": "article",51+ title: `Ledger · ${Brand.name}`,52+ });53+ });54+});55+56+describe("the root's head", () => {57+ it("carries a default description, so no page unfurls bare", () => {58+ const metas = metasOf(rootHead());59+60+ expect(metas.description).toMatch(/\S{3,}/u);61+ expect(metas["og:description"]).toBe(metas.description);62+ expect(metas["og:title"]).toBe(Brand.name);63+ expect(metas["og:type"]).toBe("website");64+ });65+});added:apps/web/test/keys.test.tsx+169 added
1+/**2+ * The keyboard's single keys: what each press does, when none acts (focus in3+ * a text field, the switch off), and the switch itself, kept in the4+ * browser's storage as a per-viewer convenience that must survive a5+ * storage that refuses to read or write.6+ */7+import { describe, expect, it } from "@effect/vitest";8+import { renderToStaticMarkup } from "react-dom/server";9+10+import {11+ intentOf,12+ KeysHelp,13+ readShortcuts,14+ writeShortcuts,15+} from "../src/features/shared/keys.tsx";16+17+/** A press of `key` outside any text field, with no modifier held. */18+const press = (key: string, inField = false) => ({19+ altKey: false,20+ ctrlKey: false,21+ inField,22+ key,23+ metaKey: false,24+});25+26+/** A `Storage` whose every read and write throws, as a blocked one does. */27+const refusing: Storage = {28+ clear: () => {29+ throw new Error("blocked");30+ },31+ getItem: () => {32+ throw new Error("blocked");33+ },34+ key: () => {35+ throw new Error("blocked");36+ },37+ get length(): number {38+ throw new Error("blocked");39+ },40+ removeItem: () => {41+ throw new Error("blocked");42+ },43+ setItem: () => {44+ throw new Error("blocked");45+ },46+};47+48+/** A `Storage` held in a map, as a browser's is. */49+const kept = (): Storage => {50+ const items = new Map<string, string>();51+52+ return {53+ clear: () => {54+ items.clear();55+ },56+ getItem: (name) => items.get(name) ?? null,57+ key: (index) => [...items.keys()][index] ?? null,58+ get length() {59+ return items.size;60+ },61+ removeItem: (name) => {62+ items.delete(name);63+ },64+ setItem: (name, value) => {65+ items.set(name, value);66+ },67+ };68+};69+70+describe("a single key", () => {71+ it("opens the keys dialog with ?", () => {72+ expect(intentOf(press("?"), true)).toStrictEqual({ kind: "keys" });73+ });74+75+ it("moves through the page's list with j and k, and its files with J and K", () => {76+ expect(77+ ["j", "k", "J", "K"].map((key) => intentOf(press(key), true))78+ ).toStrictEqual([79+ { kind: "next" },80+ { kind: "previous" },81+ { kind: "nextFile" },82+ { kind: "previousFile" },83+ ]);84+ });85+86+ it("copies the page's numbered commands with 1 to 9, and nothing with 0", () => {87+ expect(intentOf(press("1"), true)).toStrictEqual({88+ index: 1,89+ kind: "copy",90+ });91+ expect(intentOf(press("9"), true)).toStrictEqual({92+ index: 9,93+ kind: "copy",94+ });95+ expect(intentOf(press("0"), true)).toBeUndefined();96+ });97+98+ it("clears with Escape", () => {99+ expect(intentOf(press("Escape"), true)).toStrictEqual({ kind: "clear" });100+ });101+102+ it("does nothing once the switch is off, but ? still opens the dialog that holds it", () => {103+ expect(intentOf(press("j"), false)).toBeUndefined();104+ expect(intentOf(press("1"), false)).toBeUndefined();105+ expect(intentOf(press("?"), false)).toStrictEqual({ kind: "keys" });106+ });107+108+ it("does nothing while focus is in a text field, ? and Escape included", () => {109+ expect(110+ ["j", "?", "1", "Escape"].map((key) => intentOf(press(key, true), true))111+ ).toStrictEqual([undefined, undefined, undefined, undefined]);112+ });113+114+ it("leaves a press with Ctrl, Alt or Meta to the browser", () => {115+ expect(intentOf({ ...press("k"), ctrlKey: true }, true)).toBeUndefined();116+ expect(intentOf({ ...press("j"), metaKey: true }, true)).toBeUndefined();117+ expect(intentOf({ ...press("1"), altKey: true }, true)).toBeUndefined();118+ });119+});120+121+describe("the switch", () => {122+ it("is on until it is turned off, and stays as it was left", () => {123+ const storage = kept();124+125+ expect(readShortcuts(storage)).toBeTruthy();126+127+ writeShortcuts(storage, false);128+129+ expect(readShortcuts(storage)).toBeFalsy();130+131+ writeShortcuts(storage, true);132+133+ expect(readShortcuts(storage)).toBeTruthy();134+ });135+136+ it("is on when the storage refuses to read, and a refused write changes nothing", () => {137+ expect(readShortcuts(refusing)).toBeTruthy();138+ expect(() => {139+ writeShortcuts(refusing, false);140+ }).not.toThrow();141+ expect(readShortcuts()).toBeTruthy();142+ });143+144+ it("is in the dialog, with every key and what it does", () => {145+ const markup = renderToStaticMarkup(146+ <KeysHelp147+ on={false}148+ onChange={() => {149+ // A static render never presses it.150+ }}151+ />152+ );153+154+ const text = markup.replaceAll(/<[^>]+>/gu, " ");155+156+ expect(text).toContain("Single-key shortcuts");157+ expect(markup).toMatch(158+ /<button\b[^>]*aria-pressed="true"[^>]*>Off<\/button>/u159+ );160+ expect(markup).toMatch(161+ /<button\b[^>]*aria-pressed="false"[^>]*>On<\/button>/u162+ );163+164+ for (const key of ["?", "j", "k", "J", "K", "1", "9", "Esc"]) {165+ expect(markup).toContain(`<kbd`);166+ expect(text).toContain(key);167+ }168+ });169+});modified:apps/web/test/nav.test.tsx+52 added-20 removed
1 /**2- * A project's nav, rendered to HTML: the seven tabs every project page3- * shares, each linking to its page, and only the page being read marked4- * as the current one.2+ * A project's section row, rendered to HTML: the seven sections every3+ * project page shares, in one line under the page's head where the rail is4+ * not drawn, each linking to its page, and only the page being read marked5+ * as the current one. Inside the router it draws the router's links; a view6+ * rendered alone draws the same addresses as plain links.7 */8 import { describe, expect, it } from "@effect/vitest";9 import { ProjectName } from "@repo/protocol/ids";10+import { Effect } from "effect";11 import { renderToStaticMarkup } from "react-dom/server";12 13 import { ProjectNav } from "../src/features/project/project-nav.tsx";14+import { renderAt } from "./render.tsx";15 16 const datekit = ProjectName.make("datekit");17 18 /** Each link in `markup`: its text, its href, and whether it is current. */6 unmodified lines25 text: (groups?.text ?? "").replaceAll(/<[^>]+>/gu, ""),26 })27 );28 29+const sections = (current: string) =>30+ [31+ { href: "/datekit", text: "Asks" },32+ { href: "/datekit/tree/main", text: "Code" },33+ { href: "/datekit/commits/main", text: "Landings" },34+ { href: "/datekit/refs", text: "Refs" },35+ { href: "/datekit/people", text: "Policy" },36+ { href: "/datekit/ledger", text: "Ledger" },37+ { href: "/datekit/env", text: "Env shape" },38+ ].map((link) => ({ current: link.text === current, ...link }));39+25-describe("a project's nav", () => {26- it("links all seven tabs, and marks only the page being read", () => {40+describe("a project's section row", () => {41+ it("links all seven sections, and marks only the page being read", () => {42 const markup = renderToStaticMarkup(43 <ProjectNav current="code" project={datekit} />44 );45 46 expect(markup).toMatch(/^<nav\b[^>]*aria-label="datekit"/u);32- expect(linksOf(markup)).toStrictEqual([33- { current: false, href: "/datekit", text: "Overview" },34- { current: true, href: "/datekit/tree/main", text: "Code" },35- { current: false, href: "/datekit/commits/main", text: "Landings" },36- { current: false, href: "/datekit/refs", text: "Refs" },37- { current: false, href: "/datekit/people", text: "People" },38- { current: false, href: "/datekit/ledger", text: "Ledger" },39- { current: false, href: "/datekit/env", text: "Env shape" },47+ expect(linksOf(markup)).toStrictEqual(sections("Code"));48+ });49+50+ it("calls the project's policy Policy, at its address", () => {51+ const policy = linksOf(52+ renderToStaticMarkup(<ProjectNav current="people" project={datekit} />)53+ ).filter(({ current }) => current);54+55+ expect(policy).toStrictEqual([56+ { current: true, href: "/datekit/people", text: "Policy" },57 ]);58 });59 60 it("are links, not buttons", () => {3 unmodified lines64 65 expect(markup).not.toContain('role="button"');66 });67 51- it("marks the tab it is given", () => {52- const current = linksOf(53- renderToStaticMarkup(<ProjectNav current="ledger" project={datekit} />)54- ).filter((link) => link.current);68+ it.effect(69+ "draws the router's links inside the router, the page being read marked by it",70+ () =>71+ Effect.gen(function* () {72+ const markup = yield* renderAt(73+ "/datekit/ledger",74+ <ProjectNav current="ledger" project={datekit} />75+ );76 56- expect(current).toStrictEqual([57- { current: true, href: "/datekit/ledger", text: "Ledger" },58- ]);77+ expect(linksOf(markup)).toStrictEqual(sections("Ledger"));78+ expect(markup).toMatch(79+ /<a\b[^>]*data-status="active"[^>]*>Ledger<\/a>/u80+ );81+ })82+ );83+84+ it("scrolls sideways inside itself and never wraps", () => {85+ const markup = renderToStaticMarkup(86+ <ProjectNav current="ledger" project={datekit} />87+ );88+89+ expect(markup).toMatch(/^<nav\b[^>]*class="[^"]*overflow-x-auto/u);90+ expect(markup).not.toContain("flex-wrap");91 });92 });added:apps/web/test/render.tsx+73 added
1+/**2+ * A view rendered to HTML inside a router, at an address: what a view that3+ * draws the router's links (`AppLink`), reads the location or the route's4+ * params needs around it, as the app's router gives it in the browser.5+ *6+ * The routes are the app's shape without its loaders: `/`, `/today`,7+ * `/agents`, `/people/$handle` and `/$project` with its pages under it, so8+ * the shell finds the project in `/datekit/ledger` and none in `/agents`.9+ * The view itself is the root's component: it renders whatever the10+ * address, and a page's own route never runs.11+ *12+ * ```tsx13+ * it.effect("…", () =>14+ * Effect.gen(function* () {15+ * const markup = yield* renderAt("/datekit/ledger", <AppShell>…</AppShell>);16+ * })17+ * );18+ * ```19+ */20+import {21+ createMemoryHistory,22+ createRootRoute,23+ createRoute,24+ createRouter,25+ RouterProvider,26+} from "@tanstack/react-router";27+import { Effect } from "effect";28+import type { Cause } from "effect";29+import type { ComponentType, ReactNode } from "react";30+import { renderToStaticMarkup } from "react-dom/server";31+32+/** What a test may add to the routes: the rail's content on a project's pages. */33+export interface RenderOptions {34+ readonly rail?: ComponentType;35+}36+37+const routesFor = (view: ReactNode, options: RenderOptions) => {38+ const root = createRootRoute({ component: () => view });39+ const project = createRoute({ getParentRoute: () => root, path: "$project" });40+41+ return root.addChildren([42+ createRoute({ getParentRoute: () => root, path: "/" }),43+ createRoute({ getParentRoute: () => root, path: "today" }),44+ createRoute({ getParentRoute: () => root, path: "agents" }),45+ createRoute({ getParentRoute: () => root, path: "people/$handle" }),46+ project.addChildren([47+ createRoute({ getParentRoute: () => project, path: "/" }),48+ options.rail === undefined49+ ? createRoute({ getParentRoute: () => project, path: "$" })50+ : createRoute({51+ getParentRoute: () => project,52+ path: "$",53+ staticData: { rail: options.rail },54+ }),55+ ]),56+ ]);57+};58+59+/** `view`'s static markup inside a router whose location is `url`. */60+export const renderAt = (61+ url: string,62+ view: ReactNode,63+ options: RenderOptions = {}64+): Effect.Effect<string, Cause.UnknownError> => {65+ const router = createRouter({66+ history: createMemoryHistory({ initialEntries: [url] }),67+ routeTree: routesFor(view, options),68+ });69+70+ return Effect.tryPromise(() => router.load()).pipe(71+ Effect.map(() => renderToStaticMarkup(<RouterProvider router={router} />))72+ );73+};modified:apps/web/test/root.test.tsx+31 added
6 unmodified lines7 import { describe, expect, it } from "@effect/vitest";8 import { renderToStaticMarkup } from "react-dom/server";9 10 import { themeColors } from "../src/features/shared/theme.ts";11+import { getRouter } from "../src/router.tsx";12 import { rootHead, ThemeColors } from "../src/routes/__root.tsx";13 14 describe("the document's head", () => {15 it("gives each meta a name of its own, since TanStack keeps one per name", () => {58 unmodified lines74 },75 ]);76 });77 });78+79+describe("the router", () => {80+ const { options } = getRouter();81+82+ // A link fetches its page's code and loader data on hover or focus, and83+ // a click soon after reads nothing twice.84+ it("preloads a link's page on intent, and keeps what it read for a click", () => {85+ expect(options.defaultPreload).toBe("intent");86+ expect(options.defaultPreloadDelay).toBe(50);87+ expect(options.defaultStaleTime).toBeGreaterThan(0);88+ expect(options.defaultPreloadStaleTime).toBeGreaterThanOrEqual(89+ options.defaultStaleTime ?? 090+ );91+ });92+93+ it("waits 300 ms before drawing a page as pending, so a quick move never flashes", () => {94+ expect(options.defaultPendingMs).toBe(300);95+ expect(options.defaultPendingComponent).toBeDefined();96+ });97+98+ it("draws a failure and a missing page in the shell, never the router's own", () => {99+ expect(options.defaultErrorComponent).toBeDefined();100+ expect(options.defaultNotFoundComponent).toBeDefined();101+ });102+103+ it("scrolls each new page's main pane back to its top", () => {104+ expect(options.scrollRestoration).toBeTruthy();105+ expect(options.scrollToTopSelectors).toContain("#main");106+ });107+});modified:apps/web/test/shared.test.tsx+1 added-71 removed
23 unmodified lines24 import { CommandLine } from "../src/features/shared/command.tsx";25 import { CreditTrailers } from "../src/features/shared/credits.tsx";26 import { EmptyState } from "../src/features/shared/empty.tsx";27 import { HandleLink } from "../src/features/shared/handle.tsx";28-import {29- PageShell,30- SiteFooter,31- SiteHeader,32-} from "../src/features/shared/layout.tsx";28 import { OutcomeView, StageStrip } from "../src/features/shared/outcome.tsx";29 import { PostureBadge } from "../src/features/shared/posture.tsx";30 import { RefusalView } from "../src/features/shared/refusal.tsx";31 import { themeColors } from "../src/features/shared/theme.ts";344 unmodified lines376 expect(text).toContain(command);377 });378 });379 385-describe(PageShell, () => {386- it("gives a page one main region headed by its title", () => {387- const markup = markupOf(388- <PageShell title="Today">389- <p>Decisions 2 of 5</p>390- </PageShell>391- );392-393- expect(markup).toMatch(/<main\b[^>]*>.*<h1\b[^>]*>Today<\/h1>.*<\/main>/u);394- expect(markup).toContain("<p>Decisions 2 of 5</p>");395- });396-});397-398-describe("the shell", () => {399- const platformUrl = "https://platform-test.example.workers.dev";400-401- it("marks the page the reader is on in the header", () => {402- const markup = markupOf(403- <SiteHeader404- pathname="/today"405- session={<a href="/auth/signin">Sign in</a>}406- />407- );408-409- expect(markup).toMatch(/<a\b[^>]*aria-current="page"[^>]*>Today<\/a>/u);410- expect(markup).not.toMatch(/<a\b[^>]*aria-current="page"[^>]*>Asks<\/a>/u);411- expect(markup).toContain(">Sign in</a>");412- });413-414- it("links Asks, Today and Agents in the header, marking Agents current on its page", () => {415- const markup = markupOf(<SiteHeader pathname="/agents" session={null} />);416-417- const links = [418- ...markup.matchAll(419- /<a\b[^>]*href="(?<href>[^"]+)"[^>]*>(?<label>[^<]+)<\/a>/gu420- ),421- ].map(({ groups }) => [groups?.href, groups?.label]);422-423- expect(links).toStrictEqual([424- ["#main", "Skip to content"],425- ["/", Brand.name],426- ["/", "Asks"],427- ["/today", "Today"],428- ["/agents", "Agents"],429- ]);430- expect(markup).toMatch(/<a\b[^>]*aria-current="page"[^>]*>Agents<\/a>/u);431- expect(markup).not.toMatch(/<a\b[^>]*aria-current="page"[^>]*>Today<\/a>/u);432- });433-434- it("gives the command-line ways in at the foot of every page: plain git and the CLI", () => {435- const text = textOf(<SiteFooter platformUrl={platformUrl} />);436-437- expect(text).toContain("Plain git: clone any project");438- expect(text).toContain(`git clone ${platformUrl}/<project>.git`);439- expect(text).toContain(`curl -fsSL ${platformUrl}/install.sh | sh`);440- });441-442- it("sends a reader who wants to connect an agent to the Agents page", () => {443- const markup = markupOf(<SiteFooter platformUrl={platformUrl} />);444-445- expect(markup).toMatch(/<a\b[^>]*href="\/agents"[^>]*>/u);446- expect(textOf(<SiteFooter platformUrl={platformUrl} />)).toContain(447- "Connect an agent"448- );449- });450-380+describe("the theme", () => {381 it("names the paper colours the theme-color meta repeats", () => {382 expect(styles).toContain(`--background: ${themeColors.light};`);383 expect(styles).toContain(`--background: ${themeColors.dark};`);384 });23 unmodified linesadded:apps/web/test/shell.test.tsx+362 added
1+/**2+ * The shell every page sits in, rendered to HTML inside a router at an3+ * address (`render.tsx`): the rail's sections and the project's, main with4+ * its context bar, the inspector when the page has facts, the phone's5+ * bottom bar, and a skip link. Its links are the router's, so a click moves6+ * without reloading the document.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { Brand } from "@repo/brand";10+import {11+ createMemoryHistory,12+ createRootRoute,13+ createRoute,14+ createRouter,15+ Outlet,16+ RouterProvider,17+} from "@tanstack/react-router";18+import { Effect } from "effect";19+import { renderToStaticMarkup } from "react-dom/server";20+21+import { PageShell } from "../src/features/shared/layout.tsx";22+import { RouteError } from "../src/features/shared/pending.tsx";23+import { AppShell } from "../src/features/shared/shell/app-shell.tsx";24+import { RailSlot } from "../src/features/shared/shell/rail-slot.tsx";25+import { Workspace } from "../src/features/shared/shell/workspace.tsx";26+import { renderAt } from "./render.tsx";27+28+/** The element `tag` whose opening tag carries `attribute`, whole (no nested `tag`). */29+const elementOf = (markup: string, tag: string, attribute: string) =>30+ new RegExp(`<${tag}\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</${tag}>`, "u").exec(31+ markup32+ )?.[0] ?? "";33+34+/** Each link in `markup`: its text, href, and the router's marks on it. */35+const linksOf = (markup: string) =>36+ [...markup.matchAll(/<a\b(?<attributes>[^>]*)>(?<text>[\s\S]*?)<\/a>/gu)].map(37+ ({ groups }) => {38+ const attributes = groups?.attributes ?? "";39+40+ return {41+ active: /data-status="active"/u.test(attributes),42+ current: /aria-current="page"/u.exec(attributes) !== null,43+ href: /href="(?<href>[^"]*)"/u.exec(attributes)?.groups?.href,44+ text: (groups?.text ?? "")45+ .replaceAll(/<[^>]+>/gu, " ")46+ .replaceAll(/\s+/gu, " ")47+ .trim(),48+ };49+ }50+ );51+52+/** What a reader sees of `markup`, tags gone and spaces folded. */53+const textOf = (markup: string) =>54+ markup55+ .replaceAll(/<[^>]+>/gu, " ")56+ .replaceAll(/\s+/gu, " ")57+ .trim();58+59+const ledgerPage = (facts: boolean) => (60+ <AppShell>61+ <Workspace62+ crumbs={[{ label: "datekit", to: "/datekit" }, { label: "Ledger" }]}63+ title="Ledger"64+ {...(facts65+ ? { facts: <p>Posture: open</p>, factsHeading: "This ledger" }66+ : {})}67+ >68+ <p>Entries</p>69+ </Workspace>70+ </AppShell>71+);72+73+/** What a code page puts in the rail's slot. */74+const Tree = () => (75+ <RailSlot>76+ <p>src/add.ts</p>77+ </RailSlot>78+);79+80+describe("the shell", () => {81+ it.effect(82+ "names the site's sections in the rail, each a word, and the project's under it with the page being read current",83+ () =>84+ Effect.gen(function* () {85+ const markup = yield* renderAt("/datekit/ledger", ledgerPage(true));86+ const rail = elementOf(markup, "nav", 'aria-label="Site"');87+ const links = linksOf(rail);88+89+ expect(rail).not.toBe("");90+ expect(91+ links.filter(92+ ({ href, text }) =>93+ ["/", "/today", "/agents"].includes(href ?? "") &&94+ text !== Brand.name95+ )96+ ).toStrictEqual([97+ { active: false, current: false, href: "/", text: "Asks" },98+ { active: false, current: false, href: "/today", text: "Today" },99+ {100+ active: false,101+ current: false,102+ href: "/agents",103+ text: "For agents",104+ },105+ ]);106+ expect(107+ links108+ .filter(109+ ({ href }) =>110+ href?.startsWith("/datekit/") === true || href === "/datekit"111+ )112+ .map(({ href, text, current }) => ({ current, href, text }))113+ .filter(({ text }) => text !== "datekit")114+ ).toStrictEqual([115+ { current: false, href: "/datekit", text: "Asks" },116+ { current: false, href: "/datekit/tree/main", text: "Code" },117+ { current: false, href: "/datekit/commits/main", text: "Landings" },118+ { current: false, href: "/datekit/refs", text: "Refs" },119+ { current: false, href: "/datekit/people", text: "Policy" },120+ { current: true, href: "/datekit/ledger", text: "Ledger" },121+ { current: false, href: "/datekit/env", text: "Env shape" },122+ ]);123+ })124+ );125+126+ it.effect(127+ "names the current project in the rail at once, before the list of projects has arrived",128+ () =>129+ Effect.gen(function* () {130+ const rail = elementOf(131+ yield* renderAt("/datekit/ledger", ledgerPage(false)),132+ "nav",133+ 'aria-label="Site"'134+ );135+136+ expect(textOf(rail)).toContain("Projects");137+ expect(linksOf(rail).map(({ text }) => text)).toContain("datekit");138+ })139+ );140+141+ it.effect(142+ "draws every link in the rail with the router's link, which marks the page it leads to",143+ () =>144+ Effect.gen(function* () {145+ const agents = linksOf(146+ elementOf(147+ yield* renderAt("/agents", ledgerPage(false)),148+ "nav",149+ 'aria-label="Site"'150+ )151+ );152+153+ const ledger = linksOf(154+ elementOf(155+ yield* renderAt("/datekit/ledger", ledgerPage(false)),156+ "nav",157+ 'aria-label="Site"'158+ )159+ );160+161+ expect(agents.filter(({ active }) => active)).toStrictEqual([162+ { active: true, current: true, href: "/agents", text: "For agents" },163+ ]);164+ expect(ledger.filter(({ active }) => active)).toStrictEqual([165+ {166+ active: true,167+ current: true,168+ href: "/datekit/ledger",169+ text: "Ledger",170+ },171+ ]);172+ })173+ );174+175+ it.effect("shows no project's sections on a page outside a project", () =>176+ Effect.gen(function* () {177+ const rail = elementOf(178+ yield* renderAt("/agents", ledgerPage(false)),179+ "nav",180+ 'aria-label="Site"'181+ );182+183+ expect(linksOf(rail).map(({ href }) => href)).not.toContain(184+ "/datekit/ledger"185+ );186+ })187+ );188+189+ it.effect(190+ "gives the page one main region, its context bar naming the project and the page",191+ () =>192+ Effect.gen(function* () {193+ const markup = yield* renderAt("/datekit/ledger", ledgerPage(true));194+ const main = elementOf(markup, "main", 'id="main"');195+ const crumbs = elementOf(main, "nav", 'aria-label="Breadcrumb"');196+197+ expect(main).toContain("<p>Entries</p>");198+ expect(textOf(crumbs)).toBe("datekit / Ledger");199+ expect(linksOf(crumbs)).toStrictEqual([200+ { active: false, current: false, href: "/datekit", text: "datekit" },201+ ]);202+ expect(main).toMatch(/<h1\b[^>]*>Ledger<\/h1>/u);203+ })204+ );205+206+ it.effect(207+ "names the page's project from the address when the page gives no crumbs of its own",208+ () =>209+ Effect.gen(function* () {210+ const markup = yield* renderAt(211+ "/datekit/env",212+ <AppShell>213+ <PageShell title="Env shape of datekit">214+ <p>Items</p>215+ </PageShell>216+ </AppShell>217+ );218+219+ expect(220+ textOf(elementOf(markup, "nav", 'aria-label="Breadcrumb"'))221+ ).toBe("datekit / Env shape");222+ })223+ );224+225+ it.effect(226+ "gives the facts an inspector named Facts when the page has some, and none when it has none",227+ () =>228+ Effect.gen(function* () {229+ const withFacts = yield* renderAt("/datekit/ledger", ledgerPage(true));230+ const without = yield* renderAt("/datekit/ledger", ledgerPage(false));231+232+ expect(elementOf(withFacts, "aside", 'aria-label="Facts"')).toContain(233+ "Posture: open"234+ );235+ expect(elementOf(withFacts, "aside", 'aria-label="Facts"')).toContain(236+ "This ledger"237+ );238+ expect(without).not.toContain("<aside");239+ })240+ );241+242+ it.effect(243+ "gives phones a bar of sections: Asks, Today, Projects and More",244+ () =>245+ Effect.gen(function* () {246+ const bar = elementOf(247+ yield* renderAt("/datekit/ledger", ledgerPage(false)),248+ "nav",249+ 'aria-label="Sections"'250+ );251+252+ expect(textOf(bar)).toBe("Asks Today Projects More");253+ expect(linksOf(bar).map(({ href }) => href)).toStrictEqual([254+ "/",255+ "/today",256+ ]);257+ })258+ );259+260+ it.effect("lets a keyboard skip to the page's content", () =>261+ Effect.gen(function* () {262+ const markup = yield* renderAt("/today", ledgerPage(false));263+264+ expect(markup).toMatch(265+ /<a\b[^>]*href="#main"[^>]*>Skip to content<\/a>/u266+ );267+ expect(markup).toContain(Brand.name);268+ })269+ );270+271+ it.effect(272+ "keeps the rail's slot for a page that fills it, and none for a page that does not",273+ () =>274+ Effect.gen(function* () {275+ const code = yield* renderAt("/datekit/tree/main", ledgerPage(false), {276+ rail: Tree,277+ });278+279+ const ledger = yield* renderAt("/datekit/ledger", ledgerPage(false));280+281+ expect(elementOf(code, "nav", 'aria-label="Site"')).toContain(282+ "<p>src/add.ts</p>"283+ );284+ expect(ledger).not.toContain("src/add.ts");285+ })286+ );287+});288+289+describe("the shell's sources", () => {290+ // Keys only: the sources as text.291+ const sources: Readonly<Record<string, string>> = import.meta.glob(292+ "../src/features/shared/shell/*.tsx",293+ { eager: true, import: "default", query: "?raw" }294+ );295+296+ it("draw no plain anchor: every link is the router's, so a click never reloads the document", () => {297+ expect(Object.keys(sources).length).toBeGreaterThan(3);298+ expect(299+ Object.entries(sources).flatMap(([file, source]) =>300+ /<a\b/u.test(source) ? [file] : []301+ )302+ ).toStrictEqual([]);303+ });304+});305+306+describe(PageShell, () => {307+ it.effect("gives a page one main region headed by its title", () =>308+ Effect.gen(function* () {309+ const markup = yield* renderAt(310+ "/today",311+ <PageShell title="Today">312+ <p>Decisions 2 of 5</p>313+ </PageShell>314+ );315+316+ expect(elementOf(markup, "main", 'id="main"')).toMatch(317+ /<h1\b[^>]*>Today<\/h1>[\s\S]*<p>Decisions 2 of 5<\/p>/u318+ );319+ })320+ );321+});322+323+describe("a page whose read fails", () => {324+ // A transport failure is not a refusal: ink and a way to ask again,325+ // inside the shell, never the router's own error page.326+ it.effect("says the platform did not answer, in ink, inside the shell", () =>327+ Effect.gen(function* () {328+ const root = createRootRoute({329+ component: () => (330+ <AppShell>331+ <Outlet />332+ </AppShell>333+ ),334+ });335+336+ const failing = createRoute({337+ getParentRoute: () => root,338+ loader: () => Promise.reject(new Error("fetch failed")),339+ path: "$project",340+ });341+342+ const router = createRouter({343+ defaultErrorComponent: RouteError,344+ history: createMemoryHistory({ initialEntries: ["/datekit"] }),345+ routeTree: root.addChildren([failing]),346+ });347+348+ yield* Effect.tryPromise(() => router.load());349+350+ const markup = renderToStaticMarkup(<RouterProvider router={router} />);351+ const main = elementOf(markup, "main", 'id="main"');352+353+ expect(textOf(main)).toContain("The platform did not answer.");354+ expect(textOf(main)).toContain(355+ "Try again in a minute; nothing was changed."356+ );357+ expect(main).toMatch(/<button\b[^>]*>Reload<\/button>/u);358+ expect(main).not.toContain("refused");359+ expect(markup).toContain('aria-label="Site"');360+ })361+ );362+});