Skip to content
Myr

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().

authored by oscabriel · committed by oscabriel · parent 512af5a · Browse files · 54 files+3891 added−405 removed
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

54 files+3891 added−405 removed

modified:apps/web/src/components/ui/dialog.tsx+1 added-1 removed
added:apps/web/src/components/ui/sheet.tsx+85 added
1"use client";23/**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 */9import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";10import { cva } from "class-variance-authority";11import { cn } from "cn";12import { XIcon } from "lucide-react";13import type * as React from "react";1415import { Button } from "@/components/ui/button";1617function Sheet({ ...props }: DialogPrimitive.Root.Props) {18 return <DialogPrimitive.Root data-slot="sheet" {...props} />;19}2021function SheetTrigger({ ...props }: DialogPrimitive.Trigger.Props) {22 return <DialogPrimitive.Trigger data-slot="sheet-trigger" {...props} />;23}2425function SheetClose({ ...props }: DialogPrimitive.Close.Props) {26 return <DialogPrimitive.Close data-slot="sheet-close" {...props} />;27}2829const 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);4546function 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}8485export { 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 */12import { useAtomValue } from "@effect/atom-react";13import type { Handle } from "@repo/protocol/ids";14import { useLocation } from "@tanstack/react-router";15import { Option } from "effect";16import { AsyncResult } from "effect/reactivity";17import { LogIn } from "lucide-react";1816import { HandleLink } from "../shared/handle.tsx";19import { AppLink } from "../shared/link.tsx";20import { personPath } from "../shared/paths.ts";21import { whoAtom } from "./who.ts";2223/**24 * Where sign-in comes back to: the page the reader is on, without its
8 unmodified lines
33/** Sign-in, coming back to `here` afterwards. */34export const signInHref = (here: string) =>35 `/auth/signin?${new URLSearchParams({ return: here }).toString()}`;3633/** The nav's own action style: muted text, ink on hover. */37/** The session's own action style: muted text, ink on hover. */38const 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";4041/**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 */45export type SessionLayout = "bar" | "rail";4647export 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 line
90 </div>91 ),92 });9376export const SessionSlot = () => {94export const SessionSlot = ({95 layout = "bar",96}: {97 readonly layout?: SessionLayout;98}) => {99 const here = useLocation({ select: hereOf });100 const who = useAtomValue(whoAtom);101102 return (103 <SessionView104 handle={AsyncResult.isSuccess(who) ? who.value : Option.none()}105 here={here}106 layout={layout}107 />108 );109};110111/** Whether someone is signed in, as far as this browser knows yet. */112export const useSignedIn = (): boolean => {113 const who = useAtomValue(whoAtom);114115 return AsyncResult.isSuccess(who) && Option.isSome(who.value);116};
deleted:apps/web/src/features/front/reading.tsx-47 removed
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 */12import type { ProjectName } from "@repo/protocol/ids";13import type { ReactNode } from "react";1415import { buttonVariants } from "@/components/ui/button";15import { AppLink } from "../shared/link.tsx";16import { projectSections } from "../shared/shell/sections.ts";17import type { ProjectTab } from "../shared/shell/sections.ts";1817import { envPath, ledgerPath } from "../shared/paths.ts";19export type { ProjectTab } from "../shared/shell/sections.ts";2019/** Which of a project's pages is being read. */20export type ProjectTab =21 | "code"22 | "env"23 | "landings"24 | "ledger"25 | "overview"26 | "people"27 | "refs";2829/** Each tab: its label and its page's address, in the order the nav shows them. */30const 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 }[];4421export const ProjectNav = ({22 current,23 project,24}: {
1 unmodified line
26 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 lines
15import type { ProjectName } from "@repo/protocol/ids";16import type { DateTime } from "effect";1718import { EntriesTable, ReadmeSection } from "../code/tree-view.tsx";19import { ReadingRows } from "../front/reading.tsx";19import { SignedInProposeLink } from "../propose/propose-link.tsx";20import { ID, SECTION } from "../shared/classes.ts";21import { CommandLine } from "../shared/command.tsx";22import { EmptyState } from "../shared/empty.tsx";23import { PageShell } from "../shared/layout.tsx";24import { askPath } from "../shared/paths.ts";25import { ReadingRows } from "../shared/pending.tsx";26import { PostureBadge } from "../shared/posture.tsx";27import { When } from "../shared/time.tsx";28import { AskFields, AskStanding } from "./asks.tsx";29import { LandingList } from "./landings.tsx";
240 unmodified lines
added: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 */13import { useHydrated, useLocation } from "@tanstack/react-router";14import { Suspense, useCallback, useMemo, useState } from "react";15import type { ReactNode } from "react";1617import { KeysProvider } from "../keys.tsx";18import { SkipLink } from "../layout.tsx";19import { BottomBar } from "./bottom-bar.tsx";20import { ShellContext, ShellReadsContext } from "./context.ts";21import type { Overlay, ShellReads } from "./context.ts";22import { LazyOverlays } from "./lazy-overlays.ts";23import { Rail } from "./rail.tsx";24import { TopBar } from "./top-bar.tsx";2526export 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();3334 // 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 }>();4041 const overlay = opened?.at === pathname ? opened.overlay : undefined;4243 const open = useCallback(44 (next: Overlay) => {45 setOpened({ at: pathname, overlay: next });46 },47 [pathname]48 );4950 const close = useCallback(() => {51 setOpened(undefined);52 }, []);5354 const openDialog = useCallback(() => {55 open("keys");56 }, [open]);5758 const shell = useMemo(() => ({ open }), [open]);5960 const reads = useMemo(61 () => ({ projects, todayCount }),62 [projects, todayCount]63 );6465 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 */8import { CalendarCheck, Ellipsis, Folders, List } from "lucide-react";9import type { LucideIcon } from "lucide-react";1011import { AppLink } from "../link.tsx";12import { useShell } from "./context.ts";13import type { Overlay } from "./context.ts";1415const 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";1718const MARK = "size-5";1920const 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}[];2829const 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}[];3738export const BottomBar = () => {39 const { open } = useShell();4041 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 */8import { Effect } from "effect";9import { Check, Copy } from "lucide-react";10import { useState } from "react";11import type { ReactNode } from "react";1213import { Button } from "../../../components/ui/button.tsx";14import { useNumberedCommand } from "../keys.tsx";15import { AppLink } from "../link.tsx";16import type { Crumb } from "./sections.ts";1718/** The trail to the page, as a breadcrumb: each step a link but the page itself. */19export 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" : "";2930 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);6465/** Copy `command`, then show it copied for two seconds. */66const 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 );8182/**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 */87export const CopyCommand = ({ command }: { readonly command: string }) => {88 const [copied, setCopied] = useState(false);89 const number = useNumberedCommand(command);9091 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};116117export 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 */8import type { ProjectListing } from "@repo/protocol/domain/front-page";9import { ProjectName } from "@repo/protocol/ids";10import { useMatch } from "@tanstack/react-router";11import { Schema } from "effect";12import { createContext, useContext } from "react";13import type { ReactNode } from "react";1415/** One of the shell's overlays. */16export type Overlay = "keys" | "menu" | "more" | "projects";1718export interface Shell {19 readonly open: (overlay: Overlay) => void;20}2122export const ShellContext = createContext<Shell>({23 open: () => {24 // Outside the shell (a view's own test) there is nothing to open.25 },26});2728/** The shell's overlays, from inside it. */29export const useShell = (): Shell => useContext(ShellContext);3031const isProjectName = Schema.is(ProjectName);3233/**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 */38export const useCurrentProject = (): ProjectName | undefined =>39 useMatch({40 from: "/$project",41 select: ({ params }) =>42 isProjectName(params.project) ? params.project : undefined,43 shouldThrow: false,44 });4546/** What the root route read for the rail. */47export 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}5354export const ShellReadsContext = createContext<ShellReads>({});5556/**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 */61export const useProjectList = (): readonly ProjectListing[] | undefined =>62 useContext(ShellReadsContext).projects;6364/** Today's count for the rail, when there is one. */65export const useTodayCount = (): ReactNode =>66 useContext(ShellReadsContext).todayCount;
added:apps/web/src/features/shared/shell/facts-sheet.tsx+31 added
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 */7import { lazy } from "react";89export const LazyOverlays = import.meta.env.SSR10 ? undefined11 : lazy(() => import("./overlays.tsx"));1213export 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 */9import { Brand } from "@repo/brand";10import { useRouter } from "@tanstack/react-router";11import { Bot, Keyboard } from "lucide-react";12import { useRef } from "react";13import type { RefObject } from "react";1415import {16 Combobox,17 ComboboxEmpty,18 ComboboxInput,19 ComboboxItem,20 ComboboxList,21} from "../../../components/ui/combobox.tsx";22import {23 Dialog,24 DialogContent,25 DialogDescription,26 DialogHeader,27 DialogTitle,28} from "../../../components/ui/dialog.tsx";29import { Sheet, SheetContent } from "../../../components/ui/sheet.tsx";30import { SessionSlot } from "../../auth/session-slot.tsx";31import { KeysHelp, useKeys } from "../keys.tsx";32import { AppLink } from "../link.tsx";33import { useCurrentProject, useProjectList, useShell } from "./context.ts";34import type { Overlay } from "./context.ts";35import {36 PostureMark,37 ProjectSectionList,38 RAIL_ROW,39 RailContent,40 RailFoot,41} from "./rail.tsx";4243export interface OverlayProps {44 /** The overlay open now; none when all are closed. */45 readonly overlay: Overlay | undefined;46 readonly onClose: () => void;47}4849/** A sheet's or dialog's open state, as the shell holds it. */50const openState = (open: boolean, onClose: () => void) => ({51 onOpenChange: (next: boolean) => {52 if (!next) {53 onClose();54 }55 },56 open,57});5859/** Whether the screen is at least a tablet's width, read when an overlay opens. */60const atLeastTablet = () => globalThis.matchMedia("(min-width: 40rem)").matches;6162/**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 */67const 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);7980 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);115116 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};136137/** The phone's More: For agents, the project's sections, the keys, the session. */138const More = () => {139 const project = useCurrentProject();140 const listed = useProjectList();141 const { open } = useShell();142143 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};190191const KeysDialog = ({192 onClose,193 open,194}: {195 readonly onClose: () => void;196 readonly open: boolean;197}) => {198 const keys = useKeys();199200 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};220221/**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 */225const ShellOverlays = ({ onClose, overlay }: OverlayProps) => {226 const filter = useRef<HTMLInputElement>(null);227228 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};258259export 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 */18import { useMatches } from "@tanstack/react-router";19import { createElement } from "react";20import type { ComponentType, ReactNode } from "react";2122declare 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}2829/** The slot's frame: the rest of the rail's height, scrolling on its own. */30export 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);4647/** The component the deepest matched route puts in the slot, when one does. */48export const useRailContent = (): ComponentType | undefined =>49 useMatches({50 select: (matches) =>51 matches.findLast(({ staticData }) => staticData.rail !== undefined)52 ?.staticData.rail,53 });5455/** The slot's content for the address, or nothing. */56export const RailSlotOutlet = (): ReactNode => {57 const Content = useRailContent();5859 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 */15import { Brand } from "@repo/brand";16import type { ProjectListing } from "@repo/protocol/domain/front-page";17import type { ProjectName } from "@repo/protocol/ids";18import type { Posture } from "@repo/protocol/posture";19import { useLocation } from "@tanstack/react-router";20import {21 Bot,22 CalendarCheck,23 ChevronDown,24 Eye,25 Folders,26 Keyboard,27 List,28 LockKeyhole,29 LockKeyholeOpen,30 Menu,31} from "lucide-react";32import type { LucideIcon } from "lucide-react";33import type { ReactNode } from "react";3435import { Button } from "../../../components/ui/button.tsx";36import { Skeleton } from "../../../components/ui/skeleton.tsx";37import { SessionSlot } from "../../auth/session-slot.tsx";38import { postureLabel } from "../../project/posture-label.ts";39import { AppLink } from "../link.tsx";40import {41 useCurrentProject,42 useProjectList,43 useShell,44 useTodayCount,45} from "./context.ts";46import { RailSlotOutlet, useRailContent } from "./rail-slot.tsx";47import { POSTURE_WORD, projectSections, sectionOf } from "./sections.ts";4849/** A row of the rail, before the fill that marks the current one. */50const 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";5253/** A row of the rail: a word (and its mark), 32 px, filled when current. */54export const RAIL_ROW = `${RAIL_BASE} [&[aria-current]]:bg-surface`;5556/** A row's mark: 16 px at the marks' stroke, muted until the row is current. */57const MARK = "text-muted-foreground size-4 shrink-0";5859/** At most this many projects in the rail; more open the switcher. */60const SHOWN = 8;6162const 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}[];7172/** Only the page itself is current; its search (a filter, a selection) does not count. */73const EXACT = { exact: true, includeSearch: false } as const;7475/** A count of things at a rail row's end, in tabular figures, with what it counts for a screen reader. */76export 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);8889/** Today's count, as the root route read it. */90const TodayCount = () => useTodayCount() ?? null;9192/** The wordmark, home to the front page. */93export 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);106107/** Asks, Today and For agents. */108const 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);121122/** A posture's mark: a lock in the sealed role when something is kept sealed. */123const 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>;133134/** A project's posture at its row's end: the mark in its role, a short word muted, the full label as its title. */135export const PostureMark = ({ posture }: { readonly posture: Posture }) => {136 const { icon: Icon, tone } = POSTURE_MARK[posture];137138 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};154155/** 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. */157const PROJECT_ROW = RAIL_BASE;158159const 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);179180/** The current project's sections, indented under it, the open asks counted beside Asks. */181export 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 });191192 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};215216/** The list's place while it is read: three rows of the rail's height. */217const PLACEHOLDERS = ["w-24", "w-20", "w-28"] as const;218219const 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);228229/**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 */234const Projects = () => {235 const current = useCurrentProject();236 const listed = useProjectList();237 const { open } = useShell();238239 const listingOf = (project: string) =>240 listed?.find((listing) => listing.project === project);241242 const others = (listed ?? []).filter(({ project }) => project !== current);243 const room = SHOWN - (current === undefined ? 0 : 1);244245 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};296297/** The rail's foot: the session, and the Keys button that opens the `?` dialog. */298export const RailFoot = () => {299 const { open } = useShell();300301 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};318319/** The rail's sections and projects: the column's middle, and the Menu sheet's body. */320export const RailContent = (): ReactNode => (321 <div className="flex flex-col gap-2 px-2 py-2">322 <SiteSections />323 <Projects />324 </div>325);326327/**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 */332const ProjectLine = ({ project }: { readonly project: ProjectName }) => {333 const listed = useProjectList();334335 const section = useLocation({336 select: ({ pathname }) => sectionOf(pathname),337 });338339 const label = projectSections(project).find(340 ({ tab }) => tab === section341 )?.label;342343 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};367368/**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 */374export const Rail = () => {375 const slotted = useRailContent() !== undefined;376 const project = useCurrentProject();377 const { open } = useShell();378379 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 */7import type { Posture } from "@repo/protocol/posture";8import { Result } from "effect";910/** Which of a project's pages is being read. */11export type ProjectTab =12 | "code"13 | "env"14 | "landings"15 | "ledger"16 | "overview"17 | "people"18 | "refs";1920/** One of a project's sections: its word, its page, and the tab it is. */21export interface Section {22 readonly label: string;23 readonly tab: ProjectTab;24 readonly to: string;25}2627/**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 */33export 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];4243/** The first segment of each of a project's pages, by the section it sits in. */44const 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>;5758/** The site's own first segments: every other one names a project. */59const SITE = new Set(["agents", "people", "today"]);6061/** `segment` decoded, or as it came when it does not decode. */62const decoded = (segment: string) =>63 Result.getOrElse(64 Result.try(() => decodeURIComponent(segment)),65 () => segment66 );6768/** The address's segments, decoded. */69const segmentsOf = (pathname: string) =>70 pathname71 .split("/")72 .filter((segment) => segment !== "")73 .map(decoded);7475/** The project an address is in, by its first segment; none on the site's own pages. */76export const projectOf = (pathname: string): string | undefined => {77 const [first] = segmentsOf(pathname);7879 return first === undefined || SITE.has(first) ? undefined : first;80};8182/** The project section an address sits in; none for a page under none (a decision, a proposal). */83export const sectionOf = (pathname: string): ProjectTab | undefined => {84 const [first, second] = segmentsOf(pathname);8586 if (first === undefined || SITE.has(first)) {87 return undefined;88 }8990 return second === undefined91 ? "overview"92 : Object.entries(SECTION_OF).find(([segment]) => segment === second)?.[1];93};9495/** One step of the trail to a page: its word, its page (none for the page itself), and whether it is an id. */96export interface Crumb {97 readonly label: string;98 readonly mono?: boolean;99 readonly to?: string;100}101102const 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>;111112/** A section's crumb, linked to its page when a page sits below it. */113const 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);120121 return below && section !== undefined ? { label, to: section.to } : { label };122};123124/** A project's crumb, then its section's. */125const projectCrumbs = (126 project: string,127 tab: ProjectTab,128 below: boolean129): readonly Crumb[] => [130 { label: project, to: `/${project}` },131 sectionCrumb(project, tab, below),132];133134/** A code page's trail: Code, then the path in hand (none at the root). */135const pathCrumbs = (project: string, path: string): readonly Crumb[] =>136 path === ""137 ? projectCrumbs(project, "code", false)138 : [...projectCrumbs(project, "code", true), { label: path, mono: true }];139140/** The site's own pages' trails, by first segment. */141const 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>;149150/** A project's subject pages' trails (an ask, an answer, a commit, a path…), by second segment. */151const 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>;184185/**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 */190export const crumbsFor = (pathname: string): readonly Crumb[] => {191 const [first, second, third, ...rest] = segmentsOf(pathname);192193 if (first === undefined) {194 return [{ label: "Asks" }];195 }196197 const site = Object.entries(SITE_CRUMBS).find(([name]) => name === first);198199 if (site !== undefined) {200 return site[1](second);201 }202203 const subject = Object.entries(SUBJECT_CRUMBS).find(204 ([name]) => name === second205 );206207 if (subject !== undefined && third !== undefined) {208 return subject[1](first, third, rest.join("/"));209 }210211 const tab = sectionOf(pathname);212213 return tab === undefined214 ? [215 { label: first, to: `/${first}` },216 { label: rest.at(-1) ?? third ?? second ?? first },217 ]218 : projectCrumbs(first, tab, false);219};220221/** A posture in one short word for the rail, beside its mark; the full label is its title. */222export 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 */19import {20 defaultStringifySearch,21 useLocation,22 useRouter,23} from "@tanstack/react-router";24import { Effect, Option, Schema } from "effect";25import { useCallback } from "react";2627import { useEscapeClears } from "../keys.tsx";2829/** The search params a list selects by. */30export type SelectionParam = "ask" | "decision";3132/** A selection as an address's search carries it. */33const Selection = Schema.Struct({34 ask: Schema.optionalKey(Schema.String),35 decision: Schema.optionalKey(Schema.String),36});3738const decodeSelection = Schema.decodeUnknownOption(Selection);3940/**41 * `searchStr` (`?filter=…&ask=…`) with `param` set to `id`, or without it,42 * each value written as the router writes it.43 */44export const searchWith = (45 searchStr: string,46 param: SelectionParam,47 id?: string48): string => {49 const params = new URLSearchParams(searchStr);5051 params.delete(param);5253 if (id !== undefined) {54 params.set(55 param,56 new URLSearchParams(defaultStringifySearch({ [param]: id })).get(param) ??57 id58 );59 }6061 const next = params.toString();6263 return next === "" ? "" : `?${next}`;64};6566export const useSelection = (param: SelectionParam) => {67 const router = useRouter();68 const { pathname, search, searchStr } = useLocation();6970 const selected = Option.getOrUndefined(71 Option.flatMapNullishOr(decodeSelection(search), (read) => read[param])72 );7374 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 );8889 const select = useCallback(90 (id: string) => {91 move(id);92 },93 [move]94 );9596 const clear = useCallback(() => {97 move();98 }, [move]);99100 useEscapeClears(clear);101102 return { clear, select, selected };103};104105/**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 */110export 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 */9import { useLocation } from "@tanstack/react-router";10import { ChevronLeft, ChevronsUpDown, Menu } from "lucide-react";1112import { Button } from "../../../components/ui/button.tsx";13import { SessionSlot } from "../../auth/session-slot.tsx";14import { AppLink } from "../link.tsx";15import { useCurrentProject, useShell } from "./context.ts";16import { Wordmark } from "./rail.tsx";17import { crumbsFor } from "./sections.ts";1819/** The page above a subject page (its crumb before last), when the address is one. */20const parentOf = (pathname: string) => {21 const crumbs = crumbsFor(pathname);22 const parent = crumbs.at(-2);2324 return crumbs.length >= 3 && parent?.to !== undefined25 ? { label: parent.label, to: parent.to }26 : undefined;27};2829export const TopBar = () => {30 const { open } = useShell();31 const project = useCurrentProject();32 const parent = useLocation({ select: ({ pathname }) => parentOf(pathname) });3334 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 */17import { useHydrated, useLocation, useRouter } from "@tanstack/react-router";18import { Predicate } from "effect";19import { ChevronDown, PanelRight } from "lucide-react";20import { Suspense, useState } from "react";21import type { ReactNode } from "react";2223import { Button } from "../../../components/ui/button.tsx";24import { CommandSlotProvider } from "../keys.tsx";25import { ContextBar } from "./context-bar.tsx";26import { LazyFactsSheet } from "./lazy-overlays.ts";27import { crumbsFor } from "./sections.ts";28import type { Crumb } from "./sections.ts";2930export 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}6061/** Main's side padding at each width. */62export const GUTTER = "px-4 tablet:px-5 shell:px-6";6364/** How wide rows and the head run: 56 rem, from the left. */65export const MEASURE = "max-w-[56rem]";6667/** Past this many characters a title is set a step down, to stay within three lines. */68const LONG_TITLE = 80;6970const 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);9192/** The inspector's heading row: names what the facts describe, and announces it when it changes. */93const 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);101102/** The facts settling in when their subject changes: 120 ms of opacity, nothing that moves. */103const 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);114115/** The facts in main, after the head, below the shell's width. */116const 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 );157158/** A code page's Facts button, and its facts as a sheet from the right. */159const 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();168169 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};196197const 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";219220 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};298299const AtAddress = (props: WorkspaceProps) => (300 <WorkspaceView301 {...props}302 pathname={useLocation({ select: (location) => location.pathname })}303 />304);305306/**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 */311export 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 lines
5import { Brand } from "@repo/brand";67/** A page's `<title>`: the page, then the product. */8export const pageTitle = (title: string) => `${title} · ${Brand.name}`;910/**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 */21export 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 */20import { Effect, Option, Result } from "effect";21import {22 createContext,23 useCallback,24 useContext,25 useEffect,26 useId,27 useMemo,28 useRef,29 useState,30} from "react";31import type { ReactNode } from "react";3233import { Kbd } from "../../components/ui/kbd.tsx";3435/** A key pressed, as the listener reads it. */36export 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}4445/** What a key asks for. */46export 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 };5758const MOVES = {59 J: "nextFile",60 K: "previousFile",61 j: "next",62 k: "previous",63} as const satisfies Record<string, KeyIntent["kind"]>;6465const DIGIT = /^[1-9]$/u;6667/** The shell's width, from which the rail and the inspector are columns. */68const SHELL_WIDTH = "(min-width: 70rem)";6970/**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 */74export const intentOf = (75 press: KeyPress,76 on: boolean77): KeyIntent | undefined => {78 if (press.inField || press.altKey || press.ctrlKey || press.metaKey) {79 return undefined;80 }8182 if (press.key === "?") {83 return { kind: "keys" };84 }8586 if (press.key === "Escape") {87 return { kind: "clear" };88 }8990 if (!on) {91 return undefined;92 }9394 if (DIGIT.test(press.key)) {95 return { index: Number(press.key), kind: "copy" };96 }9798 const move = Object.entries(MOVES).find(([key]) => key === press.key);99100 return move === undefined ? undefined : { kind: move[1] };101};102103/** Where the switch is kept, in the browser's storage. */104const SWITCH = "keys.single";105106/** Whether the single keys are on: on unless `storage` says off, or cannot say. */107export const readShortcuts = (storage?: Storage): boolean =>108 storage === undefined ||109 Result.getOrElse(110 Result.try(() => storage.getItem(SWITCH) !== "off"),111 () => true112 );113114/** Keep the switch as `on` says; a storage that refuses keeps nothing. */115export const writeShortcuts = (storage: Storage | undefined, on: boolean) => {116 Result.try(() => storage?.setItem(SWITCH, on ? "on" : "off"));117};118119/** The browser's storage, when there is one this page may use. */120const localStorageOf = (): Storage | undefined =>121 Result.getOrUndefined(Result.try(() => globalThis.localStorage));122123/** The keys and what each does, as the dialog lists them. */124const 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;132133/** The switch's two settings, each a button that says whether it is pressed. */134const SETTINGS = [135 { label: "On", on: true },136 { label: "Off", on: false },137] as const;138139/**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 */143export 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);196197/** Which part of the page a command sits in: the inspector's are numbered first. */198export type CommandSlot = "facts" | "main";199200const SlotContext = createContext<CommandSlot>("main");201202/** Commands under `slot` number as the inspector's or main's. */203export const CommandSlotProvider = ({204 children,205 slot,206}: {207 readonly children: ReactNode;208 readonly slot: CommandSlot;209}) => <SlotContext value={slot}>{children}</SlotContext>;210211/** A list the page lets `j` and `k` move through. */212interface 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}220221/** The files a page lets `J` and `K` move between. */222interface FileRegistration {223 readonly read: () => {224 readonly onMove: (path: string) => void;225 readonly paths: readonly string[];226 };227 at?: string;228}229230interface Command {231 readonly command: string;232 readonly id: string;233 readonly slot: CommandSlot;234}235236/** What the page registers with the listener; one for the shell's life. */237interface Registry {238 readonly clearers: Set<() => void>;239 readonly files: Set<FileRegistration>;240 readonly lists: Set<ListRegistration>;241 readonly register: (command: Command) => () => void;242}243244/** What the keys show: whether they are on, the numbers, the last copy. */245interface KeysState {246 readonly copied: string | undefined;247 readonly numbered: ReadonlyMap<string, number>;248 readonly on: boolean;249 readonly setOn: (on: boolean) => void;250}251252const RegistryContext = createContext<Registry | undefined>(undefined);253254const StateContext = createContext<KeysState | undefined>(undefined);255256/** The keys' state, for the dialog. */257export const useKeys = () => useContext(StateContext);258259/** `item` in `set` until the returned function takes it out. */260const held = <A,>(set: Set<A>, item: A) => {261 set.add(item);262263 return () => {264 set.delete(item);265 };266};267268/** The last registered of `set`: the page's own, over any that left late. */269const lastOf = <A,>(set: ReadonlySet<A>): A | undefined => [...set].at(-1);270271/** Whether `event` was pressed inside something that takes typing. */272const inField = (event: KeyboardEvent) => {273 const [target] = event.composedPath();274275 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};283284/** Numbers commands 1 to 9: the inspector's first, each command once. */285const 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 ];292293 const unique = [...new Set(ordered.map(({ command }) => command))];294295 return new Map(296 unique.slice(0, 9).map((command, index) => [command, index + 1])297 );298};299300/** Copy `command`, then mark it copied for two seconds. */301const 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 );316317/** The row a key moved to: focused, scrolled to, and selected at the shell's width. */318const moveTo = (list: ListRegistration, step: 1 | -1) => {319 const { ids, onSelect } = list.read();320 const at = list.focused === undefined ? -1 : ids.indexOf(list.focused);321322 const next =323 ids[324 Math.min(325 Math.max(at === -1 && step === -1 ? 0 : at + step, 0),326 ids.length - 1327 )328 ];329330 if (next === undefined) {331 return;332 }333334 list.focused = next;335 list.focus(next);336337 const row = document.querySelector(`[data-list-key="${CSS.escape(next)}"]`);338339 if (row instanceof HTMLElement) {340 row.focus({ preventScroll: true });341 row.scrollIntoView({ block: "nearest" });342 }343344 // 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};349350const 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)];354355 if (next !== undefined) {356 files.at = next;357 onMove(next);358 }359};360361/** What the listener reads when a key is pressed. */362interface 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}369370/** Do what `intent` asks; whether it did anything (so the browser does not too). */371const act = (intent: KeyIntent, now: Pressing): boolean => {372 const { registry } = now;373374 if (intent.kind === "keys") {375 now.openDialog();376377 return true;378 }379380 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 }385386 return false;387 }388389 if (intent.kind === "copy") {390 const command = [...now.numbered].find(391 ([, index]) => index === intent.index392 )?.[0];393394 if (command !== undefined) {395 now.copy(command);396 }397398 return command !== undefined;399 }400401 if (intent.kind === "next" || intent.kind === "previous") {402 const list = lastOf(registry.lists);403404 if (list !== undefined) {405 moveTo(list, intent.kind === "next" ? 1 : -1);406 }407408 return list !== undefined;409 }410411 const files = lastOf(registry.files);412413 if (files !== undefined) {414 moveFile(files, intent.kind === "nextFile" ? 1 : -1);415 }416417 return files !== undefined;418};419420/**421 * The shell's one listener and the state behind it. `openDialog` opens the422 * keys dialog (the shell draws it).423 */424export 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>();436437 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]);444445 return () => {446 setCommands((now) => now.filter(({ id }) => id !== command.id));447 };448 },449 }),450 []451 );452453 const turn = useCallback((next: boolean) => {454 setOn(next);455 writeShortcuts(localStorageOf(), next);456 }, []);457458 const numbered = useMemo(() => numberOf(commands), [commands]);459460 // The listener reads the latest of these, kept here after each render.461 const pressing = useRef<Pressing | null>(null);462463 useEffect(() => {464 pressing.current = {465 copy: (command) => {466 Effect.runFork(copyNumbered(command, setCopied));467 },468 numbered,469 on,470 openDialog,471 registry,472 };473 });474475 useEffect(() => {476 const onKey = (event: KeyboardEvent) => {477 const now = pressing.current;478479 if (now === null || event.defaultPrevented || event.repeat) {480 return;481 }482483 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 );493494 if (intent !== undefined && act(intent, now)) {495 event.preventDefault();496 }497 };498499 document.addEventListener("keydown", onKey);500501 return () => {502 document.removeEventListener("keydown", onKey);503 };504 }, []);505506 const state = useMemo(507 () => ({ copied, numbered, on, setOn: turn }),508 [copied, numbered, on, turn]509 );510511 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};522523/** `value`, kept current in a ref after each render, for a handler to read later. */524const useLatest = <A,>(value: A) => {525 const latest = useRef(value);526527 useEffect(() => {528 latest.current = value;529 });530531 return latest;532};533534/**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 */540export 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 });547548 useEffect(549 () =>550 registry === undefined551 ? undefined552 : held(registry.lists, {553 focus: setFocused,554 read: () => latest.current,555 }),556 [latest, registry]557 );558559 return focused === undefined ? {} : { focused };560};561562/** Let `J` and `K` move between `paths` (the page's files, in order), each move calling `onMove`. */563export const useFileKeys = (564 paths: readonly string[],565 onMove: (path: string) => void566): void => {567 const registry = useContext(RegistryContext);568 const latest = useLatest({ onMove, paths });569570 useEffect(571 () =>572 registry === undefined573 ? undefined574 : held(registry.files, { read: () => latest.current }),575 [latest, registry]576 );577};578579/**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 */584export 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();589590 useEffect(591 () => registry?.register({ command, id, slot }),592 [command, id, registry, slot]593 );594595 return state?.on === true ? state.numbered.get(command) : undefined;596};597598/** The command a number key copied in the last two seconds, to show as copied. */599export const useCopiedCommand = (): Option.Option<string> =>600 Option.fromUndefinedOr(useContext(StateContext)?.copied);601602/** Let `Escape` call `clear` while the caller is on the page (the selection's). */603export const useEscapeClears = (clear: () => void): void => {604 const registry = useContext(RegistryContext);605 const latest = useLatest(clear);606607 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 */8import { Brand } from "@repo/brand";8import type { ReactNode } from "react";911import { CommandLine } from "./command.tsx";10import { Workspace } from "./shell/workspace.tsx";1113/** The content column every region lines up on. */14const COLUMN = "mx-auto w-full max-w-6xl px-4 sm:px-6";1512export 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>;1931const NAV = [32 { href: "/", label: "Asks" },33 { href: "/today", label: "Today" },34 { href: "/agents", label: "Agents" },35] as const;3637/** Whether `href` is the page at `pathname`, or the section it heads. */38const isCurrent = (href: string, pathname: string) =>39 href === "/" ? pathname === "/" : pathname.startsWith(href);4041export 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. */21export 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);7879export 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 */21import {22 defaultStringifySearch,23 Link,24 useRouter,25} from "@tanstack/react-router";26import type { ActiveOptions, AnyRouter } from "@tanstack/react-router";27import { Predicate } from "effect";28import { createElement } from "react";29import type { AnchorHTMLAttributes, ReactNode } from "react";3031/** An `AppLink`'s props: an anchor's, with the address as `to`. */32export 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}5152/** The address an `AppLink` names, as the router would write it. */53export 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}`}`;6364/**65 * `Link` over any router, whose `to` is any path: the router reads a path66 * built whole as it reads a typed address.67 */68const PathLink = Link<AnyRouter, string, string>;6970export const AppLink = (props: AppLinkProps): ReactNode => {71 const router = useRouter({ warn: false });7273 if (Predicate.isNotNullish(router)) {74 return <PathLink {...props} />;75 }7677 // 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;8889 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 */14import type { ErrorComponentProps } from "@tanstack/react-router";15import { useLocation } from "@tanstack/react-router";16import { Unplug } from "lucide-react";1718import { Button } from "../../components/ui/button.tsx";19import { Skeleton } from "../../components/ui/skeleton.tsx";20import { PageShell } from "./layout.tsx";21import { AppLink } from "./link.tsx";22import { crumbsFor, projectOf } from "./shell/sections.ts";23import { Workspace } from "./shell/workspace.tsx";2425const ROWS = ["first", "second", "third"] as const;2627/** Rows that hold a list's place while the platform answers: a row's height, two bars each. */28export 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);4243export const Reading = ({ title }: { readonly title: string }) => (44 <PageShell title={title}>45 <ReadingRows />46 </PageShell>47);4849const reload = () => {50 globalThis.location.reload();51};5253/** The platform did not answer: in ink, with a way to ask again. */54export 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);7677export const Unreachable = ({ title }: { readonly title: string }) => (78 <PageShell title={title}>79 <UnreachableNotice />80 </PageShell>81);8283/** The page's name as its address gives it: the last step of its trail. */84const useAddressTitle = () =>85 useLocation({86 select: ({ pathname }) => crumbsFor(pathname).at(-1)?.label ?? "",87 });8889/**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 */94export const PendingPage = () => (95 <PageShell title={useAddressTitle()}>96 <ReadingRows />97 </PageShell>98);99100/**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 */104export const RouteError = (_props: ErrorComponentProps) => (105 <PageShell title={useAddressTitle()}>106 <UnreachableNotice />107 </PageShell>108);109110/** An address no page serves: the trail up to what exists, and the ways onward. */111export const NotFoundPage = () => {112 const pathname = useLocation({ select: (location) => location.pathname });113 const project = projectOf(pathname);114115 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 lines
16import { watchAtom } from "../../../client/watch.ts";17import { AnswerView } from "../../../features/answer/answer-page.tsx";18import { NoSuchAsk } from "../../../features/ask/refused.tsx";19import { CODE, LINK } from "../../../features/shared/classes.ts";20import { pageTitle } from "../../../features/shared/head.ts";20import { pageHead } from "../../../features/shared/head.ts";21import { PageShell } from "../../../features/shared/layout.tsx";22import { answerPath } from "../../../features/shared/paths.ts";23import { notFoundFor } from "../../../features/shared/refusals.ts";24import { serverClient } from "../../../server/client.ts";
178 unmodified lines
203 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 lines
13 markdownAlternate,14 wantsMarkdown,15} from "../../../features/ask/markdown.ts";16import { NoSuchAsk } from "../../../features/ask/refused.tsx";17import { pageTitle } from "../../../features/shared/head.ts";17import { pageHead } from "../../../features/shared/head.ts";18import { notFoundFor } from "../../../features/shared/refusals.ts";19import { serverClient } from "../../../server/client.ts";20import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";21import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";
130 unmodified lines
152export 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 lines
modified:apps/web/src/routes/$project/blob/$rev/$.tsx+3 added-4 removed
15 unmodified lines
16 NumberedLines,17} from "../../../../features/code/blob-view.tsx";18import { ClientFile } from "../../../../features/code/client-code.tsx";19import { CodeNotFound } from "../../../../features/code/not-found.tsx";20import { pageTitle } from "../../../../features/shared/head.ts";20import { pageHead } from "../../../../features/shared/head.ts";21import { notFoundFor } from "../../../../features/shared/refusals.ts";22import { serverClient } from "../../../../server/client.ts";23import { PathsTree } from "../../tree/-paths-tree.tsx";24
83 unmodified lines
108 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 lines
14 CommitView,15} from "../../../features/code/commit-view.tsx";16import { CodeNotFound } from "../../../features/code/not-found.tsx";17import { diffAnchor } from "../../../features/code/paths.ts";18import { pageTitle } from "../../../features/shared/head.ts";18import { pageHead } from "../../../features/shared/head.ts";19import { notFoundFor } from "../../../features/shared/refusals.ts";20import { serverClient } from "../../../server/client.ts";2122// One commit and what it changed, read on the server: the browser then
88 unmodified lines
111 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 lines
14} from "../../../features/code/address.ts";15import { LOG_PAGE } from "../../../features/code/log-page.ts";16import { LogView } from "../../../features/code/log-view.tsx";17import { CodeNotFound } from "../../../features/code/not-found.tsx";18import { pageTitle } from "../../../features/shared/head.ts";18import { pageHead } from "../../../features/shared/head.ts";19import { notFoundFor } from "../../../features/shared/refusals.ts";20import { serverClient } from "../../../server/client.ts";2122// The log from a revision, a page at a time (`?from=` is where the page
82 unmodified lines
105 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 lines
17import { FinishView } from "../../../features/finish/finish-view.tsx";18import { isFinishDecision } from "../../../features/finish/patch.ts";19import type { FinishDecision } from "../../../features/finish/patch.ts";20import { EmptyState } from "../../../features/shared/empty.tsx";21import { pageTitle } from "../../../features/shared/head.ts";21import { pageHead } from "../../../features/shared/head.ts";22import { PageShell } from "../../../features/shared/layout.tsx";23import {24 DecidedNotice,25 FailureView,
127 unmodified lines
153};154155export 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 lines
28import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";29import { ProposalFailure } from "../../../features/proposal/failure.tsx";30import { ProposalView } from "../../../features/proposal/proposal-view.tsx";31import { EmptyState } from "../../../features/shared/empty.tsx";32import { pageTitle } from "../../../features/shared/head.ts";32import { pageHead } from "../../../features/shared/head.ts";33import { PageShell } from "../../../features/shared/layout.tsx";34import { serverClient } from "../../../server/client.ts";3536// `/$project/proposals/$proposal`: one proposal and the platform's draft of
161 unmodified lines
198};199200export 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 lines
20import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";21import { ProposalFailure } from "../../../features/proposal/failure.tsx";22import { ProposeView } from "../../../features/propose/propose-view.tsx";23import type { About } from "../../../features/propose/propose-view.tsx";24import { pageTitle } from "../../../features/shared/head.ts";24import { pageHead } from "../../../features/shared/head.ts";25import { PageShell } from "../../../features/shared/layout.tsx";2627// `/$project/proposals/new`: the propose form. Who is signed in and the28// project's top folders are read in the browser (the server paints the
115 unmodified lines
144 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 lines
12 revisionOf,13} from "../../../../features/code/address.ts";14import { CodeNotFound } from "../../../../features/code/not-found.tsx";15import { TreeView } from "../../../../features/code/tree-view.tsx";16import { pageTitle } from "../../../../features/shared/head.ts";16import { pageHead } from "../../../../features/shared/head.ts";17import { notFoundFor } from "../../../../features/shared/refusals.ts";18import { serverClient } from "../../../../server/client.ts";19import { readFolderWithReadme } from "../../../../server/folder.ts";20
77 unmodified lines
98};99100export 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 lines
11 repoPathOf,12 revisionOf,13} from "../../../../features/code/address.ts";14import { CodeNotFound } from "../../../../features/code/not-found.tsx";15import { pageTitle } from "../../../../features/shared/head.ts";15import { pageHead } from "../../../../features/shared/head.ts";16import { notFoundFor } from "../../../../features/shared/refusals.ts";17import { ClientWhy } from "../../../../features/why/client-why.tsx";18import { WhyFallback, WhyLines } from "../../../../features/why/why-view.tsx";19import { serverClient } from "../../../../server/client.ts";
91 unmodified lines
111};112113export 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 lines
15import { envSchemaAtom } from "../../client/env.ts";16import { watchAtom } from "../../client/watch.ts";17import { EnvView, NothingLanded } from "../../features/env/env-page.tsx";18import { UnknownProjectView } from "../../features/project/unknown-project.tsx";19import { pageTitle } from "../../features/shared/head.ts";19import { pageHead } from "../../features/shared/head.ts";20import { serverClient } from "../../server/client.ts";2122// 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 lines
123};124125export 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 lines
13import { recentLandingsAtom } from "../../client/events.ts";14import { projectsAtom } from "../../client/front.ts";15import { asksAtom } from "../../client/project.ts";16import { watchAtom } from "../../client/watch.ts";17import { Unreachable } from "../../features/front/reading.tsx";17import {18 ProjectReadingView,19 ProjectView,20} from "../../features/project/project-page.tsx";21import { UnknownProjectView } from "../../features/project/unknown-project.tsx";23import { pageTitle } from "../../features/shared/head.ts";22import { pageHead } from "../../features/shared/head.ts";23import { Unreachable } from "../../features/shared/pending.tsx";24import { serverClient } from "../../server/client.ts";25import { readFolderWithReadme } from "../../server/folder.ts";2627// A project's page. The loader asks the platform, on the server, for the
157 unmodified lines
185};186187export 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 lines
15import { ledgerAtom } from "../../client/ledger.ts";16import { watchAtom } from "../../client/watch.ts";17import { LedgerView } from "../../features/ledger/ledger-page.tsx";18import { UnknownProjectView } from "../../features/project/unknown-project.tsx";19import { pageTitle } from "../../features/shared/head.ts";19import { pageHead } from "../../features/shared/head.ts";20import { serverClient } from "../../server/client.ts";2122// 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 a
75 unmodified lines
99};100101export 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 lines
17import { policyAtom } from "../../client/policy.ts";18import { watchAtom } from "../../client/watch.ts";19import { PeopleView } from "../../features/project-people/people-view.tsx";20import { UnknownProjectView } from "../../features/project/unknown-project.tsx";21import { pageTitle } from "../../features/shared/head.ts";21import { pageHead } from "../../features/shared/head.ts";22import { serverClient } from "../../server/client.ts";2324// 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 the
98 unmodified lines
124};125126export 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 lines
8import { offsetOf, projectOf } from "../../features/code/address.ts";9import { CodeNotFound } from "../../features/code/not-found.tsx";10import { packageParamOf } from "../../features/code/refs-param.ts";11import { RefsView } from "../../features/code/refs-view.tsx";12import { pageTitle } from "../../features/shared/head.ts";12import { pageHead } from "../../features/shared/head.ts";13import { notFoundFor } from "../../features/shared/refusals.ts";14import { serverClient } from "../../server/client.ts";1516// Main, the tags and the forks, read on the server; `?from=` pages the
40 unmodified lines
57 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
1import { createFileRoute, Outlet } from "@tanstack/react-router";23// 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.11export const Route = createFileRoute("/$project")({12 component: Outlet,13});
modified:apps/web/src/routes/people/$handle.tsx+3 added-3 removed
3 unmodified lines
4import { Effect, Option, Schema } from "effect";5import { AsyncResult } from "effect/reactivity";67import { creditsAtom } from "../../client/people.ts";8import { Reading, Unreachable } from "../../features/front/reading.tsx";8import {9 NoSuchPersonView,10 PersonView,11} from "../../features/people/person-page.tsx";13import { pageTitle } from "../../features/shared/head.ts";12import { pageHead } from "../../features/shared/head.ts";13import { Reading, Unreachable } from "../../features/shared/pending.tsx";1415// 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 lines
37};3839export 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 lines
modified:apps/web/src/routes/__root.tsx+67 added-16 removed
1import { useAtomValue } from "@effect/atom-react";2import { Brand } from "@repo/brand";3import {4 createRootRoute,5 HeadContent,6 Outlet,7 Scripts,7 useLocation,8 useHydrated,9} from "@tanstack/react-router";10import { createServerFn } from "@tanstack/react-start";11import { env } from "cloudflare:workers";12import { AsyncResult } from "effect/reactivity";13import type { ReactNode } from "react";1415import monoFont from "../assets/fonts/jetbrains-mono-latin.woff2?url";16import sansFont from "../assets/fonts/public-sans-latin.woff2?url";17import { projectsAtom } from "../client/front.ts";18import { todayAtom } from "../client/today.ts";19import { TooltipProvider } from "../components/ui/tooltip.tsx";20import { MANIFEST_PATH } from "../features/agents/manifest.ts";17import { SessionSlot } from "../features/auth/session-slot.tsx";18import { SiteFooter, SiteHeader } from "../features/shared/layout.tsx";21import { useSignedIn } from "../features/auth/session-slot.tsx";22import { AppShell } from "../features/shared/shell/app-shell.tsx";23import { RailCount } from "../features/shared/shell/rail.tsx";24import { themeColors } from "../features/shared/theme.ts";2526import styles from "../styles.css?url";2723// 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()`).3334/**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 the
28 unmodified lines
65 <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);7576/** The decider's Today, read in the browser for the rail's count. */77const railToday = todayAtom();7879const TodayWaiting = () => {80 const today = useAtomValue(railToday);8182 if (!AsyncResult.isSuccess(today)) {83 return null;84 }8586 const waiting = today.value.decisions.length + today.value.overflow;8788 return waiting === 0 ? null : (89 <RailCount count={waiting} of="decisions waiting" />90 );91};9293/**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 */98const TodayCount = () => {99 const hydrated = useHydrated();100 const signedIn = useSignedIn();101102 return hydrated && signedIn ? <TodayWaiting /> : null;103};104105const 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);108109 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};122123/**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 */127export 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.";129130/** The site's icon, drawn to scale (`public/icons/icon.svg`). */131const ICON_PATH = "/icons/icon.svg";132133/**
30 unmodified lines
164 { 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});175176export 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 lines
6} from "@tanstack/react-router";78import { commands } from "../features/agents/catalog.ts";9import { AgentSetupView } from "../features/agents/setup-page.tsx";10import { pageTitle } from "../features/shared/head.ts";10import { pageHead } from "../features/shared/head.ts";11import { PageShell } from "../features/shared/layout.tsx";1213// `/agents`: how each agent connects, drawn from `@repo/agent-kit`'s14// `agentSetup` for this stage's platform and the web's own origin (the
17 unmodified lines
32};3334export 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 lines
56import { frontPageAtom, projectsAtom } from "../client/front.ts";7import { readFilter } from "../features/front/filter.ts";8import { FrontPageView } from "../features/front/front-page.tsx";9import { Reading, Unreachable } from "../features/front/reading.tsx";10import { pageTitle } from "../features/shared/head.ts";9import { pageHead } from "../features/shared/head.ts";10import { Reading, Unreachable } from "../features/shared/pending.tsx";1112// 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 every
28 unmodified lines
43};4445export 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 lines
4import { DateTime, Option, Schema } from "effect";56import { decideAtom } from "../client/decide.ts";7import { todayAtom } from "../client/today.ts";8import { pageTitle } from "../features/shared/head.ts";8import { pageHead } from "../features/shared/head.ts";9import { PageShell } from "../features/shared/layout.tsx";10import { TodayView } from "../features/today/today-page.tsx";1112// `/today`: the signed-in decider's decisions across their projects, or in
20 unmodified lines
33};3435export 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 lines
modified:apps/web/src/router.tsx+30 added-1 removed
1import { createRouter } from "@tanstack/react-router";23import {4 NotFoundPage,5 PendingPage,6 RouteError,7} from "./features/shared/pending.tsx";8import { routeTree } from "./routeTree.gen.ts";95/** 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 */26export 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 });4041declare module "@tanstack/react-router" {42 interface Register {
3 unmodified lines
modified:apps/web/src/styles.css+14 added
228 unmodified lines
229 --popover: oklch(0.235 0.009 258);230 }231}232233/*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}246247@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 lines
added: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 */8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";1011import { pageHead } from "../src/features/shared/head.ts";12import { rootHead } from "../src/routes/__root.tsx";1314/** Each meta's key as the router dedupes it: its `name`, else its `property`. */15const keyOf = (meta: Readonly<Record<string, string>>) =>16 meta.name ?? meta.property ?? (meta.title === undefined ? "" : "title");1718/** The metas of `head` as `key: content` pairs (the title as `title`). */19const 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 );2526describe(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 });3233 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 });4445 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" });4748 expect(metasOf(head)).toStrictEqual({49 "og:title": "Ledger",50 "og:type": "article",51 title: `Ledger · ${Brand.name}`,52 });53 });54});5556describe("the root's head", () => {57 it("carries a default description, so no page unfurls bare", () => {58 const metas = metasOf(rootHead());5960 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 */7import { describe, expect, it } from "@effect/vitest";8import { renderToStaticMarkup } from "react-dom/server";910import {11 intentOf,12 KeysHelp,13 readShortcuts,14 writeShortcuts,15} from "../src/features/shared/keys.tsx";1617/** A press of `key` outside any text field, with no modifier held. */18const press = (key: string, inField = false) => ({19 altKey: false,20 ctrlKey: false,21 inField,22 key,23 metaKey: false,24});2526/** A `Storage` whose every read and write throws, as a blocked one does. */27const 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};4748/** A `Storage` held in a map, as a browser's is. */49const kept = (): Storage => {50 const items = new Map<string, string>();5152 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};6970describe("a single key", () => {71 it("opens the keys dialog with ?", () => {72 expect(intentOf(press("?"), true)).toStrictEqual({ kind: "keys" });73 });7475 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 });8586 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 });9798 it("clears with Escape", () => {99 expect(intentOf(press("Escape"), true)).toStrictEqual({ kind: "clear" });100 });101102 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 });107108 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 });113114 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});120121describe("the switch", () => {122 it("is on until it is turned off, and stays as it was left", () => {123 const storage = kept();124125 expect(readShortcuts(storage)).toBeTruthy();126127 writeShortcuts(storage, false);128129 expect(readShortcuts(storage)).toBeFalsy();130131 writeShortcuts(storage, true);132133 expect(readShortcuts(storage)).toBeTruthy();134 });135136 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 });143144 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 );153154 const text = markup.replaceAll(/<[^>]+>/gu, " ");155156 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 );163164 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 */8import { describe, expect, it } from "@effect/vitest";9import { ProjectName } from "@repo/protocol/ids";10import { Effect } from "effect";11import { renderToStaticMarkup } from "react-dom/server";1213import { ProjectNav } from "../src/features/project/project-nav.tsx";14import { renderAt } from "./render.tsx";1516const datekit = ProjectName.make("datekit");1718/** Each link in `markup`: its text, its href, and whether it is current. */
6 unmodified lines
25 text: (groups?.text ?? "").replaceAll(/<[^>]+>/gu, ""),26 })27 );2829const 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 }));3925describe("a project's nav", () => {26 it("links all seven tabs, and marks only the page being read", () => {40describe("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 );4546 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 });4950 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);5455 expect(policy).toStrictEqual([56 { current: true, href: "/datekit/people", text: "Policy" },57 ]);58 });5960 it("are links, not buttons", () => {
3 unmodified lines
6465 expect(markup).not.toContain('role="button"');66 });6751 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 );7656 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 );8384 it("scrolls sideways inside itself and never wraps", () => {85 const markup = renderToStaticMarkup(86 <ProjectNav current="ledger" project={datekit} />87 );8889 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 */20import {21 createMemoryHistory,22 createRootRoute,23 createRoute,24 createRouter,25 RouterProvider,26} from "@tanstack/react-router";27import { Effect } from "effect";28import type { Cause } from "effect";29import type { ComponentType, ReactNode } from "react";30import { renderToStaticMarkup } from "react-dom/server";3132/** What a test may add to the routes: the rail's content on a project's pages. */33export interface RenderOptions {34 readonly rail?: ComponentType;35}3637const routesFor = (view: ReactNode, options: RenderOptions) => {38 const root = createRootRoute({ component: () => view });39 const project = createRoute({ getParentRoute: () => root, path: "$project" });4041 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};5859/** `view`'s static markup inside a router whose location is `url`. */60export 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 });6970 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 lines
7import { describe, expect, it } from "@effect/vitest";8import { renderToStaticMarkup } from "react-dom/server";910import { themeColors } from "../src/features/shared/theme.ts";11import { getRouter } from "../src/router.tsx";12import { rootHead, ThemeColors } from "../src/routes/__root.tsx";1314describe("the document's head", () => {15 it("gives each meta a name of its own, since TanStack keeps one per name", () => {
58 unmodified lines
74 },75 ]);76 });77});7879describe("the router", () => {80 const { options } = getRouter();8182 // 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 });9293 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 });9798 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 });102103 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 lines
24import { CommandLine } from "../src/features/shared/command.tsx";25import { CreditTrailers } from "../src/features/shared/credits.tsx";26import { EmptyState } from "../src/features/shared/empty.tsx";27import { HandleLink } from "../src/features/shared/handle.tsx";28import {29 PageShell,30 SiteFooter,31 SiteHeader,32} from "../src/features/shared/layout.tsx";28import { OutcomeView, StageStrip } from "../src/features/shared/outcome.tsx";29import { PostureBadge } from "../src/features/shared/posture.tsx";30import { RefusalView } from "../src/features/shared/refusal.tsx";31import { themeColors } from "../src/features/shared/theme.ts";
344 unmodified lines
376 expect(text).toContain(command);377 });378});379385describe(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 );392393 expect(markup).toMatch(/<main\b[^>]*>.*<h1\b[^>]*>Today<\/h1>.*<\/main>/u);394 expect(markup).toContain("<p>Decisions 2 of 5</p>");395 });396});397398describe("the shell", () => {399 const platformUrl = "https://platform-test.example.workers.dev";400401 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 );408409 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 });413414 it("links Asks, Today and Agents in the header, marking Agents current on its page", () => {415 const markup = markupOf(<SiteHeader pathname="/agents" session={null} />);416417 const links = [418 ...markup.matchAll(419 /<a\b[^>]*href="(?<href>[^"]+)"[^>]*>(?<label>[^<]+)<\/a>/gu420 ),421 ].map(({ groups }) => [groups?.href, groups?.label]);422423 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 });433434 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} />);436437 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 });441442 it("sends a reader who wants to connect an agent to the Agents page", () => {443 const markup = markupOf(<SiteFooter platformUrl={platformUrl} />);444445 expect(markup).toMatch(/<a\b[^>]*href="\/agents"[^>]*>/u);446 expect(textOf(<SiteFooter platformUrl={platformUrl} />)).toContain(447 "Connect an agent"448 );449 });450380describe("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 lines
added: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 */8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import {11 createMemoryHistory,12 createRootRoute,13 createRoute,14 createRouter,15 Outlet,16 RouterProvider,17} from "@tanstack/react-router";18import { Effect } from "effect";19import { renderToStaticMarkup } from "react-dom/server";2021import { PageShell } from "../src/features/shared/layout.tsx";22import { RouteError } from "../src/features/shared/pending.tsx";23import { AppShell } from "../src/features/shared/shell/app-shell.tsx";24import { RailSlot } from "../src/features/shared/shell/rail-slot.tsx";25import { Workspace } from "../src/features/shared/shell/workspace.tsx";26import { renderAt } from "./render.tsx";2728/** The element `tag` whose opening tag carries `attribute`, whole (no nested `tag`). */29const elementOf = (markup: string, tag: string, attribute: string) =>30 new RegExp(`<${tag}\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</${tag}>`, "u").exec(31 markup32 )?.[0] ?? "";3334/** Each link in `markup`: its text, href, and the router's marks on it. */35const linksOf = (markup: string) =>36 [...markup.matchAll(/<a\b(?<attributes>[^>]*)>(?<text>[\s\S]*?)<\/a>/gu)].map(37 ({ groups }) => {38 const attributes = groups?.attributes ?? "";3940 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 );5152/** What a reader sees of `markup`, tags gone and spaces folded. */53const textOf = (markup: string) =>54 markup55 .replaceAll(/<[^>]+>/gu, " ")56 .replaceAll(/\s+/gu, " ")57 .trim();5859const 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);7273/** What a code page puts in the rail's slot. */74const Tree = () => (75 <RailSlot>76 <p>src/add.ts</p>77 </RailSlot>78);7980describe("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);8889 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 );125126 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 );135136 expect(textOf(rail)).toContain("Projects");137 expect(linksOf(rail).map(({ text }) => text)).toContain("datekit");138 })139 );140141 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 );152153 const ledger = linksOf(154 elementOf(155 yield* renderAt("/datekit/ledger", ledgerPage(false)),156 "nav",157 'aria-label="Site"'158 )159 );160161 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 );174175 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 );182183 expect(linksOf(rail).map(({ href }) => href)).not.toContain(184 "/datekit/ledger"185 );186 })187 );188189 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"');196197 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 );205206 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 );218219 expect(220 textOf(elementOf(markup, "nav", 'aria-label="Breadcrumb"'))221 ).toBe("datekit / Env shape");222 })223 );224225 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));231232 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 );241242 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 );251252 expect(textOf(bar)).toBe("Asks Today Projects More");253 expect(linksOf(bar).map(({ href }) => href)).toStrictEqual([254 "/",255 "/today",256 ]);257 })258 );259260 it.effect("lets a keyboard skip to the page's content", () =>261 Effect.gen(function* () {262 const markup = yield* renderAt("/today", ledgerPage(false));263264 expect(markup).toMatch(265 /<a\b[^>]*href="#main"[^>]*>Skip to content<\/a>/u266 );267 expect(markup).toContain(Brand.name);268 })269 );270271 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 });278279 const ledger = yield* renderAt("/datekit/ledger", ledgerPage(false));280281 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});288289describe("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 );295296 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});305306describe(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 );315316 expect(elementOf(markup, "main", 'id="main"')).toMatch(317 /<h1\b[^>]*>Today<\/h1>[\s\S]*<p>Decisions 2 of 5<\/p>/u318 );319 })320 );321});322323describe("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 });335336 const failing = createRoute({337 getParentRoute: () => root,338 loader: () => Promise.reject(new Error("fetch failed")),339 path: "$project",340 });341342 const router = createRouter({343 defaultErrorComponent: RouteError,344 history: createMemoryHistory({ initialEntries: ["/datekit"] }),345 routeTree: root.addChildren([failing]),346 });347348 yield* Effect.tryPromise(() => router.load());349350 const markup = renderToStaticMarkup(<RouterProvider router={router} />);351 const main = elementOf(markup, "main", 'id="main"');352353 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});