what a page says unasked: toasts, progress, problems with rows, states
npx shadcn add @ag/hudAlready installed? Preview an update
npx shadcn add @ag/hud --dry-runYour installed source stays unchanged until you update it. How updates work
Latest changes · 2026-11-06
- New, replacing
toast(breaking): what a page says unasked, Ink'sInkHUDon the web.<Hud />once, thenhudfrom anywhere: entries keyed by their producer and named by what they are, a toast (gone after 5 s of being seen), a progress (shown past its reveal, a band along its foot, ending in place as a toast or a problem), a problem (stands until its cause is gone or dismissed) and a state (shown once it has held a second);post,update,end,reconcile(everything a source holds now),toast,promiseandread(the live readout under the hand). One column at the top end, one width and two lines per entry, in arrival order; an entry's rows open in a panel beside the column, each with its own state and verbs; what does not fit folds into one row, never evicted; held still under the pointer, nothing in it changing size or place until the hand leaves; a verb markeddestructivetakes a press only once the pointer has rested on it or the keyboard moved there. Migration:<Toaster />becomes<Hud />;toast(title, { description, action })becomeshud.toast(title, { detail, action });toast.error(x)a problem (hud.post({ key, kind: "problem", title: x }));toast.loading(x)a progress (hud.post({ key, kind: "progress", title: x, reveal: 0 }), ended withhud.end(key, …));toast.promise(p, { loading, success, error })becomeshud.promise(p, { progress, toast, problem });toast.dismiss(id)becomeshud.dismiss(key).toast.tsxis gone;mise add hudnames every place still importing it.
also called toast, snackbar, notification, notice, job queue
shelf controls
uses button, material, scroll-area, spinner
used by components, history
the demo above, verbatim
"use client"
import * as React from "react"
import { Sample } from "@/app/samples"
import { Button } from "@/registry/base-nova/ui/button"
import { type HudRow, hud, undismissed } from "@/registry/base-nova/ui/hud"
// #region save
/** Something that takes a moment and sometimes fails. */
const save = () =>
new Promise<number>((resolve, reject) =>
setTimeout(
() =>
Math.random() > 0.3
? resolve(35)
: reject(new Error("the network went away")),
1500,
),
)
// #endregion
// #region files
/** Damaged files, each living through its heal on its own row. */
type File = {
name: string
detail: string
state: HudRow["state"]
healed: boolean
}
const DAMAGED: File[] = [
{
name: "harbour at dusk.mov",
detail: "damaged 0:28–0:42",
state: "idle",
healed: false,
},
{
name: "cut short interview.mp4",
detail: "cut short at 4:59 of 21:59",
state: "idle",
healed: false,
},
{
name: "rooftop.mov",
detail: "damaged 0:04–0:06",
state: "idle",
healed: false,
},
]
// #endregion
export default function HudDemo() {
return (
<div className="space-y-6">
<Sample name="kinds" title="every kind" glance>
<Kinds />
</Sample>
<Sample
name="rows"
title="a problem whose rows act in place"
description="heal a file: its own row shows the work and what to do next; nothing new appears"
with="files"
>
<Damaged />
</Sample>
<Sample
name="fold"
title="the fold"
description="more than half the window holds folds into one row; hover the column and arrivals are counted"
>
<Button
variant="secondary"
onClick={() => {
for (let n = 1; n <= 12; n++) hud.toast(`tagged photo ${n}`)
}}
>
twelve toasts
</Button>
</Sample>
</div>
)
}
function Kinds() {
const [n, setN] = React.useState(0)
return (
<div className="flex flex-wrap gap-2">
<Button
variant="secondary"
onClick={() =>
hud.toast("exported wall.mov", { detail: "in your downloads" })
}
>
toast
</Button>
<Button
variant="secondary"
onClick={() => {
const key = `export ${n}`
setN(n + 1)
hud.post({
key,
kind: "progress",
title: "exporting wall",
progress: 0,
reveal: 0,
})
let p = 0
const t = setInterval(() => {
p += 0.1
if (p >= 1) {
clearInterval(t)
hud.end(key, { toast: "exported wall.mov" })
} else
hud.update(key, (e) => ({ ...e, progress: p, detail: "writing" }))
}, 200)
}}
>
progress
</Button>
<Button
variant="secondary"
onClick={() =>
hud.promise(save(), {
progress: "saving",
toast: (frames) => `${frames} frames saved`,
problem: (e) => `not saved: ${(e as Error).message}`,
})
}
>
a promise
</Button>
<Button variant="secondary" onClick={() => hud.read("−3 s")}>
readout
</Button>
<Button
variant="secondary"
onClick={() => hud.read("nothing to undo", { refusal: true })}
>
a refusal
</Button>
</div>
)
}
function Damaged() {
const [files, setFiles] = React.useState<File[]>([])
const heal = React.useCallback((name: string) => {
const change = (edit: (f: File) => File) =>
setFiles((all) => all.map((f) => (f.name === name ? edit(f) : f)))
let p = 0
const t = setInterval(() => {
p += 0.1
if (p < 1) return change((f) => ({ ...f, state: { working: p } }))
clearInterval(t)
change((f) =>
f.name.startsWith("cut")
? {
...f,
state: "failed",
detail: "the written file failed its check",
}
: {
...f,
state: "done",
healed: true,
detail: "healed: a clean copy beside it",
},
)
}, 150)
}, [])
const forget = React.useCallback(
(name: string) => setFiles((all) => all.filter((f) => f.name !== name)),
[],
)
React.useEffect(() => {
const rows = undismissed(
"demo damaged",
files.map<HudRow>((f) => ({
id: f.name,
title: f.name,
detail: f.detail,
tone: "warn",
state: f.state,
verbs:
f.state === "done"
? [
{
label: "replace the original",
prominent: true,
onClick: () => forget(f.name),
},
{ label: "keep both", onClick: () => forget(f.name) },
]
: f.state === "failed"
? [{ label: "heal again", onClick: () => heal(f.name) }]
: typeof f.state === "object"
? []
: [{ label: "heal", onClick: () => heal(f.name) }],
rows: f.healed
? [
{
id: `${f.name} copy`,
title: `${f.name} (healed)`,
detail: "a new file",
state: "done",
},
]
: [],
})),
)
hud.reconcile(
"demo damaged",
rows.length === 0
? []
: [
{
key: "demo damaged",
kind: "problem",
title: `${rows.length} damaged files`,
detail: `${files.filter((f) => f.healed).length} healed`,
rows,
},
],
)
}, [files, heal, forget])
return (
<Button variant="secondary" onClick={() => setFiles(DAMAGED)}>
find damaged files
</Button>
)
}the source, every file an install writes
"use client"
// The HUD: what an app tells a person without being asked, in one column at the
// window's top end, under the page's header. Its kinds and laws are lib/hud-core's.
//
// <Hud /> once per page, in the layout
// hud.toast("exported wall.mov", { detail: "in your downloads" })
// hud.post({ key: "export", kind: "progress", title: "exporting wall", progress: 0.04, reveal: 0 })
// hud.update("export", (e) => ({ ...e, progress: 0.5, detail: "writing" }))
// hud.end("export", { toast: "exported wall.mov" }) or { problem: "it stopped at 62%" }
// hud.reconcile("library", facts.map(toEntry)) everything a source holds now
// hud.promise(save(), { progress: "saving", toast: "saved", problem: (e) => String(e) })
// hud.read("−3 s") the live value under the hand
//
// `hud` can be called from anywhere, inside React or out (an action, a fetch's catch).
// Every entry is one width (22.5rem) and two lines tall, whatever it says, in arrival
// order, never reordered; progress is a band along its foot. An entry's rows open in a
// panel beside the column, so opening one moves no other, and a row's verb shows its
// work on that row. What does not fit in half the window folds into one last row,
// never evicted, with what ended this session under "earlier". While the pointer or the
// keyboard is in the column nothing moves: what ends keeps its room, inert, a row that
// leaves stays where it stood, what arrives is counted; what a press there makes (an
// undo's toast) shows at once. A toast's time runs only while a page drawing it is seen.
// What the store says (`said`) is read out from live regions apart from the drawing, a
// problem and a refusal at once. F6 moves the keyboard into the column and back.
//
// ONE Hud per page (a second throws). It draws in the body, inside whatever element is
// fullscreen while one is, or in the `container` it is given. `top` is where it stands
// (under the shell's bar, `--shell-bar`, by default). `scopes` are the entries it shows
// (default every one).
import {
ChevronLeft,
CircleAlert,
CircleCheck,
CircleX,
Info,
X,
} from "lucide-react"
import * as React from "react"
import { createPortal } from "react-dom"
import { cn } from "@/lib/utils"
import {
createHud,
dismissible,
foldOrder,
type HudEntry,
type HudKept,
type HudReach,
type HudRow,
type HudTone,
toneOf,
} from "@/registry/base-nova/lib/hud-core"
import { Button } from "@/registry/base-nova/ui/button"
import {
type Material,
type Scheme,
useMaterial,
useSurfaceScheme,
} from "@/registry/base-nova/ui/material"
import {
FLARE_INK,
FLARE_LIGHT,
glassVariants,
schemeOf,
} from "@/registry/base-nova/ui/material-glass"
import { ScrollArea } from "@/registry/base-nova/ui/scroll-area"
import { Spinner } from "@/registry/base-nova/ui/spinner"
export type {
HudAction,
HudEntry,
HudKind,
HudOutcome,
HudProgress,
HudRow,
HudTone,
} from "@/registry/base-nova/lib/hud-core"
/** Where dismissals are kept between visits. */
const REMEMBERED = "ag-hud-dismissed"
/** The page's one HUD: every call goes here, the <Hud /> draws it. Its memory lives in
* `localStorage`, which a browser may refuse (private windows, a full quota): then
* dismissals last the visit, and the page is told once in the console. */
export const hud = createHud({
memory: {
read: () => {
try {
return JSON.parse(
localStorage.getItem(REMEMBERED) ?? "{}",
) as Partial<HudKept>
} catch (error) {
console.warn(
"hud: dismissals could not be read; they last this visit",
error,
)
return {}
}
},
write: (kept) => {
try {
localStorage.setItem(REMEMBERED, JSON.stringify(kept))
} catch (error) {
console.warn(
"hud: dismissals could not be kept; they last this visit",
error,
)
}
},
},
})
/** The HUD's state, re-read on every change. */
export function useHud() {
return React.useSyncExternalStore(hud.subscribe, hud.state, hud.state)
}
/** Each tone as the tokens name it. */
const TONE: Record<HudTone, string | null> = {
ok: "var(--tone-ok)",
warn: "var(--tone-warn)",
bad: "var(--tone-bad)",
info: "var(--tone-info)",
neutral: null,
}
const PLAIN_FACE =
"rounded-xl border border-border bg-popover text-popover-foreground shadow-lg"
const GLASS_FACE = cn(
glassVariants({ shape: "surface" }),
"[--glass-radius:--theme(--radius-2xl)] [--glass-blur:18px]",
)
/** An entry arrives fading in from its trailing edge; still under reduced motion. */
const ARRIVES =
"transition-[opacity,translate] duration-150 starting:translate-x-2 starting:opacity-0 motion-reduce:transition-none"
/** The gap between entries, in px: what an entry's offset is counted in. */
const GAP = 8
/** How long a leaving entry fades before its room closes, ms. */
const LEAVES = 150
/** Huds mounted now: one at most (the header says why). */
let mounted = 0
/** The element fullscreen right now, which the HUD must be drawn inside to be seen. */
function useFullscreenElement(): Element | null {
const [el, setEl] = React.useState<Element | null>(null)
React.useEffect(() => {
const read = () => setEl(document.fullscreenElement)
read()
document.addEventListener("fullscreenchange", read)
return () => document.removeEventListener("fullscreenchange", read)
}, [])
return el
}
/** The entries as drawn: each that left kept a moment, fading, before its room closes. */
function useLeaving(entries: readonly HudEntry[]) {
const [leaving, setLeaving] = React.useState<HudEntry[]>([])
const last = React.useRef<readonly HudEntry[]>(entries)
React.useEffect(() => {
const now = new Set(entries.map((e) => e.key))
const gone = last.current.filter((e) => !now.has(e.key))
last.current = entries
if (gone.length === 0) return
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
setLeaving((l) => [...l, ...gone])
const t = window.setTimeout(
() => setLeaving((l) => l.filter((e) => !gone.includes(e))),
LEAVES,
)
return () => window.clearTimeout(t)
}, [entries])
return leaving
}
/** The keyboard is in the column or its panel: the controls there are Tab's stops,
* and only then (Tab from the page never stops in the HUD). */
const KeysIn = React.createContext(false)
/** What is opened beside the column: an entry's rows, or what the fold holds. */
type Opened = { entry: string } | "fold" | null
/** The HUD, drawn: once per page. */
export function Hud({
top = "calc(var(--shell-bar, 0px) + 1rem)",
scopes,
material,
scheme,
container,
}: {
/** Where the column starts, a CSS length: under the shell's bar by default. */
top?: string
/** The entries it shows by their scope ("app" when they name none); every one by
* default. */
scopes?: string[]
material?: Material
scheme?: Scheme
/** Where it is drawn. Default: the body, or the fullscreen element while there is
* one. */
container?: Element | null
}) {
React.useEffect(() => {
mounted += 1
if (mounted > 1) {
mounted -= 1
throw new Error(
"a second <Hud> is mounted: every hud call goes to one store, so it would be drawn and announced twice; mount one Hud per page",
)
}
return () => {
mounted -= 1
}
}, [])
const host = React.useId()
const state = useHud()
const m = useMaterial(material)
const fullscreen = useFullscreenElement()
const [opened, setOpened] = React.useState<Opened>(null)
const [room, setRoom] = React.useState(0)
const [entryHeight, setEntryHeight] = React.useState(0)
const [panelOffset, setPanelOffset] = React.useState(0)
const [panelHeight, setPanelHeight] = React.useState(0)
const panelBox = React.useRef<HTMLDivElement>(null)
/** The keyboard is in the column or its panel: their controls are Tab's stops. */
const [keysIn, setKeysIn] = React.useState(false)
React.useEffect(() => {
const el = panelBox.current
if (!el) {
setPanelHeight(0)
return
}
const o = new ResizeObserver(() => setPanelHeight(el.offsetHeight))
o.observe(el)
return () => o.disconnect()
})
const column = React.useRef<HTMLElement>(null)
const before = React.useRef<HTMLElement | null>(null)
const [target, setTarget] = React.useState<Element | null>(null)
/** The keys shown when a hand came in: what the hand stays over. */
const [still, setStill] = React.useState<string[] | null>(null)
const shows = React.useCallback(
(e: HudEntry) => !scopes || scopes.includes(e.scope ?? "app"),
[scopes],
)
const scopeKey = scopes?.join(" ")
React.useEffect(() => setTarget(document.body), [])
React.useEffect(() => {
const said = () =>
hud.seen(
host,
document.visibilityState === "visible",
scopeKey?.split(" "),
)
said()
document.addEventListener("visibilitychange", said)
const measure = () => setRoom(window.innerHeight / 2)
measure()
window.addEventListener("resize", measure)
return () => {
hud.seen(host, false)
hud.hand(`${host} column`, false)
hud.hand(`${host} panel`, false)
document.removeEventListener("visibilitychange", said)
window.removeEventListener("resize", measure)
}
}, [host, scopeKey])
const entries = state.entries.filter(shows)
const held = state.held.filter(shows).length
// What was put away and still holds, in key order: the fold row shows while any is.
const away = [...state.away.values()]
.filter(shows)
.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
const earlier = state.earlier.filter(
({ entry }) => !state.away.has(entry.key),
)
const fits =
entryHeight > 0
? Math.max(1, Math.floor((room + GAP) / (entryHeight + GAP)))
: Number.POSITIVE_INFINITY
// The column as the hand found it, while it is in.
React.useEffect(() => {
if (!state.frozen) setStill(null)
else
setStill(
(s) =>
s ??
lay(state.entries.filter(shows), 0, fits, null).shown.map(
(e) => e.key,
),
)
}, [state.frozen, state.entries, shows, fits])
const laid = lay(entries, held, fits, still)
const leaving = useLeaving(laid.shown)
// An open panel whose entry left, or ended under the hand, closes.
React.useEffect(() => {
if (opened === null || opened === "fold") return
if (
!state.entries.some((e) => e.key === opened.entry) ||
state.ended.has(opened.entry)
)
setOpened(null)
}, [opened, state.entries, state.ended])
// F6: the keyboard into the column and back to where it was; nothing when the column
// holds nothing.
React.useEffect(() => {
const f6 = (e: KeyboardEvent) => {
if (e.key !== "F6") return
const el = column.current
if (!el) return
if (el.contains(document.activeElement)) {
e.preventDefault()
const back = before.current
before.current = null
if (back?.isConnected) back.focus()
else (document.activeElement as HTMLElement | null)?.blur()
return
}
const first = el.querySelector<HTMLElement>("[data-slot=hud-entry]")
if (!first) return
e.preventDefault()
before.current = document.activeElement as HTMLElement | null
first.focus()
}
window.addEventListener("keydown", f6)
return () => window.removeEventListener("keydown", f6)
}, [])
const openedEntry =
opened && opened !== "fold"
? state.entries.find((e) => e.key === opened.entry)
: undefined
// The panel stands in the column's region (its room, half the window): level with what
// it opens, risen as far as it must to end inside the region. While a hand is in, its
// rise holds from its first measured layout, so a row joining its foot never lifts the
// rows above.
const openedId =
opened === null ? null : opened === "fold" ? "fold" : opened.entry
const rise = Math.max(0, Math.min(panelOffset, room - panelHeight))
const [heldRise, setHeldRise] = React.useState<{
opened: string
rise: number
} | null>(null)
React.useLayoutEffect(() => {
if (!state.frozen) setHeldRise(null)
else if (openedId !== null && panelHeight > 0)
setHeldRise((h) =>
h?.opened === openedId ? h : { opened: openedId, rise },
)
}, [state.frozen, openedId, panelHeight, rise])
const hand = (part: string) => ({
onPointerEnter: () => hud.hand(`${host} ${part}`, true),
onPointerLeave: () => hud.hand(`${host} ${part}`, false),
onFocus: () => {
hud.hand(`${host} ${part} keys`, true)
setKeysIn(true)
},
onBlur: (e: React.FocusEvent) => {
const next = e.relatedTarget as Node | null
if (e.currentTarget.contains(next)) return
hud.hand(`${host} ${part} keys`, false)
const root = column.current?.parentElement
if (!root?.contains(next)) setKeysIn(false)
},
})
const where = container ?? fullscreen ?? target
if (!where) return null
return createPortal(
<KeysIn.Provider value={keysIn}>
<div
data-slot="hud"
className="pointer-events-none fixed inset-x-4 z-[60] flex flex-row-reverse items-start gap-2 sm:right-6"
style={{ top }}
// A control is pressed by a key's first press alone: a held key's repeats press
// nothing, so a yes armed while ⏎ or space is held is never pressed by the hold,
// and a held ⏎ opens a panel once.
onKeyDownCapture={(e) => {
if (e.repeat && (e.key === "Enter" || e.key === " ")) {
e.preventDefault()
e.stopPropagation()
}
}}
>
<section
ref={column}
aria-label="notifications"
className="pointer-events-auto flex w-[min(22.5rem,calc(100vw-2rem))] flex-col gap-2"
{...hand("column")}
onKeyDown={(e) => {
const items = [
...(column.current?.querySelectorAll<HTMLElement>(
"[data-slot=hud-entry]",
) ?? []),
]
const i = items.indexOf(document.activeElement as HTMLElement)
if (i < 0) return
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault()
items[
Math.min(
Math.max(i + (e.key === "ArrowDown" ? 1 : -1), 0),
items.length - 1,
)
]?.focus()
} else if (e.key === "Enter") {
const item = items[i] as HTMLElement
const key = item.dataset.key
if (item.dataset.rows === undefined || !key) return
e.preventDefault()
setPanelOffset(item.offsetTop)
setOpened((o) =>
o !== null && o !== "fold" && o.entry === key
? null
: { entry: key },
)
} else if (e.key === "Escape") {
e.preventDefault()
if (opened) setOpened(null)
else {
const back = before.current
before.current = null
if (back?.isConnected) back.focus()
else (document.activeElement as HTMLElement | null)?.blur()
}
}
}}
>
{[...laid.shown, ...leaving].map((e, i) => {
const gone = leaving.includes(e)
return (
<Entry
key={gone ? `${e.key} leaving` : e.key}
entry={e}
ended={gone || state.ended.has(e.key)}
leaving={gone}
open={
opened !== null && opened !== "fold" && opened.entry === e.key
}
toggle={(offset) => {
setPanelOffset(offset)
setOpened((o) =>
o !== null && o !== "fold" && o.entry === e.key
? null
: { entry: e.key },
)
}}
measure={i === 0 ? setEntryHeight : undefined}
material={m}
scheme={scheme}
/>
)
})}
{(laid.folds || away.length > 0) && (
<Fold
folded={laid.folded}
held={held}
away={away.length}
open={opened === "fold"}
toggle={(offset) => {
setPanelOffset(offset)
setOpened((o) => (o === "fold" ? null : "fold"))
}}
material={m}
scheme={scheme}
/>
)}
</section>
{(openedEntry || opened === "fold") && (
<div
ref={panelBox}
className="pointer-events-auto w-[min(22.5rem,calc(100vw-2rem))]"
style={{
marginTop: heldRise?.opened === openedId ? heldRise.rise : rise,
}}
{...hand("panel")}
>
<Panel
title={openedEntry?.title ?? "more"}
maxHeight={`${Math.max(room, entryHeight)}px`}
material={m}
scheme={scheme}
close={() => setOpened(null)}
>
{openedEntry
? (openedEntry.rows ?? []).map((r) => (
<Row
key={r.id}
entry={openedEntry.key}
row={r}
leftRows={state.leftRows.get(openedEntry.key) ?? NO_ROWS}
frozen={state.frozen}
material={m}
scheme={scheme}
/>
))
: [
...laid.folded.map((e) => (
<Entry
key={e.key}
entry={e}
ended={state.ended.has(e.key)}
leaving={false}
open={false}
toggle={() => setOpened({ entry: e.key })}
material={m}
scheme={scheme}
/>
)),
(away.length > 0 || earlier.length > 0) && (
<p
key="earlier"
className="pt-1 font-medium text-[11px] text-current/55 uppercase tracking-wide"
>
earlier
</p>
),
// What was put away and still holds: first, each with its way back.
...away.map((entry) => (
<div
key={`away ${entry.key}`}
className="flex items-baseline gap-2"
>
<div className="min-w-0 flex-1">
<Row
entry={null}
row={{
id: entry.key,
title: entry.title,
detail: entry.detail,
tone: toneOf(entry),
}}
leftRows={NO_ROWS}
frozen={false}
material={m}
scheme={scheme}
/>
</div>
<Button
variant="secondary"
size="sm"
material={m}
tabIndex={keysIn ? 0 : -1}
onClick={() => hud.bringBack(entry.key)}
>
show again
</Button>
</div>
)),
...earlier.slice(0, 20).map(({ id, entry }) => (
<Row
key={`earlier ${id}`}
entry={null}
row={{
id: String(id),
title: entry.title,
detail: entry.detail,
tone: toneOf(entry),
}}
leftRows={NO_ROWS}
frozen={false}
material={m}
scheme={scheme}
/>
)),
]}
</Panel>
</div>
)}
<Readout scopes={scopes} material={m} scheme={scheme} />
<Announcer />
</div>
</KeysIn.Provider>,
where,
)
}
/** The column as it is laid: what shows, in arrival order, and what folds into one
* row (the lowest kind first, then the oldest; problems last). Under the hand
* (`still`): what showed stays, the rest is the fold's, after it. */
function lay(
entries: readonly HudEntry[],
held: number,
fits: number,
still: string[] | null,
) {
if (still) {
const kept = new Set(still)
return {
shown: still.flatMap((key) => entries.filter((e) => e.key === key)),
folded: entries.filter((e) => !kept.has(e.key)),
folds: held > 0 || entries.some((e) => !kept.has(e.key)),
}
}
const room =
held > 0 || entries.length > fits ? Math.max(0, fits - 1) : entries.length
const over = entries.length - room
if (over <= 0)
return { shown: [...entries], folded: [] as HudEntry[], folds: held > 0 }
const folding = new Set(
entries
.map((e, i) => ({ e, i }))
.sort((a, b) => foldOrder(a.e.kind) - foldOrder(b.e.kind) || a.i - b.i)
.slice(0, over)
.map((x) => x.e.key),
)
return {
shown: entries.filter((e) => !folding.has(e.key)),
folded: entries.filter((e) => folding.has(e.key)),
folds: true,
}
}
/** A surface of the HUD's: an entry, the fold, the panel, the readout. */
function useSurface(
material: Material,
scheme: Scheme | undefined,
tone: HudTone,
) {
const [s, here] = useSurfaceScheme<HTMLDivElement>(scheme)
const hue = TONE[tone]
return {
s,
here,
className: cn(
schemeOf(s),
material === "glass" ? GLASS_FACE : PLAIN_FACE,
hue !== null && [material === "glass" && FLARE_LIGHT, FLARE_INK],
),
style:
hue === null
? undefined
: ({ "--flare-hue": hue } as React.CSSProperties),
}
}
const MARK: Record<HudTone, React.ReactNode> = {
ok: <CircleCheck />,
warn: <CircleAlert />,
bad: <CircleX />,
info: <Info />,
neutral: <CircleCheck />,
}
/** A mark: work whose share is not known turns; the rest wear their tone's symbol. */
function Mark({ tone, turning }: { tone: HudTone; turning: boolean }) {
return (
<span
aria-hidden
className="grid size-4 shrink-0 place-items-center text-(--flare-ink,currentColor) [&_svg]:size-4"
>
{turning ? <Spinner size="sm" /> : MARK[tone]}
</span>
)
}
/** One entry: two lines whatever it says, so every entry is one height. */
function Entry({
entry,
ended,
leaving,
open,
toggle,
measure,
material,
scheme,
}: {
entry: HudEntry
ended: boolean
leaving: boolean
open: boolean
toggle: (offset: number) => void
measure?: (height: number) => void
material: Material
scheme?: Scheme
}) {
const surface = useSurface(material, scheme, toneOf(entry))
// Its controls are Tab's stops only while the keyboard is in the column.
const stop = React.useContext(KeysIn) ? 0 : -1
const box = React.useRef<HTMLDivElement | null>(null)
React.useEffect(() => {
const el = box.current
if (!measure || !el) return
const o = new ResizeObserver(() => measure(el.offsetHeight))
o.observe(el)
return () => o.disconnect()
}, [measure])
const share = typeof entry.progress === "number" ? entry.progress : null
const rows = entry.rows ?? []
const canDismiss = dismissible(entry)
const chrome = useHud().chrome.get(entry.key)
const offset = () => box.current?.offsetTop ?? 0
const percent = share === null ? undefined : `${Math.floor(share * 100)}%`
return (
<div
ref={(node) => {
box.current = node
surface.here(node)
}}
data-slot="hud-entry"
data-kind={entry.kind}
data-material={material}
// Reached on purpose (F6, then the arrows), never by Tab from the page.
tabIndex={-1}
data-key={entry.key}
data-rows={rows.length > 0 ? "" : undefined}
className={cn(
surface.className,
ARRIVES,
"relative flex items-center gap-3 overflow-hidden px-4 py-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",
ended && "opacity-50",
leaving && "opacity-0",
)}
style={surface.style}
inert={ended}
>
<Mark tone={toneOf(entry)} turning={entry.progress === "unknown"} />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="truncate font-medium leading-5">{entry.title}</p>
<p className="truncate text-current/65 leading-5" title={entry.detail}>
{entry.detail ?? " "}
{percent && <span className="tabular-nums"> · {percent}</span>}
</p>
</div>
<div
data-slot="hud-entry-actions"
className="-my-1 flex shrink-0 items-center gap-1"
>
{(["action", "cancel"] as const).map((which) => {
const verb = entry[which]
if (!verb) return null
// Held unseen: its place kept, hidden, unpressable, out of reach.
const shown = verb.shown !== false
return (
<PressButton
// Another verb in the place (its words, or shown where it was held) is
// another control: its stillness starts afresh.
key={`${which} ${verb.label} ${shown}`}
variant={which === "action" ? "secondary" : "ghost"}
size="sm"
material={material}
scheme={surface.s}
tabIndex={shown ? stop : -1}
disabled={verb.armed === false || !shown}
aria-hidden={shown ? undefined : true}
className={cn(!shown && "invisible")}
press={(reach) => hud.act(entry.key, which, reach)}
>
{verb.label}
</PressButton>
)
})}
{/* The chevron and the ✕ as they stood when a hand came in: one that would
appear waits until it leaves, one that goes keeps its place, inert. */}
{(chrome?.rows ?? rows.length > 0) && (
<Button
variant="ghost"
size="icon-sm"
corners="pill"
material={material}
scheme={surface.s}
tabIndex={rows.length > 0 ? stop : -1}
disabled={rows.length === 0}
aria-hidden={rows.length > 0 ? undefined : true}
aria-label={open ? "close" : "show each"}
aria-expanded={open}
onClick={() => toggle(offset())}
className={cn(
"text-current/55 hover:text-current",
rows.length === 0 && "invisible",
)}
>
<ChevronLeft
className={cn("transition-transform", open && "rotate-180")}
/>
</Button>
)}
{(chrome?.dismiss ?? canDismiss) && (
<Button
variant="ghost"
size="icon-sm"
corners="pill"
material={material}
scheme={surface.s}
tabIndex={canDismiss ? stop : -1}
disabled={!canDismiss}
aria-hidden={canDismiss ? undefined : true}
aria-label="dismiss"
onClick={() => hud.dismiss(entry.key)}
className={cn(
"-mr-2 text-current/45 hover:text-current",
!canDismiss && "invisible",
)}
>
<X />
</Button>
)}
</div>
{share !== null && (
<span
aria-hidden
className="absolute inset-x-4 bottom-0 h-0.5 origin-left bg-current/15"
>
<span
className="block h-full origin-left bg-(--flare-ink,currentColor)"
style={{ transform: `scaleX(${share})` }}
/>
</span>
)}
</div>
)
}
/** What the column holds past its room, what arrived under the hand, and what was put
* away and still holds: one row, an entry's height, the problems it holds said in
* their tone. */
function Fold({
folded,
held,
away,
open,
toggle,
material,
scheme,
}: {
folded: HudEntry[]
held: number
away: number
open: boolean
toggle: (offset: number) => void
material: Material
scheme?: Scheme
}) {
const problems = folded.filter((e) => e.kind === "problem").length
const surface = useSurface(
material,
scheme,
problems > 0 ? "warn" : "neutral",
)
const box = React.useRef<HTMLDivElement | null>(null)
const words = [
folded.length > 0 && `${folded.length} more`,
held > 0 && `${held} new`,
away > 0 && `${away} put away`,
]
.filter(Boolean)
.join(" · ")
return (
<div
ref={(node) => {
box.current = node
surface.here(node)
}}
data-slot="hud-fold"
className={cn(
surface.className,
"flex items-center gap-3 px-4 py-3 text-sm",
)}
style={surface.style}
>
<Mark tone={problems > 0 ? "warn" : "neutral"} turning={false} />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="truncate font-medium leading-5">{words}</p>
<p className="truncate text-(--flare-ink,currentColor)/80 leading-5">
{problems > 0
? `${problems} problem${problems === 1 ? "" : "s"} among them`
: " "}
</p>
</div>
<Button
variant="ghost"
size="icon-sm"
corners="pill"
material={material}
scheme={surface.s}
tabIndex={React.useContext(KeysIn) ? 0 : -1}
aria-label={open ? "close" : "show what is folded"}
aria-expanded={open}
onClick={() => toggle(box.current?.offsetTop ?? 0)}
className="-mr-2 text-current/55 hover:text-current"
>
<ChevronLeft
className={cn("transition-transform", open && "rotate-180")}
/>
</Button>
</div>
)
}
/** The panel beside the column: what an entry is about, row by row, scrolling past its
* room (`maxHeight`, the window less where it stands). */
function Panel({
title,
maxHeight,
close,
material,
scheme,
children,
}: {
title: string
maxHeight: string
close: () => void
material: Material
scheme?: Scheme
children: React.ReactNode
}) {
const surface = useSurface(material, scheme, "neutral")
return (
<div
ref={surface.here}
data-slot="hud-panel"
className={cn(surface.className, ARRIVES, "flex flex-col text-sm")}
style={{ maxHeight }}
>
<div className="flex items-center gap-2 px-4 pt-3 pb-2">
<p className="min-w-0 flex-1 truncate font-medium">{title}</p>
<Button
variant="ghost"
size="icon-sm"
corners="pill"
material={material}
scheme={surface.s}
aria-label="close"
onClick={close}
className="-mr-2 text-current/45 hover:text-current"
>
<X />
</Button>
</div>
<ScrollArea className="flex min-h-0 flex-col gap-3 px-4 pb-3">
{children}
</ScrollArea>
</div>
)
}
const ROW_STATE_TONE = { done: "ok", failed: "bad" } as const
const NO_ROWS: ReadonlySet<string> = new Set()
/** How a press reached a control (`HudReach`), read from the press itself: a click by its
* count (`detail`; 0 when no pointer made it, a key or an assistive action), a tap by its
* `pointerType`; with how long the control had stood where it stands when the press
* began, timed from its mounting (another verb in the place is another control, by its
* key), from any render that moved it, and from a move seen as a pointer comes over it
* (a scroll under a resting pointer). */
function useReach() {
const box = React.useRef<HTMLElement | null>(null)
const since = React.useRef(0)
const at = React.useRef<DOMRect | null>(null)
const down = React.useRef<{ time: number; touch: boolean } | null>(null)
const moved = React.useCallback(() => {
const el = box.current
if (!el) return
const r = el.getBoundingClientRect()
const was = at.current
if (
was &&
was.x === r.x &&
was.y === r.y &&
was.width === r.width &&
was.height === r.height
)
return
at.current = r
since.current = performance.now()
}, [])
// Every render: the first seeds it, any that moved it starts it again.
React.useLayoutEffect(moved)
return {
ref: box,
onPointerEnter: moved,
onPointerLeave: moved,
onPointerDown: (e: React.PointerEvent) => {
moved()
down.current = {
time: performance.now(),
touch: e.pointerType === "touch",
}
},
reach: (e: React.MouseEvent): HudReach => {
const d = down.current
down.current = null
if (e.detail === 0 || !d) return "key"
const still = d.time - since.current
return d.touch
? { touch: { still } }
: { pointer: { still, clicks: e.detail } }
},
}
}
/** A HUD verb: its press says how it reached it (`useReach`). */
function PressButton({
press,
...props
}: Omit<React.ComponentProps<typeof Button>, "onClick" | "ref"> & {
press: (reach: HudReach) => void
}) {
const { reach, ...handlers } = useReach()
return <Button {...props} {...handlers} onClick={(e) => press(reach(e))} />
}
/** One row of a panel: its mark, its words whole, its own state, its verbs (run as the
* entry was last posted), the rows under it. A row that left under the hand stays,
* dim and inert, at any depth; under the hand a row is never shorter than it stood
* when the hand came in, so a row losing a verb or a line moves nothing below it. */
function Row({
entry,
row,
leftRows,
frozen,
material,
scheme,
depth = 0,
}: {
/** The entry it belongs to; null for what is only read (earlier). */
entry: string | null
row: HudRow
/** The rows of its entry that left under the hand. */
leftRows: ReadonlySet<string>
/** A hand is in the column. */
frozen: boolean
material: Material
scheme?: Scheme
depth?: number
}) {
const left = leftRows.has(row.id)
const open = useReach()
// Its height, and its detail's, held while a hand is in: the row never shorter than the
// tallest it stood (from when the hand came in, or from its first layout in a panel
// opened under it), the detail's words held to the lines they stood in.
const box = React.useRef<HTMLDivElement | null>(null)
const detail = React.useRef<HTMLParagraphElement | null>(null)
const [held, setHeld] = React.useState<number | null>(null)
const [detailHeld, setDetailHeld] = React.useState<{
height: number
lines: number
} | null>(null)
React.useLayoutEffect(() => {
if (!frozen) {
setHeld(null)
setDetailHeld(null)
return
}
const measure = () => {
const el = box.current
if (el) setHeld((h) => Math.max(h ?? 0, el.offsetHeight))
const p = detail.current
if (p)
setDetailHeld(
(d) =>
d ?? {
height: p.offsetHeight,
lines: Math.max(
1,
Math.round(
p.offsetHeight /
Number.parseFloat(getComputedStyle(p).lineHeight),
),
),
},
)
}
measure()
const o = new ResizeObserver(measure)
if (box.current) o.observe(box.current)
return () => o.disconnect()
}, [frozen])
const st = row.state ?? "idle"
const working = typeof st === "object"
const share = working && typeof st.working === "number" ? st.working : null
const tone: HudTone =
st === "done" || st === "failed"
? ROW_STATE_TONE[st]
: working
? "info"
: (row.tone ?? "neutral")
const [s] = useSurfaceScheme<HTMLDivElement>(scheme)
return (
<div
ref={box}
data-slot="hud-row"
className={cn(
"flex flex-col gap-1",
depth > 0 && "pl-4",
left && "opacity-50",
)}
style={held === null ? undefined : { minHeight: held }}
inert={left}
>
<div
className="flex items-start gap-2"
style={
TONE[tone]
? ({ "--flare-ink": TONE[tone] } as React.CSSProperties)
: undefined
}
>
<span className="mt-0.5">
<Mark tone={tone} turning={working && share === null} />
</span>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
{row.open && entry ? (
<button
type="button"
title={row.open.tip ?? row.open.label}
ref={open.ref as React.RefObject<HTMLButtonElement>}
onPointerEnter={open.onPointerEnter}
onPointerLeave={open.onPointerLeave}
onPointerDown={open.onPointerDown}
onClick={(e) => hud.actRow(entry, row.id, "open", open.reach(e))}
className="truncate text-left font-medium leading-5 hover:underline"
>
{row.title}
</button>
) : (
<p className="truncate font-medium leading-5">{row.title}</p>
)}
{row.detail && (
<p
ref={detail}
className="overflow-hidden text-current/65 text-xs leading-4"
style={
detailHeld
? {
height: detailHeld.height,
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: detailHeld.lines,
}
: undefined
}
>
{row.detail}
</p>
)}
{/* The room of a working row's line, kept by every row a press acts on, drawn
empty while it does not work: work starting moves nothing. */}
{entry && (
<span
aria-hidden
className={cn(
"mt-1 block h-0.5",
share !== null && "bg-current/15",
)}
>
{share !== null && (
<span
className="block h-full origin-left bg-current"
style={{ transform: `scaleX(${share})` }}
/>
)}
</span>
)}
{entry && (row.verbs ?? []).length > 0 && (
<div className="mt-1 flex flex-wrap gap-1">
{(row.verbs ?? []).map((v) => {
const shown = v.shown !== false
return (
<PressButton
// Another verb in the place is another control: its stillness
// starts afresh.
key={`${v.label} ${shown}`}
variant={v.prominent ? "default" : "secondary"}
size="sm"
material={material}
scheme={s}
title={v.tip}
disabled={v.armed === false || !shown}
aria-hidden={shown ? undefined : true}
tabIndex={shown ? undefined : -1}
className={cn(!shown && "invisible")}
press={(reach) => hud.actRow(entry, row.id, v.label, reach)}
>
{/* As wide as every verb that stands in this place. */}
<span className="grid">
{[...new Set(v.room ?? [])]
.filter((words) => words !== v.label)
.map((words) => (
<span
key={words}
className="invisible col-start-1 row-start-1"
>
{words}
</span>
))}
<span className="col-start-1 row-start-1">{v.label}</span>
</span>
</PressButton>
)
})}
</div>
)}
</div>
</div>
{(row.rows ?? []).map((r) => (
<Row
key={r.id}
entry={entry}
row={r}
leftRows={leftRows}
frozen={frozen}
material={material}
scheme={scheme}
depth={depth + 1}
/>
))}
</div>
)
}
/** The live value under the hand, centred over the page, never taking a press: drawn
* where its scope is shown. One for a whole gesture, arriving once, its words changing
* in place, as wide as the widest words it has said since it showed, so it never
* resizes as the value moves. */
function Readout({
scopes,
material,
scheme,
}: {
scopes?: string[]
material: Material
scheme?: Scheme
}) {
const { readout } = useHud()
const surface = useSurface(
material,
scheme,
readout?.refusal ? "warn" : "neutral",
)
const shown = !!readout && (!scopes || scopes.includes(readout.scope))
const box = React.useRef<HTMLDivElement | null>(null)
// Held for one gesture: another starts from its own words.
const [widest, setWidest] = React.useState({ gesture: -1, width: 0 })
const here = surface.here
const at = React.useCallback(
(node: HTMLDivElement | null) => {
here(node)
box.current = node
},
[here],
)
const words = readout?.words
const gesture = readout?.gesture ?? -1
const held = widest.gesture === gesture ? widest.width : 0
// biome-ignore lint/correctness/useExhaustiveDependencies: measured again as its words change
React.useLayoutEffect(() => {
if (!shown) return
const node = box.current
if (!node) return
// Its own width, the held one set aside.
const was = node.style.minWidth
node.style.minWidth = ""
const width = node.offsetWidth
node.style.minWidth = was
setWidest((w) =>
w.gesture === gesture
? { gesture, width: Math.max(w.width, width) }
: { gesture, width },
)
}, [shown, words, gesture])
if (!readout || !shown) return null
return (
<div
ref={at}
data-slot="hud-readout"
aria-hidden
className={cn(
surface.className,
ARRIVES,
"-translate-x-1/2 -translate-y-1/2 pointer-events-none fixed top-1/2 left-1/2 px-4 py-2 text-center font-medium tabular-nums",
)}
style={{ ...surface.style, minWidth: held || undefined }}
>
{readout.words}
</div>
)
}
/** What the store says, read out once each from live regions apart from the drawing:
* a problem and a refusal at once, the rest politely. Every one its own node, so
* several arrivals are each said. */
function Announcer() {
const { said } = useHud()
return (
<>
<div role="status" className="sr-only">
{said
.filter((s) => !s.urgent)
.map((s) => (
<p key={s.id}>{s.words}</p>
))}
</div>
<div role="alert" className="sr-only">
{said
.filter((s) => s.urgent)
.map((s) => (
<p key={s.id}>{s.words}</p>
))}
</div>
</>
)
}
/** The rows a producer's problem counts, its dismissed ones left out. */
export function undismissed(key: string, rows: HudRow[]): HudRow[] {
const gone = hud.dismissedRows(key)
return rows.filter((r) => !gone.has(r.id))
}// HUD: what an app tells a person without being asked, as data and its laws, with no
// React and no DOM. The kernel under `ui/hud`, one design shared with its SwiftUI
// twin.
//
// An ENTRY is keyed by its producer: posted again with its key, it changes in place.
// Its KIND decides when it shows and leaves, never the caller:
// toast something happened whose result is not on screen: gone after 5 s of
// being seen by a host drawing its scope.
// progress work under way: shown once it has run past its `reveal` (300 ms: work
// that ends sooner is never seen), then for 600 ms at least; it ends where
// it stands, quietly, as a toast or as a problem.
// problem something failed or needs the person: stands until its cause is gone or
// it is dismissed. One a source reconciles (a fact a reload says again) is
// remembered dismissed with the rows it held until its source stops saying
// it, or a row it did not hold appears.
// state a condition that holds: shown once it has held 1 s, gone 1 s after. ✕
// hides it until its words change or its source stops saying it.
// The READOUT is the live value under the hand (a seek, a key refused): one at a time,
// standing its words' reading time, or held while a drag holds; a refusal longer than a
// glance stands as a problem instead.
//
// Order is arrival, never reordered. While a hand (the pointer or the keyboard) is in
// the column, and a short grace after: nothing moves. What ends keeps its room
// (`ended`), a row that leaves stays where it stood (`leftRows`), what arrives is counted
// (`held`), and the clock stands still; when it leaves, the column settles once. What a
// press in the column itself makes (an undo's toast) shows at once. The clock runs only
// while a host is seen and no hand is in. What ended this session is `earlier`, newest
// first. Every arrival, end and change of kind is said once (`said`), a problem at once.
/** Every kind, in the order they fold when the column is full (the first first). */
export const HUD_KINDS = ["toast", "progress", "state", "problem"] as const
export type HudKind = (typeof HUD_KINDS)[number]
export type HudTone = "ok" | "warn" | "bad" | "info" | "neutral"
/** How far work is: unknown (a spinner), or a share done, 0..1. */
export type HudProgress = "unknown" | number
export interface HudAction {
label: string
onClick: () => void
/** What the verb will do, said under the hand. */
tip?: string
/** The one verb that answers. */
prominent?: boolean
/** Pressable now (default true): a verb that answers a question just asked waits
* until a second press of the click that asked could no longer land on it. */
armed?: boolean
/** Labels its place is as wide as, beside its own: every verb that stands there in
* another state of the row, so no verb moves as the row changes. */
room?: string[]
/** Drawn (default true): false holds the place of a verb of the row's other state,
* unseen and unpressable, so the row never wraps differently. */
shown?: boolean
/** It destroys what it names: a press is taken only when it reached the verb on
* purpose (`HudReach`), so a press that lands on it because the layout moved it there
* never takes. */
destructive?: boolean
}
/** How a press reached its verb, read from the press itself: a click with how long the
* control had stood where it stands (ms since it appeared, moved, or another verb took
* its place) when the button went down, and the click's count (`detail`: a double
* click's second press is 2); a tap with how long the control had stood still when the
* finger landed; or a key or an assistive action, on purpose. */
export type HudReach =
| { pointer: { still: number; clicks: number } }
| { touch: { still: number } }
| "key"
/** How long a destructive verb stands still before a click or a tap on it is taken: a
* double click's interval (the web has no system value; 500 ms is the platforms'
* default). */
export const HUD_DWELL = 500
/** Whether a person can put an entry away: everything but work, which ends by itself.
* The one rule the chrome and the ✕ read. */
export const dismissible = (entry: HudEntry) => entry.kind !== "progress"
export type HudRowState = "idle" | { working: HudProgress } | "done" | "failed"
/** One thing an entry is about (a file), with its own live state and verbs, and the
* rows under it. Its words are shown, never logged. */
export interface HudRow {
/** Stable for the thing it names: what a dismissal is remembered by. */
id: string
title: string
detail?: string
tone?: HudTone
state?: HudRowState
/** A press on its title. */
open?: HudAction
verbs?: HudAction[]
rows?: HudRow[]
}
export interface HudEntry {
/** The producer's name for what it says, never a person's words or a reason (it is
* remembered). */
key: string
kind: HudKind
title: string
/** One line in the column, whole in the panel. */
detail?: string
tone?: HudTone
progress?: HudProgress
rows?: HudRow[]
action?: HudAction
cancel?: HudAction
/** Where it belongs: a host draws the scopes it shows. Default "app". */
scope?: string
/** Progress: ms it runs before it shows. Default 300; 0 for work a person just
* started. */
reveal?: number
/** Progress whose result is on screen: it ends silently. */
transient?: boolean
}
export type HudOutcome =
| "quietly"
| { toast: string; detail?: string }
| { problem: string; detail?: string }
export interface HudReadout {
words: string
/** A key or a menu item refused: said at once. */
refusal: boolean
/** Where the hand is: a host draws the readouts of the scopes it shows. */
scope: string
/** Each reading's own, so the same words read twice are two readings. */
serial: number
/** The gesture it belongs to: what the drawing holds its widest width for. */
gesture: number
}
/** Dismissals kept across reloads: a problem's rows by its key, rows by their entry's.
* Read whatever a later build added: a field not there is empty. */
export interface HudKept {
entries: Record<string, string[]>
rows: Record<string, string[]>
}
/** Where dismissals are kept (localStorage under a name, say); none forgets them. */
export interface HudMemory {
read(): Partial<HudKept>
write(kept: HudKept): void
}
/** One thing said to a screen reader: each its own, a problem's and a refusal's at
* once, the rest politely. */
export interface HudSaid {
id: number
words: string
urgent: boolean
}
/** Which of an entry's own controls stand. */
export interface HudChrome {
rows: boolean
dismiss: boolean
}
export interface HudState {
/** Every entry shown now, in arrival order. */
entries: readonly HudEntry[]
/** What ended this session, newest first, each its own id (a key can end twice). */
earlier: readonly { id: number; entry: HudEntry }[]
/** What a source still says that the person put away (a problem dismissed, a state
* hidden, every row of an entry kept), by key: listed under "earlier" with a way
* back (`bringBack`), so the column is never the only door to a fact that stands. */
away: ReadonlyMap<string, HudEntry>
/** Entries that ended while a hand was in the column: they keep their room, inert. */
ended: ReadonlySet<string>
/** Rows that left while a hand was in the column, by their entry's key: they keep
* their room, dim and inert. */
leftRows: ReadonlyMap<string, ReadonlySet<string>>
/** Each entry's own controls as they stood when a hand came in (the chevron that opens
* its rows, the ✕), held while it stays: a control that would appear waits, one that
* goes keeps its place, inert. Empty while no hand is in. */
chrome: ReadonlyMap<string, HudChrome>
/** Entries that arrived while a hand was in the column: counted, not drawn. */
held: readonly HudEntry[]
readout: HudReadout | null
/** A hand is in a column: nothing moves. */
frozen: boolean
/** The scopes a seen host draws ("all" while one draws every scope): a page's own
* clocks run only while what they time is seen, as a toast's does. */
seenScopes: ReadonlySet<string> | "all"
/** The last few things said, oldest first. */
said: readonly HudSaid[]
}
export interface Hud {
state(): HudState
/** Called after every change; returns the unsubscribe. */
subscribe(listener: () => void): () => void
post(entry: HudEntry): void
update(key: string, change: (entry: HudEntry) => HudEntry): void
end(key: string, outcome: HudOutcome): void
/** Everything `source` says now: what it no longer says ends, the rest posts. One
* change, one notice. `remembered` false: the source's facts last the session, so a
* problem of it put away is remembered for the session only. A row put away is never
* forgotten for not being said (a source fills its rows bit by bit): its source
* forgets it (`forget`) when the thing it names is gone. */
reconcile(source: string, entries: HudEntry[], remembered?: boolean): void
/** The rows of `key` whose things are gone: their dismissals are forgotten. */
forget(rows: Iterable<string>, key: string): void
toast(title: string, options?: { detail?: string; action?: HudAction }): void
/** A promise as work: progress while it runs, a toast or a problem as it settles.
* The promise is handed back. */
promise<V>(
promise: Promise<V>,
said: {
progress: string
toast: string | ((value: V) => string)
problem: string | ((error: unknown) => string)
},
): Promise<V>
read(
words: string,
options?: { refusal?: boolean; holding?: boolean; scope?: string },
): void
clearReadout(): void
/** The entry as last posted: what a press runs (its closures are never compared). */
latest(key: string): HudEntry | undefined
/** A source's entry as its producer last gave it, every row it holds, the rows put
* away included: what a producer reads beside `dismissedRows` to count what it said
* and what was kept. Nothing for an event, which is never said again. */
given(key: string): HudEntry | undefined
/** A press on an entry's action or its cancel, found in the entry as last said:
* refused while not armed or held unseen and, destructive, when it reached the verb
* by layout (a double click's second press, a click or a tap on a verb that had not
* stood still `HUD_DWELL`); what it posts shows at once, and a toast's action
* dismisses it. */
act(key: string, which: "action" | "cancel", reach: HudReach): void
/** A press on a row's verb (by its label), or on its title (`"open"`), found in the
* entry as last said (a row that left under the hand, or one under it, takes none);
* refused as `act` refuses; what it posts shows at once. */
actRow(key: string, row: string, verb: string, reach: HudReach): void
dismiss(key: string): void
dismissRow(row: string, key: string): void
/** An entry put away (`away`) shown again: its dismissal, and its rows' when every
* row was put away, forgotten, so it stands until it changes or is put away again. */
bringBack(key: string): void
dismissedRows(key: string): ReadonlySet<string>
/** A hand (a host's part by its id) is in a column, or left it. */
hand(host: string, inside: boolean): void
/** A host drawing `scopes` is seen, or stopped being seen (the page hidden). */
seen(host: string, seen: boolean, scopes?: readonly string[]): void
}
const TOAST_SEEN = 5000
const WORK_AT_LEAST = 600
const SETTLE = 1000
const EARLIER_KEPT = 50
const SAID_KEPT = 6
const TICK = 250
/** How long the column stays still after the hand leaves it: crossing a gap between
* two entries, or between the column and its panel, is no leaving. */
const HAND_GRACE = 300
/** How long a readout stands after the hand rests: the time to notice it, then each
* word's reading (`readingTime`). */
const NOTICE = 500
/** Reading speed for a readout's words: 200 words a minute, a third of a second a
* word rounded down. */
const PER_WORD = 300
/** A refusal that takes longer than this to read is no readout: it stands as a
* problem. */
const READOUT_MOST = 3000
/** How long `words` stand, ms: the notice, then each word's reading. A number's unit is
* part of its word ("−3 s", "40 %" read as one). */
export function readingTime(words: string): number {
let count = 0
let afterNumber = false
for (const token of words.split(/\s+/).filter(Boolean)) {
const unit = afterNumber && token.length <= 2 && !/\d/.test(token)
if (!unit) count += 1
afterNumber = /\d/.test(token)
}
return NOTICE + PER_WORD * count
}
/** Where a kind stands in the folding order (`HUD_KINDS`): the lowest folds first. */
export const foldOrder = (kind: HudKind) => HUD_KINDS.indexOf(kind)
/** The tone an entry wears: its own, else its kind's. */
export function toneOf(entry: HudEntry): HudTone {
if (entry.tone) return entry.tone
return entry.kind === "problem"
? "warn"
: entry.kind === "toast"
? "neutral"
: "info"
}
/** Two entries saying the same, their verbs' closures aside (JSON drops functions). */
const same = (a: HudEntry, b: HudEntry) =>
JSON.stringify(a) === JSON.stringify(b)
/** A verb held unseen (`shown: false`) is never armed: one rule, asserted. */
function heldUnseenNeverArmed(entry: HudEntry) {
const check = (v: HudAction | undefined) => {
if (v && v.shown === false && v.armed !== false)
throw new Error(`hud: ${v.label} is held unseen, so it is never armed`)
}
const rows = (list: readonly HudRow[] | undefined) => {
for (const row of list ?? []) {
for (const v of row.verbs ?? []) check(v)
rows(row.rows)
}
}
check(entry.action)
check(entry.cancel)
rows(entry.rows)
}
// Under the hand nothing changes geometry: every row keeps its place, its height, its
// verbs' places and its child rows as they stood; words change in place; what would grow
// (a detail line, a verb, a child row) waits until the hand leaves, and what goes leaves
// its place behind, unseen (a verb) or inert (a row, at any depth). Only a new top-level
// row may join, at the end, where it moves nothing.
const unseen = (v: HudAction): HudAction => ({
label: v.label,
onClick: () => {},
prominent: v.prominent,
room: v.room,
armed: false,
shown: false,
})
/** The words a verb's place holds (its room and its own), as one key. */
const placeWords = (v: HudAction) =>
[...new Set([...(v.room ?? []), v.label])].sort().join("\n")
/** Verbs by place: each standing place keeps its verb when the fresh one there is the
* same verb or one of its place's (`room`), else holds the place unseen; a verb past the
* standing places waits. Two verbs share a place only when they are drawn alike there:
* the same words held and the same prominence, so the place keeps its width. */
function holdVerbs(
fresh: readonly HudAction[] | undefined,
standing: readonly HudAction[] | undefined,
): HudAction[] {
return (standing ?? []).map((s, i) => {
const f = fresh?.[i]
if (
f &&
(f.label === s.label ||
(s.room ?? []).includes(f.label) ||
(f.room ?? []).includes(s.label))
) {
if (
placeWords(f) !== placeWords(s) ||
(f.prominent ?? false) !== (s.prominent ?? false)
)
throw new Error(
`hud: ${f.label} and ${s.label} share a place but are drawn differently`,
)
return f
}
return unseen(s)
})
}
/** An entry's control: one that goes holds its place unseen, one that would appear
* waits. */
function holdControl(
fresh: HudAction | undefined,
standing: HudAction | undefined,
): HudAction | undefined {
if (!fresh && standing) return unseen(standing)
if (fresh && !standing) return undefined
return fresh
}
/** `row` and every row under it, left: inert in place. */
function leaveRow(row: HudRow, left: Set<string>) {
left.add(row.id)
for (const child of row.rows ?? []) leaveRow(child, left)
}
function holdRows(
fresh: readonly HudRow[] | undefined,
standing: readonly HudRow[] | undefined,
left: Set<string>,
top: boolean,
): HudRow[] {
const now = new Map((fresh ?? []).map((r) => [r.id, r]))
const rows: HudRow[] = []
for (const row of standing ?? []) {
const f = now.get(row.id)
if (f) {
rows.push({
...f,
// A detail's line is held: one that would appear waits, one that goes keeps
// its words.
detail: row.detail === undefined ? undefined : (f.detail ?? row.detail),
verbs: holdVerbs(f.verbs, row.verbs),
rows: holdRows(f.rows, row.rows, left, false),
})
} else {
rows.push(row)
leaveRow(row, left)
}
}
if (top) {
const had = new Set((standing ?? []).map((r) => r.id))
rows.push(...(fresh ?? []).filter((r) => !had.has(r.id)))
}
return rows
}
/** A row by its id, at any depth. */
function findRow(
rows: readonly HudRow[] | undefined,
id: string,
): HudRow | undefined {
for (const row of rows ?? []) {
if (row.id === id) return row
const deeper = findRow(row.rows, id)
if (deeper) return deeper
}
return undefined
}
interface Life {
shown: number
/** A toast's ms left to be seen. */
seenLeft?: number
/** When it leaves: a state that stopped holding, work ended before its 600 ms. */
leaves?: number
}
/** The timers the store runs its laws on: the page's own, or a law's, which steps them
* itself rather than wait on the wall clock. */
export interface HudTimers {
setTimeout(run: () => void, ms: number): unknown
clearTimeout(id: unknown): void
setInterval(run: () => void, ms: number): unknown
clearInterval(id: unknown): void
}
const pageTimers: HudTimers = {
setTimeout: (run, ms) => setTimeout(run, ms),
clearTimeout: (id) => clearTimeout(id as ReturnType<typeof setTimeout>),
setInterval: (run, ms) => setInterval(run, ms),
clearInterval: (id) => clearInterval(id as ReturnType<typeof setInterval>),
}
export function createHud(
options: { memory?: HudMemory; now?: () => number; timers?: HudTimers } = {},
): Hud {
const now = options.now ?? (() => Date.now())
const timers = options.timers ?? pageTimers
const memory = options.memory
// Read on first use, never at creation: a page's one HUD is made where no storage
// exists yet (a server rendering it).
// What a later build added to the memory, carried through every write untouched.
let kept: {
entries: Map<string, Set<string>>
rows: Map<string, Set<string>>
others: Record<string, unknown>
} | null = null
const keptNow = () => {
if (kept) return kept
const read = (memory?.read() ?? {}) as Record<string, unknown>
const { entries, rows, ...others } = read
const sets = (v: unknown) =>
new Map(
Object.entries((v as Record<string, string[]> | undefined) ?? {}).map(
([k, ids]) => [k, new Set(Array.isArray(ids) ? ids : [])],
),
)
kept = { entries: sets(entries), rows: sets(rows), others }
return kept
}
const remember = () => {
const k = keptNow()
memory?.write({
...k.others,
entries: Object.fromEntries(
[...k.entries].map(([key, v]) => [key, [...v]]),
),
rows: Object.fromEntries([...k.rows].map(([key, v]) => [key, [...v]])),
} as HudKept)
}
/** Sources whose facts last the session: their problems put away are remembered for
* the session only. */
const sessionSources = new Set<string>()
const sessionDismissed = new Map<string, Set<string>>()
/** Problems said as they arrived under the hand: not said again when they show. */
const announcedHeld = new Set<string>()
let state: HudState = {
entries: [],
earlier: [],
away: new Map(),
ended: new Set(),
leftRows: new Map(),
chrome: new Map(),
held: [],
readout: null,
frozen: false,
seenScopes: new Set(),
said: [],
}
/** Each shown entry as last posted: its closures, and its data while a hand holds the
* column still. */
const latestByKey = new Map<string, HudEntry>()
/** Each entry as its producer last posted it, every row it holds: what putting a row
* away, an update and `away` start from, so all of it comes back. */
const givenByKey = new Map<string, HudEntry>()
const waiting = new Map<string, { entry: HudEntry; at: number }>()
const hiddenStates = new Map<string, string>()
const lives = new Map<string, Life>()
const sources = new Map<string, Set<string>>()
const hands = new Set<string>()
const seers = new Map<string, readonly string[] | undefined>()
const listeners = new Set<() => void>()
let clock: unknown = null
let unfreeze: unknown = null
let readoutClear: unknown = null
let serial = 0
let quiet = 0
let owed = false
let acting = 0
const notify = () => {
if (quiet > 0) {
owed = true
return
}
for (const l of listeners) l()
}
const set = (next: Partial<HudState>) => {
state = { ...state, ...next }
notify()
}
/** Changes made inside `run` notify once, at its end. */
const batch = (run: () => void) => {
quiet += 1
try {
run()
} finally {
quiet -= 1
if (quiet === 0 && owed) {
owed = false
notify()
}
}
}
const announce = (entry: HudEntry) => {
serial += 1
const words = [entry.title, entry.detail].filter(Boolean).join(", ")
set({
said: [
...state.said,
{ id: serial, words, urgent: entry.kind === "problem" },
].slice(-SAID_KEPT),
})
}
const withoutDismissedRows = (entry: HudEntry): HudEntry => {
const gone = keptNow().rows.get(entry.key)
if (!gone?.size || !entry.rows) return entry
return { ...entry, rows: entry.rows.filter((r) => !gone.has(r.id)) }
}
/** A problem dismissed with its rows (for the session, or across reloads): rowless,
* until its source stops saying it; with rows, until a row it did not hold appears. */
const isDismissed = (entry: HudEntry) => {
const ids = (entry.rows ?? []).map((r) => r.id)
const session = sessionDismissed.get(entry.key)
if (session) {
if (ids.every((id) => session.has(id))) return true
sessionDismissed.delete(entry.key)
return false
}
const rows = keptNow().entries.get(entry.key)
if (!rows) return false
if (ids.every((id) => rows.has(id))) return true
keptNow().entries.delete(entry.key)
remember()
return false
}
/** What the person put away and a source saying it again does not undo. */
const putAway = (entry: HudEntry) =>
entry.kind === "problem"
? isDismissed(entry)
: entry.kind === "state" &&
hiddenStates.get(entry.key) ===
JSON.stringify([entry.title, entry.detail])
/** An entry changed while a hand is in the column: its rows keep their order and
* their room (a row that left stays, `leftRows`), new ones join at the end. */
const frozenRows = (entry: HudEntry, standing: HudEntry): HudEntry => {
// Rebuilt from what stands: a row that left stays inert, one said again is a row
// again.
const left = new Set<string>()
const rows = holdRows(entry.rows, standing.rows, left, true)
const leftRows = new Map(state.leftRows)
if (left.size > 0) leftRows.set(entry.key, left)
else leftRows.delete(entry.key)
set({ leftRows })
return {
...entry,
rows,
action: holdControl(entry.action, standing.action),
cancel: holdControl(entry.cancel, standing.cancel),
}
}
/** The one rule a standing entry changes by, a post's, an end's and a press's alike:
* what it says shows at once; under the hand its rows keep their places, a row that
* left inert in its place, applied whole once the hand leaves; else it applies whole
* now, nothing left over. */
const changed = (entry: HudEntry, standing: HudEntry): HudEntry => {
if (state.frozen) return frozenRows(entry, standing)
if (state.leftRows.has(entry.key)) {
const leftRows = new Map(state.leftRows)
leftRows.delete(entry.key)
set({ leftRows })
}
return entry
}
const show = (entry: HudEntry) => {
if (state.frozen && acting === 0) {
set({ held: [...state.held, entry] })
// A problem is said at once, even while the column holds still, and only then.
if (entry.kind === "problem") {
announce(entry)
announcedHeld.add(entry.key)
}
return
}
latestByKey.set(entry.key, entry)
lives.set(entry.key, {
shown: now(),
seenLeft: entry.kind === "toast" ? TOAST_SEEN : undefined,
})
set({ entries: [...state.entries, entry] })
if (!announcedHeld.delete(entry.key)) announce(entry)
run()
}
const leave = (key: string) => {
const entry = state.entries.find((e) => e.key === key)
if (!entry) return
if (state.frozen) {
if (!state.ended.has(key)) set({ ended: new Set([...state.ended, key]) })
return
}
lives.delete(key)
latestByKey.delete(key)
serial += 1
const leftRows = new Map(state.leftRows)
leftRows.delete(key)
set({
entries: state.entries.filter((e) => e.key !== key),
earlier: [{ id: serial, entry }, ...state.earlier].slice(0, EARLIER_KEPT),
leftRows,
})
}
/** Whether a source holds `key` (`reconcile`): its entry is said again, so what it
* gave is kept; an event's never is. */
const sourced = (key: string) =>
[...sources.values()].some((keys) => keys.has(key))
/** `entry` kept as its producer gave it, every row it holds, for a source's key alone;
* written by every change of an entry, so it never goes stale. */
const keepGiven = (entry: HudEntry) => {
if (sourced(entry.key)) givenByKey.set(entry.key, entry)
}
/** `entry` ended as `kind`, from what its producer gave, kept as given and shown less
* the rows put away. */
const ending = (
entry: HudEntry,
kind: "toast" | "problem",
title: string,
detail?: string,
): HudEntry => {
const ended: HudEntry = {
...(givenByKey.get(entry.key) ?? entry),
kind,
title,
detail,
progress: undefined,
tone: undefined,
cancel: undefined,
}
keepGiven(ended)
return withoutDismissedRows(ended)
}
const ticking = () =>
!state.frozen &&
seers.size > 0 &&
(waiting.size > 0 ||
[...lives.values()].some(
(l) => l.seenLeft !== undefined || l.leaves !== undefined,
))
const step = () => {
const t = now()
batch(() => {
for (const [key, w] of waiting) {
if (w.at <= t) {
waiting.delete(key)
show(w.entry)
}
}
const seenScopes = new Set<string>()
let everyScope = false
for (const scopes of seers.values()) {
if (!scopes) everyScope = true
else for (const s of scopes) seenScopes.add(s)
}
for (const [key, life] of [...lives]) {
const entry = latestByKey.get(key)
if (life.leaves !== undefined && life.leaves <= t) leave(key)
else if (
life.seenLeft !== undefined &&
entry &&
(everyScope || seenScopes.has(entry.scope ?? "app"))
) {
const less = life.seenLeft - TICK
if (less <= 0) leave(key)
else life.seenLeft = less
}
}
})
if (!ticking() && clock) {
timers.clearInterval(clock)
clock = null
}
}
// One clock for every timed law, running only while it has something to do.
const run = () => {
if (!clock && ticking()) clock = timers.setInterval(step, TICK)
}
/** `key` kept as put away (`entry`), or no longer (`undefined`): written only when it
* changes. */
const putBack = (key: string, entry: HudEntry | undefined) => {
const was = state.away.get(key)
if (entry ? was !== undefined && same(was, entry) : was === undefined)
return
const away = new Map(state.away)
if (entry) away.set(key, entry)
else away.delete(key)
set({ away })
}
/** What its source stopped saying: a dismissal of it as a whole is forgotten; its
* rows' dismissals stay, forgotten only by its source (`forget`), so an entry that
* left when its last row was put away brings none back when it is said again. */
const gone = (key: string) => {
putBack(key, undefined)
givenByKey.delete(key)
hiddenStates.delete(key)
sessionDismissed.delete(key)
if (keptNow().entries.delete(key)) remember()
if (waiting.delete(key)) return
// Said under the hand and gone before it showed: its next showing is said.
announcedHeld.delete(key)
if (state.held.some((e) => e.key === key))
set({ held: state.held.filter((e) => e.key !== key) })
const entry = latestByKey.get(key)
if (!entry) return
if (entry.kind === "progress") hud.end(key, "quietly")
else if (entry.kind === "state") {
const life = lives.get(key)
if (life) life.leaves = now() + SETTLE
run()
} else if (entry.kind === "problem") leave(key)
}
const settle = () => {
batch(() => {
for (const key of state.ended) {
// Out of `ended` first, so `leave` takes it now.
set({ ended: new Set([...state.ended].filter((k) => k !== key)) })
leave(key)
}
const entries = state.entries.map((e) => latestByKey.get(e.key) ?? e)
const arrived = state.held
set({
ended: new Set(),
leftRows: new Map(),
chrome: new Map(),
held: [],
entries,
})
for (const entry of arrived) show(entry)
})
run()
}
/** Whether a press reached `verb` on purpose. A destructive one takes a key or an
* assistive action, a single click on a verb that had stood still `HUD_DWELL`, and a
* tap on one that had stood still that long before the finger landed; a double
* click's second press, or a press on a verb that just appeared or moved there, is
* refused, felt and said in its input's words. */
const reached = (verb: HudAction, reach: HudReach) => {
if (!verb.destructive || reach === "key") return true
const words =
"touch" in reach
? reach.touch.still < HUD_DWELL && "hold still on it, then press"
: reach.pointer.clicks >= 2
? "click it once"
: reach.pointer.still < HUD_DWELL &&
"rest the pointer on it, then press"
if (!words) return true
hud.read(words, { refusal: true })
return false
}
/** Runs a press made in the column: what it posts shows at once. */
const pressed = (press: () => void) => {
acting += 1
try {
press()
} finally {
acting -= 1
}
}
const hud: Hud = {
state: () => state,
subscribe(listener) {
listeners.add(listener)
return () => listeners.delete(listener)
},
post(given) {
if (
typeof given.progress === "number" &&
!Number.isFinite(given.progress)
)
throw new Error(
`hud.post: ${given.key} says a share of ${given.progress}`,
)
heldUnseenNeverArmed(given)
keepGiven(given)
const entry = withoutDismissedRows(given)
const i = state.entries.findIndex((e) => e.key === entry.key)
if (i >= 0) {
const standing = state.entries[i] as HudEntry
const life = lives.get(entry.key)
if (life) life.leaves = undefined
latestByKey.set(entry.key, entry)
const shown = changed(entry, standing)
// Said again, it stands again: out of `ended`, whatever the hand; unless the
// person put it away (a problem dismissed, a state hidden), which a source saying
// it again never undoes.
const ended = state.ended.has(entry.key) && !putAway(entry)
if (same(shown, standing) && !ended) return
if (standing.kind !== entry.kind) announce(entry)
const entries = [...state.entries]
entries[i] = shown
set(
ended
? {
entries,
ended: new Set([...state.ended].filter((k) => k !== entry.key)),
}
: { entries },
)
return
}
const h = state.held.findIndex((e) => e.key === entry.key)
if (h >= 0) {
const held = [...state.held]
held[h] = entry
set({ held })
return
}
const w = waiting.get(entry.key)
if (w) {
w.entry = entry
return
}
// Put away (it, or every row it holds): kept where the person can bring it back,
// never the only door to a fact that stands.
if (putAway(entry) || (given.rows?.length && !entry.rows?.length)) {
putBack(given.key, given)
return
}
putBack(entry.key, undefined)
if (entry.kind === "state") hiddenStates.delete(entry.key)
if (entry.kind === "progress" && (entry.reveal ?? 300) > 0) {
waiting.set(entry.key, { entry, at: now() + (entry.reveal ?? 300) })
run()
} else if (entry.kind === "state") {
waiting.set(entry.key, { entry, at: now() + SETTLE })
run()
} else show(entry)
},
update(key, change) {
const shown = latestByKey.get(key)
// Changed from what its producer said, every row it holds.
if (shown) return hud.post(change(givenByKey.get(key) ?? shown))
const w = waiting.get(key)
if (w) {
const changed = change(givenByKey.get(key) ?? w.entry)
heldUnseenNeverArmed(changed)
keepGiven(changed)
w.entry = withoutDismissedRows(changed)
return
}
const h = state.held.findIndex((e) => e.key === key)
if (h >= 0) {
const held = [...state.held]
const changed = change(givenByKey.get(key) ?? (held[h] as HudEntry))
heldUnseenNeverArmed(changed)
keepGiven(changed)
held[h] = withoutDismissedRows(changed)
set({ held })
}
},
end(key, outcome) {
const w = waiting.get(key)
if (w) {
waiting.delete(key)
if (outcome !== "quietly")
show(
"toast" in outcome
? ending(w.entry, "toast", outcome.toast, outcome.detail)
: ending(w.entry, "problem", outcome.problem, outcome.detail),
)
return
}
const h = state.held.findIndex((e) => e.key === key)
if (h >= 0) {
const held = [...state.held]
const was = held[h] as HudEntry
if (outcome === "quietly") {
held.splice(h, 1)
announcedHeld.delete(key)
} else if ("toast" in outcome) {
// Not what was said under the hand: said when it shows.
held[h] = ending(was, "toast", outcome.toast, outcome.detail)
announcedHeld.delete(key)
} else {
const problem = ending(
was,
"problem",
outcome.problem,
outcome.detail,
)
held[h] = problem
announce(problem)
announcedHeld.add(key)
}
set({ held })
return
}
const entry = latestByKey.get(key)
if (!entry) return
if (outcome === "quietly") {
const leaves = (lives.get(key)?.shown ?? now()) + WORK_AT_LEAST
if (leaves <= now()) leave(key)
else {
const life = lives.get(key)
if (life) life.leaves = leaves
run()
}
return
}
const ended =
"toast" in outcome
? ending(entry, "toast", outcome.toast, outcome.detail)
: ending(entry, "problem", outcome.problem, outcome.detail)
lives.set(key, {
shown: now(),
seenLeft: "toast" in outcome ? TOAST_SEEN : undefined,
})
latestByKey.set(key, ended)
// The one rule a standing entry changes by (`changed`).
const entries = state.entries.map((e) =>
e.key === key ? changed(ended, e) : e,
)
set({ entries })
announce(ended)
run()
},
reconcile(source, said, remembered = true) {
const keys = new Set(said.map((e) => e.key))
if (keys.size !== said.length)
throw new Error(`hud.reconcile: ${source} says a key twice`)
if (!remembered) sessionSources.add(source)
batch(() => {
for (const key of sources.get(source) ?? [])
if (!keys.has(key)) gone(key)
sources.set(source, keys)
for (const entry of said) hud.post(entry)
})
},
forget(rows, key) {
// Read once: an iterable may be a generator, spent by its first walk.
const ids = [...rows]
const dismissed = keptNow().rows.get(key)
if (!dismissed || !ids.some((id) => dismissed.has(id))) return
for (const id of ids) dismissed.delete(id)
if (dismissed.size === 0) keptNow().rows.delete(key)
remember()
notify()
},
toast(title, o = {}) {
serial += 1
hud.post({
key: `toast ${serial}`,
kind: "toast",
title,
detail: o.detail,
action: o.action,
})
},
promise(promise, said) {
serial += 1
const key = `promise ${serial}`
hud.post({ key, kind: "progress", title: said.progress, reveal: 0 })
promise.then(
(v) =>
hud.end(key, {
toast:
typeof said.toast === "function" ? said.toast(v) : said.toast,
}),
(e) =>
hud.end(key, {
problem:
typeof said.problem === "function"
? said.problem(e)
: said.problem,
}),
)
return promise
},
read(words, o = {}) {
const refusal = o.refusal ?? false
const scope = o.scope ?? "app"
const reading = readingTime(words)
if (refusal && reading > READOUT_MOST) {
hud.post({ key: "refused", kind: "problem", title: words, scope })
return
}
if (
refusal ||
state.readout?.words !== words ||
state.readout?.scope !== scope
) {
serial += 1
// A gesture is the readings shown without a rest between, in one place; a
// refusal is a gesture of its own.
const shown = state.readout
const gesture =
shown && !refusal && !shown.refusal && shown.scope === scope
? shown.gesture
: serial
set({ readout: { words, refusal, scope, serial, gesture } })
}
if (refusal) {
serial += 1
set({
said: [...state.said, { id: serial, words, urgent: true }].slice(
-SAID_KEPT,
),
})
}
if (readoutClear) timers.clearTimeout(readoutClear)
readoutClear = null
if (o.holding) return
readoutClear = timers.setTimeout(() => {
readoutClear = null
set({ readout: null })
}, reading)
},
clearReadout() {
if (readoutClear) timers.clearTimeout(readoutClear)
readoutClear = null
if (state.readout) set({ readout: null })
},
latest: (key) => latestByKey.get(key),
given: (key) => givenByKey.get(key),
act(key, which, reach) {
const entry = latestByKey.get(key)
if (!entry || state.ended.has(key)) return
const verb = which === "action" ? entry.action : entry.cancel
if (!verb || verb.armed === false || verb.shown === false) return
if (!reached(verb, reach)) return
pressed(() => {
verb.onClick()
if (entry.kind === "toast") hud.dismiss(key)
})
},
actRow(key, row, verb, reach) {
const entry = latestByKey.get(key)
if (!entry || state.ended.has(key)) return
if (state.leftRows.get(key)?.has(row)) return
const found = findRow(entry.rows, row)
const press =
verb === "open"
? found?.open
: found?.verbs?.find((v) => v.label === verb)
if (press && press.armed !== false && press.shown !== false)
if (reached(press, reach)) pressed(press.onClick)
},
dismiss(key) {
const entry = latestByKey.get(key)
if (!entry) return
const source = [...sources].find(([, keys]) => keys.has(key))?.[0]
const reconciled = source !== undefined
if (reconciled && entry.kind === "problem") {
const rows = new Set((entry.rows ?? []).map((r) => r.id))
if (sessionSources.has(source)) sessionDismissed.set(key, rows)
else {
keptNow().entries.set(key, rows)
remember()
}
}
if (reconciled && entry.kind === "state")
hiddenStates.set(key, JSON.stringify([entry.title, entry.detail]))
if (reconciled && (entry.kind === "problem" || entry.kind === "state"))
putBack(key, givenByKey.get(key) ?? entry)
leave(key)
},
bringBack(key) {
const entry = state.away.get(key)
if (!entry) return
putBack(key, undefined)
sessionDismissed.delete(key)
hiddenStates.delete(key)
const k = keptNow()
k.entries.delete(key)
const kept = k.rows.get(key)
if (kept && !withoutDismissedRows(entry).rows?.length) {
// Only the rows it holds come back: another row kept stays kept.
for (const r of entry.rows ?? []) kept.delete(r.id)
if (kept.size === 0) k.rows.delete(key)
}
remember()
// A press in the panel: what it shows, shows at once.
pressed(() => hud.post(entry))
},
dismissRow(row, key) {
const k = keptNow()
const rows = k.rows.get(key) ?? new Set<string>()
rows.add(row)
k.rows.set(key, rows)
remember()
const entry = latestByKey.get(key)
if (!entry) {
notify()
return
}
// Said again as its producer said it: the post leaves the rows put away out, and
// what was given stays whole.
const whole = givenByKey.get(key) ?? entry
if (!withoutDismissedRows(whole).rows?.length) {
// Kept where it can come back only while a source says it.
if ([...sources.values()].some((keys) => keys.has(key)))
putBack(key, whole)
leave(key)
} else hud.post(whole)
},
dismissedRows: (key) => new Set(keptNow().rows.get(key) ?? []),
hand(host, inside) {
if (inside) hands.add(host)
else hands.delete(host)
if (hands.size > 0) {
if (unfreeze) timers.clearTimeout(unfreeze)
unfreeze = null
if (!state.frozen)
set({
frozen: true,
chrome: new Map(
state.entries.map((e) => [
e.key,
{
rows: (e.rows?.length ?? 0) > 0,
dismiss: dismissible(e),
},
]),
),
})
return
}
if (!state.frozen || unfreeze) return
unfreeze = timers.setTimeout(() => {
unfreeze = null
if (hands.size > 0) return
set({ frozen: false })
settle()
}, HAND_GRACE)
},
seen(host, seen, scopes) {
if (seen) seers.set(host, scopes)
else seers.delete(host)
const all = [...seers.values()]
const next: ReadonlySet<string> | "all" = all.some((s) => !s)
? "all"
: new Set(all.flatMap((s) => s ?? []))
const was = state.seenScopes
const same =
next === "all" || was === "all"
? next === was
: next.size === was.size && [...next].every((s) => was.has(s))
if (!same) set({ seenScopes: next })
run()
},
}
return hud
}