nish-ui 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/canvas/system-canvas.tsx","../src/cn.ts","../src/components/flow.tsx","../src/components/hooks.tsx","../src/components/icons.tsx","../src/components/primitives.tsx","../src/components/canvas/follow-caption.tsx","../src/components/display.tsx","../src/components/canvas/follow.ts","../src/components/canvas/view.ts","../src/components/canvas/icons.tsx","../src/components/canvas/layout.ts","../src/components/canvas/legend.tsx","../src/components/canvas/minimap.tsx","../src/components/canvas/node.tsx","../src/components/canvas/route.ts"],"sourcesContent":["import {\n Fragment,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type FocusEvent as ReactFocusEvent,\n type KeyboardEvent as ReactKeyboardEvent,\n type MouseEvent as ReactMouseEvent,\n type PointerEvent as ReactPointerEvent,\n} from 'react';\nimport { cn } from '../../cn';\nimport { usePrefersReducedMotion } from '../flow';\nimport { IconButton } from '../primitives';\nimport { FollowCaption } from './follow-caption';\nimport { useFollow } from './follow';\nimport { FitIcon, FollowIcon, MinusIcon, PlusIcon } from './icons';\nimport { chooseLayout, layoutCandidates, SCROLL_K, type CanvasLayout } from './layout';\nimport { EdgeLegend } from './legend';\nimport { Minimap, type MinimapHandle } from './minimap';\nimport { hueStyle, NodeView } from './node';\nimport { labelPoint, routeEdges, type Box } from './route';\nimport type { CanvasEdgeKind, CanvasGroup, CanvasHue, CanvasNode, SystemCanvasProps } from './types';\nimport { ANIM_MS, centerOn, clampK, DOUBLE_MS, DOUBLE_PX, DRAG_PX, ease, FIT_PAD, FOLLOW_MS, KEY_PAN, LABEL_K, LOD_K, MIN_K, PHONE_K, PHONE_MAX_W, ZOOM_STEP, zoomAround, type View } from './view';\n\nconst insetFor = (w: number, minimap: boolean) => (minimap && w >= MINIMAP_MIN_W ? TOP_INSET_MINIMAP : TOP_INSET);\nconst NO_KINDS: CanvasEdgeKind[] = [];\n// World-free screen px kept clear at the top for the legend button (12 px offset + 44 px button + gap), and with the minimap (176 x ~130 at top 12) shown.\nconst TOP_INSET = 64;\nconst TOP_INSET_MINIMAP = 150;\nconst MINIMAP_MIN_W = 600;\n// Screen px from either side that the corner overlays (legend, minimap) can cover.\nconst CORNER_W = 200;\nconst initialHidden = (kinds: CanvasEdgeKind[]) => new Set(kinds.filter((k) => k.hidden).map((k) => k.id));\n\n// SystemCanvas: a pannable, zoomable graph-paper canvas of grouped nodes and edges that\n// light up where work is happening. The layout is computed (layoutSystem), never stored.\n//\n// Pan and zoom never go through React state: the view lives in a ref and is written\n// straight to the world layer (`transform`) and the viewport's background-position and\n// background-size, so a drag or a wheel tick re-renders nothing. Motion lives in CSS\n// (src/css/base.css, `nish-canvas-*`), inside `prefers-reduced-motion: no-preference`.\n// =====================================================================================\n// SystemCanvas\n// =====================================================================================\n\n/** A pannable, zoomable graph-paper canvas of grouped nodes joined by edges. Nodes with\n * `active` pulse in their group's hue, edges into them flow, and `heat` leaves a fading\n * glow behind. Drag or scroll to pan, ctrl+scroll or pinch to zoom, arrow keys, `+`, `-`\n * and `0` from the keyboard. */\nexport function SystemCanvas({\n groups,\n edges,\n columns,\n bands,\n layout: layoutMode = 'auto',\n edgeKinds,\n follow,\n onFollowChange,\n minimap = true,\n selected = null,\n onSelect,\n height = '100%',\n label = 'System map',\n className,\n}: SystemCanvasProps) {\n const reduced = usePrefersReducedMotion();\n const viewportRef = useRef<HTMLDivElement>(null);\n const worldRef = useRef<HTMLDivElement>(null);\n const view = useRef<View>({ x: 0, y: 0, k: 1 });\n const target = useRef<View | null>(null); // where a running animation is heading\n const raf = useRef(0);\n const size = useRef({ w: 0, h: 0 });\n const touched = useRef(false); // the viewer moved the view; stop auto-fitting\n const zoomLabelRef = useRef<HTMLSpanElement>(null);\n const miniRef = useRef<MinimapHandle>(null);\n const [labelsOn, setLabelsOn] = useState(true);\n const [hoverId, setHoverId] = useState<string | null>(null);\n const [viewport, setViewport] = useState({ w: 0, h: 0 }); // follow re-flies when this changes\n\n // --- edge kinds: hidden kinds are left out of the layout and the routing ----------\n const kindList = edgeKinds ?? NO_KINDS;\n const kindSig = kindList.map((k) => k.id).join('|');\n const [hiddenState, setHiddenState] = useState(() => ({\n sig: kindSig,\n set: initialHidden(kindList),\n }));\n let hiddenKinds = hiddenState.set;\n if (hiddenState.sig !== kindSig) {\n const next = { sig: kindSig, set: initialHidden(kindList) };\n setHiddenState(next);\n hiddenKinds = next.set;\n }\n const toggleKind = useCallback((id: string) => {\n setHiddenState((s) => {\n const set = new Set(s.set);\n if (!set.delete(id)) set.add(id);\n return { sig: s.sig, set };\n });\n }, []);\n const visibleEdges = useMemo(() => edges.filter((e) => !e.kind || !hiddenKinds.has(e.kind)), [edges, hiddenKinds]);\n const lineOf = useMemo(() => new Map(kindList.map((k) => [k.id, k.line ?? 'solid'] as const)), [kindList]);\n\n // --- follow is controlled when `follow` is set ----------------------------------\n const [internalFollow, setInternalFollow] = useState(false);\n const followOn = follow ?? internalFollow;\n const followRef = useRef(followOn);\n const followProps = useRef({ controlled: follow !== undefined, onFollowChange });\n const setFollow = useCallback((on: boolean) => {\n if (!followProps.current.controlled) setInternalFollow(on);\n followProps.current.onFollowChange?.(on);\n }, []);\n /** The viewer moved the view: stop auto-fitting and stop following. */\n const markMoved = useCallback(() => {\n touched.current = true;\n if (followRef.current) {\n followRef.current = false; // a burst of events in one frame stops follow once\n setFollow(false);\n }\n }, [setFollow]);\n\n const sig = groups.map((g) => `${g.id}:${g.column}:${g.band ?? ''}:${g.nodes.map((n) => n.id).join(',')}`).join('|');\n const visSig = visibleEdges.map((e) => `${e.id}:${e.from}:${e.to}`).join('|');\n // The layout and the viewport size it was picked for (0 until the first measurement).\n // The candidates do not depend on the viewport, so a resize only re-chooses between them.\n const cands = useMemo(() => layoutCandidates(groups, visibleEdges, layoutMode), [sig, visSig, layoutMode]); // eslint-disable-line react-hooks/exhaustive-deps\n const [picked, setPicked] = useState(() => ({ layout: chooseLayout(cands, { w: 0, h: 0 }), w: 0, h: 0 }));\n const layout = picked.layout;\n const latest = useRef({\n cands,\n minimap,\n groups,\n layout,\n vis: visibleEdges,\n mode: layoutMode,\n });\n // Event handlers and effects read the latest props through refs; synced first, before the other layout effects.\n useLayoutEffect(() => {\n followRef.current = followOn;\n followProps.current = { controlled: follow !== undefined, onFollowChange };\n latest.current = { cands, minimap, groups, layout, vis: visibleEdges, mode: layoutMode };\n });\n\n // --- applying a view ---------------------------------------------------------\n const apply = useCallback((v: View) => {\n view.current = v;\n const world = worldRef.current;\n const vp = viewportRef.current;\n if (world) world.style.transform = `translate3d(${v.x}px,${v.y}px,0) scale(${v.k})`;\n if (vp) {\n // Written straight onto the viewport: inherited custom properties would restyle every descendant.\n const maj = `${120 * v.k}px ${120 * v.k}px`;\n const min = `${24 * v.k}px ${24 * v.k}px`;\n vp.style.backgroundPosition = `${v.x}px ${v.y}px`;\n vp.style.backgroundSize = `${maj}, ${maj}, ${min}, ${min}`;\n vp.dataset.grid = v.k < LOD_K ? 'major' : 'both';\n const lod = v.k < LOD_K ? 'far' : 'near';\n if (vp.dataset.lod !== lod) vp.dataset.lod = lod;\n }\n miniRef.current?.setView(v, size.current);\n const zl = zoomLabelRef.current;\n if (zl) {\n const text = `${Math.round(v.k * 100)}%`;\n if (zl.textContent !== text) zl.textContent = text;\n }\n const on = v.k >= LABEL_K;\n setLabelsOn((old) => (old === on ? old : on));\n }, []);\n\n const stop = useCallback(() => {\n cancelAnimationFrame(raf.current);\n raf.current = 0;\n target.current = null;\n }, []);\n\n /** Moves to `v`: a 300 ms ease (`ms`), or at once when `animate` is false or motion is reduced. */\n const go = useCallback(\n (v: View, animate: boolean, ms = ANIM_MS) => {\n cancelAnimationFrame(raf.current);\n if (!animate || reduced) {\n target.current = null;\n apply(v);\n return;\n }\n const from = { ...view.current };\n target.current = v;\n const t0 = performance.now();\n const step = (now: number) => {\n const t = Math.min(1, (now - t0) / ms);\n const e = ease(t);\n // Interpolate zoom in log space so the motion feels even.\n const k = from.k * Math.pow(v.k / from.k, e);\n apply({\n k,\n x: from.x + (v.x - from.x) * e,\n y: from.y + (v.y - from.y) * e,\n });\n if (t < 1) raf.current = requestAnimationFrame(step);\n else {\n raf.current = 0;\n target.current = null;\n apply(v);\n }\n };\n raf.current = requestAnimationFrame(step);\n },\n [apply, reduced],\n );\n\n /** The fitted view: the whole layout with 48 px padding; on a phone (fit below 0.55) the\n * zoom stays 0.55 and the view centers on the first active node, else the first group. */\n const fitView = useCallback((): View => {\n const { w, h } = size.current;\n const { groups: gs, layout: lay, minimap: mini } = latest.current;\n const cw = Math.max(1, lay.width);\n const ch = Math.max(1, lay.height + lay.titleRoom);\n // The legend and minimap sit in the top corners: keep a strip clear for them only when a card\n // of the map, fitted without that strip, would land under one of them.\n const inset = insetFor(w, mini);\n const free = Math.min((w - FIT_PAD * 2) / cw, (h - FIT_PAD * 2) / ch, 1);\n const fx = (w - cw * free) / 2;\n const fy = FIT_PAD + (h - FIT_PAD * 2 - ch * free) / 2 + lay.titleRoom * free;\n const underCorner = Object.values(lay.groups).some((b) => {\n const top0 = fy + b.y * free;\n const left = fx + b.x * free;\n const right = left + b.w * free;\n return top0 < inset && (left < CORNER_W || right > w - CORNER_W);\n });\n const top = underCorner ? inset : FIT_PAD;\n const availH = h - top - FIT_PAD;\n const fit = Math.min((w - FIT_PAD * 2) / cw, availH / ch, 1);\n if (fit >= PHONE_K || (w >= PHONE_MAX_W && fit >= SCROLL_K - 0.05) || gs.length === 0) {\n const k = clampK(Number.isFinite(fit) && fit > 0 ? fit : 1);\n return {\n k,\n x: (w - lay.width * k) / 2,\n y: top + (availH - ch * k) / 2 + lay.titleRoom * k,\n };\n }\n let box: Box | undefined;\n let activeGroup: Box | undefined;\n for (const g of gs) {\n const n = g.nodes.find((node) => node.active);\n if (n) {\n box = lay.nodes[n.id];\n activeGroup = lay.groups[g.id];\n break;\n }\n }\n // Fill the width when the map is narrower than the canvas at the phone zoom (an unfolded Fold).\n const pk = clampK(Math.min(1, Math.max(PHONE_K, (w - 48) / Math.max(1, lay.width))));\n // The map's top edge never drops below the overlay row and its bottom never rises above the\n // bottom padding, so the view never opens on empty canvas above or below the map.\n const pinY = (y: number) => Math.max(Math.min(y, top + lay.titleRoom * pk), h - FIT_PAD - lay.height * pk);\n const centerX = (lay.width * pk <= w - 24 ? (w - lay.width * pk) / 2 : undefined);\n if (!box) {\n // Nothing active: open on the top of the map (the first band), centered across when it fits.\n const first = lay.groups[gs[0]!.id];\n const x = centerX ?? (first ? w / 2 - (first.x + first.w / 2) * pk : FIT_PAD);\n return { k: pk, x, y: top + lay.titleRoom * pk };\n }\n // Keep the box head clear of the overlay row. A node centers x on its group (as follow does) when\n // the group fits, so the group's left cards and title are not cut off.\n const v = centerOn(w, h, pk, box);\n const gb = activeGroup;\n if (centerX !== undefined) v.x = centerX;\n else if (gb && gb.w * pk <= w - 24) v.x = w / 2 - (gb.x + gb.w / 2) * pk;\n return { ...v, y: pinY(Math.max(h / 2, top + (box.h * pk) / 2) - (box.y + box.h / 2) * pk) };\n }, []);\n\n const doFit = useCallback(\n (animate: boolean) => {\n if (size.current.w <= 0 || size.current.h <= 0) return;\n go(fitView(), animate);\n },\n [fitView, go],\n );\n\n // Pick the layout for the current viewport and data. A resize only swaps the layout when the\n // chosen candidate (mode or row width) changes, so a resize inside one candidate re-renders\n // nothing; otherwise it just refits.\n const relayout = useCallback(\n (data: boolean) => {\n const { cands: cs, layout: cur } = latest.current;\n const { w, h } = size.current;\n const next = chooseLayout(cs, { w, h });\n if (!data && next.mode === cur.mode && next.width === cur.width && next.height === cur.height) {\n if (!touched.current && !followRef.current) doFit(false);\n return;\n }\n setPicked({ layout: next, w, h });\n // Publish the size in the same render as the new layout so follow flies once, for the real size.\n if (followRef.current) setViewport((old) => (old.w === w && old.h === h ? old : { w, h }));\n },\n [doFit],\n );\n\n // The first measurement happens before paint; later size changes are throttled to a frame.\n const layoutRaf = useRef(0);\n const settleTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n /** Publishes the measured size to follow's state once a resize settles, also while follow is off, so\n * switching follow on never starts from a stale size. */\n const syncViewport = useCallback(() => {\n const { w, h } = size.current;\n setViewport((old) => (old.w === w && old.h === h ? old : { w, h }));\n }, []);\n useLayoutEffect(() => {\n const vp = viewportRef.current;\n if (!vp) return;\n let first = true;\n const measure = () => {\n const r = vp.getBoundingClientRect();\n size.current = { w: r.width, h: r.height };\n if (first) {\n first = false;\n setViewport({ w: r.width, h: r.height });\n relayout(true);\n return;\n }\n if (layoutRaf.current) return;\n layoutRaf.current = requestAnimationFrame(() => {\n layoutRaf.current = 0;\n relayout(false);\n // The minimap's visibility and view rect follow the new size even when the view stays put.\n miniRef.current?.setView(view.current, size.current);\n // Follow re-flies only once a resize settles; nothing re-renders per frame.\n clearTimeout(settleTimer.current);\n settleTimer.current = setTimeout(syncViewport, 150);\n });\n };\n measure();\n const ro = new ResizeObserver(measure);\n ro.observe(vp);\n return () => {\n ro.disconnect();\n cancelAnimationFrame(layoutRaf.current);\n layoutRaf.current = 0;\n clearTimeout(settleTimer.current);\n };\n }, [relayout, syncViewport]);\n\n // Switching follow on picks up any size change that happened while it was off.\n useEffect(() => {\n if (followOn) syncViewport();\n }, [followOn, syncViewport]);\n\n const firstData = useRef(true);\n useLayoutEffect(() => {\n if (firstData.current) {\n firstData.current = false;\n return;\n }\n relayout(true);\n }, [sig, visSig, layoutMode, relayout]);\n\n // A new layout: the first one fits at once; a different one slides the cards to their new\n // places (data-relayout switches the CSS transition on for a moment) and refits.\n const prevLayout = useRef<CanvasLayout | null>(null);\n const fitted = useRef(false);\n const relayoutTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n useLayoutEffect(() => {\n const prev = prevLayout.current;\n prevLayout.current = layout;\n if (picked.w <= 0 || picked.h <= 0) return; // picked before the first measurement\n if (!fitted.current) {\n fitted.current = true;\n doFit(false);\n return;\n }\n const moved = !prev || prev.mode !== layout.mode || prev.width !== layout.width || prev.height !== layout.height;\n if (!moved) {\n if (!touched.current && !followRef.current) doFit(false);\n return;\n }\n const vp = viewportRef.current;\n if (vp) {\n vp.dataset.relayout = 'true';\n clearTimeout(relayoutTimer.current);\n relayoutTimer.current = setTimeout(() => {\n delete vp.dataset.relayout;\n }, 500);\n }\n stop(); // a running fly would aim at the old layout\n if (!touched.current && !followRef.current) doFit(true);\n }, [layout, picked.w, picked.h, doFit, stop]);\n\n useEffect(() => () => clearTimeout(relayoutTimer.current), []);\n\n useEffect(() => () => cancelAnimationFrame(raf.current), []);\n\n // --- zoom and pan helpers ----------------------------------------------------\n const zoomBy = useCallback(\n (factor: number, animate: boolean) => {\n markMoved();\n const base = target.current ?? view.current;\n const { w, h } = size.current;\n go(zoomAround(base, base.k * factor, w / 2, h / 2), animate);\n },\n [go, markMoved],\n );\n\n // --- wheel (needs a non-passive listener) ------------------------------------\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp) return;\n const onWheel = (e: WheelEvent) => {\n if ((e.target as Element | null)?.closest('[data-canvas-ui]')) return;\n e.preventDefault();\n stop();\n markMoved();\n const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? size.current.h : 1;\n const v = view.current;\n if (e.ctrlKey) {\n const r = vp.getBoundingClientRect();\n apply(zoomAround(v, v.k * Math.exp(-e.deltaY * unit * 0.0015), e.clientX - r.left, e.clientY - r.top));\n } else {\n apply({ ...v, x: v.x - e.deltaX * unit, y: v.y - e.deltaY * unit });\n }\n };\n vp.addEventListener('wheel', onWheel, { passive: false });\n return () => vp.removeEventListener('wheel', onWheel);\n }, [apply, stop, markMoved]);\n\n // --- pointers: drag, click vs drag, pinch ------------------------------------\n const pointers = useRef(new Map<number, { x: number; y: number }>());\n const gesture = useRef<{\n mode: 'none' | 'pending' | 'pan' | 'pinch';\n startX: number;\n startY: number;\n lastX: number;\n lastY: number;\n pinchDist: number;\n pinchMid: { x: number; y: number };\n pinchView: View;\n }>({\n mode: 'none',\n startX: 0,\n startY: 0,\n lastX: 0,\n lastY: 0,\n pinchDist: 1,\n pinchMid: { x: 0, y: 0 },\n pinchView: { x: 0, y: 0, k: 1 },\n });\n const dragged = useRef(false);\n const lastTap = useRef<{\n t: number;\n x: number;\n y: number;\n el: Element;\n } | null>(null);\n const lastDouble = useRef(0); // when a double-tap last fired, so the browser's own dblclick is ignored\n\n const local = (e: { clientX: number; clientY: number }) => {\n const r = viewportRef.current!.getBoundingClientRect();\n return { x: e.clientX - r.left, y: e.clientY - r.top };\n };\n\n /** A double-click or double-tap: on a group head zoom to the group, on empty canvas zoom in. */\n const doubleAt = (el: Element, p: { x: number; y: number }) => {\n if (el.closest('[data-canvas-ui]') || el.closest('.nish-canvas-slot')) return;\n const { w, h } = size.current;\n const head = el.closest('.nish-canvas-head');\n if (head) {\n const box = latest.current.layout.groups[(head as HTMLElement).dataset.canvasId ?? ''];\n if (!box) return;\n const k = Math.min(1.5, Math.max(MIN_K, Math.min((w - FIT_PAD * 2) / box.w, (h - FIT_PAD * 2) / box.h)));\n markMoved();\n go(centerOn(w, h, k, box), true);\n return;\n }\n markMoved();\n const base = target.current ?? view.current;\n go(zoomAround(base, base.k * 1.5, p.x, p.y), true);\n };\n\n const onDoubleClick = (e: ReactMouseEvent<HTMLDivElement>) => {\n if (performance.now() - lastDouble.current < 600) return;\n doubleAt(e.target as Element, local(e));\n };\n\n const startPinch = () => {\n const pts = [...pointers.current.values()];\n const [a, b] = pts as [{ x: number; y: number }, { x: number; y: number }];\n const g = gesture.current;\n g.mode = 'pinch';\n g.pinchDist = Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));\n g.pinchMid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n g.pinchView = { ...view.current };\n dragged.current = true;\n };\n\n const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (e.pointerType === 'mouse' && e.button !== 0) return;\n if ((e.target as Element).closest('[data-canvas-ui]')) return;\n stop();\n const p = local(e);\n pointers.current.set(e.pointerId, p);\n const vp = viewportRef.current!;\n const g = gesture.current;\n if (pointers.current.size === 1) {\n dragged.current = false;\n g.mode = 'pending';\n g.startX = g.lastX = p.x;\n g.startY = g.lastY = p.y;\n } else if (pointers.current.size === 2) {\n for (const id of pointers.current.keys()) {\n try {\n vp.setPointerCapture(id);\n } catch {\n // The pointer already ended.\n }\n }\n markMoved();\n startPinch();\n }\n };\n\n const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (!pointers.current.has(e.pointerId)) return;\n const p = local(e);\n pointers.current.set(e.pointerId, p);\n const g = gesture.current;\n if (g.mode === 'pinch' && pointers.current.size >= 2) {\n const [a, b] = [...pointers.current.values()] as [{ x: number; y: number }, { x: number; y: number }];\n const dist = Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));\n const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n const s = g.pinchView;\n const k = clampK(s.k * (dist / g.pinchDist));\n // The world point that was under the start midpoint follows the current midpoint.\n const wx = (g.pinchMid.x - s.x) / s.k;\n const wy = (g.pinchMid.y - s.y) / s.k;\n apply({ k, x: mid.x - wx * k, y: mid.y - wy * k });\n return;\n }\n if (g.mode === 'pending') {\n if (Math.hypot(p.x - g.startX, p.y - g.startY) < DRAG_PX) return;\n stop();\n g.mode = 'pan';\n dragged.current = true;\n markMoved();\n setHoverId(null);\n try {\n viewportRef.current!.setPointerCapture(e.pointerId);\n } catch {\n // The pointer already ended.\n }\n viewportRef.current!.dataset.dragging = 'true';\n }\n if (g.mode === 'pan') {\n const v = view.current;\n apply({ ...v, x: v.x + (p.x - g.lastX), y: v.y + (p.y - g.lastY) });\n g.lastX = p.x;\n g.lastY = p.y;\n }\n };\n\n const endPointer = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (!pointers.current.delete(e.pointerId)) return;\n const vp = viewportRef.current!;\n try {\n vp.releasePointerCapture(e.pointerId);\n } catch {\n // Not captured.\n }\n const g = gesture.current;\n if (pointers.current.size === 1 && g.mode === 'pinch') {\n // One finger stays down: carry on as a pan from where it is.\n const [rest] = [...pointers.current.values()] as [{ x: number; y: number }];\n g.mode = 'pan';\n g.lastX = rest.x;\n g.lastY = rest.y;\n } else if (pointers.current.size === 0) {\n if (g.mode === 'pending' && e.pointerType === 'touch' && e.type === 'pointerup') {\n // A touch tap that did not drag; two close together on the same thing are a double-tap.\n const p = local(e);\n const now = performance.now();\n const el = (e.target as Element).closest('[data-canvas-id]') ?? (e.target as Element);\n const lt = lastTap.current;\n if (lt && now - lt.t <= DOUBLE_MS && lt.el === el && Math.hypot(p.x - lt.x, p.y - lt.y) <= DOUBLE_PX) {\n lastTap.current = null;\n lastDouble.current = now;\n doubleAt(e.target as Element, p);\n } else {\n lastTap.current = { t: now, x: p.x, y: p.y, el };\n }\n }\n g.mode = 'none';\n delete vp.dataset.dragging;\n // The click that follows this pointerup is swallowed when the pointer dragged.\n setTimeout(() => {\n dragged.current = false;\n }, 0);\n }\n };\n\n const onClickCapture = (e: { stopPropagation: () => void; preventDefault: () => void }) => {\n if (dragged.current) {\n e.stopPropagation();\n e.preventDefault();\n }\n };\n\n // --- hover focus (mouse and pen only; touch uses selection) -------------------\n const onPointerOver = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (e.pointerType === 'touch' || gesture.current.mode === 'pan' || gesture.current.mode === 'pinch') return;\n if (typeof window.matchMedia === 'function' && !window.matchMedia('(hover: hover)').matches) return;\n const id = (e.target as Element).closest('[data-canvas-id]')?.getAttribute('data-canvas-id') ?? null;\n setHoverId((old) => (old === id ? old : id));\n };\n const onPointerLeave = () => setHoverId(null);\n\n // --- selecting something brings it into view ---------------------------------\n const prevSelected = useRef(selected);\n useEffect(() => {\n if (prevSelected.current === selected) return;\n prevSelected.current = selected;\n if (!selected || followRef.current) return;\n const lay = latest.current.layout;\n const box = lay.nodes[selected] ?? lay.groups[selected];\n const { w, h } = size.current;\n if (!box || w <= 0 || h <= 0) return;\n const v = target.current ?? view.current;\n const left = box.x * v.k + v.x;\n const top = box.y * v.k + v.y;\n const inside = left >= 0 && top >= 0 && left + box.w * v.k <= w && top + box.h * v.k <= h;\n if (inside && v.k >= LOD_K) return;\n const k = clampK(Math.max(v.k, 0.8));\n const next = centerOn(w, h, k, box);\n // On a phone the drawer covers the bottom: use the top 45%.\n if (w < PHONE_MAX_W) next.y = (h * 0.45) / 2 - (box.y + box.h / 2) * k;\n touched.current = true;\n go(next, true);\n }, [selected, go]);\n\n // --- keyboard ----------------------------------------------------------------\n // The viewport is never scrolled by the browser; focus pans the view instead.\n const onScroll = () => {\n const vp = viewportRef.current;\n if (vp && (vp.scrollLeft !== 0 || vp.scrollTop !== 0)) {\n vp.scrollLeft = 0;\n vp.scrollTop = 0;\n }\n };\n\n const onFocusCapture = (e: ReactFocusEvent<HTMLDivElement>) => {\n const vp = viewportRef.current;\n const el = e.target as HTMLElement;\n if (!vp || el === vp) return;\n if (pointers.current.size > 0 || !el.matches(':focus-visible')) return;\n const id = (el.closest('[data-canvas-id]') as HTMLElement | null)?.dataset.canvasId;\n if (!id) return;\n const box = latest.current.layout.nodes[id] ?? latest.current.layout.groups[id];\n if (!box) return;\n const v = view.current;\n const { w, h } = size.current;\n const left = box.x * v.k + v.x;\n const top = box.y * v.k + v.y;\n if (left >= 0 && top >= 0 && left + box.w * v.k <= w && top + box.h * v.k <= h) return;\n markMoved();\n go(centerOn(w, h, v.k, box), true);\n };\n\n const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {\n if (e.altKey || e.metaKey) return;\n if ((e.target as Element).closest('[data-canvas-ui]')) return;\n const v = view.current;\n switch (e.key) {\n case 'ArrowLeft':\n stop();\n markMoved();\n apply({ ...v, x: v.x + KEY_PAN });\n break;\n case 'ArrowRight':\n stop();\n markMoved();\n apply({ ...v, x: v.x - KEY_PAN });\n break;\n case 'ArrowUp':\n stop();\n markMoved();\n apply({ ...v, y: v.y + KEY_PAN });\n break;\n case 'ArrowDown':\n stop();\n markMoved();\n apply({ ...v, y: v.y - KEY_PAN });\n break;\n case '+':\n case '=':\n zoomBy(ZOOM_STEP, true);\n break;\n case '-':\n case '_':\n zoomBy(1 / ZOOM_STEP, true);\n break;\n case '0':\n touched.current = false;\n doFit(true);\n break;\n default:\n return;\n }\n e.preventDefault();\n };\n\n // --- content (re-rendered only when data changes, never on pan or zoom) ------\n const columnIndex = useMemo(() => {\n const order = [...new Set(groups.map((g) => g.column))].sort((a, b) => a - b);\n return new Map(order.map((c, i) => [c, i]));\n }, [sig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const lookup = useMemo(() => {\n const nodes = new Map<string, { group: CanvasGroup; node: CanvasNode }>();\n const grps = new Map<string, CanvasGroup>();\n for (const g of groups) {\n grps.set(g.id, g);\n for (const n of g.nodes) nodes.set(n.id, { group: g, node: n });\n }\n return { nodes, grps };\n }, [groups]);\n\n const headerViews = useMemo(\n () =>\n layout.headers.flatMap((h) => {\n const text = layout.mode === 'bands' ? (bands?.[h.index] ?? columns?.[h.index]) : columns?.[h.index];\n return text ? [{ key: `${layout.mode}:${h.index}`, x: h.x, y: h.y, text }] : [];\n }),\n [layout, bands, columns],\n );\n\n // Routing depends only on the layout and the visible edge ends, so a pan, a zoom or an\n // activity update never recomputes it.\n const routes = useMemo(() => routeEdges(layout, groups, visibleEdges), [layout, visSig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const { edgeViews, ports } = useMemo(() => {\n const hueOf = (id: string): { hue: CanvasHue | undefined; active: boolean } | undefined => {\n const n = lookup.nodes.get(id);\n if (n) return { hue: n.group.hue, active: !!n.node.active };\n const g = lookup.grps.get(id);\n if (g) return { hue: g.hue, active: g.nodes.some((x) => x.active) };\n return undefined;\n };\n const views = visibleEdges.flatMap((edge) => {\n const route = routes[edge.id];\n const to = hueOf(edge.to);\n if (!route || !to) return [];\n const line = edge.dashed ? 'dashed' : ((edge.kind ? lineOf.get(edge.kind) : undefined) ?? 'solid');\n return [\n {\n edge,\n route,\n line,\n mid: labelPoint(route.points),\n hue: to.hue,\n active: to.active,\n },\n ];\n });\n // Quiet edges first so an active edge that shares a trunk with one draws on top.\n views.sort((a, b) => Number(a.active) - Number(b.active));\n // Source ports only: the arrowheads mark where an edge ends.\n const dots = new Map<string, { x: number; y: number; hue: CanvasHue | undefined; active: boolean }>();\n for (const v of views) {\n const p = v.route.points[0]!;\n const key = `${p[0]}|${p[1]}`;\n const old = dots.get(key);\n if (!old || (v.active && !old.active)) dots.set(key, { x: p[0], y: p[1], hue: v.hue, active: v.active });\n }\n return { edgeViews: views, ports: [...dots.entries()] };\n }, [visibleEdges, routes, lookup, lineOf]);\n\n // Focus: the hovered thing, else the selected one. Its edges stay lit, the cards at their\n // other ends stay clear, everything else dims.\n const focus = useMemo(() => {\n const id = hoverId ?? selected;\n if (!id) return null;\n const node = lookup.nodes.get(id);\n const grp = node ? node.group : lookup.grps.get(id);\n if (!grp) return null;\n const mine = new Set<string>(node ? [id] : [id, ...grp.nodes.map((n) => n.id)]);\n const related = new Set<string>([id, grp.id]);\n if (!node) for (const n of grp.nodes) related.add(n.id);\n const addEnd = (eid: string) => {\n related.add(eid);\n const n = lookup.nodes.get(eid);\n if (n) related.add(n.group.id);\n const g = lookup.grps.get(eid);\n if (g) for (const x of g.nodes) related.add(x.id);\n };\n const hot = new Set<string>();\n for (const e of visibleEdges) {\n if (!mine.has(e.from) && !mine.has(e.to)) continue;\n hot.add(e.id);\n addEnd(e.from);\n addEnd(e.to);\n }\n return { related, hot };\n }, [hoverId, selected, lookup, visibleEdges]);\n\n // --- follow --------------------------------------------------------------------\n const fly = useCallback((v: View) => go(v, true, FOLLOW_MS), [go]);\n const { step } = useFollow({\n on: followOn,\n groups,\n layout,\n size: viewport,\n fit: fitView,\n inset: TOP_INSET,\n fly,\n });\n const canFollow = useMemo(() => groups.some((g) => g.nodes.some((n) => n.active !== undefined)), [groups]);\n\n const jumpTo = useCallback(\n (wx: number, wy: number) => {\n stop();\n markMoved();\n const { w, h } = size.current;\n const v = view.current;\n apply({ k: v.k, x: w / 2 - wx * v.k, y: h / 2 - wy * v.k });\n },\n [apply, stop, markMoved],\n );\n\n const layoutKey = `${layout.mode}:${layout.width}`;\n\n return (\n <div\n ref={viewportRef}\n role=\"application\"\n aria-label={label}\n aria-roledescription=\"canvas\"\n tabIndex={0}\n className={cn('nish-canvas', className)}\n style={{ height }}\n data-grid=\"both\"\n data-lod=\"near\"\n data-focus={focus ? 'true' : undefined}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endPointer}\n onPointerCancel={endPointer}\n onPointerOver={onPointerOver}\n onPointerLeave={onPointerLeave}\n onDoubleClick={onDoubleClick}\n onClickCapture={onClickCapture}\n onKeyDown={onKeyDown}\n onScroll={onScroll}\n onFocusCapture={onFocusCapture}\n >\n <div ref={worldRef} className=\"nish-canvas-world\" style={{ width: layout.width, height: layout.height }}>\n {headerViews.map((t) => (\n <div key={t.key} className=\"nish-canvas-coltitle\" style={layout.mode === 'bands' ? { left: t.x, top: t.y, lineHeight: 1, transform: 'translateY(-100%)' } : { left: t.x, top: t.y }}>\n {t.text}\n </div>\n ))}\n\n <svg key={`e${layoutKey}`} className=\"nish-canvas-edges\" width={layout.width} height={layout.height} aria-hidden=\"true\" focusable=\"false\">\n {edgeViews.map(({ edge, route, line, mid, hue, active }) => {\n const hot = focus?.hot.has(edge.id) ?? false;\n const end = route.points[route.points.length - 1]!;\n const [ex, ey] = end;\n const arrow = route.dir === 'down' ? `M${ex} ${ey}L${ex - 3.5} ${ey - 8}L${ex + 3.5} ${ey - 8}Z` : `M${ex} ${ey}L${ex - 8} ${ey - 3.5}L${ex - 8} ${ey + 3.5}Z`;\n return (\n <g key={edge.id} style={hueStyle(hue)} className=\"nish-canvas-edge\" data-active={active || undefined} data-line={line} data-hot={hot || undefined}>\n <path className=\"nish-canvas-edge-line\" d={route.d} fill=\"none\" />\n <path className=\"nish-canvas-arrow\" d={arrow} />\n {active ? <circle className=\"nish-canvas-dot\" r=\"3.5\" style={{ offsetPath: `path(\"${route.d}\")` }} /> : null}\n {edge.label && (labelsOn || hot) ? (\n <text className=\"nish-canvas-edge-label\" x={mid.x} y={mid.y - 6} textAnchor=\"middle\">\n {edge.label}\n </text>\n ) : null}\n </g>\n );\n })}\n </svg>\n\n <svg key={`p${layoutKey}`} className=\"nish-canvas-ports\" width={layout.width} height={layout.height} aria-hidden=\"true\" focusable=\"false\">\n {ports.map(([key, p]) => (\n <circle key={key} className=\"nish-canvas-port\" cx={p.x} cy={p.y} r={3} style={hueStyle(p.hue)} data-active={p.active || undefined} />\n ))}\n </svg>\n\n {groups.map((g) => {\n const box = layout.groups[g.id];\n if (!box) return null;\n const live = g.nodes.some((n) => n.active);\n const delay = (columnIndex.get(g.column) ?? 0) * 80;\n return (\n <Fragment key={g.id}>\n <div\n className=\"nish-canvas-group\"\n style={\n {\n ...hueStyle(g.hue),\n left: box.x,\n top: box.y,\n width: box.w,\n height: box.h,\n '--nish-canvas-delay': `${delay}ms`,\n } as CSSProperties\n }\n data-live={live || undefined}\n data-selected={selected === g.id || undefined}\n data-related={focus?.related.has(g.id) || undefined}\n >\n <span className=\"nish-canvas-band\" aria-hidden=\"true\" />\n <button type=\"button\" className=\"nish-canvas-head\" data-canvas-id={g.id} aria-pressed={selected === g.id} onClick={() => onSelect?.(g.id, 'group')}>\n <span className=\"nish-canvas-headtext\">\n <span className=\"nish-canvas-title\">{g.title}</span>\n {g.subtitle ? <span className=\"nish-canvas-subtitle\">{g.subtitle}</span> : null}\n </span>\n {g.badge ? <span className=\"nish-canvas-badge\">{g.badge}</span> : null}\n </button>\n </div>\n {g.nodes.map((n) => {\n const nb = layout.nodes[n.id];\n if (!nb) return null;\n return (\n <NodeView\n key={n.id}\n node={n}\n groupTitle={g.title}\n hue={g.hue}\n box={nb}\n selected={selected === n.id}\n dim={focus ? !focus.related.has(n.id) : false}\n delay={delay}\n onSelect={onSelect}\n />\n );\n })}\n </Fragment>\n );\n })}\n </div>\n\n <EdgeLegend kinds={kindList} hidden={hiddenKinds} onToggle={toggleKind} />\n {minimap ? <Minimap layout={layout} groups={groups} handleRef={miniRef} onJump={jumpTo} /> : null}\n <FollowCaption step={step} />\n\n <div data-canvas-ui className=\"nish-canvas-controls\">\n <span ref={zoomLabelRef} className=\"nish-canvas-zoom\" aria-hidden=\"true\">\n 100%\n </span>\n <IconButton label=\"Zoom out\" variant=\"ghost\" className=\"size-11\" onClick={() => zoomBy(1 / ZOOM_STEP, true)}>\n <MinusIcon />\n </IconButton>\n <IconButton label=\"Zoom in\" variant=\"ghost\" className=\"size-11\" onClick={() => zoomBy(ZOOM_STEP, true)}>\n <PlusIcon />\n </IconButton>\n <IconButton\n label=\"Fit to screen\"\n variant=\"ghost\"\n className=\"size-11\"\n onClick={() => {\n touched.current = false;\n doFit(true);\n }}\n >\n <FitIcon />\n </IconButton>\n {canFollow ? (\n <IconButton label=\"Follow activity\" variant=\"ghost\" className=\"size-11\" active={followOn} aria-pressed={followOn} onClick={() => setFollow(!followOn)}>\n <FollowIcon />\n </IconButton>\n ) : null}\n </div>\n </div>\n );\n}\n","import { clsx, type ClassValue } from 'clsx';\nimport { extendTailwindMerge } from 'tailwind-merge';\n\n// tailwind-merge has to know the th-* colors and the custom shadows are colors and\n// shadows, or it treats `text-th-hi text-sm` as a conflict and drops one. The same goes\n// for the extra type sizes: without `text: ['2xs', '3xs']` it may read text-2xs as a\n// color and drop text-th-hi next to it. scripts/build.mjs asserts both cases.\nconst twMerge = extendTailwindMerge({\n extend: {\n theme: {\n text: ['2xs', '3xs'],\n },\n classGroups: {\n shadow: [{ shadow: ['card', 'pop', 'modal'] }],\n },\n },\n});\n\n/** Conditional Tailwind classes with conflict resolution. */\nexport function cn(...inputs: ClassValue[]): string {\n return twMerge(clsx(inputs));\n}\n","import {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactElement,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport { cn } from '../cn';\nimport { ago } from '../format';\nimport { useMediaQuery, useNow } from './hooks';\nimport { Tooltip } from './overlay';\nimport { Badge, type BadgeHue } from './primitives';\n\n// Animated components for live views of multi-step work: FlowSteps, StepBar, AgentNode,\n// WorkflowBoard, ActivityFeed, TickerText and AnimatedList.\n//\n// Motion lives in CSS (src/css/base.css, `nish-flow-*`), inside\n// `prefers-reduced-motion: no-preference`, so under reduced motion every state change is\n// instant and nothing loops. Animations run on a state change, never on a re-render with\n// the same data: a component remembers what it showed last and only plays what changed.\n\nconst EASE = 'cubic-bezier(0.22, 1, 0.36, 1)';\n\n/** True while the viewer asks for reduced motion. False on the server and before hydration. */\nexport function usePrefersReducedMotion(): boolean {\n return useMediaQuery('(prefers-reduced-motion: reduce)');\n}\n\nconst warned = new Set<string>();\n\n/** Dev-only console warning, once per message. Bundlers replace `process.env.NODE_ENV`;\n * where nothing does, the ReferenceError is caught and nothing is printed. */\nfunction warnDev(message: string): void {\n if (warned.has(message)) return;\n try {\n if (process.env.NODE_ENV !== 'production') {\n warned.add(message);\n console.warn(message);\n }\n } catch {\n // No process or no console.\n }\n}\n\n/** Plays a one-shot effect on an element when `value` changes (never on mount): sets\n * data-fx to the name `pick` returns, restarts the CSS animation if one was running,\n * and clears it again. The attribute is set on the DOM directly, so a re-render with the\n * same data cannot cut the animation short. */\nfunction useTransitionFx<S extends string>(\n value: S,\n ref: RefObject<HTMLElement | null>,\n pick: (from: S, to: S) => string | null,\n): void {\n const prev = useRef(value);\n useLayoutEffect(() => {\n const from = prev.current;\n prev.current = value;\n if (from === value) return;\n const el = ref.current;\n if (!el) return;\n el.removeAttribute('data-fx');\n const fx = pick(from, value);\n if (!fx) return;\n void el.offsetWidth;\n el.setAttribute('data-fx', fx);\n const timer = setTimeout(() => el.removeAttribute('data-fx'), 700);\n return () => {\n clearTimeout(timer);\n el.removeAttribute('data-fx');\n };\n }, [value, ref, pick]);\n}\n\n/** Ids that appeared after the first render. They stay flagged while they are in `ids`, so\n * an item's enter animation is not cut off by the next render. With `skipFirst` the ids\n * of the first render are never fresh. */\nfunction useFreshIds(ids: string[], skipFirst: boolean): Set<string> {\n const key = ids.join('\\n');\n const [seen, setSeen] = useState(() => ({\n key,\n known: new Set(ids),\n fresh: new Set(skipFirst ? [] : ids),\n }));\n if (seen.key === key) return seen.fresh;\n // The ids changed: derive the next sets during render (React's \"adjust state on a prop\n // change\" pattern), so a new item is flagged on the very render that adds it.\n const fresh = new Set([...seen.fresh].filter((id) => ids.includes(id)));\n for (const id of ids) if (!seen.known.has(id)) fresh.add(id);\n setSeen({ key, known: new Set(ids), fresh });\n return fresh;\n}\n\nfunction CheckSvg({ size, className }: { size: number; className?: string }) {\n return (\n <svg\n className={cn('nish-flow-check', className)}\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={3}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path d=\"M5 12.5l4.5 4.5L19 7.5\" pathLength={1} />\n </svg>\n );\n}\n\nfunction CrossSvg({ size }: { size: number }) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={3}\n strokeLinecap=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path d=\"M6.5 6.5l11 11M17.5 6.5l-11 11\" />\n </svg>\n );\n}\n\n// =====================================================================================\n// FlowSteps\n// =====================================================================================\n\nexport type FlowStepStatus = 'pending' | 'active' | 'done' | 'failed';\n\nexport interface FlowStepItem {\n id: string;\n label: ReactNode;\n status: FlowStepStatus;\n meta?: ReactNode;\n}\n\nexport interface FlowStepsProps {\n steps: FlowStepItem[];\n /** auto: horizontal when the container is at least 640px wide and there are at most 8 steps; else vertical. */\n orientation?: 'auto' | 'vertical' | 'horizontal';\n /** aria-label of the list. Default \"Progress\". */\n label?: string;\n className?: string;\n}\n\nconst NODE_STATUS: Record<FlowStepStatus, string> = {\n pending: 'border-2 border-th-line text-th-hi3',\n active: 'border-2 border-th-accent text-th-hi',\n done: 'bg-th-ok-fill text-th-on-ok',\n failed: 'bg-th-loss-fill text-th-on-loss',\n};\n\nconst STEP_SR: Partial<Record<FlowStepStatus, string>> = { done: ', done', failed: ', failed' };\n\nfunction pickStepFx(from: FlowStepStatus, to: FlowStepStatus): string | null {\n if (to === 'done') return 'done';\n if (to === 'failed') return 'failed';\n return from === to ? null : null;\n}\n\n/** Horizontal labels clamp to two lines; a text label gets its full text as a tooltip\n * (hover on desktop, tap on a phone, focus from the keyboard). */\nfunction withFullText(text: ReactNode, label: ReactElement) {\n if (typeof text !== 'string') return label;\n return (\n <Tooltip tip={text} className=\"nish-flow-label-tip max-w-full min-w-0\">\n {label}\n </Tooltip>\n );\n}\n\nfunction StepRow({\n step,\n index,\n last,\n sweeping,\n}: {\n step: FlowStepItem;\n index: number;\n last: boolean;\n sweeping: boolean;\n}) {\n const nodeRef = useRef<HTMLSpanElement>(null);\n useTransitionFx(step.status, nodeRef, pickStepFx);\n const { status } = step;\n return (\n <li\n className=\"nish-flow-step nish-flow-rise\"\n data-status={status}\n aria-current={status === 'active' ? 'step' : undefined}\n style={{ '--nish-flow-delay': `${Math.min(index * 40, 400)}ms` } as CSSProperties}\n >\n <span\n ref={nodeRef}\n className={cn(\n 'nish-flow-node grid size-7 place-items-center rounded-full text-xs font-medium tabular-nums',\n NODE_STATUS[status],\n )}\n aria-hidden=\"true\"\n >\n {status === 'done' ? (\n <CheckSvg size={16} />\n ) : status === 'failed' ? (\n <CrossSvg size={14} />\n ) : (\n index + 1\n )}\n {status === 'active' ? (\n <>\n <svg className=\"nish-flow-arc text-th-accent\" viewBox=\"0 0 28 28\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"14\" cy=\"14\" r=\"13\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeDasharray=\"20 62\" />\n </svg>\n <span className=\"nish-flow-ripple\" />\n </>\n ) : null}\n </span>\n <span className=\"nish-flow-text\">\n {withFullText(\n step.label,\n <span\n className={cn(\n 'nish-flow-label text-sm',\n status === 'active' ? 'font-medium text-th-hi' : status === 'failed' ? 'text-th-loss' : 'text-th-hi2',\n )}\n >\n {step.label}\n {STEP_SR[status] ? <span className=\"sr-only\">{STEP_SR[status]}</span> : null}\n </span>,\n )}\n {step.meta != null ? <span className=\"nish-flow-meta text-xs text-th-hi3\">{step.meta}</span> : null}\n </span>\n {last ? null : (\n <span\n className=\"nish-flow-conn\"\n data-on={status === 'done'}\n aria-hidden=\"true\"\n style={sweeping ? ({ '--nish-flow-delay': `${index * 60}ms` } as CSSProperties) : undefined}\n >\n <span className=\"nish-flow-fill\" />\n <span className=\"nish-flow-shimmer\" />\n <span className=\"nish-flow-sweep\" />\n </span>\n )}\n </li>\n );\n}\n\n/** A plan as a flow of steps: numbered nodes joined by connectors that fill as steps\n * finish. The active step ripples, a finishing step draws its check, a failing one\n * shakes, and when the last step finishes a sweep runs along the connectors. Vertical on\n * narrow containers, horizontal from 640px (up to 8 steps). */\nexport function FlowSteps({ steps, orientation = 'auto', label = 'Progress', className }: FlowStepsProps) {\n const allDone = steps.length > 0 && steps.every((s) => s.status === 'done');\n const prevAll = useRef<boolean | null>(null);\n const [sweeping, setSweeping] = useState(false);\n useLayoutEffect(() => {\n const was = prevAll.current;\n prevAll.current = allDone;\n if (!allDone) {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- state is synced from a prop/DOM measurement inside the effect (React 19 rule flagged at adoption)\n setSweeping(false);\n return;\n }\n if (was === false && steps.length > 1) {\n setSweeping(true);\n const timer = setTimeout(() => setSweeping(false), steps.length * 60 + 1000);\n return () => clearTimeout(timer);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [allDone]);\n\n const orient = orientation === 'auto' && steps.length > 8 ? 'vertical' : orientation;\n return (\n <div className={cn('nish-flow-steps-box', className)}>\n <ol className=\"nish-flow-steps\" data-orient={orient} data-sweep={sweeping || undefined} aria-label={label}>\n {steps.map((step, i) => (\n <StepRow key={step.id} step={step} index={i} last={i === steps.length - 1} sweeping={sweeping} />\n ))}\n </ol>\n </div>\n );\n}\n\n// =====================================================================================\n// StepBar\n// =====================================================================================\n\nexport interface StepBarProps {\n total: number;\n done: number;\n /** pulses the current segment */\n active?: boolean;\n label?: string;\n className?: string;\n}\n\n/** A compact progress bar of segments, one per step (a continuous bar above 12). Done\n * segments fill in, the current one pulses while `active`. */\nexport function StepBar({ total, done, active = false, label, className }: StepBarProps) {\n const t = Number.isFinite(total) ? Math.max(0, Math.floor(total)) : 0;\n const d = Number.isFinite(done) ? Math.min(t, Math.max(0, Math.floor(done))) : 0;\n const props = {\n role: 'progressbar' as const,\n 'aria-valuemin': 0,\n 'aria-valuemax': t,\n 'aria-valuenow': d,\n 'aria-label': label ?? 'Progress',\n };\n if (t > 12) {\n return (\n <div {...props} className={cn('relative h-1.5 overflow-hidden rounded-full bg-th-line', className)}>\n <div\n className=\"h-full rounded-full bg-th-ok-fill motion-safe:transition-[width] motion-safe:duration-[400ms]\"\n style={{ width: `${(d / t) * 100}%` }}\n />\n {active && d < t ? (\n <div\n className=\"absolute inset-y-0 rounded-full bg-th-accent motion-safe:animate-pulse\"\n style={{ left: `${(d / t) * 100}%`, width: `max(6px, ${100 / t}%)` }}\n />\n ) : null}\n </div>\n );\n }\n return (\n <div {...props} className={cn('flex h-1.5 gap-[3px]', className)}>\n {Array.from({ length: t }, (_, i) => (\n <div key={i} className=\"relative h-full min-w-0 flex-1 overflow-hidden rounded-full bg-th-line\">\n <div\n className={cn(\n 'absolute inset-0 origin-left rounded-full bg-th-ok-fill motion-safe:transition-transform motion-safe:duration-[400ms]',\n i < d ? 'scale-x-100' : 'scale-x-0',\n )}\n />\n {i === d ? (\n <div className={cn('absolute inset-0 rounded-full bg-th-accent', active ? 'motion-safe:animate-pulse' : 'opacity-0')} />\n ) : null}\n </div>\n ))}\n </div>\n );\n}\n\n// =====================================================================================\n// TickerText\n// =====================================================================================\n\nexport interface TickerTextProps {\n text: string;\n as?: 'span' | 'p' | 'div';\n className?: string;\n}\n\n/** One line of text that swaps with a short slide when it changes: the old text rises and\n * fades out while the new text comes up from below. Long text ends in an ellipsis. */\nexport function TickerText({ text, as = 'span', className }: TickerTextProps) {\n const reduced = usePrefersReducedMotion();\n const [state, setState] = useState<{ text: string; prev: string | null }>({ text, prev: null });\n let cur = state;\n if (state.text !== text) {\n cur = { text, prev: reduced ? null : state.text };\n setState(cur);\n }\n const animating = cur.prev !== null;\n useEffect(() => {\n if (!animating) return;\n const timer = setTimeout(() => setState((s) => (s.prev === null ? s : { ...s, prev: null })), 300);\n return () => clearTimeout(timer);\n }, [animating, cur.text]);\n\n const Tag = as;\n return (\n <Tag className={cn('nish-flow-ticker grid min-w-0 overflow-hidden', className)} title={cur.text}>\n {cur.prev !== null ? (\n <span key={`prev:${cur.prev}`} className=\"nish-flow-ticker-out\" aria-hidden=\"true\">\n {cur.prev}\n </span>\n ) : null}\n <span key={cur.text} className={animating ? 'nish-flow-ticker-in' : undefined}>\n {cur.text}\n </span>\n </Tag>\n );\n}\n\n// =====================================================================================\n// AgentNode\n// =====================================================================================\n\nexport type AgentNodeState = 'queued' | 'running' | 'done' | 'failed';\n\nexport interface AgentNodeProps {\n label: string;\n state: AgentNodeState;\n /** Short model name; opus, sonnet, haiku and fable get their own badge hue. */\n model?: string | null;\n activity?: string;\n /** Right-aligned small text, e.g. elapsed time. */\n meta?: ReactNode;\n onClick?: () => void;\n className?: string;\n}\n\nconst STATE_WORD: Record<AgentNodeState, string> = {\n queued: 'Queued',\n running: 'Running',\n done: 'Done',\n failed: 'Failed',\n};\n\nconst AGENT_STATE: Record<AgentNodeState, string> = {\n queued: 'border-dashed border-th-line opacity-70',\n running: 'border-th-accent',\n done: 'border-th-ok-fill/40',\n failed: 'border-th-loss-fill',\n};\n\nconst MODEL_HUE: [string, BadgeHue][] = [\n ['opus', 'violet'],\n ['sonnet', 'sky'],\n ['haiku', 'emerald'],\n ['fable', 'amber'],\n];\n\nfunction modelFamily(model: string): [string, BadgeHue] | undefined {\n const m = model.toLowerCase();\n return MODEL_HUE.find(([name]) => m.includes(name));\n}\n\nfunction ModelBadge({ model }: { model: string }) {\n const family = modelFamily(model);\n return (\n <Badge size=\"xs\" hue={family?.[1]} className=\"shrink-0\">\n {family ? family[0] : model}\n </Badge>\n );\n}\n\nfunction pickAgentFx(from: AgentNodeState, to: AgentNodeState): string | null {\n if (from === to) return null;\n if (to === 'done') return 'done';\n if (to === 'failed') return 'failed';\n return null;\n}\n\nfunction AgentIcon({ state }: { state: AgentNodeState }) {\n if (state === 'running') {\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center text-th-accent\">\n <svg className=\"nish-flow-agent-spin\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"6\" stroke=\"currentColor\" strokeOpacity=\"0.25\" strokeWidth=\"2\" />\n <path d=\"M8 2a6 6 0 0 1 6 6\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </span>\n );\n }\n if (state === 'done') {\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center rounded-full bg-th-ok-fill text-th-on-ok\">\n <CheckSvg size={12} />\n </span>\n );\n }\n if (state === 'failed') {\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center rounded-full bg-th-loss-fill text-th-on-loss\">\n <CrossSvg size={11} />\n </span>\n );\n }\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center\">\n <span className=\"size-4 rounded-full border-2 border-dashed border-th-ghost\" />\n </span>\n );\n}\n\n/** One agent or task as a card: state icon, label, model badge, a live activity line.\n * A running agent has a comet of accent circling its border; finishing pops the check;\n * failing shakes once. Pass `onClick` to make the card a button. */\nexport function AgentNode({ label, state, model, activity, meta, onClick, className }: AgentNodeProps) {\n const ref = useRef<HTMLElement>(null);\n useTransitionFx(state, ref, pickAgentFx);\n const aria = `${label}: ${STATE_WORD[state]}`;\n const classes = cn(\n 'nish-flow-agent block min-h-16 w-full min-w-0 rounded-xl border bg-th-surface p-3 text-left',\n AGENT_STATE[state],\n onClick &&\n 'cursor-pointer transition-colors hover:bg-th-elevated focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-th-accent',\n className,\n );\n const body = (\n <>\n <span className=\"flex min-w-0 items-start gap-2\">\n <AgentIcon state={state} />\n <span className=\"line-clamp-2 min-w-0 flex-1 text-sm font-medium leading-5 text-th-hi [overflow-wrap:anywhere]\">{label}</span>\n {meta != null ? <span className=\"shrink-0 text-xs leading-5 tabular-nums text-th-hi3\">{meta}</span> : null}\n </span>\n {model || activity ? (\n <span className=\"mt-1.5 flex min-w-0 items-center gap-2\">\n {model ? <ModelBadge model={model} /> : null}\n {activity ? <TickerText as=\"span\" text={activity} className=\"min-w-0 flex-1 text-xs text-th-hi3\" /> : null}\n </span>\n ) : null}\n </>\n );\n if (onClick) {\n return (\n <button type=\"button\" ref={ref as RefObject<HTMLButtonElement | null>} className={classes} data-state={state} aria-label={aria} onClick={onClick}>\n {body}\n </button>\n );\n }\n return (\n <article ref={ref} className={classes} data-state={state} aria-label={aria}>\n {body}\n </article>\n );\n}\n\n// =====================================================================================\n// WorkflowBoard\n// =====================================================================================\n\nexport interface WorkflowBoardPhase {\n id: string;\n title: string;\n detail?: ReactNode;\n model?: string | null;\n}\n\nexport interface WorkflowBoardAgent extends Omit<AgentNodeProps, 'className' | 'onClick'> {\n id: string;\n /** phase id or title */\n phase: string | null;\n}\n\nexport interface WorkflowBoardProps {\n phases: WorkflowBoardPhase[];\n agents: WorkflowBoardAgent[];\n /** aria-label. Default \"Workflow\". */\n label?: string;\n className?: string;\n}\n\ntype PhaseState = 'waiting' | 'pending' | 'active' | 'done';\n\nconst OTHER_ID = '__nish-flow-other__';\n\nfunction phaseState(agents: WorkflowBoardAgent[]): PhaseState {\n if (agents.length === 0) return 'waiting';\n if (agents.some((a) => a.state === 'running')) return 'active';\n if (agents.every((a) => a.state === 'done' || a.state === 'failed')) return 'done';\n return 'pending';\n}\n\nfunction PhaseConnector({ flowing }: { flowing: boolean }) {\n return (\n <svg className=\"nish-flow-phase-conn\" data-flow={flowing} viewBox=\"0 0 24 12\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <path className=\"nish-flow-dashline\" d=\"M1 6h15\" strokeDasharray=\"3 3\" />\n <path d=\"M16 2.5L20.5 6 16 9.5\" />\n </svg>\n );\n}\n\n/** A workflow as columns of phases (stacked on narrow containers), each phase holding its\n * agents as AgentNodes. A phase waits, glows while an agent runs and gets a check when\n * all its agents finish; new agents rise in, staggered. */\nexport function WorkflowBoard({ phases, agents, label = 'Workflow', className }: WorkflowBoardProps) {\n const fresh = useFreshIds(\n agents.map((a) => a.id),\n false,\n );\n const columns = useMemo(() => {\n const byId = new Map<string, WorkflowBoardPhase>();\n const byTitle = new Map<string, WorkflowBoardPhase>();\n for (const p of phases) {\n if (!byId.has(p.id)) byId.set(p.id, p);\n if (!byTitle.has(p.title)) byTitle.set(p.title, p);\n }\n const groups = new Map<string, WorkflowBoardAgent[]>();\n const other: WorkflowBoardAgent[] = [];\n for (const a of agents) {\n const phase = a.phase === null ? undefined : (byId.get(a.phase) ?? byTitle.get(a.phase));\n if (!phase) {\n other.push(a);\n continue;\n }\n const list = groups.get(phase.id);\n if (list) list.push(a);\n else groups.set(phase.id, [a]);\n }\n const cols: { phase: WorkflowBoardPhase; agents: WorkflowBoardAgent[]; state: PhaseState }[] = phases.map((phase) => {\n const list = groups.get(phase.id) ?? [];\n return { phase, agents: list, state: phaseState(list) };\n });\n // Duplicate phase ids share one group; the later column shows the same agents once.\n const seen = new Set<string>();\n for (const c of cols) {\n if (seen.has(c.phase.id)) {\n c.agents = [];\n c.state = 'waiting';\n }\n seen.add(c.phase.id);\n }\n if (other.length) cols.push({ phase: { id: OTHER_ID, title: 'Other' }, agents: other, state: phaseState(other) });\n return cols;\n }, [phases, agents]);\n\n return (\n <section aria-label={label} className={cn('nish-flow-board-box', className)}>\n <div className=\"nish-flow-board\">\n {columns.map((col, ci) => {\n const { phase, state } = col;\n const finished = col.agents.filter((a) => a.state === 'done' || a.state === 'failed').length;\n const total = col.agents.length;\n const next = columns[ci + 1];\n const flowing =\n (state === 'done' || state === 'active') &&\n next !== undefined &&\n (next.state === 'waiting' || next.state === 'pending' || next.state === 'active');\n return (\n <div\n key={phase.id}\n role=\"group\"\n aria-label={phase.title}\n data-state={state}\n className={cn(\n 'nish-flow-phase rounded-xl border bg-th-elevated/40 p-3',\n state === 'active' ? 'border-th-accent/50' : 'border-th-line',\n )}\n >\n <div className={cn('flex min-w-0 items-center gap-2', state === 'waiting' && 'opacity-60')}>\n {state === 'done' ? (\n <span className=\"grid size-4 shrink-0 place-items-center rounded-full bg-th-ok-fill text-th-on-ok\">\n <CheckSvg size={10} />\n </span>\n ) : null}\n <span className={cn('min-w-0 flex-1 truncate text-sm font-medium', state === 'active' ? 'text-th-accent' : 'text-th-hi')}>\n {phase.title}\n </span>\n {phase.model ? <ModelBadge model={phase.model} /> : null}\n <span className=\"shrink-0 text-xs tabular-nums text-th-hi3\">\n {finished}/{total}\n </span>\n </div>\n <div\n className={cn('mt-2 h-1 overflow-hidden rounded-full bg-th-line', state === 'waiting' && 'opacity-60')}\n aria-hidden=\"true\"\n >\n <div\n className=\"h-full rounded-full bg-th-ok-fill motion-safe:transition-[width] motion-safe:duration-500\"\n style={{ width: total ? `${(finished / total) * 100}%` : '0%' }}\n />\n </div>\n {phase.detail != null ? <div className=\"mt-2 text-xs text-th-hi3\">{phase.detail}</div> : null}\n <div className=\"mt-3 flex min-w-0 flex-col gap-2\">\n {total === 0 ? (\n <p className=\"text-xs text-th-hi3\">Waiting</p>\n ) : (\n col.agents.map((a, ai) => {\n const { id, phase: _phase, ...node } = a;\n return (\n <div\n key={id}\n className={fresh.has(id) ? 'nish-flow-rise' : undefined}\n style={fresh.has(id) ? ({ '--nish-flow-delay': `${Math.min(ai * 60, 600)}ms` } as CSSProperties) : undefined}\n >\n <AgentNode {...node} />\n </div>\n );\n })\n )}\n </div>\n {next ? <PhaseConnector flowing={flowing} /> : null}\n </div>\n );\n })}\n </div>\n </section>\n );\n}\n\n// =====================================================================================\n// ActivityFeed\n// =====================================================================================\n\nexport interface ActivityItem {\n id: string;\n at: number;\n text: ReactNode;\n tone?: 'neutral' | 'accent' | 'ok' | 'warn' | 'loss';\n source?: ReactNode;\n}\n\nexport interface ActivityFeedProps {\n items: ActivityItem[];\n /** default 50 */\n max?: number;\n now?: number;\n /** default \"Activity\" */\n label?: string;\n empty?: ReactNode;\n className?: string;\n}\n\nconst FEED_DOT: Record<NonNullable<ActivityItem['tone']>, string> = {\n neutral: 'bg-th-ghost',\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n};\n\n/** A timeline of short updates, newest first. A new update opens its row, fades in and\n * flashes the accent tint. Items present on the first render do not animate. */\nexport function ActivityFeed({ items, max = 50, now, label = 'Activity', empty, className }: ActivityFeedProps) {\n const internalNow = useNow(15000);\n const clock = now ?? internalNow;\n const shown = useMemo(() => [...items].sort((a, b) => b.at - a.at).slice(0, Math.max(0, max)), [items, max]);\n const fresh = useFreshIds(\n shown.map((i) => i.id),\n true,\n );\n if (shown.length === 0) {\n return <div className={cn('text-sm text-th-hi3', className)}>{empty ?? 'No activity yet'}</div>;\n }\n return (\n <ol className={cn('nish-flow-feed', className)} aria-label={label}>\n {shown.map((item) => (\n <li key={item.id} className=\"nish-flow-feed-item\" data-fresh={fresh.has(item.id) || undefined} data-tone={item.tone ?? 'neutral'}>\n <div className=\"nish-flow-feed-inner\">\n <div className=\"nish-flow-feed-row\">\n <span className={cn('nish-flow-feed-dot', FEED_DOT[item.tone ?? 'neutral'])} aria-hidden=\"true\" />\n <div className=\"min-w-0\">\n <div className=\"break-words text-sm text-th-hi2\">{item.text}</div>\n {item.source != null ? <div className=\"break-words text-xs text-th-hi3\">{item.source}</div> : null}\n </div>\n <span className=\"pt-0.5 text-right text-xs tabular-nums text-th-hi3\">{ago(item.at, { now: clock, style: 'short' })}</span>\n </div>\n </div>\n </li>\n ))}\n </ol>\n );\n}\n\n// =====================================================================================\n// AnimatedList\n// =====================================================================================\n\nexport interface AnimatedListProps<T> {\n items: T[];\n getKey: (item: T) => string;\n children: (item: T, phase: 'enter' | 'idle' | 'exit') => ReactNode;\n /** How long a removed item stays to animate out. Default 420. */\n exitMs?: number;\n as?: 'ul' | 'ol' | 'div';\n className?: string;\n itemClassName?: string;\n}\n\ntype ListPhase = 'enter' | 'idle' | 'exit';\ninterface ListEntry<T> {\n key: string;\n item: T;\n phase: ListPhase;\n}\ninterface ListState<T> {\n src: T[];\n reduced: boolean;\n entries: ListEntry<T>[];\n}\n\nconst ENTER_MS = 400;\nconst MOVE_MS = 300;\n\n/** The entries to render for `items`: new keys enter, removed keys stay at their last\n * index as \"exit\" (when animating), a key that comes back during its exit stops exiting.\n * When a key repeats, the first item wins. */\nfunction reconcile<T>(prev: ListEntry<T>[], items: T[], getKey: (item: T) => string, animate: boolean): ListEntry<T>[] {\n const prevMap = new Map(prev.map((e) => [e.key, e]));\n const seen = new Set<string>();\n const next: ListEntry<T>[] = [];\n for (const item of items) {\n const key = getKey(item);\n if (seen.has(key)) {\n warnDev(`AnimatedList: duplicate key \"${key}\"; only the first item with it is shown.`);\n continue;\n }\n seen.add(key);\n const old = prevMap.get(key);\n const phase: ListPhase = !old ? (animate ? 'enter' : 'idle') : old.phase === 'exit' ? 'idle' : old.phase;\n next.push({ key, item, phase: animate ? phase : 'idle' });\n }\n if (animate) {\n // Each exiting entry goes right after the key that preceded it in `prev`.\n prev.forEach((e, i) => {\n if (seen.has(e.key)) return;\n let at = 0;\n if (i > 0) {\n const before = prev[i - 1]!.key;\n const idx = next.findIndex((x) => x.key === before);\n at = idx === -1 ? Math.min(i, next.length) : idx + 1;\n }\n next.splice(at, 0, e.phase === 'exit' ? e : { ...e, phase: 'exit' });\n });\n }\n return next;\n}\n\n/** A list whose items animate: new ones rise in, removed ones fade and close the gap\n * before they are dropped, and the rest slide to their new place (FLIP). The render\n * function gets each item's phase. Under reduced motion changes are instant. */\nexport function AnimatedList<T>({\n items,\n getKey,\n children,\n exitMs = 420,\n as = 'ul',\n className,\n itemClassName,\n}: AnimatedListProps<T>) {\n const reduced = usePrefersReducedMotion();\n const [state, setState] = useState<ListState<T>>(() => ({\n src: items,\n reduced,\n entries: reconcile([], items, getKey, false),\n }));\n let current = state;\n if (state.src !== items || state.reduced !== reduced) {\n current = { src: items, reduced, entries: reconcile(state.entries, items, getKey, !reduced) };\n setState(current);\n }\n const entries = current.entries;\n\n const els = useRef(new Map<string, HTMLElement>());\n const rects = useRef(new Map<string, { x: number; y: number }>());\n const anims = useRef(new Map<string, Animation>());\n const lastKeys = useRef<string | null>(null);\n const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());\n\n // Enter and exit timers: one per entry in that phase.\n useEffect(() => {\n const wanted = new Set<string>();\n for (const e of entries) {\n if (e.phase === 'idle') continue;\n const id = `${e.phase}:${e.key}`;\n wanted.add(id);\n if (timers.current.has(id)) continue;\n timers.current.set(\n id,\n setTimeout(\n () => {\n timers.current.delete(id);\n if (e.phase === 'exit') {\n // Fresh positions for the slide that follows the removal.\n const fresh = new Map<string, { x: number; y: number }>();\n els.current.forEach((el, k) => fresh.set(k, { x: el.offsetLeft, y: el.offsetTop }));\n rects.current = fresh;\n }\n setState((s) => ({\n ...s,\n entries:\n e.phase === 'exit'\n ? s.entries.filter((x) => !(x.key === e.key && x.phase === 'exit'))\n : s.entries.map((x) => (x.key === e.key && x.phase === 'enter' ? { ...x, phase: 'idle' as const } : x)),\n }));\n },\n e.phase === 'exit' ? exitMs : ENTER_MS,\n ),\n );\n }\n timers.current.forEach((timer, id) => {\n if (!wanted.has(id)) {\n clearTimeout(timer);\n timers.current.delete(id);\n }\n });\n }, [entries, exitMs]);\n useEffect(\n () => () => {\n timers.current.forEach((timer) => clearTimeout(timer));\n timers.current.clear();\n },\n [],\n );\n\n // FLIP: items that stayed move from their old place to the new one.\n useLayoutEffect(() => {\n const next = new Map<string, { x: number; y: number }>();\n els.current.forEach((el, k) => next.set(k, { x: el.offsetLeft, y: el.offsetTop }));\n const keyList = entries.map((e) => e.key).join('\\n');\n const reordered = lastKeys.current !== null && lastKeys.current !== keyList;\n lastKeys.current = keyList;\n const live = new Set(entries.map((e) => e.key));\n anims.current.forEach((anim, k) => {\n if (!live.has(k)) {\n anim.cancel();\n anims.current.delete(k);\n }\n });\n // Focus inside an exiting item moves to a staying neighbour.\n const active = typeof document !== 'undefined' ? document.activeElement : null;\n if (active) {\n const ei = entries.findIndex((e) => e.phase === 'exit' && els.current.get(e.key)?.contains(active));\n if (ei !== -1) {\n const target = [...entries.slice(ei + 1), ...entries.slice(0, ei).reverse()].find((e) => e.phase !== 'exit');\n const focusable = target\n ? els.current.get(target.key)?.querySelector<HTMLElement>('a[href], button, input, select, textarea, [tabindex]:not([tabindex=\"-1\"])')\n : null;\n if (focusable) focusable.focus({ preventScroll: true });\n }\n }\n if (!reduced && reordered) {\n for (const e of entries) {\n if (e.phase === 'exit') continue;\n const a = rects.current.get(e.key);\n const b = next.get(e.key);\n const el = els.current.get(e.key);\n if (!a || !b || !el || typeof el.animate !== 'function') continue;\n let dx = a.x - b.x;\n let dy = a.y - b.y;\n const running = anims.current.get(e.key);\n if (running) {\n // Start from where the item is drawn now, not from its layout position.\n const r1 = el.getBoundingClientRect();\n running.cancel();\n anims.current.delete(e.key);\n const r2 = el.getBoundingClientRect();\n dx += r1.left - r2.left;\n dy += r1.top - r2.top;\n }\n if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;\n const anim = el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {\n duration: MOVE_MS,\n easing: EASE,\n });\n anims.current.set(e.key, anim);\n anim.onfinish = () => {\n if (anims.current.get(e.key) === anim) anims.current.delete(e.key);\n };\n }\n }\n rects.current = next;\n }, [entries, reduced]);\n\n const Root = as;\n const Item = as === 'div' ? 'div' : 'li';\n return (\n <Root className={className}>\n {entries.map((e) => (\n <Item\n key={e.key}\n ref={(el: HTMLElement | null) => {\n if (!el) return;\n els.current.set(e.key, el);\n return () => {\n if (els.current.get(e.key) === el) els.current.delete(e.key);\n };\n }}\n className={cn('nish-flow-item', itemClassName)}\n data-phase={e.phase}\n aria-hidden={e.phase === 'exit' || undefined}\n inert={e.phase === 'exit' || undefined}\n style={e.phase === 'exit' ? ({ '--nish-flow-exit-ms': `${exitMs}ms` } as CSSProperties) : undefined}\n >\n <div className=\"nish-flow-item-inner\">{children(e.item, e.phase)}</div>\n </Item>\n ))}\n </Root>\n );\n}\n","import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { cn } from '../cn';\nimport { ago, dateTime } from '../format';\nimport { useLatest } from './latest';\n\n/** True while the CSS media query matches. False on the server and before hydration. */\nexport function useMediaQuery(query: string): boolean {\n const subscribe = useCallback(\n (onChange: () => void) => {\n if (typeof window === 'undefined' || !window.matchMedia) return () => {};\n const mq = window.matchMedia(query);\n mq.addEventListener('change', onChange);\n return () => mq.removeEventListener('change', onChange);\n },\n [query],\n );\n const get = () => typeof window !== 'undefined' && !!window.matchMedia && window.matchMedia(query).matches;\n return useSyncExternalStore(subscribe, get, () => false);\n}\n\nexport type Breakpoint = 'base' | 'sm' | 'md' | 'lg' | 'xl';\n\n/** Tailwind's breakpoints, in px. Phone = below sm; narrow = below md (cover screen and small tablets). */\nexport const BREAKPOINTS = { sm: 640, md: 768, lg: 1024, xl: 1280 } as const;\nexport const PHONE_QUERY = '(max-width: 639.98px)';\nexport const NARROW_QUERY = '(max-width: 767.98px)';\n\nconst BREAKPOINT_QUERIES: [Exclude<Breakpoint, 'base'>, string][] = (['xl', 'lg', 'md', 'sm'] as const).map((name) => [\n name,\n `(min-width: ${BREAKPOINTS[name]}px)`,\n]);\n\n/** True below 640px (the Fold's cover screen, any phone held upright). */\nexport function usePhone(): boolean {\n return useMediaQuery(PHONE_QUERY);\n}\n\n/** True below 768px: where BottomNav shows and NavRail hides. */\nexport function useNarrow(): boolean {\n return useMediaQuery(NARROW_QUERY);\n}\n\nfunction currentBreakpoint(): Breakpoint {\n if (typeof window === 'undefined' || !window.matchMedia) return 'base';\n for (const [name, q] of BREAKPOINT_QUERIES) if (window.matchMedia(q).matches) return name;\n return 'base';\n}\n\nfunction subscribeBreakpoint(onChange: () => void): () => void {\n if (typeof window === 'undefined' || !window.matchMedia) return () => {};\n const lists = BREAKPOINT_QUERIES.map(([, q]) => window.matchMedia(q));\n lists.forEach((l) => l.addEventListener('change', onChange));\n return () => lists.forEach((l) => l.removeEventListener('change', onChange));\n}\n\n/** The largest Tailwind breakpoint the viewport has reached: base, sm (640), md (768), lg (1024) or xl (1280). */\nexport function useBreakpoint(): Breakpoint {\n return useSyncExternalStore(subscribeBreakpoint, currentBreakpoint, () => 'base');\n}\n\n/**\n * Sets document.title to \"title · app\" (or just the app, or just the title) and restores\n * the previous title on unmount. An undefined title with no app leaves the title alone.\n */\nexport function useDocumentTitle(title: string | undefined, o: { app?: string } = {}): void {\n const app = o.app;\n useEffect(() => {\n if (typeof document === 'undefined') return;\n const next = title && app ? `${title} · ${app}` : title || app;\n if (!next) return;\n const previous = document.title;\n document.title = next;\n return () => {\n document.title = previous;\n };\n }, [title, app]);\n}\n\n/** Date.now() that updates every intervalMs, paused while the tab is hidden. */\nexport function useNow(intervalMs = 30000): number {\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (typeof document === 'undefined') return;\n let id: ReturnType<typeof setInterval> | undefined;\n const start = () => {\n if (id === undefined) id = setInterval(() => setNow(Date.now()), intervalMs);\n };\n const stop = () => {\n if (id !== undefined) clearInterval(id);\n id = undefined;\n };\n const onVisibility = () => {\n if (document.visibilityState === 'visible') {\n setNow(Date.now());\n start();\n } else stop();\n };\n if (document.visibilityState !== 'hidden') start();\n document.addEventListener('visibilitychange', onVisibility);\n return () => {\n stop();\n document.removeEventListener('visibilitychange', onVisibility);\n };\n }, [intervalMs]);\n return now;\n}\n\nconst LOCAL_EVENT = 'nish-local-storage';\n\nfunction readStored<T>(key: string, initial: T, raw: boolean): T {\n try {\n const text = window.localStorage.getItem(key);\n if (text === null) return initial;\n return raw ? (text as T) : (JSON.parse(text) as T);\n } catch {\n return initial;\n }\n}\n\n/**\n * State kept in localStorage. JSON by default, the raw string with { raw: true }. Never\n * throws (private mode, quota and bad JSON fall back to the initial value) and follows\n * changes from other tabs and from other hooks on the same key.\n */\nexport function useLocalStorage<T>(\n key: string,\n initial: T,\n o: { raw?: boolean } = {},\n): [T, (next: T | ((prev: T) => T)) => void] {\n const raw = !!o.raw;\n const initialRef = useLatest(initial);\n const [value, setValueState] = useState<T>(() =>\n typeof window === 'undefined' ? initial : readStored(key, initial, raw),\n );\n const valueRef = useLatest(value);\n const instanceRef = useRef<object>({});\n\n useEffect(() => {\n const sync = () => setValueState(readStored(key, initialRef.current, raw));\n sync();\n const onStorage = (e: StorageEvent) => {\n if (e.key === null || e.key === key) sync();\n };\n const onLocal = (e: Event) => {\n const d = (e as CustomEvent<{ key: string; source: object }>).detail;\n if (d && d.key === key && d.source !== instanceRef.current) sync();\n };\n window.addEventListener('storage', onStorage);\n window.addEventListener(LOCAL_EVENT, onLocal);\n return () => {\n window.removeEventListener('storage', onStorage);\n window.removeEventListener(LOCAL_EVENT, onLocal);\n };\n }, [initialRef, key, raw]);\n\n const setValue = useCallback(\n (next: T | ((prev: T) => T)) => {\n const resolved = typeof next === 'function' ? (next as (prev: T) => T)(valueRef.current) : next;\n valueRef.current = resolved;\n setValueState(resolved);\n try {\n window.localStorage.setItem(key, raw ? String(resolved) : JSON.stringify(resolved));\n } catch {\n // Storage unavailable: the value still lives in memory.\n }\n try {\n window.dispatchEvent(new CustomEvent(LOCAL_EVENT, { detail: { key, source: instanceRef.current } }));\n } catch {\n // No window events.\n }\n },\n [key, raw, valueRef],\n );\n\n return [value, setValue];\n}\n\nexport interface RelativeTimeProps {\n /** The moment: a Date, epoch milliseconds or a date string. */\n value: Date | number | string;\n /** \"3m ago\" (short, default) or \"3 minutes ago\" (long). */\n style?: 'short' | 'long';\n /** How often the text refreshes, in milliseconds. Default 30000. */\n refreshMs?: number;\n /** Classes for the time element. */\n className?: string;\n}\n\n/** A self-updating \"3m ago\". The full date and time show on hover and in the dateTime attribute. */\nexport function RelativeTime({ value, style = 'short', refreshMs = 30000, className }: RelativeTimeProps) {\n const now = useNow(refreshMs);\n const d = new Date(value);\n const iso = Number.isNaN(d.getTime()) ? undefined : d.toISOString();\n return (\n <time dateTime={iso} title={dateTime(value)} className={cn('tabular-nums', className)}>\n {ago(value, { now, style })}\n </time>\n );\n}\n","import type { SVGProps } from 'react';\n\n/** The handful of icons the shared components need, inlined so the package does not\n * pin apps to one lucide-react version. 24px grid, 2px stroke, lucide geometry. */\ntype IconProps = SVGProps<SVGSVGElement> & { size?: number };\n\nfunction Svg({ size = 16, children, ...rest }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...rest}\n >\n {children}\n </svg>\n );\n}\n\nexport const XIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </Svg>\n);\n\nexport const CheckCircleIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m9 12 2 2 4-4\" />\n </Svg>\n);\n\nexport const AlertTriangleIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4M12 17h.01\" />\n </Svg>\n);\n\nexport const InfoIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 16v-4M12 8h.01\" />\n </Svg>\n);\n\nexport const RotateIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8\" />\n <path d=\"M21 3v5h-5\" />\n </Svg>\n);\n\nexport const LoaderIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M21 12a9 9 0 1 1-6.22-8.56\" />\n </Svg>\n);\n\nexport const SunIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <path d=\"M12 2v2M12 20v2m-7.07-2.93 1.41-1.41M17.66 6.34l1.41-1.41M2 12h2m16 0h2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41\" />\n </Svg>\n);\n\nexport const MoonIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9\" />\n </Svg>\n);\n\nexport const MonitorIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"20\" height=\"14\" x=\"2\" y=\"3\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </Svg>\n);\n\nexport const ChevronDownIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m6 9 6 6 6-6\" />\n </Svg>\n);\n\nexport const CheckIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M20 6 9 17l-5-5\" />\n </Svg>\n);\n\nexport const ClockIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 6v6l4 2\" />\n </Svg>\n);\n\n/** Three horizontal dots. */\nexport const MoreIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"19\" cy=\"12\" r=\"1\" />\n <circle cx=\"5\" cy=\"12\" r=\"1\" />\n </Svg>\n);\n\nexport const BellIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9\" />\n <path d=\"M10.3 21a1.94 1.94 0 0 0 3.4 0\" />\n </Svg>\n);\n\nexport const SettingsIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </Svg>\n);\n\n/** A panel with its left column and an arrow pointing in: collapse a sidebar. */\nexport const PanelLeftCloseIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M9 3v18\" />\n <path d=\"m16 15-3-3 3-3\" />\n </Svg>\n);\n\n/** A panel with its left column and an arrow pointing out: expand a sidebar. */\nexport const PanelLeftOpenIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M9 3v18\" />\n <path d=\"m14 9 3 3-3 3\" />\n </Svg>\n);\n","import {\n forwardRef,\n useId,\n type ButtonHTMLAttributes,\n type HTMLAttributes,\n type InputHTMLAttributes,\n type ReactNode,\n type Ref,\n type SelectHTMLAttributes,\n} from 'react';\nimport { cn } from '../cn';\nimport { ChevronDownIcon, LoaderIcon } from './icons';\n\n// Controls grow to the 44px tap target on touch screens (pointer-coarse) and stay\n// compact under a mouse, so dense desktop tables keep their density.\n//\n// One recipe per look: each component that also has a class form (buttonClass,\n// iconButtonClass, cardClass, fieldClass, badgeClass) renders exactly that function's\n// output, so an <a>, a router <Link> or a one-off control can match it without copying\n// a class string.\n\n// --- Button -------------------------------------------------------------------------\n\nexport type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger' | 'soft' | 'subtle' | 'link';\nexport type ButtonSize = 'xs' | 'sm' | 'md' | 'lg';\n\nconst BUTTON_VARIANT: Record<ButtonVariant, string> = {\n primary: 'bg-th-accent text-th-on-accent hover:bg-th-accent/90 active:bg-th-accent/80',\n secondary: 'border border-th-line-strong bg-th-surface text-th-hi hover:bg-th-elevated',\n ghost: 'text-th-hi2 hover:bg-th-elevated hover:text-th-hi',\n danger: 'bg-th-loss text-th-on-loss hover:bg-th-loss/90 active:bg-th-loss/80',\n soft: 'bg-th-accent-soft text-th-accent hover:bg-th-accent/20 active:bg-th-accent/25',\n subtle: 'bg-th-elevated text-th-hi hover:bg-th-overlay',\n link: 'h-auto p-0 font-medium text-th-accent underline-offset-2 hover:underline',\n};\n\nconst BUTTON_SIZE: Record<ButtonSize, string> = {\n xs: 'h-6 gap-1 px-2 text-2xs pointer-coarse:min-h-11',\n sm: 'h-7 gap-1.5 px-2.5 text-xs pointer-coarse:min-h-11',\n md: 'h-9 gap-2 px-3.5 text-sm pointer-coarse:min-h-11',\n lg: 'h-11 gap-2 px-5 text-base',\n};\n\n// A link button sits inline in text: it keeps the size's type and gap, but has no\n// height, no padding and no touch growth.\nconst LINK_SIZE: Record<ButtonSize, string> = {\n xs: 'gap-1 text-2xs',\n sm: 'gap-1 text-xs',\n md: 'gap-1.5 text-sm',\n lg: 'gap-2 text-base',\n};\n\nconst BUTTON_BASE =\n 'inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap rounded-lg font-medium transition-[color,background-color,border-color,transform] duration-150';\n\n// Touch press feedback for filled buttons and icon buttons; never on a disabled one.\nconst PRESS = 'pointer-coarse:not-disabled:active:scale-[0.97]';\n\n// A link button's hit area grows to 44px on touch with an invisible ::after, so the\n// layout does not move.\nconst LINK_HIT =\n \"pointer-coarse:relative pointer-coarse:after:absolute pointer-coarse:after:-inset-x-2 pointer-coarse:after:-inset-y-3 pointer-coarse:after:content-['']\";\n\n// Disabled reads as disabled in every theme: a flat, quiet fill and faint text, instead\n// of a dimmed copy of the enabled color. A link only fades its text.\nconst BUTTON_DISABLED =\n 'disabled:pointer-events-none disabled:border disabled:border-th-line disabled:bg-th-elevated disabled:text-th-ghost disabled:shadow-none';\nconst LINK_DISABLED = 'disabled:pointer-events-none disabled:text-th-ghost disabled:no-underline';\n\nexport interface ButtonClassOptions {\n /** Same variants as Button. Default \"secondary\". */\n variant?: ButtonVariant;\n /** Same sizes as Button. Default \"md\". */\n size?: ButtonSize;\n /** Link variant only: skip the 44px touch hit area, for a link inside running text. */\n inline?: boolean;\n /** Extra classes, merged last (tailwind-merge resolves conflicts). */\n className?: string;\n}\n\n/** The classes `<Button>` renders, minus its `disabled:` styles. Use it on `<a>`, router\n * `<Link>`s and `<a download>` so links that look like buttons match them exactly. */\nexport function buttonClass({ variant = 'secondary', size = 'md', inline = false, className }: ButtonClassOptions = {}): string {\n return cn(\n BUTTON_BASE,\n variant === 'link' ? LINK_SIZE[size] : BUTTON_SIZE[size],\n variant === 'link' ? !inline && LINK_HIT : PRESS,\n BUTTON_VARIANT[variant],\n className,\n );\n}\n\nexport interface LinkClassOptions {\n /** accent: the accent color (default). muted: grey text that lights up on hover. */\n tone?: 'accent' | 'muted';\n /** Skip the 44px touch hit area, for a link inside running text. */\n inline?: boolean;\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes for a text link on a router `<Link>` or `<a>`: tone, underline on hover\n * and, on touch screens, a 44px hit area that does not move the layout. */\nexport function linkClass({ tone = 'accent', inline = false, className }: LinkClassOptions = {}): string {\n return cn(\n 'font-medium underline-offset-2 transition-colors duration-150 hover:underline',\n tone === 'accent' ? 'text-th-accent' : 'text-th-hi3 hover:text-th-hi',\n !inline && LINK_HIT,\n className,\n );\n}\n\n/** Classes that hide a row action until its row is hovered or focused, and always show\n * it on touch screens (there is no hover). Put `group` on the row. */\nexport function revealClass(className?: string): string {\n return cn(\n 'opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100',\n className,\n );\n}\n\nexport interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** primary: the one main action in a view. secondary: everything else. ghost:\n * toolbars and quiet actions. danger: destructive actions. soft: an accent action\n * that is not the main one (replaces \"accent outline\" buttons). subtle: a filled,\n * quiet button for dense toolbars and chips on a surface. link: looks like a text\n * link and sits inline in text (no height or padding; on touch screens an invisible\n * 44px hit area, unless `inline`). */\n variant?: ButtonVariant;\n /** xs for dense tool rows (24px), sm for dense rows and toolbars, lg for a page's\n * main call to action. xs, sm and md grow to 44px on touch screens. */\n size?: ButtonSize;\n /** Link variant only: skip the 44px touch hit area, for a link inside running text. */\n inline?: boolean;\n /** Shows a spinner and disables the button. */\n loading?: boolean;\n /** Icon before the label (16px for md and lg, 12–14px for xs and sm). Replaced by the\n * spinner while loading. */\n icon?: ReactNode;\n}\n\n/** The standard button. Defaults to type=\"button\", so it never submits a form by\n * accident; pass type=\"submit\" for the one that should. */\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(\n { variant = 'secondary', size = 'md', inline = false, loading = false, icon, className, children, disabled, type = 'button', ...rest },\n ref,\n) {\n return (\n <button\n ref={ref}\n type={type}\n disabled={disabled || loading}\n aria-busy={loading || undefined}\n className={buttonClass({\n variant,\n size,\n inline,\n className: cn(variant === 'link' ? LINK_DISABLED : BUTTON_DISABLED, className),\n })}\n {...rest}\n >\n {loading ? <LoaderIcon size={size === 'xs' || size === 'sm' ? 12 : 14} className=\"animate-spin\" /> : icon}\n {children}\n </button>\n );\n});\n\n// --- IconButton ---------------------------------------------------------------------\n\nexport type IconButtonSize = '2xs' | 'xs' | 'sm' | 'md';\nexport type IconButtonVariant = 'ghost' | 'subtle' | 'soft';\n\nconst ICON_SIZE: Record<IconButtonSize, string> = {\n '2xs': 'size-5 rounded',\n xs: 'size-6 rounded-md',\n sm: 'size-7 rounded-lg',\n md: 'size-9 rounded-lg',\n};\n\nconst ICON_VARIANT: Record<IconButtonVariant, { idle: string; active: string }> = {\n ghost: { idle: 'text-th-hi3 hover:bg-th-elevated hover:text-th-hi', active: 'bg-th-elevated text-th-hi' },\n subtle: { idle: 'bg-th-elevated text-th-hi hover:bg-th-overlay', active: 'bg-th-overlay text-th-hi' },\n soft: { idle: 'bg-th-accent-soft text-th-accent hover:bg-th-accent/20', active: 'bg-th-accent/25 text-th-accent' },\n};\n\nconst ICON_DANGER = 'hover:bg-th-loss-soft hover:text-th-loss active:bg-th-loss-soft active:text-th-loss';\n\nexport interface IconButtonClassOptions {\n /** Same sizes as IconButton. Default \"md\". */\n size?: IconButtonSize;\n /** Same variants as IconButton. Default \"ghost\". */\n variant?: IconButtonVariant;\n /** Same tones as IconButton. Default \"neutral\". */\n tone?: 'neutral' | 'danger';\n /** The pressed look (IconButton also sets aria-pressed; set it yourself on a link). */\n active?: boolean;\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes `<IconButton>` renders. Use it on an icon-only `<a>` or router `<Link>`,\n * and give that element an aria-label. */\nexport function iconButtonClass({\n size = 'md',\n variant = 'ghost',\n tone = 'neutral',\n active = false,\n className,\n}: IconButtonClassOptions = {}): string {\n return cn(\n 'inline-flex shrink-0 items-center justify-center transition-[color,background-color,border-color,transform] duration-150',\n PRESS,\n 'disabled:pointer-events-none disabled:bg-transparent disabled:text-th-ghost',\n 'pointer-coarse:min-h-11 pointer-coarse:min-w-11',\n ICON_SIZE[size],\n ICON_VARIANT[variant].idle,\n active && ICON_VARIANT[variant].active,\n tone === 'danger' && ICON_DANGER,\n active && tone === 'danger' && 'bg-th-loss-soft text-th-loss',\n className,\n );\n}\n\nexport interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** Required: an icon-only button needs a name for screen readers and tooltips. It is\n * also the title, so tests that query by title keep working. */\n label: string;\n /** 2xs: 20px (row-level reveal actions, 22px widget title bars), xs: 24px (dense\n * headers), sm: 28px, md: 36px. All grow to 44px on touch screens. */\n size?: IconButtonSize;\n /** Pressed state for toggles (sets aria-pressed). */\n active?: boolean;\n /** ghost: no fill until hover (default). subtle: a quiet filled square for toolbars on\n * a surface. soft: an accent tint for the highlighted action. */\n variant?: IconButtonVariant;\n /** danger: hover and pressed turn loss-red, for delete and remove actions. */\n tone?: 'neutral' | 'danger';\n}\n\n/** A square button holding only an icon, with its label as aria-label and title. */\nexport const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton(\n { label, size = 'md', active = false, variant = 'ghost', tone = 'neutral', className, children, type = 'button', ...rest },\n ref,\n) {\n return (\n <button\n ref={ref}\n type={type}\n aria-label={label}\n title={label}\n aria-pressed={active || undefined}\n className={iconButtonClass({ size, variant, tone, active, className })}\n {...rest}\n >\n {children}\n </button>\n );\n});\n\n// --- Card and CardHeader ------------------------------------------------------------\n\nexport type CardPadding = 'none' | 'sm' | 'md' | 'lg';\nexport type CardElement = 'div' | 'section' | 'article' | 'aside' | 'li';\n\nconst CARD_PADDING: Record<CardPadding, string> = {\n none: '',\n sm: 'p-3',\n md: 'p-4 sm:p-5',\n lg: 'p-6',\n};\n\nexport interface CardClassOptions {\n /** Inner padding. Default \"md\". */\n padding?: CardPadding;\n /** Kept from v0.2: false is the same as padding=\"none\". */\n padded?: boolean;\n /** Hover styles for cards that are links or buttons. */\n interactive?: boolean;\n /** surface: the bordered panel (default). inset: a quiet elevated box for use inside\n * another card. */\n variant?: 'surface' | 'inset';\n /** Extra classes, merged last. */\n className?: string;\n}\n\nconst resolvePadding = (padding: CardPadding | undefined, padded: boolean | undefined): CardPadding =>\n padding ?? (padded === false ? 'none' : 'md');\n\n/** The classes `<Card>` renders. Use it on a router `<Link>` or `<a>` that is a whole\n * card: `<Link className={cardClass({ interactive: true })}>`. */\nexport function cardClass({ padding, padded, interactive = false, variant = 'surface', className }: CardClassOptions = {}): string {\n const inset = variant === 'inset';\n return cn(\n inset ? 'rounded-lg border border-transparent bg-th-elevated' : 'rounded-xl border border-th-line bg-th-surface shadow-card',\n CARD_PADDING[resolvePadding(padding, padded)],\n interactive &&\n (inset\n ? 'transition-colors duration-150 hover:bg-th-overlay'\n : 'transition-colors duration-150 hover:border-th-line-strong hover:bg-th-elevated/60'),\n className,\n );\n}\n\nexport interface CardHeaderProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {\n /** The card's heading. */\n title: ReactNode;\n /** A quieter line under the title. */\n description?: ReactNode;\n /** Right-aligned slot: a Button, an IconButton, a Badge, a Segmented. It wraps under\n * the title on narrow cards. */\n action?: ReactNode;\n /** A small icon before the title (16px). */\n icon?: ReactNode;\n /** The heading level. Default \"h2\". */\n as?: 'h2' | 'h3' | 'h4';\n /** A bottom border and its own padding (px-4 py-3), for unpadded cards whose content\n * runs edge to edge (tables, lists, widgets). */\n divided?: boolean;\n /** id for the heading element, so a section can point aria-labelledby at it. */\n titleId?: string;\n}\n\n/** The header row of a card: title, optional description and icon, and an action slot. */\nexport function CardHeader({\n title,\n description,\n action,\n icon,\n as: Heading = 'h2',\n divided = false,\n titleId,\n className,\n ...rest\n}: CardHeaderProps) {\n return (\n <div\n className={cn(\n 'flex flex-wrap items-center justify-between gap-x-3 gap-y-2',\n divided && 'border-b border-th-line px-4 py-3',\n className,\n )}\n {...rest}\n >\n <div className=\"flex min-w-0 items-start gap-2\">\n {icon ? (\n <span className=\"mt-0.5 inline-flex shrink-0 text-th-hi3\" aria-hidden=\"true\">\n {icon}\n </span>\n ) : null}\n <div className=\"min-w-0\">\n <Heading id={titleId} className=\"text-sm font-semibold text-th-hi\">\n {title}\n </Heading>\n {description ? <p className=\"mt-0.5 text-xs text-th-hi3\">{description}</p> : null}\n </div>\n </div>\n {action ? <div className=\"flex shrink-0 flex-wrap items-center gap-2\">{action}</div> : null}\n </div>\n );\n}\n\nexport interface CardProps extends Omit<HTMLAttributes<HTMLElement>, 'title'> {\n /** The element to render. Use section or article for a titled region, li inside a list. */\n as?: CardElement;\n /** Inner padding: sm p-3, md p-4 (p-5 from 640px; the default), lg p-6, none for\n * tables and lists that run edge to edge. Use this, not className=\"p-3\", which would\n * keep md's sm:p-5. */\n padding?: CardPadding;\n /** Kept from v0.2: false is the same as padding=\"none\". padding wins when both are set. */\n padded?: boolean;\n /** Hover styles for cards that are links or buttons. */\n interactive?: boolean;\n /** surface: the bordered panel with the card shadow (default). inset: bg-th-elevated,\n * no border color, no shadow and rounded-lg, for a box inside another card. */\n variant?: 'surface' | 'inset';\n /** Renders a CardHeader first. On an unpadded card the header is divided (its own\n * padding and a bottom border). */\n title?: ReactNode;\n /** The header's description; only with title. */\n description?: ReactNode;\n /** The header's right-aligned action slot; only with title. */\n action?: ReactNode;\n}\n\n/** The surface panel every widget, table and form sits in. */\nexport const Card = forwardRef<HTMLElement, CardProps>(function Card(\n { as = 'div', padding, padded, interactive = false, variant = 'surface', title, description, action, className, children, ...rest },\n ref,\n) {\n const Tag = as as 'div';\n const pad = resolvePadding(padding, padded);\n const headingId = useId();\n const region = title != null && (as === 'section' || as === 'article' || as === 'aside');\n return (\n <Tag\n ref={ref as Ref<HTMLDivElement>}\n aria-labelledby={region && !rest['aria-label'] && !rest['aria-labelledby'] ? headingId : undefined}\n className={cardClass({ padding: pad, interactive, variant, className })}\n {...rest}\n >\n {title != null ? (\n <CardHeader\n title={title}\n description={description}\n action={action}\n titleId={headingId}\n divided={pad === 'none'}\n className={pad === 'none' ? undefined : 'mb-3'}\n />\n ) : null}\n {children}\n </Tag>\n );\n});\n\n// --- Badge --------------------------------------------------------------------------\n\nexport type BadgeTone = 'neutral' | 'accent' | 'ok' | 'loss' | 'warn' | 'info' | 'on-accent';\ntype Tone = BadgeTone;\nexport type BadgeHue = 'emerald' | 'indigo' | 'amber' | 'lime' | 'rose' | 'sky' | 'violet' | 'teal';\n\nconst BADGE_TONE: Record<Tone, string> = {\n neutral: 'border-th-line bg-th-elevated text-th-hi2',\n accent: 'border-th-accent/30 bg-th-accent-soft text-th-accent',\n ok: 'border-th-ok/30 bg-th-ok-soft text-th-ok',\n loss: 'border-th-loss/30 bg-th-loss-soft text-th-loss',\n warn: 'border-th-warn/30 bg-th-warn-soft text-th-warn',\n info: 'border-th-info/30 bg-th-info-soft text-th-info',\n // A label on a solid accent fill (inside a primary Button or an accent link).\n 'on-accent': 'border-transparent bg-th-on-accent/20 text-th-on-accent',\n};\n\n// Full literal class names, so Tailwind's scanner finds every one.\nconst BADGE_HUE: Record<BadgeHue, string> = {\n emerald: 'border-th-emerald/30 bg-th-emerald-soft text-th-hi',\n indigo: 'border-th-indigo/30 bg-th-indigo-soft text-th-hi',\n amber: 'border-th-amber/30 bg-th-amber-soft text-th-hi',\n lime: 'border-th-lime/30 bg-th-lime-soft text-th-hi',\n rose: 'border-th-rose/30 bg-th-rose-soft text-th-hi',\n sky: 'border-th-sky/30 bg-th-sky-soft text-th-hi',\n violet: 'border-th-violet/30 bg-th-violet-soft text-th-hi',\n teal: 'border-th-teal/30 bg-th-teal-soft text-th-hi',\n};\n\n// The dot is StatusDot's xs recipe (6px, the tone's -fill).\nconst DOT_TONE: Record<Tone, string> = {\n neutral: 'bg-th-ghost',\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n loss: 'bg-th-loss-fill',\n warn: 'bg-th-warn-fill',\n info: 'bg-th-info-fill',\n 'on-accent': 'bg-th-on-accent',\n};\n\nconst DOT_HUE: Record<BadgeHue, string> = {\n emerald: 'bg-th-emerald',\n indigo: 'bg-th-indigo',\n amber: 'bg-th-amber',\n lime: 'bg-th-lime',\n rose: 'bg-th-rose',\n sky: 'bg-th-sky',\n violet: 'bg-th-violet',\n teal: 'bg-th-teal',\n};\n\nexport interface BadgeClassOptions {\n /** Same tones as Badge. Default \"neutral\". */\n tone?: Tone;\n /** Same hues as Badge; overrides tone. */\n hue?: BadgeHue;\n /** Same sizes as Badge. Default \"sm\". */\n size?: 'xs' | 'sm';\n /** Same variants as Badge. Default \"pill\". */\n variant?: 'pill' | 'tag';\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes `<Badge>` renders (without the dot), for a badge-shaped link or a\n * label inside a third-party renderer. */\nexport function badgeClass({ tone = 'neutral', hue, size = 'sm', variant = 'pill', className }: BadgeClassOptions = {}): string {\n return cn(\n 'inline-flex items-center gap-1 whitespace-nowrap rounded-full border font-medium',\n size === 'xs' ? 'px-1.5 py-0 text-3xs leading-4' : 'px-2 py-0.5 text-xs leading-4',\n hue ? BADGE_HUE[hue] : BADGE_TONE[tone],\n variant === 'tag' && 'rounded-sm border-transparent font-semibold uppercase tracking-wide',\n className,\n );\n}\n\nexport interface BadgeProps extends HTMLAttributes<HTMLSpanElement> {\n /** Text on its own soft tint; every tone clears 4.5:1 in every theme. on-accent: a\n * small label inside a solid accent fill (a primary Button, an accent link), in the\n * on-accent color over a 20% on-accent tint. It has no hover state; pair a short\n * label with sr-only text that says what it means. */\n tone?: Tone;\n /** A color with no meaning (stores, categories, tags): the hue's soft tint with hi\n * text, so it reads in every theme. Overrides tone. */\n hue?: BadgeHue;\n /** sm: the default 12px pill. xs: 10px text for dense rows and table cells. */\n size?: 'xs' | 'sm';\n /** pill: rounded (default). tag: square corners, no border, bold uppercase, for\n * tag-shaped labels (\"CALL\", \"NEW\"). */\n variant?: 'pill' | 'tag';\n /** A leading 6px status dot in the tone's fill (or the hue). Pair it with text that\n * says the state; the dot itself is hidden from screen readers. */\n dot?: boolean;\n}\n\n/** A small status pill: counts, states, tags. */\nexport function Badge({ tone = 'neutral', hue, size = 'sm', variant = 'pill', dot = false, className, children, ...rest }: BadgeProps) {\n return (\n <span className={badgeClass({ tone, hue, size, variant, className })} {...rest}>\n {dot ? (\n <span aria-hidden=\"true\" className={cn('inline-block size-1.5 shrink-0 rounded-full', hue ? DOT_HUE[hue] : DOT_TONE[tone])} />\n ) : null}\n {children}\n </span>\n );\n}\n\n// --- Fields: Input, Select (and the shared FIELD recipe) -----------------------------\n\nexport type FieldSize = 'xs' | 'sm' | 'md';\n\n/** The field look without size: border, fill, hover, focus ring, disabled and invalid.\n * Internal to the package (Textarea in forms.tsx builds on it); apps use fieldClass(). */\nexport const FIELD =\n 'w-full min-w-0 rounded-lg border border-th-line-strong bg-th-elevated text-th-hi placeholder:text-th-ghost ' +\n 'transition-colors duration-150 hover:border-th-hi3/60 focus:border-th-accent focus:outline-none focus:ring-2 focus:ring-th-accent/25 ' +\n 'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-th-loss';\n\n// Touch screens always get 16px text (text-base), so iOS does not zoom on focus. Under a\n// mouse the size's own text size applies at every width, so a narrow popout window\n// driven by a mouse keeps its dense text.\n// Padding is split into pl and pr, so a slot or a select chevron can replace one side\n// without fighting a px class.\nconst FIELD_SIZE: Record<FieldSize, { box: string; pad: string; text: string }> = {\n xs: { box: 'h-7 pointer-coarse:min-h-11', pad: 'pl-2 pr-2', text: 'text-2xs pointer-coarse:text-base' },\n sm: { box: 'h-8 pointer-coarse:min-h-11', pad: 'pl-2.5 pr-2.5', text: 'text-xs pointer-coarse:text-base' },\n md: { box: 'h-9 pointer-coarse:min-h-11', pad: 'pl-3 pr-3', text: 'text-sm pointer-coarse:text-base' },\n};\n\nconst FIELD_INVALID = 'border-th-loss hover:border-th-loss';\n\nexport interface FieldClassOptions {\n /** md h-9 (default), sm h-8, xs h-7. All grow to 44px on touch screens. */\n size?: FieldSize;\n /** The red invalid border, for elements that do not set aria-invalid themselves. */\n invalid?: boolean;\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes `<Input>` renders: the shared field look at a size. Use it for a one-off\n * control (a date input, a contenteditable) instead of copying a class string. */\nexport function fieldClass({ size = 'md', invalid = false, className }: FieldClassOptions = {}): string {\n const s = FIELD_SIZE[size];\n return cn(FIELD, s.box, s.pad, s.text, invalid && FIELD_INVALID, className);\n}\n\nexport interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> {\n /** Red border and aria-invalid. Pair it with an error message tied by aria-describedby. */\n invalid?: boolean;\n /** md h-9 (default), sm h-8 with 12px text, xs h-7 with 11px text. Touch screens\n * always get 16px text and a 44px height. (Replaces the native size attribute; set a width with\n * className instead.) */\n size?: FieldSize;\n /** A decorative slot inside the left edge: a search icon, a \"$\" prefix. It ignores\n * pointer events, so clicks reach the input. */\n leading?: ReactNode;\n /** A slot inside the right edge that may be interactive: a clear IconButton, a unit\n * suffix. */\n trailing?: ReactNode;\n /** Classes for the wrapper span that holds the slots (only rendered with leading or\n * trailing). className stays on the input. */\n wrapperClassName?: string;\n}\n\n/** Text input. 16px text on touch screens so iOS does not zoom the page on focus. */\nexport const Input = forwardRef<HTMLInputElement, InputProps>(function Input(\n { invalid, size = 'md', leading, trailing, wrapperClassName, className, ...rest },\n ref,\n) {\n const input = (\n <input\n ref={ref}\n aria-invalid={invalid || undefined}\n className={fieldClass({ size, className: cn(leading != null && 'pl-8', trailing != null && 'pr-8', className) })}\n {...rest}\n />\n );\n if (leading == null && trailing == null) return input;\n return (\n <span className={cn('relative inline-flex w-full min-w-0 items-center', wrapperClassName)}>\n {leading != null ? (\n <span className=\"pointer-events-none absolute inset-y-0 left-0 flex w-8 items-center justify-center text-sm text-th-hi2\">\n {leading}\n </span>\n ) : null}\n {input}\n {trailing != null ? (\n <span className=\"absolute inset-y-0 right-0 flex min-w-8 items-center justify-center pr-0.5 text-sm text-th-hi2\">{trailing}</span>\n ) : null}\n </span>\n );\n});\n\nconst SELECT_SIZE: Record<FieldSize, { pad: string; chevron: string; icon: number }> = {\n xs: { pad: 'pl-2 pr-6', chevron: 'right-1.5', icon: 12 },\n sm: { pad: 'pl-2.5 pr-7', chevron: 'right-2', icon: 13 },\n md: { pad: 'pl-3 pr-8', chevron: 'right-2.5', icon: 14 },\n};\n\nexport interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'> {\n /** Red border and aria-invalid. */\n invalid?: boolean;\n /** md h-9 (default), sm h-8, xs h-7, the same as Input. Touch screens get 16px text\n * and a 44px height. (Replaces the native size attribute, which turns a select into a list box.) */\n size?: FieldSize;\n /** Classes for the inner <select> itself. className sizes the wrapper (width, margin);\n * use this instead of reaching in with [&>select]:… */\n selectClassName?: string;\n}\n\n/** Native select (keeps the platform picker on phones) with the shared field look. */\nexport const Select = forwardRef<HTMLSelectElement, SelectProps>(function Select(\n { invalid, size = 'md', selectClassName, className, children, ...rest },\n ref,\n) {\n const s = SELECT_SIZE[size];\n return (\n <span className={cn('relative inline-flex w-full min-w-0', className)}>\n <select\n ref={ref}\n aria-invalid={invalid || undefined}\n className={fieldClass({ size, className: cn('appearance-none', s.pad, selectClassName) })}\n {...rest}\n >\n {children}\n </select>\n <ChevronDownIcon size={s.icon} className={cn('pointer-events-none absolute top-1/2 -translate-y-1/2 text-th-hi3', s.chevron)} />\n </span>\n );\n});\n\n// --- Label --------------------------------------------------------------------------\n\n/** Small uppercase label for form fields and section headings. */\nexport function Label({ className, ...rest }: HTMLAttributes<HTMLSpanElement>) {\n return <span className={cn('text-xs font-medium uppercase tracking-wider text-th-hi3', className)} {...rest} />;\n}\n","import { memo } from 'react';\nimport { StatusDot } from '../display';\nimport { TickerText } from '../flow';\nimport type { FollowStep } from './follow';\n\n/** The pill at the bottom left of the canvas saying what follow mode is looking at. */\nexport const FollowCaption = memo(function FollowCaption({ step }: { step: FollowStep | null }) {\n if (!step) return null;\n const only = step.targets.length === 1 ? step.targets[0]! : null;\n const text =\n step.mode === 'idle'\n ? 'Following · waiting for activity'\n : only\n ? `Following · ${only.group} › ${only.label}`\n : `Following ${step.targets.length} active pieces`;\n return (\n <div\n data-canvas-ui\n role=\"status\"\n aria-live=\"polite\"\n className=\"absolute bottom-[68px] left-3 z-10 flex max-w-[min(420px,calc(100%-24px))] items-center gap-2 rounded-xl border border-th-line bg-th-surface px-3 py-2 text-xs text-th-hi shadow-card min-[600px]:bottom-3\"\n >\n <StatusDot tone=\"accent\" pulse={step.mode !== 'idle'} />\n <div className=\"min-w-0\">\n <div className=\"truncate\">{text}</div>\n {only?.note ? <TickerText as=\"div\" text={only.note} className=\"truncate text-th-ghost\" /> : null}\n </div>\n </div>\n );\n});\n","import {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n type HTMLAttributes,\n type ReactNode,\n type SVGProps,\n} from 'react';\nimport { cn } from '../cn';\nimport { Skeleton } from './feedback';\nimport { AlertTriangleIcon, CheckCircleIcon, ChevronDownIcon, InfoIcon, XIcon } from './icons';\nimport { useHeightVar, useStuck } from './layout-vars';\nimport { DropdownMenu, Tooltip } from './overlay';\nimport { Badge, Button, Card, IconButton, type ButtonProps } from './primitives';\nimport { ThemeToggle } from './theme-toggle';\n\n// Read-only display pieces: notices, status marks, numbers, meters, small charts,\n// headers. Every color is a role; fills (*-fill) for marks, plain roles for text.\n\n// --- icons only this file needs (24px grid, 2px stroke, lucide geometry) -------------\n\ntype IconProps = SVGProps<SVGSVGElement> & { size?: number };\n\nfunction Svg({ size = 16, children, ...rest }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...rest}\n >\n {children}\n </svg>\n );\n}\n\nconst CopyIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" />\n <path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\" />\n </Svg>\n);\n\nconst CheckIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M20 6 9 17l-5-5\" />\n </Svg>\n);\n\nconst ChevronRightIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m9 18 6-6-6-6\" />\n </Svg>\n);\n\n// --- shared tone maps -----------------------------------------------------------------\n\n/** Status tones shared by the display components. */\nexport type StatusTone = 'ok' | 'warn' | 'loss' | 'info' | 'accent' | 'neutral';\n\n/** Solid fills for marks (dots, bars, meters). */\nconst FILL: Record<StatusTone, string> = {\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n info: 'bg-th-info-fill',\n accent: 'bg-th-accent',\n neutral: 'bg-th-ghost',\n};\n\n// =====================================================================================\n// Callout\n// =====================================================================================\n\nexport type CalloutTone = 'neutral' | 'accent' | 'info' | 'ok' | 'warn' | 'loss';\n\n// box: translucent tint that sits in the flow. bar: the same tint flattened onto the page\n// background (-soft-solid), so content scrolling under a sticky bar never shows through.\nconst CALLOUT_TONE: Record<CalloutTone, { box: string; bar: string; icon: string }> = {\n neutral: { box: 'border-th-line bg-th-elevated', bar: 'border-th-line bg-th-elevated', icon: 'text-th-hi3' },\n accent: { box: 'border-th-accent/30 bg-th-accent-soft', bar: 'border-th-accent/30 bg-th-accent-soft-solid', icon: 'text-th-accent' },\n info: { box: 'border-th-info/30 bg-th-info-soft', bar: 'border-th-info/30 bg-th-info-soft-solid', icon: 'text-th-info' },\n ok: { box: 'border-th-ok/30 bg-th-ok-soft', bar: 'border-th-ok/30 bg-th-ok-soft-solid', icon: 'text-th-ok' },\n warn: { box: 'border-th-warn/30 bg-th-warn-soft', bar: 'border-th-warn/30 bg-th-warn-soft-solid', icon: 'text-th-warn' },\n loss: { box: 'border-th-loss/30 bg-th-loss-soft', bar: 'border-th-loss/30 bg-th-loss-soft-solid', icon: 'text-th-loss' },\n};\n\nconst CALLOUT_CLAMP = { 1: 'line-clamp-1', 2: 'line-clamp-2', 3: 'line-clamp-3' } as const;\n\nfunction defaultCalloutIcon(tone: CalloutTone, size: number): ReactNode {\n if (tone === 'ok') return <CheckCircleIcon size={size} />;\n if (tone === 'warn' || tone === 'loss') return <AlertTriangleIcon size={size} />;\n return <InfoIcon size={size} />;\n}\n\nexport interface CalloutProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title' | 'onClick'> {\n /** What kind of notice: info and accent for news, ok for success, warn for something to\n * check, loss for a failure. neutral is a plain grey note. */\n tone?: CalloutTone;\n /** Leading icon. Defaults by tone (Info, CheckCircle or AlertTriangle); false hides it. */\n icon?: ReactNode | false;\n /** A short bold first line. */\n title?: ReactNode;\n /** The body text. */\n children?: ReactNode;\n /** Usually one small Button or link, shown after the text. */\n action?: ReactNode;\n /** Adds a Dismiss button that calls this. */\n onDismiss?: () => void;\n /** box: a rounded tinted box in the flow (default). bar: full width with square\n * corners and no side borders, for a sticky page-level alert. */\n variant?: 'box' | 'bar';\n /** Tighter padding and xs text, for widgets and table cells. */\n compact?: boolean;\n /** Announce it when it appears: role=\"alert\" for loss, role=\"status\" otherwise.\n * Leave it off for notices that are part of the page from the start. */\n live?: boolean;\n /** Sticks under the app header (`top: var(--nish-header-h)`), above page content. Pair\n * with variant=\"bar\". */\n sticky?: boolean;\n /** Limits the body to 1, 2 or 3 lines with an ellipsis, instead of growing. */\n clamp?: 1 | 2 | 3;\n /** Makes the icon, title and text one link (at least 44px tall) with a trailing\n * chevron. `action` and the dismiss button stay separate controls beside it. */\n href?: string;\n /** Like href, but a button. */\n onClick?: () => void;\n /** Shows a \"+{count}\" badge after the title, for \"and 3 more\" notices. */\n count?: number;\n}\n\n/** An inline notice: a tinted box with an icon, an optional title, text and an action.\n * variant=\"bar\" is opaque, so it can stick under the header without content showing\n * through. */\nexport function Callout({\n tone = 'info',\n icon,\n title,\n children,\n action,\n onDismiss,\n variant = 'box',\n compact = false,\n live = false,\n sticky = false,\n clamp,\n href,\n onClick,\n count,\n className,\n ...rest\n}: CalloutProps) {\n const t = CALLOUT_TONE[tone];\n const shown = icon === false ? null : (icon ?? defaultCalloutIcon(tone, compact ? 14 : 16));\n const interactive = href != null || onClick != null;\n const iconEl = shown ? <span className={cn('shrink-0', compact ? 'mt-px' : 'mt-0.5', t.icon)}>{shown}</span> : null;\n const text = (\n <div className=\"min-w-0 flex-1 basis-60\">\n {title || count != null ? (\n <p className=\"flex items-center gap-2 font-medium leading-snug text-th-hi\">\n {title ? <span className=\"min-w-0\">{title}</span> : null}\n {count != null ? (\n <Badge tone={tone} aria-label={`${count} more`} className=\"shrink-0\">\n +{count}\n </Badge>\n ) : null}\n </p>\n ) : null}\n {children ? (\n <div className={cn('leading-snug text-th-hi2', title || count != null ? 'mt-0.5' : null, clamp && CALLOUT_CLAMP[clamp])}>\n {children}\n </div>\n ) : null}\n </div>\n );\n const actionEl = action ? <div className=\"flex shrink-0 items-center gap-2\">{action}</div> : null;\n const dismissEl = onDismiss ? (\n <IconButton label=\"Dismiss\" size=\"xs\" onClick={onDismiss} className=\"-my-0.5 -mr-1\">\n <XIcon size={14} />\n </IconButton>\n ) : null;\n const chevron = <ChevronDownIcon size={16} className=\"-rotate-90 shrink-0 self-center text-th-hi3\" />;\n const hit = cn(\n 'flex min-h-11 min-w-0 flex-1 items-start text-left outline-none focus-visible:ring-2 focus-visible:ring-th-accent/40',\n compact ? 'gap-2' : 'gap-3',\n // Pull the padding of the row into the link so the whole row is the target.\n compact ? '-my-2 py-2' : '-my-3 py-3',\n );\n return (\n <div\n role={live ? (tone === 'loss' ? 'alert' : 'status') : undefined}\n className={cn(\n 'flex border',\n variant === 'bar' && action ? 'items-center' : 'items-start',\n compact ? 'gap-2 px-3 py-2 text-xs' : 'gap-3 px-4 py-3 text-sm',\n variant === 'bar' ? 'w-full rounded-none border-x-0' : 'rounded-xl',\n variant === 'bar' ? t.bar : t.box,\n sticky && 'sticky top-[var(--nish-header-h,0px)] z-20',\n className,\n )}\n {...rest}\n >\n {interactive ? (\n <>\n {href != null ? (\n <a href={href} className={hit}>\n {iconEl}\n <span className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2\">{text}</span>\n {chevron}\n </a>\n ) : (\n <button type=\"button\" onClick={onClick} className={hit}>\n {iconEl}\n <span className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2\">{text}</span>\n {chevron}\n </button>\n )}\n {actionEl}\n {dismissEl}\n </>\n ) : (\n <>\n {iconEl}\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2\">\n {text}\n {actionEl}\n </div>\n {dismissEl}\n </>\n )}\n </div>\n );\n}\n\n// =====================================================================================\n// StatusDot\n// =====================================================================================\n\nconst DOT_SIZE = { xs: 'size-1.5', sm: 'size-2', md: 'size-2.5', lg: 'size-3.5' } as const;\n\nconst HALO: Record<StatusTone, string> = {\n ok: 'ring-4 ring-th-ok-fill/25',\n warn: 'ring-4 ring-th-warn-fill/25',\n loss: 'ring-4 ring-th-loss-fill/25',\n info: 'ring-4 ring-th-info-fill/25',\n accent: 'ring-4 ring-th-accent/25',\n neutral: 'ring-4 ring-th-ghost/25',\n};\n\nexport interface StatusDotProps {\n /** ok, warn, loss and info use the status fills; accent the accent; neutral the ghost grey. */\n tone: StatusTone;\n /** xs 6px, sm 8px (default), md 10px, lg 14px. */\n size?: keyof typeof DOT_SIZE;\n /** Gently pulses the opacity, for \"live\" or \"running\". Still under reduced motion. */\n pulse?: boolean;\n /** A soft ring around the dot, for a header status. */\n halo?: boolean;\n /** The accessible name read by screen readers (\"Up\", \"Degraded\"; role=\"img\"). Without it the\n * dot is aria-hidden, so always pair it with visible text then. */\n label?: string;\n className?: string;\n}\n\n/** A small round status mark. Color is never the only signal: give it a label or\n * put text beside it. */\nexport function StatusDot({ tone, size = 'sm', pulse = false, halo = false, label, className }: StatusDotProps) {\n return (\n <span\n role={label ? 'img' : undefined}\n aria-label={label}\n aria-hidden={label ? undefined : true}\n className={cn(\n 'inline-block shrink-0 rounded-full',\n DOT_SIZE[size],\n FILL[tone],\n halo && HALO[tone],\n pulse && 'motion-safe:animate-pulse',\n className,\n )}\n />\n );\n}\n\n// =====================================================================================\n// Stat, StatGrid, signTone\n// =====================================================================================\n\n/** ok for a positive number, loss for a negative one, neutral for zero or nothing.\n * Replaces `n >= 0 ? gain : loss` ternaries. */\nexport function signTone(n: number | null | undefined): 'ok' | 'loss' | 'neutral' {\n if (n == null || Number.isNaN(n) || n === 0) return 'neutral';\n return n > 0 ? 'ok' : 'loss';\n}\n\nconst STAT_VALUE_SIZE = { sm: 'text-base', md: 'text-xl', lg: 'text-2xl' } as const;\nconst STAT_SKELETON = { sm: 'h-6', md: 'h-7', lg: 'h-8' } as const;\nconst STAT_TONE = { ok: 'text-th-ok', loss: 'text-th-loss', warn: 'text-th-warn', neutral: 'text-th-hi' } as const;\n\n// Set by StatGrid so each Stat renders a <div> of <dt>/<dd> inside its <dl>.\nconst InStatGrid = createContext(false);\n\nexport interface StatProps {\n /** What the number is: \"Open positions\", \"Uptime (30d)\". */\n label: ReactNode;\n /** The number, already formatted (\"$12,480\", \"99.95%\"). */\n value: ReactNode;\n /** A quiet line under the value: a change, a date, a unit. */\n sub?: ReactNode;\n /** Colors the value: ok for gains, loss for losses, warn for attention. Use\n * signTone(n) for signed numbers. */\n tone?: 'ok' | 'loss' | 'warn' | 'neutral';\n /** An explanation shown in a tooltip on the label (dotted underline). */\n tip?: ReactNode;\n /** Value size: sm 16px, md 20px (default), lg 24px. */\n size?: keyof typeof STAT_VALUE_SIZE;\n /** card: a small Card (default). inset: a grey box for use inside a card. plain: no box. */\n variant?: 'card' | 'inset' | 'plain';\n /** Skeleton bars of the same size instead of the value and sub. */\n loading?: boolean;\n className?: string;\n}\n\n/** One labelled number. Inside a StatGrid it is a row of the grid's <dl>; on its own it\n * renders its own <dl>. */\nexport function Stat({\n label,\n value,\n sub,\n tone = 'neutral',\n tip,\n size = 'md',\n variant = 'card',\n loading = false,\n className,\n}: StatProps) {\n const inGrid = useContext(InStatGrid);\n // hi3 clears 4.5:1 on bg and surface only; on the elevated inset box the quiet text is hi2.\n const quiet = variant === 'inset' ? 'text-th-hi2' : 'text-th-hi3';\n const body = (\n <>\n <dt className={cn('text-xs', quiet)}>\n {tip ? (\n <Tooltip tip={tip} variant=\"hint\">\n {label}\n </Tooltip>\n ) : (\n label\n )}\n </dt>\n {loading ? (\n <dd className=\"mt-1\" aria-busy=\"true\">\n <Skeleton className={cn('w-24', STAT_SKELETON[size])} />\n {sub ? <Skeleton className=\"mt-1.5 h-3 w-16\" /> : null}\n </dd>\n ) : (\n <>\n <dd\n className={cn(\n 'mt-0.5 font-semibold tabular-nums tracking-tight [overflow-wrap:anywhere]',\n STAT_VALUE_SIZE[size],\n STAT_TONE[tone],\n )}\n >\n {value}\n </dd>\n {sub ? <dd className={cn('mt-0.5 text-xs', quiet)}>{sub}</dd> : null}\n </>\n )}\n </>\n );\n const Box = inGrid ? 'div' : 'dl';\n if (variant === 'card') {\n return (\n <Card padding=\"sm\" className={cn('min-w-0', className)}>\n {inGrid ? body : <dl>{body}</dl>}\n </Card>\n );\n }\n return <Box className={cn('min-w-0', variant === 'inset' && 'rounded-lg bg-th-elevated p-3', className)}>{body}</Box>;\n}\n\nconst GRID_BASE = { 1: 'grid-cols-1', 2: 'grid-cols-2', 3: 'grid-cols-3', 4: 'grid-cols-4' } as const;\nconst GRID_MD = {\n 2: 'md:grid-cols-2',\n 3: 'md:grid-cols-3',\n 4: 'md:grid-cols-4',\n 5: 'md:grid-cols-5',\n 6: 'md:grid-cols-6',\n} as const;\n\nexport interface StatGridProps {\n /** Columns on phones (base, default 2) and from 768px (md, default 4). */\n cols?: { base?: keyof typeof GRID_BASE; md?: keyof typeof GRID_MD };\n /** Stat elements. */\n children: ReactNode;\n className?: string;\n}\n\n/** A responsive grid of Stats, rendered as one <dl>. */\nexport function StatGrid({ cols, children, className }: StatGridProps) {\n return (\n <dl className={cn('grid gap-3', GRID_BASE[cols?.base ?? 2], GRID_MD[cols?.md ?? 4], className)}>\n <InStatGrid.Provider value={true}>{children}</InStatGrid.Provider>\n </dl>\n );\n}\n\n// =====================================================================================\n// Meter, toneFor\n// =====================================================================================\n\n/** ok, warn or loss for a value against two thresholds. When loss is above warn, higher\n * is worse (disk use: { warn: 75, loss: 90 }). When loss is below warn, lower is worse\n * (battery: { warn: 30, loss: 10 }). */\nexport function toneFor(value: number, t: { warn: number; loss: number }): 'ok' | 'warn' | 'loss' {\n if (t.loss >= t.warn) return value >= t.loss ? 'loss' : value >= t.warn ? 'warn' : 'ok';\n return value <= t.loss ? 'loss' : value <= t.warn ? 'warn' : 'ok';\n}\n\ntype ChartTone = `chart-${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8}`;\nexport type MeterTone = 'accent' | 'ok' | 'warn' | 'loss' | 'info' | 'neutral' | ChartTone;\n\nconst METER_FILL: Record<MeterTone, string> = {\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n info: 'bg-th-info-fill',\n neutral: 'bg-th-hi3',\n 'chart-1': 'bg-th-chart-1',\n 'chart-2': 'bg-th-chart-2',\n 'chart-3': 'bg-th-chart-3',\n 'chart-4': 'bg-th-chart-4',\n 'chart-5': 'bg-th-chart-5',\n 'chart-6': 'bg-th-chart-6',\n 'chart-7': 'bg-th-chart-7',\n 'chart-8': 'bg-th-chart-8',\n};\n\nconst METER_THICK = { xs: 'h-1', sm: 'h-1.5', md: 'h-2.5' } as const;\nconst METER_THICK_V = { xs: 'w-1', sm: 'w-1.5', md: 'w-2.5' } as const;\n\nexport interface MeterProps {\n /** The current value, between min and max (clamped). */\n value: number;\n /** Default 0. */\n min?: number;\n /** Default 100. */\n max?: number;\n /** Accessible name: what is being measured (\"Disk used\"). Required, since the bar has no text. */\n label: string;\n /** Fill color. Overrides thresholds. Default: from thresholds, else accent. neutral:\n * a gray fill for a quantity with no status meaning (swap, a share of a total). */\n tone?: MeterTone;\n /** Picks ok, warn or loss from the value (see toneFor) when tone is not given. */\n thresholds?: { warn: number; loss: number };\n /** Bar thickness: xs 4px, sm 6px (default), md 10px. */\n size?: keyof typeof METER_THICK;\n /** vertical fills from the bottom; give the meter a height (className=\"h-16\"). */\n orientation?: 'horizontal' | 'vertical';\n /** Track color: elevated on a surface (default), overlay when the meter sits on an\n * elevated box. */\n track?: 'elevated' | 'overlay';\n /** meter: a measurement (role=\"meter\"). progress: work being done (role=\"progressbar\"). */\n kind?: 'meter' | 'progress';\n /** Shows the rounded percentage beside a horizontal bar. */\n showValue?: boolean;\n className?: string;\n}\n\n/** A thin bar showing how full something is: disk, quota, progress, a score. */\nexport function Meter({\n value,\n min = 0,\n max = 100,\n label,\n tone,\n thresholds,\n size = 'sm',\n orientation = 'horizontal',\n track = 'elevated',\n kind = 'meter',\n showValue = false,\n className,\n}: MeterProps) {\n const span = max - min || 1;\n const clamped = Math.min(Math.max(value, min), max);\n const pct = ((clamped - min) / span) * 100;\n const resolved: MeterTone = tone ?? (thresholds ? toneFor(clamped, thresholds) : 'accent');\n const vertical = orientation === 'vertical';\n const bar = (\n <div\n role={kind === 'progress' ? 'progressbar' : 'meter'}\n aria-label={label}\n aria-valuemin={min}\n aria-valuemax={max}\n aria-valuenow={clamped}\n aria-valuetext={`${Math.round(pct)}%`}\n className={cn(\n 'relative shrink-0 overflow-hidden rounded-full',\n track === 'overlay' ? 'bg-th-overlay' : 'bg-th-elevated',\n vertical ? cn('h-full', METER_THICK_V[size]) : cn('w-full', METER_THICK[size]),\n !showValue && className,\n )}\n >\n <div\n className={cn(\n 'absolute rounded-full duration-300 ease-out motion-reduce:transition-none',\n vertical ? 'inset-x-0 bottom-0 transition-[height]' : 'inset-y-0 left-0 transition-[width]',\n METER_FILL[resolved],\n )}\n style={vertical ? { height: `${pct}%` } : { width: `${pct}%` }}\n />\n </div>\n );\n if (!showValue || vertical) return bar;\n return (\n <div className={cn('flex w-full items-center gap-2', className)}>\n {bar}\n <span aria-hidden=\"true\" className=\"w-9 shrink-0 text-right text-xs tabular-nums text-th-hi3\">\n {Math.round(pct)}%\n </span>\n </div>\n );\n}\n\n// =====================================================================================\n// Sparkline\n// =====================================================================================\n\nexport type SparklineTone = ChartTone | 'accent' | 'ok' | 'warn' | 'loss' | 'info';\n\nconst SPARK_TONE: Record<SparklineTone, string> = {\n accent: 'text-th-accent',\n ok: 'text-th-ok-fill',\n warn: 'text-th-warn-fill',\n loss: 'text-th-loss-fill',\n info: 'text-th-info-fill',\n 'chart-1': 'text-th-chart-1',\n 'chart-2': 'text-th-chart-2',\n 'chart-3': 'text-th-chart-3',\n 'chart-4': 'text-th-chart-4',\n 'chart-5': 'text-th-chart-5',\n 'chart-6': 'text-th-chart-6',\n 'chart-7': 'text-th-chart-7',\n 'chart-8': 'text-th-chart-8',\n};\n\nexport interface SparklineProps {\n /** The series, oldest first. null leaves a gap (a missed check, a closed market). */\n values: (number | null)[];\n /** Accessible name, ideally with the trend: \"Response time, last 24 hours, 120 to 180 ms\". */\n label: string;\n /** Line color. Default chart-1. */\n tone?: SparklineTone;\n /** Width in px. Default 120; pass className=\"w-full\" to stretch it. */\n width?: number;\n /** Height in px. Default 28. */\n height?: number;\n /** Shades the area under the line. */\n fill?: boolean;\n /** Bottom of the scale. Default: the smallest value. */\n min?: number;\n /** Top of the scale. Default: the largest value. */\n max?: number;\n className?: string;\n}\n\n/** A tiny line chart with no axes, for a trend beside a number. Plain SVG, no chart\n * library. Gaps at nulls; a flat dashed line when there is no data. */\nexport function Sparkline({\n values,\n label,\n tone = 'chart-1',\n width = 120,\n height = 28,\n fill = false,\n min,\n max,\n className,\n}: SparklineProps) {\n const nums = values.filter((v): v is number => v != null && Number.isFinite(v));\n const empty = nums.length === 0;\n const lo = min ?? (empty ? 0 : Math.min(...nums));\n const hi = max ?? (empty ? 1 : Math.max(...nums));\n const pad = 2; // keep the stroke inside the box at the extremes\n const x = (i: number) => (values.length <= 1 ? width / 2 : (i / (values.length - 1)) * width);\n const y = (v: number) => (hi === lo ? height / 2 : pad + (1 - (v - lo) / (hi - lo)) * (height - 2 * pad));\n\n // One path per unbroken run; a single point becomes a zero-length round-capped dot.\n const runs: { x: number; y: number }[][] = [];\n let run: { x: number; y: number }[] = [];\n values.forEach((v, i) => {\n if (v == null || !Number.isFinite(v)) {\n if (run.length) runs.push(run);\n run = [];\n } else run.push({ x: x(i), y: y(v) });\n });\n if (run.length) runs.push(run);\n\n const line = (r: { x: number; y: number }[]) =>\n r.length === 1 ? `M${r[0].x},${r[0].y}h0` : r.map((p, i) => `${i ? 'L' : 'M'}${p.x},${p.y}`).join('');\n const area = (r: { x: number; y: number }[]) =>\n r.length < 2 ? '' : `${line(r)}L${r[r.length - 1].x},${height}L${r[0].x},${height}Z`;\n\n return (\n <svg\n role=\"img\"\n aria-label={empty ? `${label}: no data` : label}\n width={width}\n height={height}\n viewBox={`0 0 ${width} ${height}`}\n preserveAspectRatio=\"none\"\n className={cn('block shrink-0 overflow-visible', empty ? 'text-th-line-strong' : SPARK_TONE[tone], className)}\n >\n {empty ? (\n <path\n d={`M0,${height / 2}H${width}`}\n stroke=\"currentColor\"\n strokeWidth={1.5}\n strokeDasharray=\"3 3\"\n vectorEffect=\"non-scaling-stroke\"\n />\n ) : (\n <>\n {fill ? runs.map((r, i) => <path key={`a${i}`} d={area(r)} fill=\"currentColor\" fillOpacity={0.15} />) : null}\n {runs.map((r, i) => (\n <path\n key={i}\n d={line(r)}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={1.5}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n vectorEffect=\"non-scaling-stroke\"\n />\n ))}\n </>\n )}\n </svg>\n );\n}\n\n// =====================================================================================\n// Disclosure\n// =====================================================================================\n\nexport interface DisclosureProps {\n /** The always-visible row that opens and closes it. */\n summary: ReactNode;\n /** What it reveals. */\n children: ReactNode;\n /** Starts open (uncontrolled). */\n defaultOpen?: boolean;\n /** Controlled open state; pair it with onOpenChange. */\n open?: boolean;\n /** Called with the new state when the reader toggles it. */\n onOpenChange?: (open: boolean) => void;\n /** plain: a bare row (default). card: a bordered surface box. */\n variant?: 'plain' | 'card';\n className?: string;\n}\n\n/** Show-more on native <details>/<summary>: keyboard and find-in-page work for free,\n * with a chevron that turns when open. */\nexport function Disclosure({\n summary,\n children,\n defaultOpen = false,\n open,\n onOpenChange,\n variant = 'plain',\n className,\n}: DisclosureProps) {\n const card = variant === 'card';\n return (\n <details\n // Uncontrolled, React writes defaultOpen once and the element owns the state after;\n // controlled, React writes it whenever `open` changes.\n open={open ?? defaultOpen}\n onToggle={(e) => {\n const now = e.currentTarget.open;\n // Skip the toggle event React's own write of `open` causes.\n if (open === undefined || now !== open) onOpenChange?.(now);\n }}\n className={cn(\n 'group',\n card && 'rounded-xl border border-th-line bg-th-surface shadow-card',\n className,\n )}\n >\n <summary\n className={cn(\n 'flex cursor-pointer list-none items-center gap-2 rounded-lg text-sm font-medium text-th-hi select-none',\n '[&::-webkit-details-marker]:hidden hover:text-th-hi pointer-coarse:min-h-11',\n card ? 'px-4 py-3' : 'py-1.5',\n )}\n >\n <ChevronRightIcon\n size={14}\n className=\"shrink-0 text-th-hi3 transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none\"\n />\n <span className=\"min-w-0 flex-1\">{summary}</span>\n </summary>\n <div className={cn('text-sm text-th-hi2', card ? 'border-t border-th-line px-4 py-3' : 'pb-2 pl-6 pt-1')}>\n {children}\n </div>\n </details>\n );\n}\n\n// =====================================================================================\n// Kbd\n// =====================================================================================\n\n/** A keyboard key or shortcut, e.g. <Kbd>⌘K</Kbd>. */\nexport function Kbd({ className, ...rest }: HTMLAttributes<HTMLElement>) {\n return (\n <kbd\n className={cn(\n 'inline-flex min-w-[1.5em] items-center justify-center rounded border border-th-line-strong bg-th-elevated px-1.5 font-mono text-2xs leading-4 text-th-hi2',\n className,\n )}\n {...rest}\n />\n );\n}\n\n// =====================================================================================\n// copyText, CopyButton\n// =====================================================================================\n\n/** Copies text to the clipboard. Uses the Clipboard API, falling back to a hidden\n * textarea for insecure origins and old browsers. Resolves true when it worked. */\nexport async function copyText(text: string): Promise<boolean> {\n try {\n if (typeof navigator !== 'undefined' && navigator.clipboard && window.isSecureContext) {\n await navigator.clipboard.writeText(text);\n return true;\n }\n } catch {\n // permission denied or not focused: try the fallback\n }\n if (typeof document === 'undefined') return false;\n const ta = document.createElement('textarea');\n ta.value = text;\n ta.setAttribute('readonly', '');\n ta.style.position = 'fixed';\n ta.style.top = '-1000px';\n ta.style.opacity = '0';\n const active = document.activeElement as HTMLElement | null;\n document.body.appendChild(ta);\n ta.select();\n let ok = false;\n try {\n ok = document.execCommand('copy');\n } catch {\n ok = false;\n }\n ta.remove();\n active?.focus?.();\n return ok;\n}\n\nconst COPIED_MS = 1_500;\n\nexport interface CopyButtonProps {\n /** What lands on the clipboard. */\n text: string;\n /** Button text, and the accessible name when iconOnly. Default \"Copy\". */\n label?: string;\n /** Shown for 1.5s after a copy and announced politely. Default \"Copied\". */\n copiedLabel?: string;\n /** A square IconButton instead of a labelled Button. */\n iconOnly?: boolean;\n /** Button size (or IconButton size when iconOnly). Default sm. */\n size?: 'sm' | 'md';\n /** Button variant when not iconOnly. Default secondary. */\n variant?: ButtonProps['variant'];\n /** Called after each copy attempt with whether it worked. */\n onCopy?: (ok: boolean) => void;\n className?: string;\n}\n\n/** Copies text with one click, shows \"Copied\" for 1.5s and tells screen readers. */\nexport function CopyButton({\n text,\n label = 'Copy',\n copiedLabel = 'Copied',\n iconOnly = false,\n size = 'sm',\n variant = 'secondary',\n onCopy,\n className,\n}: CopyButtonProps) {\n const [copied, setCopied] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => () => {\n if (timer.current) clearTimeout(timer.current);\n }, []);\n const onClick = async () => {\n const ok = await copyText(text);\n onCopy?.(ok);\n if (!ok) return;\n setCopied(true);\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(() => setCopied(false), COPIED_MS);\n };\n const iconSize = size === 'sm' ? 14 : 16;\n const icon = copied ? <CheckIcon size={iconSize} className=\"text-th-ok\" /> : <CopyIcon size={iconSize} />;\n return (\n <>\n {iconOnly ? (\n <IconButton label={copied ? copiedLabel : label} size={size} onClick={onClick} className={className}>\n {icon}\n </IconButton>\n ) : (\n <Button variant={variant} size={size} icon={icon} onClick={onClick} className={className}>\n {copied ? copiedLabel : label}\n </Button>\n )}\n <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {copied ? copiedLabel : ''}\n </span>\n </>\n );\n}\n\n// =====================================================================================\n// PageHeader\n// =====================================================================================\n\nexport interface PageHeaderProps {\n /** The page's title. */\n title: ReactNode;\n /** One sentence under the title. */\n description?: ReactNode;\n /** A small line above the title (a section or a breadcrumb). */\n eyebrow?: ReactNode;\n /** A back link above everything, e.g. the app's own\n * <Link className={buttonClass({ variant: 'link' })}>← Jobs</Link>. */\n back?: ReactNode;\n /** Buttons on the right; they wrap under the title on phones. */\n actions?: ReactNode;\n /** Heading level. Default h1. */\n as?: 'h1' | 'h2';\n /** Sticks under the app header (`top: var(--nish-header-h)`) with an opaque background\n * while the page scrolls; a bottom border appears once it is stuck. */\n sticky?: boolean;\n /** Sticky only: under 640px, once stuck, hide the description and show the title as\n * one truncated line, so the bar stays short. Default true. */\n collapseWhenStuck?: boolean;\n className?: string;\n}\n\n/** The title block at the top of a page: optional back link and eyebrow, the title,\n * a description and actions. */\nexport function PageHeader({\n title,\n description,\n eyebrow,\n back,\n actions,\n as: H = 'h1',\n sticky = false,\n collapseWhenStuck = true,\n className,\n}: PageHeaderProps) {\n const ref = useRef<HTMLElement>(null);\n const stuck = useStuck(ref) && sticky;\n const collapsed = stuck && collapseWhenStuck;\n return (\n <header\n ref={ref}\n className={cn(\n 'flex flex-col gap-2',\n sticky &&\n cn(\n 'sticky top-[var(--nish-header-h,0px)] z-20 -mx-[var(--nish-page-gutter,1rem)] border-b bg-th-bg px-[var(--nish-page-gutter,1rem)] py-3',\n stuck ? 'border-th-line' : 'border-transparent',\n ),\n className,\n )}\n >\n {back ? <div className=\"text-sm\">{back}</div> : null}\n <div className=\"flex flex-wrap items-end justify-between gap-x-4 gap-y-3\">\n <div className=\"min-w-0 flex-1 basis-64\">\n {eyebrow ? <p className=\"mb-1 text-xs font-medium uppercase tracking-wider text-th-hi3\">{eyebrow}</p> : null}\n <H\n className={cn(\n 'text-2xl font-semibold tracking-tight text-th-hi [overflow-wrap:anywhere]',\n collapsed && 'max-sm:truncate max-sm:text-base max-sm:[overflow-wrap:normal]',\n )}\n >\n {title}\n </H>\n {description ? <p className={cn('mt-1 text-sm text-th-hi2', collapsed && 'max-sm:hidden')}>{description}</p> : null}\n </div>\n {actions ? <div className=\"flex flex-wrap items-center gap-2\">{actions}</div> : null}\n </div>\n </header>\n );\n}\n\n// =====================================================================================\n// AppHeader\n// =====================================================================================\n\nexport interface AppHeaderProps {\n /** The app's name, shown as the wordmark. */\n name: ReactNode;\n /** An icon before the name, drawn in the accent color. */\n icon?: ReactNode;\n /** Replaces the icon and name, and their home link, with your own node (a profile\n * switcher, a wordmark with a subtitle). It is not wrapped in a link; `name` stays for\n * screen readers. */\n brand?: ReactNode;\n /** Where the \"← nish.software\" pill goes. Default https://nish.software. */\n hubHref?: string;\n /** Buttons before the theme toggle. */\n actions?: ReactNode;\n /** A second row of nav links (use tabClass on each, aria-current on the active one). */\n nav?: ReactNode;\n /** Replaces the default <ThemeToggle />; false hides it. */\n themeToggle?: ReactNode | false;\n /** Sticks to the top of the page. Default true. */\n sticky?: boolean;\n /** Classes for the inner rows, e.g. \"mx-auto max-w-6xl\" to match the page width. */\n innerClassName?: string;\n /** Makes the icon and name one link home (a 44px target), e.g. \"/\". */\n homeHref?: string;\n /** Under 640px show only the icon; the name stays for screen readers, so the pill,\n * actions and theme toggle fit on one row. Needs an icon. */\n hideNameBelow?: 'sm';\n /** Names the nav row's <nav> landmark (\"Trackers\"), so several navs on a page can be\n * told apart. */\n navLabel?: string;\n /** Under 480px the hub pill shrinks to its arrow (.nish-pill-link--compact), for\n * headers with a long name. */\n compactPill?: boolean;\n /** Frosted glass (`bg-th-bg/80 backdrop-blur-xl`) where the browser supports\n * backdrop-filter. Off by default: the header is opaque. */\n glass?: boolean;\n /** Extra MenuItems. From 640px they render after `actions`; under 640px they collapse\n * into a \"More actions\" kebab menu, so the row never wraps. */\n overflowActions?: ReactNode;\n className?: string;\n}\n\n/** A 3-dot \"more\" icon for the overflow kebab. */\nfunction MoreVerticalIcon({ size = 18 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\">\n <circle cx=\"12\" cy=\"5\" r=\"1.8\" />\n <circle cx=\"12\" cy=\"12\" r=\"1.8\" />\n <circle cx=\"12\" cy=\"19\" r=\"1.8\" />\n </svg>\n );\n}\n\n/** The shared app header: the hub pill, the wordmark, actions and the theme toggle,\n * with an optional nav row. Opaque by default (glass is opt-in), safe-area aware. A\n * sticky header publishes its height as `--nish-header-h` for the rest of the layout. */\nexport function AppHeader({\n name,\n icon,\n brand,\n hubHref = 'https://nish.software',\n actions,\n nav,\n themeToggle,\n sticky = true,\n innerClassName,\n homeHref,\n hideNameBelow,\n navLabel,\n compactPill = false,\n glass = false,\n overflowActions,\n className,\n}: AppHeaderProps) {\n const ref = useRef<HTMLElement>(null);\n useHeightVar(ref, '--nish-header-h', sticky);\n const stuck = useStuck(ref) && sticky;\n // From sm the overflow actions sit in the header row, outside any menu: MenuItem renders\n // as a menu row (role=menuitem, tabIndex -1), so make them ordinary tabbable buttons.\n const inlineActionsRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n inlineActionsRef.current?.querySelectorAll<HTMLElement>('[role=\"menuitem\"]').forEach((el) => {\n el.removeAttribute('role');\n el.tabIndex = el.getAttribute('aria-disabled') === 'true' ? -1 : 0;\n });\n });\n const toggle = themeToggle === false ? null : (themeToggle ?? <ThemeToggle />);\n const hideName = hideNameBelow === 'sm' && icon != null;\n const mark = (\n <>\n {icon ? <span className=\"shrink-0 text-th-accent [&>svg]:size-5\">{icon}</span> : null}\n <span className={cn('truncate', hideName && 'max-sm:sr-only')}>{name}</span>\n </>\n );\n const markClass = 'inline-flex min-w-0 items-center gap-2 text-xl font-bold tracking-tight text-th-hi';\n return (\n <header\n ref={ref}\n className={cn(\n 'border-b border-th-line pl-[env(safe-area-inset-left)] pr-[env(safe-area-inset-right)] pt-[env(safe-area-inset-top)]',\n glass ? 'bg-th-bg supports-[backdrop-filter]:bg-th-bg/80 supports-[backdrop-filter]:backdrop-blur-xl' : 'bg-th-bg',\n sticky && 'sticky top-0 z-30 transition-shadow',\n stuck && 'shadow-[var(--nish-shadow-card)]',\n className,\n )}\n >\n <div\n className={cn(\n '@container/header flex min-h-14 flex-nowrap items-center gap-2 px-[var(--nish-page-gutter,1rem)] py-2 sm:gap-3',\n innerClassName,\n )}\n >\n {compactPill ? (\n <a className=\"nish-pill-link nish-pill-link--compact\" href={hubHref} title=\"Back to nish.software\">\n ← <span className=\"nish-pill-link-label\">nish.software</span>\n </a>\n ) : (\n <a\n className=\"nish-pill-link @max-[400px]/header:min-w-11 @max-[400px]/header:justify-center @max-[400px]/header:px-1.5 @max-[400px]/header:[&_.nish-pill-link-label]:sr-only\"\n href={hubHref}\n title=\"Back to nish.software\"\n >\n ← <span className=\"nish-pill-link-label\">nish.software</span>\n </a>\n )}\n {brand != null ? (\n <div className=\"flex min-w-0 items-center\">\n <span className=\"sr-only\">{name}</span>\n {brand}\n </div>\n ) : homeHref != null ? (\n <a href={homeHref} className={cn(markClass, 'min-h-11 min-w-11 rounded-lg', hideName && 'max-sm:justify-center')}>\n {mark}\n </a>\n ) : (\n <span className={markClass}>{mark}</span>\n )}\n <div className=\"ml-auto flex shrink-0 items-center gap-2\">\n {actions}\n {overflowActions ? (\n <>\n <div ref={inlineActionsRef} className=\"hidden items-center gap-2 sm:flex [&>button]:w-auto\">\n {overflowActions}\n </div>\n <div className=\"sm:hidden\">\n <DropdownMenu\n align=\"end\"\n trigger={\n <IconButton label=\"More actions\">\n <MoreVerticalIcon />\n </IconButton>\n }\n >\n {overflowActions}\n </DropdownMenu>\n </div>\n </>\n ) : null}\n {toggle}\n </div>\n </div>\n {nav ? (\n <nav\n aria-label={navLabel}\n className={cn('nish-no-scrollbar -mb-px flex gap-6 overflow-x-auto px-[var(--nish-page-gutter,1rem)]', innerClassName)}\n >\n {nav}\n </nav>\n ) : null}\n </header>\n );\n}\n\n// =====================================================================================\n// SectionHeader\n// =====================================================================================\n\nexport interface SectionHeaderProps {\n /** The section's title. */\n title: ReactNode;\n /** id for the heading, so the section can point aria-labelledby at it. */\n id?: string;\n /** Heading level. Default h2. */\n as?: 'h1' | 'h2' | 'h3';\n /** Quiet text on the right (\"Updated 2 min ago\", \"3 of 12\"). */\n meta?: ReactNode;\n /** A control on the right, after meta (a Button, a Segmented, a link). */\n action?: ReactNode;\n className?: string;\n}\n\n/** The heading row of a section inside a page: the title, with optional meta text\n * and an action on the right. Smaller than PageHeader, larger than CardHeader. */\nexport function SectionHeader({ title, id, as: H = 'h2', meta, action, className }: SectionHeaderProps) {\n return (\n <div className={cn('mb-3 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1', className)}>\n <H id={id} className=\"min-w-0 text-lg font-semibold tracking-tight text-th-hi [overflow-wrap:anywhere]\">\n {title}\n </H>\n {meta != null || action != null ? (\n <div className=\"flex items-center gap-3\">\n {meta != null ? <span className=\"text-sm text-th-hi3\">{meta}</span> : null}\n {action}\n </div>\n ) : null}\n </div>\n );\n}\n\n// =====================================================================================\n// KeyValueList\n// =====================================================================================\n\nexport interface KeyValueItem {\n /** React key; unique in the list. */\n key: string;\n /** The left side: a name, often with a StatusDot or an icon. */\n label: ReactNode;\n /** The right side: a value, a Badge, a status. */\n value: ReactNode;\n /** Let the row wrap instead of staying on one line; it grows taller than 44px (32px\n * dense) when the text wraps. Both the `ul` and `dl` forms.\n * - `true` or `'anywhere'`: a long value with no spaces (a path, a URL, an id). The value\n * cell may shrink and breaks anywhere (`break-all`); the label keeps its width.\n * - `'words'`: prose (a phrase-long status or error). Both cells wrap at word breaks,\n * labels first: the label keeps its one-line width up to 60% of the row\n * (`shrink-0 max-w-[calc(60%-0.75rem)]`), so a short label never wraps one word per\n * line, and the value takes the rest, at least 40% (`min-w-0 flex-1 text-right`). A\n * word splits only when it alone is wider than its cell (`overflow-wrap: anywhere`).\n * Without `wrap` the value keeps its full width, so keep it short. */\n wrap?: boolean | 'anywhere' | 'words';\n}\n\nexport interface KeyValueListProps {\n items: KeyValueItem[];\n /** Rows 32px tall instead of 44px, for dense panels. */\n dense?: boolean;\n /** ul: a list of rows (default). dl: a description list with dt and dd, for label\n * and value pairs that read as \"name: value\". */\n as?: 'ul' | 'dl';\n className?: string;\n}\n\n/** Label and value rows with dividers: services and their status, runner details,\n * vitals. Each row is at least 44px tall (32px dense); an item with `wrap` lets its row\n * wrap and grow: `true`/`'anywhere'` for a path or URL, `'words'` for prose. */\nexport function KeyValueList({ items, dense = false, as = 'ul', className }: KeyValueListProps) {\n // A wrapping row gets vertical padding so wrapped lines clear the dividers; a single\n // line still fits inside the 44px (32px dense) minimum, so its height is unchanged.\n const row = (wrap: KeyValueItem['wrap']) =>\n cn(\n 'flex min-w-0 items-center justify-between gap-3 border-b border-th-line last:border-b-0',\n dense ? 'min-h-8' : 'min-h-11',\n wrap && (dense ? 'py-1' : 'py-2'),\n );\n // Cell widths per mode. None: the value keeps its width. anywhere: the value shrinks and\n // breaks anywhere, the label keeps its width. words: both wrap at word breaks; the label\n // does not shrink below its one-line width until it reaches 60% of the row (so a flex\n // shrink never tips \"Earnings Calendar\" onto two lines), and the value fills the rest.\n const labelCls = (wrap: KeyValueItem['wrap']) =>\n wrap === 'words'\n ? 'min-w-0 shrink-0 max-w-[calc(60%_-_0.75rem)] [overflow-wrap:anywhere]'\n : wrap\n ? 'shrink-0'\n : 'min-w-0';\n const valueCls = (wrap: KeyValueItem['wrap']) =>\n wrap === 'words' ? 'min-w-0 flex-1 [overflow-wrap:anywhere]' : wrap ? 'min-w-0 break-all' : 'shrink-0';\n if (as === 'dl') {\n return (\n <dl className={cn('grid text-sm text-th-hi', className)}>\n {items.map((it) => (\n <div key={it.key} className={row(it.wrap)}>\n <dt className={cn('text-th-hi2', labelCls(it.wrap))}>{it.label}</dt>\n <dd className={cn('m-0 text-right', valueCls(it.wrap))}>{it.value}</dd>\n </div>\n ))}\n </dl>\n );\n }\n return (\n <ul className={cn('grid text-sm text-th-hi', className)}>\n {items.map((it) => (\n <li key={it.key} className={row(it.wrap)}>\n <span className={cn('flex items-center gap-2', labelCls(it.wrap))}>{it.label}</span>\n <span className={cn('flex items-center justify-end gap-2 text-right', valueCls(it.wrap))}>\n {it.value}\n </span>\n </li>\n ))}\n </ul>\n );\n}\n\n// =====================================================================================\n// ChartLegend\n// =====================================================================================\n\nexport type ChartLegendTone = ChartTone | 'accent' | 'ok' | 'warn' | 'loss' | 'info';\n\n// Full literal class names, so Tailwind's scanner finds every one. Marks use -fill.\nconst LEGEND_FILL: Record<ChartLegendTone, string> = {\n 'chart-1': 'bg-th-chart-1',\n 'chart-2': 'bg-th-chart-2',\n 'chart-3': 'bg-th-chart-3',\n 'chart-4': 'bg-th-chart-4',\n 'chart-5': 'bg-th-chart-5',\n 'chart-6': 'bg-th-chart-6',\n 'chart-7': 'bg-th-chart-7',\n 'chart-8': 'bg-th-chart-8',\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n info: 'bg-th-info-fill',\n};\n\nexport interface ChartLegendItem {\n /** The series name. */\n label: string;\n /** The series color, the same role the chart draws it in. */\n tone: ChartLegendTone;\n}\n\nexport interface ChartLegendProps {\n items: ChartLegendItem[];\n /** line: a short 3px x 10px stroke, for line charts (default). dot: an 8px dot, for\n * bars and points. */\n marker?: 'line' | 'dot';\n /** Accessible name of the list. Default \"Legend\". */\n label?: string;\n className?: string;\n}\n\n/** The key for a multi-series chart (uPlot and canvas charts draw none of their own):\n * each series' color mark and name. The marks are decorative; the names carry it. */\nexport function ChartLegend({ items, marker = 'line', label = 'Legend', className }: ChartLegendProps) {\n return (\n <ul aria-label={label} className={cn('flex flex-wrap gap-x-4 gap-y-1 text-xs text-th-hi2', className)}>\n {items.map((it) => (\n <li key={it.label} className=\"inline-flex items-center gap-1.5\">\n <i\n aria-hidden=\"true\"\n className={cn('inline-block shrink-0', marker === 'dot' ? 'size-2 rounded-full' : 'h-0.75 w-2.5 rounded-sm', LEGEND_FILL[it.tone])}\n />\n {it.label}\n </li>\n ))}\n </ul>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { CanvasGroup } from './types';\nimport type { CanvasLayout } from './layout';\nimport type { Box } from './route';\nimport { centerOn, clampK, type View } from './view';\n\nexport interface FollowTarget {\n id: string;\n label: string;\n group: string;\n note?: string;\n box: Box;\n /** The node's group box; on a phone the camera centers x on it so the group is not cut off. */\n groupBox?: Box;\n at: number;\n}\n\nexport interface FollowStep {\n /** 'all': every active node is in view (`targets`); 'one': visiting a single node (`targets` holds just that one); 'idle': nothing active. */\n view: View;\n targets: FollowTarget[];\n mode: 'all' | 'one' | 'idle';\n}\n\nconst CYCLE_MS = 6000;\nconst BBOX_PAD = 80;\nconst VIEW_PAD = 96; // 2 x FIT_PAD\nconst PHONE_W = 600;\nconst PHONE_TOP = 0.45;\n\n/** Active nodes newest first (activeAt desc, missing = 0; ties keep layout order: group order, then node order). */\nexport function followTargets(groups: CanvasGroup[], layout: CanvasLayout): FollowTarget[] {\n const out: FollowTarget[] = [];\n for (const g of groups) {\n for (const n of g.nodes) {\n const box = layout.nodes[n.id];\n if (!n.active || !box) continue;\n out.push({ id: n.id, label: n.label, group: g.title, note: n.note, box, groupBox: layout.groups[g.id], at: n.activeAt ?? 0 });\n }\n }\n // Array.prototype.sort is stable, so equal times keep layout order.\n return out.sort((a, b) => b.at - a.at);\n}\n\n/** `view` for centering a world rect at zoom `k`; on a phone the center sits in the top 45% of the viewport (the drawer may cover the rest). */\nfunction place(w: number, h: number, k: number, box: Box, groupBox?: Box, top = 0): View {\n const v = centerOn(w, h, k, box);\n if (w >= PHONE_W) return v;\n // Never let the box head slide under the overlay row (`top` px): center at max(22.5% of h, top + half the box).\n const y = Math.max((h * PHONE_TOP) / 2, top + (box.h * k) / 2) - (box.y + box.h / 2) * k;\n // Center x on the node's group when the group fits the width, so its title and left cards stay on screen.\n if (groupBox && groupBox.w * k <= w - 24) return { ...v, x: w / 2 - (groupBox.x + groupBox.w / 2) * k, y };\n return { ...v, y };\n}\n\n/** The view for step `i` (0-based) of following `targets` in a w x h viewport. */\nexport function followStep(targets: FollowTarget[], i: number, w: number, h: number, fit: View, top = 0): FollowStep {\n if (targets.length === 0) return { mode: 'idle', view: fit, targets: [] };\n const phone = w < PHONE_W;\n const single = phone ? 0.8 : 1;\n if (targets.length === 1) {\n return { mode: 'all', targets, view: place(w, h, single, targets[0]!.box, targets[0]!.groupBox, top) };\n }\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (const t of targets) {\n x0 = Math.min(x0, t.box.x);\n y0 = Math.min(y0, t.box.y);\n x1 = Math.max(x1, t.box.x + t.box.w);\n y1 = Math.max(y1, t.box.y + t.box.h);\n }\n const bbox: Box = { x: x0 - BBOX_PAD, y: y0 - BBOX_PAD, w: x1 - x0 + 2 * BBOX_PAD, h: y1 - y0 + 2 * BBOX_PAD };\n const kAll = Math.min((w - VIEW_PAD) / bbox.w, (h - VIEW_PAD) / bbox.h, 1.1);\n if (kAll >= (phone ? 0.55 : 0.75)) {\n return { mode: 'all', targets, view: place(w, h, clampK(kAll), bbox, undefined, top) };\n }\n const target = targets[((i % targets.length) + targets.length) % targets.length]!;\n return { mode: 'one', targets: [target], view: place(w, h, single, target.box, target.groupBox, top) };\n}\n\n// Sorted, so a reorder by activeAt alone (same set of ids) does not count as a change and re-fly.\nexport const followSignature = (targets: FollowTarget[]) => targets.map((t) => t.id).sort().join('|');\nconst captionKey = (targets: FollowTarget[]) => targets.map((t) => `${t.id}:${t.label}:${t.group}:${t.note ?? ''}`).join('|');\n\n/** While `on`, flies the camera to the active nodes: on switch-on, when the set of active ids\n * changes, when the layout or viewport changes, and every 6 s while visiting one at a time.\n * Data polls that leave the active ids alone do not fly. */\nexport function useFollow(o: {\n on: boolean;\n groups: CanvasGroup[];\n layout: CanvasLayout;\n size: { w: number; h: number };\n fit: () => View;\n /** Height in px of the overlay row (legend) a phone view keeps clear. */\n inset?: number;\n fly: (v: View) => void;\n}): { step: FollowStep | null } {\n const { on, groups, layout, size } = o;\n const latest = useRef(o);\n useEffect(() => {\n latest.current = o;\n });\n const index = useRef(0);\n /** The piece shown in 'one' mode, by id. */\n const visiting = useRef<string | null>(null);\n const [step, setStep] = useState<FollowStep | null>(null);\n\n const targets = on ? followTargets(groups, layout) : [];\n const sig = followSignature(targets);\n const caption = captionKey(targets);\n\n // The visiting index restarts only when follow turns on or the active ids change, not on a resize or relayout.\n const indexKey = useRef('');\n useEffect(() => {\n if (!on) {\n indexKey.current = '';\n return;\n }\n const key = sig;\n if (indexKey.current !== key) {\n indexKey.current = key;\n index.current = 0;\n visiting.current = null;\n }\n let timer: ReturnType<typeof setInterval> | undefined;\n const run = (advance: boolean) => {\n const cur = latest.current;\n const ts = followTargets(cur.groups, cur.layout);\n // The order is newest first, so it shifts as activity times change: find the piece being\n // visited by id, not by its old position, and step to the one after it.\n const at = visiting.current ? ts.findIndex((t) => t.id === visiting.current) : -1;\n index.current = at < 0 ? 0 : advance ? at + 1 : at;\n const next = followStep(ts, index.current, cur.size.w, cur.size.h, cur.fit(), cur.inset ?? 0);\n visiting.current = next.mode === 'one' ? (next.targets[0]?.id ?? null) : null;\n setStep(next);\n cur.fly(next.view);\n if (next.mode === 'one' && timer === undefined) timer = setInterval(() => run(true), CYCLE_MS);\n if (next.mode !== 'one' && timer !== undefined) {\n clearInterval(timer);\n timer = undefined;\n }\n };\n run(false);\n return () => {\n if (timer !== undefined) clearInterval(timer);\n };\n }, [on, sig, layout, size.w, size.h]);\n\n // Keep the caption's text fresh when a poll changes a note without changing which ids are active.\n useEffect(() => {\n if (!on) return;\n const cur = latest.current;\n const ts = followTargets(cur.groups, cur.layout);\n setStep((prev) => {\n if (!prev || prev.mode === 'idle') return prev;\n // 'one' keeps showing the piece the view is on (by id), with its fresh note; 'all' shows every active piece.\n const fresh = prev.mode === 'one' ? ts.filter((t) => t.id === visiting.current) : ts;\n if (fresh.length === 0 || captionKey(prev.targets) === captionKey(fresh)) return prev;\n return { ...prev, targets: fresh };\n });\n }, [on, caption]);\n\n return { step: on ? step : null };\n}\n","// View math: a view is the world-to-screen transform, screen = world * k + (x, y).\n\nexport interface View {\n x: number;\n y: number;\n k: number;\n}\n\nexport const MIN_K = 0.3;\nexport const MAX_K = 2;\nexport const PHONE_K = 0.55;\nexport const PHONE_MAX_W = 600; // viewports narrower than this keep the readable phone zoom when fit is small\nexport const FIT_PAD = 48;\nexport const TITLE_ROOM = 36; // world px above y=0 taken by the column titles\nexport const LABEL_K = 0.8;\nexport const ANIM_MS = 300;\nexport const FOLLOW_MS = 700; // follow mode's fly\nexport const LOD_K = 0.6; // below this zoom the cards drop their details\nexport const DOUBLE_MS = 300; // two taps this close make a double-tap\nexport const DOUBLE_PX = 10;\nexport const DRAG_PX = 4;\nexport const KEY_PAN = 48;\nexport const ZOOM_STEP = 1.25;\n\nexport const clampK = (k: number) => Math.min(MAX_K, Math.max(MIN_K, k));\nexport const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);\n\n/** The view after zooming to `k` while keeping the world point under (px, py) fixed. */\nexport function zoomAround(v: View, k: number, px: number, py: number): View {\n const nk = clampK(k);\n const r = nk / v.k;\n return { k: nk, x: px - (px - v.x) * r, y: py - (py - v.y) * r };\n}\n\nexport function centerOn(w: number, h: number, k: number, box: { x: number; y: number; w: number; h: number }): View {\n return { k, x: w / 2 - (box.x + box.w / 2) * k, y: h / 2 - (box.y + box.h / 2) * k };\n}\n","import type { ReactNode, SVGProps } from 'react';\nimport type { CanvasNodeKind } from './types';\n\nexport function Svg({ children, ...rest }: SVGProps<SVGSVGElement>) {\n return (\n <svg\n width={16}\n height={16}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...rest}\n >\n {children}\n </svg>\n );\n}\n\nexport const KIND_ICON: Record<CanvasNodeKind, ReactNode> = {\n ui: (\n <>\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M3 9h18\" />\n </>\n ),\n service: (\n <>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"7\" rx=\"2\" />\n <rect x=\"3\" y=\"14\" width=\"18\" height=\"7\" rx=\"2\" />\n <path d=\"M7 6.5h.01M7 17.5h.01\" />\n </>\n ),\n worker: (\n <>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n <path d=\"M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4\" />\n </>\n ),\n library: (\n <>\n <path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\" />\n <path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\" />\n </>\n ),\n infra: <path d=\"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z\" />,\n data: (\n <>\n <ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\" />\n <path d=\"M3 5v14a9 3 0 0 0 18 0V5\" />\n <path d=\"M3 12a9 3 0 0 0 18 0\" />\n </>\n ),\n tool: <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z\" />,\n docs: (\n <>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <path d=\"M14 2v6h6M8 13h8M8 17h5\" />\n </>\n ),\n};\n\nexport const PlusIcon = () => (\n <Svg>\n <path d=\"M12 5v14M5 12h14\" />\n </Svg>\n);\nexport const MinusIcon = () => (\n <Svg>\n <path d=\"M5 12h14\" />\n </Svg>\n);\nexport const FitIcon = () => (\n <Svg>\n <path d=\"M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3\" />\n <rect x=\"8\" y=\"8\" width=\"8\" height=\"8\" rx=\"1\" />\n </Svg>\n);\nexport const FollowIcon = () => (\n <Svg>\n <circle cx=\"12\" cy=\"12\" r=\"7\" />\n <path d=\"M12 2v3M12 19v3M2 12h3M19 12h3\" />\n <circle cx=\"12\" cy=\"12\" r=\"1.5\" fill=\"currentColor\" />\n </Svg>\n);\n","import type { CanvasEdge, CanvasGroup, CanvasLayoutMode } from \"./types\";\nimport { FIT_PAD, PHONE_K, PHONE_MAX_W } from \"./view\";\n\n// =====================================================================================\n// Layout\n// =====================================================================================\n\nexport interface CanvasLayout {\n mode: \"columns\" | \"bands\";\n width: number;\n height: number;\n /** World px above y = 0 taken by the headers: 36 in \"columns\" (titles sit above the cards), 0 in \"bands\" (titles sit inside). */\n titleRoom: number;\n /** Top-left of each column's (\"columns\") or band's (\"bands\") title, world px; `index` is the column or band value. */\n headers: { index: number; x: number; y: number }[];\n groups: Record<string, { x: number; y: number; w: number; h: number }>;\n nodes: Record<string, { x: number; y: number; w: number; h: number }>;\n}\n\nexport const NODE_W = 172;\nexport const NODE_H = 56;\nexport const NODE_GAP = 12;\nexport const GROUP_PAD = 16;\nexport const GROUP_HEAD = 52;\nexport const MIN_COLUMN_STEP = 420;\nexport const CHANNEL_EDGE = 60; // width of the routing channel left of the first and right of the last sub-column\nexport const GROUP_GAP_X = 56; // \"bands\": horizontal gap between groups in a row\nexport const BAND_TITLE = 40; // \"bands\": extra room above a band's first row for its title\n\nconst GAP_MIN = 72; // \"bands\": smallest and largest gap between two rows\nconst GAP_MAX = 240;\nconst COLUMN_TITLE_ROOM = 36;\n\n/** Where every group and node sits, in world units (px at zoom 1). Pure and deterministic.\n *\n * \"columns\" (default): columns are the distinct `column` values in ascending order, groups\n * stack in the order given, nodes sit in a 2-column grid inside their group (1 column for a\n * group of one), and each column is centered against the tallest. The first sub-column starts\n * 60 px in and `width` includes 60 px after the last, which is room for the edge lanes\n * outside the cards.\n *\n * \"bands\": bands are the distinct `band ?? column` values in ascending order, stacked top to\n * bottom; each band wraps its groups (by `column`, then input order) into rows no wider than\n * `width`. The gaps between rows grow with the number of edge ends that need lanes there. */\nexport interface LayoutOptions {\n /** Default \"columns\". */\n mode?: \"columns\" | \"bands\";\n /** \"bands\" only: the widest a row of groups may get, world px (at least one group per row). */\n width?: number;\n /** \"bands\" only: used to size the gaps between rows for the edge lanes. */\n edges?: CanvasEdge[];\n columnGap?: number;\n rowGap?: number;\n}\n\ninterface Size {\n w: number;\n h: number;\n cols: number;\n}\n\nfunction sizeGroups(groups: CanvasGroup[]): Map<string, Size> {\n const sized = new Map<string, Size>();\n for (const g of groups) {\n const cols = g.nodes.length > 1 ? 2 : 1;\n const rows = Math.ceil(g.nodes.length / cols);\n const w = GROUP_PAD * 2 + cols * NODE_W + (cols - 1) * NODE_GAP;\n const h =\n GROUP_HEAD +\n GROUP_PAD +\n (rows > 0 ? rows * NODE_H + (rows - 1) * NODE_GAP : 0);\n sized.set(g.id, { w, h, cols });\n }\n return sized;\n}\n\nfunction placeGroup(\n out: CanvasLayout,\n g: CanvasGroup,\n s: Size,\n x: number,\n y: number,\n) {\n out.groups[g.id] = { x, y, w: s.w, h: s.h };\n g.nodes.forEach((n, i) => {\n out.nodes[n.id] = {\n x: x + GROUP_PAD + (i % s.cols) * (NODE_W + NODE_GAP),\n y: y + GROUP_HEAD + Math.floor(i / s.cols) * (NODE_H + NODE_GAP),\n w: NODE_W,\n h: NODE_H,\n };\n });\n}\n\ninterface Row {\n band: number;\n firstOfBand: boolean;\n list: CanvasGroup[];\n w: number;\n h: number;\n}\n\nfunction layoutBands(\n groups: CanvasGroup[],\n width: number,\n edges: CanvasEdge[],\n): CanvasLayout {\n const out: CanvasLayout = {\n mode: \"bands\",\n width: 0,\n height: 0,\n titleRoom: 0,\n headers: [],\n groups: {},\n nodes: {},\n };\n if (groups.length === 0) return out;\n const sized = sizeGroups(groups);\n const bandOf = (g: CanvasGroup) => g.band ?? g.column;\n const bandIds = [...new Set(groups.map(bandOf))].sort((a, b) => a - b);\n\n // Rows, filled greedily left to right; a row always holds at least one group.\n const rows: Row[] = [];\n for (const band of bandIds) {\n const members = groups\n .map((g, i) => ({ g, i }))\n .filter((m) => bandOf(m.g) === band)\n .sort((a, b) => a.g.column - b.g.column || a.i - b.i)\n .map((m) => m.g);\n let cur: Row | null = null;\n for (const g of members) {\n const s = sized.get(g.id)!;\n if (cur && cur.w + GROUP_GAP_X + s.w <= width) {\n cur.list.push(g);\n cur.w += GROUP_GAP_X + s.w;\n cur.h = Math.max(cur.h, s.h);\n } else {\n cur = { band, firstOfBand: cur === null, list: [g], w: s.w, h: s.h };\n rows.push(cur);\n }\n }\n }\n\n // Which row every group and node is in.\n const rowOf = new Map<string, number>();\n rows.forEach((r, ri) => {\n for (const g of r.list) {\n rowOf.set(g.id, ri);\n for (const n of g.nodes) rowOf.set(n.id, ri);\n }\n });\n\n // Edge ends that need a lane in the gap between row r and r + 1, counted by distinct id per\n // direction: the source end just below its row, the target end just above its row.\n const ends: Set<string>[] = Array.from(\n { length: Math.max(0, rows.length - 1) },\n () => new Set<string>(),\n );\n for (const e of edges) {\n const s = rowOf.get(e.from);\n const t = rowOf.get(e.to);\n if (s === undefined || t === undefined || s === t) continue;\n if (s < t) {\n ends[s]!.add(`df:${e.from}`);\n ends[t - 1]!.add(`dt:${e.to}`);\n } else {\n ends[s - 1]!.add(`uf:${e.from}`);\n ends[t]!.add(`ut:${e.to}`);\n }\n }\n\n const widest = rows.reduce((m, r) => Math.max(m, r.w), 0);\n out.width = CHANNEL_EDGE + widest + CHANNEL_EDGE;\n let y = CHANNEL_EDGE + BAND_TITLE;\n rows.forEach((r, ri) => {\n if (ri > 0) {\n const gap = Math.min(\n GAP_MAX,\n Math.max(GAP_MIN, 40 + 8 * ends[ri - 1]!.size),\n );\n y += gap + (r.firstOfBand ? BAND_TITLE : 0);\n }\n let x = CHANNEL_EDGE + (widest - r.w) / 2;\n r.list.forEach((g, gi) => {\n const s = sized.get(g.id)!;\n placeGroup(out, g, s, x, y);\n if (r.firstOfBand && gi === 0)\n out.headers.push({ index: r.band, x, y: y - 12 }); // the header's bottom edge sits here (see system-canvas.tsx), clear of arrowheads\n x += s.w + GROUP_GAP_X;\n });\n if (ri === rows.length - 1) out.height = y + r.h + CHANNEL_EDGE;\n y += r.h;\n });\n return out;\n}\n\nexport function layoutSystem(\n groups: CanvasGroup[],\n o: LayoutOptions = {},\n): CanvasLayout {\n if (o.mode === \"bands\")\n return layoutBands(groups, o.width ?? 0, o.edges ?? []);\n const columnGap = o.columnGap ?? 120;\n const rowGap = o.rowGap ?? 40;\n const columns = [...new Set(groups.map((g) => g.column))].sort(\n (a, b) => a - b,\n );\n const sized = sizeGroups(groups);\n const stackHeight = (list: CanvasGroup[]) =>\n list.reduce((sum, g) => sum + sized.get(g.id)!.h, 0) +\n Math.max(0, list.length - 1) * rowGap;\n const whole = columns.map((c) => groups.filter((g) => g.column === c));\n const sorted = whole.map(stackHeight).sort((a, b) => a - b);\n const median =\n sorted.length === 0 ? 0 : sorted[Math.floor(sorted.length / 2)]!;\n // A column taller than 1.5x the median wraps into 2 or 3 sub-columns (order kept) so the whole\n // map stays close to the viewport's aspect ratio.\n const members: CanvasGroup[][] = [];\n for (const list of whole) {\n const h = stackHeight(list);\n const parts =\n median > 0 && list.length > 1\n ? Math.min(3, list.length, Math.ceil(h / (median * 1.5)))\n : 1;\n if (parts <= 1) {\n members.push(list);\n continue;\n }\n const goal = h / parts;\n let cur: CanvasGroup[] = [];\n let cuts = 0;\n for (const g of list) {\n if (\n cur.length > 0 &&\n cuts < parts - 1 &&\n stackHeight(cur) + rowGap + sized.get(g.id)!.h / 2 > goal\n ) {\n members.push(cur);\n cur = [];\n cuts++;\n }\n cur.push(g);\n }\n members.push(cur);\n }\n const heights = members.map(stackHeight);\n const tallest = heights.reduce((m, h) => Math.max(m, h), 0);\n\n const out: CanvasLayout = {\n mode: \"columns\",\n width: 0,\n height: tallest,\n titleRoom: COLUMN_TITLE_ROOM,\n headers: [],\n groups: {},\n nodes: {},\n };\n let x = members.length > 0 ? CHANNEL_EDGE : 0;\n members.forEach((list, ci) => {\n const widest = list.reduce((m, g) => Math.max(m, sized.get(g.id)!.w), 0);\n let y = (tallest - heights[ci]!) / 2;\n for (const g of list) {\n placeGroup(out, g, sized.get(g.id)!, x, y);\n y += sized.get(g.id)!.h + rowGap;\n }\n out.width = Math.max(out.width, x + widest);\n x += Math.max(MIN_COLUMN_STEP, widest + columnGap);\n });\n if (members.length > 0) out.width += CHANNEL_EDGE;\n for (const c of columns) {\n const boxes = groups\n .filter((g) => g.column === c)\n .map((g) => out.groups[g.id]!);\n out.headers.push({\n index: c,\n x: Math.min(...boxes.map((b) => b.x)),\n y: Math.min(...boxes.map((b) => b.y)) - COLUMN_TITLE_ROOM,\n });\n }\n return out;\n}\n\n/** Layouts that do not depend on the viewport: every bands candidate (the row width that fits the\n * n widest groups side by side, n = 1..most groups in a band) and, in \"auto\", the columns layout. */\nexport interface LayoutCandidates {\n mode: CanvasLayoutMode;\n bands: CanvasLayout[];\n columns: CanvasLayout | null;\n}\n\nexport function layoutCandidates(\n groups: CanvasGroup[],\n edges: CanvasEdge[],\n mode: CanvasLayoutMode = \"auto\",\n): LayoutCandidates {\n if (mode === \"columns\")\n return {\n mode,\n bands: [],\n columns: layoutSystem(groups, { mode: \"columns\" }),\n };\n const sized = sizeGroups(groups);\n const widths = groups.map((g) => sized.get(g.id)!.w).sort((a, b) => b - a);\n const perBand = new Map<number, number>();\n for (const g of groups) {\n const b = g.band ?? g.column;\n perBand.set(b, (perBand.get(b) ?? 0) + 1);\n }\n const maxN = Math.max(0, ...perBand.values());\n const rowWidths: number[] = [];\n let sum = 0;\n for (let n = 1; n <= maxN; n++) {\n sum += widths[n - 1]!;\n rowWidths.push(sum + (n - 1) * GROUP_GAP_X);\n }\n if (rowWidths.length === 0) rowWidths.push(0);\n return {\n mode,\n bands: [...new Set(rowWidths)].map((width) =>\n layoutSystem(groups, { mode: \"bands\", width, edges }),\n ),\n columns: mode === \"auto\" ? layoutSystem(groups, { mode: \"columns\" }) : null,\n };\n}\n\n// Only canvases narrower than this are treated as phones (one readable column at the phone zoom).\n// From 480 to 600 px the best-scoring candidate is used unless it would fit below the phone zoom.\nconst PHONE_LAYOUT_W = 480;\n// Below this best score a canvas 600 px or wider also gets the fits-across layout.\nexport const SCROLL_K = 0.35;\n\n/** Picks from `layoutCandidates` for a viewport. Cheap, so it can run on every resize. */\nexport function chooseLayout(\n c: LayoutCandidates,\n viewport: { w: number; h: number },\n): CanvasLayout {\n if (c.mode === \"columns\") return c.columns!;\n const candidates = c.bands;\n if (viewport.w <= 0 || viewport.h <= 0) return candidates[0]!;\n const score = (l: CanvasLayout) => {\n if (l.width <= 0 || l.height <= 0) return 1;\n return Math.min(\n (viewport.w - 2 * FIT_PAD) / l.width,\n (viewport.h - 2 * FIT_PAD) / (l.height + l.titleRoom),\n 1,\n );\n };\n const scores = candidates.map(score);\n const top = Math.max(...scores);\n let best = 0; // ties (within 0.005 of the top score) go to the larger row width\n scores.forEach((s, i) => {\n if (top - s < 0.005) best = i;\n });\n // fitView keeps the phone zoom (PHONE_K) below PHONE_MAX_W when the fit is smaller, so below\n // PHONE_MAX_W use the same threshold here: the widest candidate that fits at the phone zoom.\n // From PHONE_MAX_W up the same happens when even the best candidate would open below\n // SCROLL_K (fitView's overlay insets make the real fit a little smaller than this score):\n // a readable map that fits across and scrolls down beats a whole map too small to read.\n if (\n viewport.w < PHONE_LAYOUT_W ||\n top < (viewport.w < PHONE_MAX_W ? PHONE_K : SCROLL_K)\n ) {\n let pick = candidates[0]!;\n for (const x of candidates) if (x.width * PHONE_K <= viewport.w - 24) pick = x;\n return pick;\n }\n const bands = candidates[best]!;\n if (c.mode === \"bands\" || !c.columns) return bands;\n return score(c.columns) > scores[best]! ? c.columns : bands;\n}\n\n/** The layout to show in a viewport of `viewport` px. \"columns\" and \"bands\" use that mode;\n * \"auto\" picks whichever candidate shows the map biggest. Pure and deterministic. */\nexport function pickLayout(\n groups: CanvasGroup[],\n edges: CanvasEdge[],\n viewport: { w: number; h: number },\n mode: CanvasLayoutMode = \"auto\",\n): CanvasLayout {\n return chooseLayout(layoutCandidates(groups, edges, mode), viewport);\n}\n","import { memo, useEffect, useId, useRef, useState } from 'react';\nimport { cn } from '../../cn';\nimport { Svg } from './icons';\nimport type { CanvasEdgeKind } from './types';\n\nconst DASH: Record<NonNullable<CanvasEdgeKind['line']>, { dash?: string; width: number; cap?: 'round' }> = {\n solid: { width: 1.75 },\n dashed: { dash: '6 5', width: 1.75 },\n dotted: { dash: '0.5 6', width: 2.25, cap: 'round' },\n};\n\nfunction Sample({ line }: { line: CanvasEdgeKind['line'] }) {\n const d = DASH[line ?? 'solid'];\n return (\n <svg width={28} height={10} viewBox=\"0 0 28 10\" aria-hidden=\"true\" focusable=\"false\" className=\"shrink-0\">\n <line x1={2} y1={5} x2={26} y2={5} stroke=\"currentColor\" strokeWidth={d.width} strokeDasharray={d.dash} strokeLinecap={d.cap} />\n </svg>\n );\n}\n\n/** The \"Lines\" button and its panel: one row per edge kind to show or hide it. */\nexport const EdgeLegend = memo(function EdgeLegend({ kinds, hidden, onToggle }: { kinds: CanvasEdgeKind[]; hidden: ReadonlySet<string>; onToggle: (id: string) => void }) {\n const [open, setOpen] = useState(false);\n const rootRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const panelId = useId();\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: PointerEvent) => {\n if (!rootRef.current?.contains(e.target as Node)) setOpen(false);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n e.stopPropagation();\n setOpen(false);\n buttonRef.current?.focus();\n };\n document.addEventListener('pointerdown', onDown, true);\n document.addEventListener('keydown', onKey, true);\n return () => {\n document.removeEventListener('pointerdown', onDown, true);\n document.removeEventListener('keydown', onKey, true);\n };\n }, [open]);\n\n if (kinds.length === 0) return null;\n const nHidden = kinds.filter((k) => hidden.has(k.id)).length;\n\n return (\n <div ref={rootRef} data-canvas-ui className=\"absolute left-3 top-3 z-[5] flex flex-col items-start gap-1.5\">\n <button\n ref={buttonRef}\n type=\"button\"\n aria-expanded={open}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen((o) => !o)}\n className=\"inline-flex h-11 items-center gap-2 rounded-xl border border-th-line bg-th-surface px-3 text-sm text-th-hi shadow-pop outline-none hover:bg-th-elevated focus-visible:ring-2 focus-visible:ring-th-accent\"\n >\n <Svg>\n <path d=\"M3 6h18M3 12h18M3 18h18\" />\n </Svg>\n <span>Lines</span>\n {nHidden > 0 ? <span className=\"text-th-hi3\">· {nHidden} hidden</span> : null}\n </button>\n {open ? (\n <div id={panelId} role=\"menu\" aria-label=\"Lines\" className=\"overflow-hidden rounded-xl border border-th-line bg-th-surface shadow-pop\" style={{ width: 'min(240px, calc(100vw - 24px))' }}>\n {kinds.map((k) => {\n const on = !hidden.has(k.id);\n return (\n <button\n key={k.id}\n type=\"button\"\n role=\"menuitemcheckbox\"\n aria-checked={on}\n onClick={() => onToggle(k.id)}\n className={cn(\n 'flex h-11 w-full items-center gap-3 px-3 text-left text-sm outline-none hover:bg-th-elevated focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-th-accent',\n on ? 'text-th-hi' : 'text-th-hi3',\n )}\n >\n <Sample line={k.line} />\n <span className=\"min-w-0 flex-1 truncate\">{k.label}</span>\n <span aria-hidden=\"true\" className={cn('relative h-5 w-9 shrink-0 rounded-full border transition-colors', on ? 'border-th-accent bg-th-accent' : 'border-th-line-strong bg-th-elevated')}>\n <span className={cn('absolute top-0.5 size-3.5 rounded-full transition-all', on ? 'left-[18px] bg-th-on-accent' : 'left-0.5 bg-th-hi3')} />\n </span>\n </button>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n});\n","import { memo, useCallback, useEffect, useImperativeHandle, useRef, type PointerEvent as ReactPointerEvent, type RefObject } from 'react';\nimport type { CanvasLayout } from './layout';\nimport type { CanvasGroup } from './types';\nimport type { View } from './view';\n\nexport interface MinimapHandle {\n setView(v: View, size: { w: number; h: number }): void;\n}\n\nconst MAP_W = 176;\nconst MAP_MAX_H = 132;\nconst MAP_MIN_H = 60;\nconst MIN_CANVAS_W = 600;\n\nconst hueVar = (hue: string | undefined, soft: boolean) => (hue ? `var(--nish-${hue}${soft ? '-soft' : ''})` : soft ? 'var(--nish-accent-soft)' : 'var(--nish-accent)');\n\n/** A small overview of the whole map with the current view drawn on it. Click or drag to move the view. */\nexport const Minimap = memo(function Minimap({\n layout,\n groups,\n handleRef,\n onJump,\n}: {\n layout: CanvasLayout;\n groups: CanvasGroup[];\n handleRef: RefObject<MinimapHandle | null>;\n onJump: (worldX: number, worldY: number) => void;\n}) {\n const wrapRef = useRef<HTMLDivElement>(null);\n const svgRef = useRef<SVGSVGElement>(null);\n const rectRef = useRef<SVGRectElement>(null);\n const last = useRef<{ v: View; size: { w: number; h: number } } | null>(null);\n\n const totalH = layout.height + layout.titleRoom;\n const ok = layout.width > 0 && totalH > 0;\n const s = ok ? Math.min(MAP_W / layout.width, MAP_MAX_H / totalH) : 1;\n const mapH = ok ? Math.min(MAP_MAX_H, Math.max(MAP_MIN_H, (MAP_W * totalH) / layout.width)) : MAP_MIN_H;\n const ox = (MAP_W - layout.width * s) / 2;\n const oy = (mapH - totalH * s) / 2;\n\n const draw = useCallback(() => {\n const cur = last.current;\n const wrap = wrapRef.current;\n const rect = rectRef.current;\n if (!cur || !wrap || !rect) return;\n const { v, size } = cur;\n wrap.style.display = size.w < MIN_CANVAS_W ? 'none' : '';\n const x0 = Math.max(0, ox + (-v.x / v.k) * s);\n const y0 = Math.max(0, oy + (-v.y / v.k + layout.titleRoom) * s);\n const x1 = Math.min(MAP_W, ox + ((-v.x + size.w) / v.k) * s);\n const y1 = Math.min(mapH, oy + ((-v.y + size.h) / v.k + layout.titleRoom) * s);\n rect.setAttribute('x', String(x0));\n rect.setAttribute('y', String(y0));\n rect.setAttribute('width', String(Math.max(0, x1 - x0)));\n rect.setAttribute('height', String(Math.max(0, y1 - y0)));\n }, [ox, oy, s, mapH, layout.titleRoom]);\n\n useImperativeHandle(\n handleRef,\n () => ({\n setView(v, size) {\n last.current = { v, size };\n draw();\n },\n }),\n [draw],\n );\n\n // The scale changed with a new layout: redraw the view rect from the last view.\n useEffect(() => {\n draw();\n }, [draw]);\n\n const jump = (e: ReactPointerEvent<SVGSVGElement>) => {\n const svg = svgRef.current;\n if (!svg || !ok) return;\n const box = svg.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return;\n const px = ((e.clientX - box.left) / box.width) * MAP_W;\n const py = ((e.clientY - box.top) / box.height) * mapH;\n onJump((px - ox) / s, (py - oy) / s - layout.titleRoom);\n };\n\n return (\n <div\n ref={wrapRef}\n data-canvas-ui\n aria-hidden=\"true\"\n className=\"nish-canvas-minimap absolute right-3 top-3 z-[5] overflow-hidden rounded-xl border border-th-line bg-th-surface shadow-pop\"\n style={{ display: 'none' }}\n >\n <svg\n ref={svgRef}\n width={MAP_W}\n height={mapH}\n viewBox={`0 0 ${MAP_W} ${mapH}`}\n className=\"block cursor-pointer touch-none\"\n onPointerDown={(e) => {\n if (e.button !== 0) return;\n e.currentTarget.setPointerCapture(e.pointerId);\n jump(e);\n }}\n onPointerMove={(e) => {\n if (e.currentTarget.hasPointerCapture(e.pointerId)) jump(e);\n }}\n onPointerUp={(e) => {\n if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);\n }}\n >\n {groups.map((g) => {\n const b = layout.groups[g.id];\n if (!b) return null;\n return (\n <rect\n key={g.id}\n x={ox + b.x * s}\n y={oy + (b.y + layout.titleRoom) * s}\n width={b.w * s}\n height={b.h * s}\n rx={3}\n fill={hueVar(g.hue, true)}\n stroke={hueVar(g.hue, false)}\n strokeWidth={1}\n />\n );\n })}\n {groups.map((g) =>\n g.nodes.map((n) => {\n const b = layout.nodes[n.id];\n if (!n.active || !b) return null;\n return <circle key={n.id} cx={ox + (b.x + b.w / 2) * s} cy={oy + (b.y + b.h / 2 + layout.titleRoom) * s} r={3} fill={hueVar(g.hue, false)} />;\n }),\n )}\n <rect ref={rectRef} x={0} y={0} width={0} height={0} fill=\"var(--nish-accent)\" fillOpacity={0.1} stroke=\"var(--nish-accent)\" strokeWidth={1} />\n </svg>\n </div>\n );\n});\n","import { memo, useLayoutEffect, useRef, type CSSProperties } from 'react';\nimport { TickerText } from '../flow';\nimport { KIND_ICON, Svg } from './icons';\nimport type { CanvasHue, CanvasNode } from './types';\n\nexport function hueStyle(hue: CanvasHue | undefined): CSSProperties {\n return {\n '--c': hue ? `var(--nish-${hue})` : 'var(--nish-accent)',\n '--c-soft': hue ? `var(--nish-${hue}-soft)` : 'var(--nish-accent-soft)',\n } as CSSProperties;\n}\n\ninterface NodeViewProps {\n node: CanvasNode;\n groupTitle: string;\n hue: CanvasHue | undefined;\n box: { x: number; y: number; w: number; h: number };\n selected: boolean;\n /** Hover or selection focus is on something else: fade this card. */\n dim: boolean;\n delay: number;\n onSelect: ((id: string, type: 'node' | 'group') => void) | undefined;\n}\n\nexport const clamp01 = (n: number | undefined) => (n == null || !Number.isFinite(n) ? 0 : Math.min(1, Math.max(0, n)));\n\n/** Plays a one-time \"ping\" when `active` turns on after mount. Sets data-fx on the DOM so a\n * re-render with the same data cannot cut it short. */\nfunction usePing(active: boolean) {\n const ref = useRef<HTMLButtonElement>(null);\n const prev = useRef(active);\n useLayoutEffect(() => {\n const was = prev.current;\n prev.current = active;\n const el = ref.current;\n if (!el || was || !active) return;\n el.removeAttribute('data-fx');\n void el.offsetWidth;\n el.setAttribute('data-fx', 'ping');\n const timer = setTimeout(() => el.removeAttribute('data-fx'), 450);\n return () => clearTimeout(timer);\n }, [active]);\n return ref;\n}\n\nexport const NodeView = memo(\n function NodeView({ node, groupTitle, hue, box, selected, dim, delay, onSelect }: NodeViewProps) {\n const active = !!node.active;\n const heat = clamp01(node.heat);\n const ref = usePing(active);\n const count = node.count ?? 0;\n const style: CSSProperties = {\n ...hueStyle(hue),\n left: box.x,\n top: box.y,\n width: box.w,\n height: box.h,\n '--nish-canvas-delay': `${delay}ms`,\n } as CSSProperties;\n // The afterglow is drawn by the card (`.nish-canvas-node[data-heat]` in base.css), whose rounded\n // corners and border the slot does not have; the slot only carries the values.\n if (!active && heat > 0) {\n const vars = style as Record<string, string>;\n vars['--nish-canvas-heat-line'] = `color-mix(in srgb, var(--c) ${Math.round(heat * 70)}%, var(--nish-line))`;\n vars['--nish-canvas-heat-glow'] = `0 0 ${Math.round(6 + heat * 16)}px color-mix(in srgb, var(--c) ${Math.round(heat * 60)}%, transparent)`;\n }\n const aria = `${node.label}, ${groupTitle}${active ? (node.note ? `, active: ${node.note}` : ', active') : ''}`;\n return (\n <div className=\"nish-canvas-slot\" style={style} data-active={active || undefined} data-dim={dim || undefined}>\n <button\n ref={ref}\n type=\"button\"\n className=\"nish-canvas-node\"\n data-canvas-id={node.id}\n data-active={active || undefined}\n data-selected={selected || undefined}\n data-heat={heat > 0 || undefined}\n aria-label={aria}\n title={node.detail || undefined}\n aria-pressed={selected}\n onClick={() => onSelect?.(node.id, 'node')}\n >\n {node.kind ? (\n <span className=\"nish-canvas-icon\" aria-hidden=\"true\">\n <Svg>{KIND_ICON[node.kind]}</Svg>\n </span>\n ) : null}\n <span className=\"nish-canvas-text\">\n <span className=\"nish-canvas-label\">{node.label}</span>\n {active && node.note ? (\n <span className=\"nish-canvas-note\" aria-hidden=\"true\">\n <TickerText text={node.note} as=\"span\" />\n </span>\n ) : node.detail ? (\n <span className=\"nish-canvas-detail\">{node.detail}</span>\n ) : null}\n </span>\n {count > 1 ? <span className=\"nish-canvas-count\">{count}</span> : null}\n {active ? <span className=\"nish-canvas-live\" aria-hidden=\"true\" /> : null}\n </button>\n </div>\n );\n },\n (a, b) =>\n a.groupTitle === b.groupTitle &&\n a.hue === b.hue &&\n a.selected === b.selected &&\n a.dim === b.dim &&\n a.delay === b.delay &&\n a.onSelect === b.onSelect &&\n a.box.x === b.box.x &&\n a.box.y === b.box.y &&\n a.node.id === b.node.id &&\n a.node.label === b.node.label &&\n a.node.kind === b.node.kind &&\n a.node.detail === b.node.detail &&\n a.node.active === b.node.active &&\n a.node.note === b.node.note &&\n a.node.count === b.node.count &&\n Math.round(clamp01(a.node.heat) * 100) === Math.round(clamp01(b.node.heat) * 100),\n);\n","import type { CanvasEdge, CanvasGroup } from './types';\nimport { CHANNEL_EDGE, NODE_GAP, type CanvasLayout } from './layout';\n\nexport interface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nexport interface RoutedEdge {\n id: string;\n /** The corners of the line, source port first. Every segment is horizontal or vertical. */\n points: [number, number][];\n /** The same line as an SVG path with rounded corners; also valid for CSS `offset-path`. */\n d: string;\n /** Direction of travel of the last segment: \"right\" in \"columns\", \"down\" in \"bands\". */\n dir: 'right' | 'down';\n}\n\nconst LANE_MARGIN = 16; // a lane keeps this far from the cards on both sides of its channel\nconst TRACK_GAP = 8; // distance between corridor tracks\nconst CLEARANCE = 8; // distance a corridor track keeps from group boxes\nconst OUTSIDE_GAP = 24; // first track above the top group or below the bottom group\nconst CORNER_R = 6;\n\ninterface Port {\n key: string;\n x: number;\n y: number;\n col: number;\n}\n\ninterface Wire {\n edge: CanvasEdge;\n src: Port;\n dst: Port;\n mode: 'next' | 'far' | 'back';\n exit: string;\n entry: string;\n}\n\ninterface Lane {\n key: string;\n ys: number;\n n: number;\n x: number;\n}\n\n/** A horizontal stretch some edge already occupies; `track` marks corridor tracks. */\ninterface HSeg {\n y: number;\n xa: number;\n xb: number;\n src: string;\n dst: string;\n track: boolean;\n}\n\n/** `pts` as an SVG path whose corners are quarter arcs of radius 6 (less on short segments). */\nfunction roundedPath(pts: [number, number][]): string {\n const f = (v: number) => String(Math.round(v * 100) / 100);\n let d = `M${f(pts[0]![0])} ${f(pts[0]![1])}`;\n for (let i = 1; i < pts.length - 1; i++) {\n const [ax, ay] = pts[i - 1]!;\n const [bx, by] = pts[i]!;\n const [cx, cy] = pts[i + 1]!;\n const r = Math.min(CORNER_R, (Math.abs(bx - ax) + Math.abs(by - ay)) / 2, (Math.abs(cx - bx) + Math.abs(cy - by)) / 2);\n const ux = Math.sign(bx - ax);\n const uy = Math.sign(by - ay);\n const vx = Math.sign(cx - bx);\n const vy = Math.sign(cy - by);\n d += `L${f(bx - ux * r)} ${f(by - uy * r)}A${f(r)} ${f(r)} 0 0 ${ux * vy - uy * vx > 0 ? 1 : 0} ${f(bx + vx * r)} ${f(by + vy * r)}`;\n }\n const last = pts[pts.length - 1]!;\n return `${d}L${f(last[0])} ${f(last[1])}`;\n}\n\n/** Drops repeated points and the middle point of three in a row, so only corners stay. */\nfunction corners(pts: [number, number][]): [number, number][] {\n const out: [number, number][] = [];\n for (const p of pts) {\n const prev = out[out.length - 1];\n if (prev && prev[0] === p[0] && prev[1] === p[1]) continue;\n const before = out[out.length - 2];\n if (prev && before && ((before[0] === prev[0] && prev[0] === p[0]) || (before[1] === prev[1] && prev[1] === p[1]))) out.pop();\n out.push(p);\n }\n return out;\n}\n\n/** Where an edge label sits: the middle of the longest segment. */\nexport function labelPoint(pts: [number, number][]): { x: number; y: number } {\n let best = { x: pts[0]![0], y: pts[0]![1] };\n let len = -1;\n for (let i = 1; i < pts.length; i++) {\n const [ax, ay] = pts[i - 1]!;\n const [bx, by] = pts[i]!;\n const l = Math.abs(bx - ax) + Math.abs(by - ay);\n if (l > len) {\n len = l;\n best = { x: (ax + bx) / 2, y: (ay + by) / 2 };\n }\n }\n return best;\n}\n\nconst flip = (b: Box): Box => ({ x: b.y, y: b.x, w: b.h, h: b.w });\n\n/** Routes every edge as an orthogonal line (horizontal and vertical segments, rounded corners)\n * from the right border of its source card to the left border of its target card. A node\n * attaches at its own center height, a group at its card's middle. Group boxes are clustered\n * into sub-columns by x; the gaps between them (and 60 px outside the first and last) are\n * channels, where vertical lanes run: one lane per source port (edges from a port share a\n * trunk) and one per target port (edges into a port merge). An edge to a sub-column further\n * right than the next travels along a horizontal corridor free of cards; backward edges and\n * edges inside one sub-column do the same, mirrored. Two edges share a line only at a shared\n * source or target port. Pure and deterministic; the result is keyed by edge id and skips\n * edges with an unknown end. In a \"bands\" layout the same router runs on the transposed layout\n * (x and y swapped) and the points are swapped back: lines leave the bottom border of the\n * source card and enter the top border of the target card, and `dir` is \"down\". */\nexport function routeEdges(layout: CanvasLayout, groups: CanvasGroup[], edges: CanvasEdge[]): Record<string, RoutedEdge> {\n if (layout.mode !== 'bands') return routeColumns(layout, groups, edges);\n const t: CanvasLayout = { ...layout, mode: 'columns', width: layout.height, height: layout.width, groups: {}, nodes: {} };\n for (const id of Object.keys(layout.groups)) t.groups[id] = flip(layout.groups[id]!);\n for (const id of Object.keys(layout.nodes)) t.nodes[id] = flip(layout.nodes[id]!);\n // An edge between two nodes of one group would loop around the whole card through the outer\n // corridors. Draw a short connector between the two cards inside the group instead.\n const groupOf = new Map<string, string>();\n for (const g of groups) for (const n of g.nodes) groupOf.set(n.id, g.id);\n const inside: CanvasEdge[] = [];\n const outside: CanvasEdge[] = [];\n for (const e of edges) {\n const g = groupOf.get(e.from);\n (g !== undefined && g === groupOf.get(e.to) ? inside : outside).push(e);\n }\n const routed = routeColumns(t, groups, outside);\n const result: Record<string, RoutedEdge> = {};\n for (const e of inside) {\n const a = layout.nodes[e.from];\n const b = layout.nodes[e.to];\n if (!a || !b || e.from === e.to) continue;\n let points: [number, number][];\n let dir: 'right' | 'down';\n if (b.y >= a.y + a.h) {\n // Target below: bottom border to top border, with a bend in the gap when not aligned.\n const ax = a.x + a.w / 2;\n const bx = b.x + b.w / 2;\n if (b.y <= a.y + a.h + NODE_GAP + 1) {\n const my = (a.y + a.h + b.y) / 2;\n points = corners([[ax, a.y + a.h], [ax, my], [bx, my], [bx, b.y]]);\n } else {\n // Rows are not adjacent: a straight drop would cross the cards in between. Leave a's\n // bottom, jog into the column gutter in the gap below a, run down it, then jog to b's\n // center in the gap above b.\n const gb = layout.groups[groupOf.get(e.from)!];\n const hasRightColumn = !!gb && gb.x + gb.w - (a.x + a.w) > NODE_GAP + 20;\n const gx = hasRightColumn ? a.x + a.w + NODE_GAP / 2 : a.x - NODE_GAP / 2;\n const y1 = a.y + a.h + NODE_GAP / 2;\n const y2 = b.y - NODE_GAP / 2;\n points = corners([[ax, a.y + a.h], [ax, y1], [gx, y1], [gx, y2], [bx, y2], [bx, b.y]]);\n }\n dir = 'down';\n } else if (b.x >= a.x + a.w && Math.abs(b.y - a.y) < 1) {\n // Same row, target to the right: right border to left border.\n const cy = a.y + a.h / 2;\n points = [[a.x + a.w, cy], [b.x, cy]];\n dir = 'right';\n } else {\n // Upward or leftward links inside a group have no clean short route; the link is left out.\n continue;\n }\n result[e.id] = { id: e.id, points, d: roundedPath(points), dir };\n }\n for (const id of Object.keys(routed)) {\n const points = routed[id]!.points.map(([x, y]): [number, number] => [y, x]);\n result[id] = { id, points, d: roundedPath(points), dir: 'down' };\n }\n return result;\n}\n\nfunction routeColumns(layout: CanvasLayout, groups: CanvasGroup[], edges: CanvasEdge[]): Record<string, RoutedEdge> {\n const result: Record<string, RoutedEdge> = {};\n const cards: { id: string; box: Box }[] = [];\n for (const g of groups) {\n const box = layout.groups[g.id];\n if (box) cards.push({ id: g.id, box });\n }\n if (cards.length === 0) return result;\n\n // --- sub-columns and channels ----------------------------------------------------\n const colX = [...new Set(cards.map((c) => c.box.x))].sort((a, b) => a - b);\n const cols = colX.map((x) => ({ x, right: x, boxes: [] as Box[] }));\n const colOf = new Map<string, number>();\n for (const { id, box } of cards) {\n const ci = colX.indexOf(box.x);\n colOf.set(id, ci);\n cols[ci]!.right = Math.max(cols[ci]!.right, box.x + box.w);\n cols[ci]!.boxes.push(box);\n }\n /** Channel j is left of sub-column j; channel 0 and channel `cols.length` are the outer ones. */\n const channelOf = (j: number): [number, number] => {\n if (j <= 0) return [cols[0]!.x - CHANNEL_EDGE, cols[0]!.x];\n if (j >= cols.length) return [cols[cols.length - 1]!.right, cols[cols.length - 1]!.right + CHANNEL_EDGE];\n return [cols[j - 1]!.right, cols[j]!.x];\n };\n const minY = cards.reduce((m, c) => Math.min(m, c.box.y), Infinity);\n const maxY = cards.reduce((m, c) => Math.max(m, c.box.y + c.box.h), -Infinity);\n\n // --- ports and wires ---------------------------------------------------------------\n const groupOfNode = new Map<string, string>();\n for (const g of groups) for (const n of g.nodes) groupOfNode.set(n.id, g.id);\n const portOf = (id: string, side: 'o' | 'i'): Port | undefined => {\n const nb = layout.nodes[id];\n const gid = nb ? groupOfNode.get(id) : id;\n const gb = gid ? layout.groups[gid] : undefined;\n if (!gid || !gb || !colOf.has(gid)) return undefined;\n const y = nb ? nb.y + nb.h / 2 : gb.y + gb.h / 2;\n return { key: `${side}|${gid}|${y}`, x: side === 'o' ? gb.x + gb.w : gb.x, y, col: colOf.get(gid)! };\n };\n const fanOut = new Map<string, number>();\n const wires: Wire[] = [];\n for (const edge of edges) {\n const src = portOf(edge.from, 'o');\n const dst = portOf(edge.to, 'i');\n if (!src || !dst) continue;\n fanOut.set(src.key, (fanOut.get(src.key) ?? 0) + 1);\n wires.push({ edge, src, dst, mode: dst.col === src.col + 1 ? 'next' : dst.col > src.col ? 'far' : 'back', exit: '', entry: '' });\n }\n\n // --- lanes -------------------------------------------------------------------------\n const lanes = new Map<string, Lane>();\n const inChannel = new Map<number, Lane[]>();\n const lane = (channel: number, key: string, w: Wire): string => {\n const id = `${channel}|${key}`;\n let l = lanes.get(id);\n if (!l) {\n l = { key: id, ys: 0, n: 0, x: 0 };\n lanes.set(id, l);\n const list = inChannel.get(channel);\n if (list) list.push(l);\n else inChannel.set(channel, [l]);\n }\n l.ys += (w.src.y + w.dst.y) / 2;\n l.n++;\n return id;\n };\n for (const w of wires) {\n if (w.mode === 'next') {\n // One vertical in the channel between the two sub-columns: the source trunk when the\n // source fans out, else the target's merge lane.\n w.exit = w.entry = lane(w.dst.col, fanOut.get(w.src.key)! > 1 ? w.src.key : w.dst.key, w);\n } else {\n w.exit = lane(w.src.col + 1, w.src.key, w);\n w.entry = lane(w.dst.col, w.dst.key, w);\n }\n }\n // Lanes spread evenly over the channel minus the margins, ordered by the average height of\n // their edges (6 px apart or more while they fit; more lanes than that share the width evenly).\n for (const [channel, list] of inChannel) {\n const [l, r] = channelOf(channel);\n const lo = l + LANE_MARGIN;\n const hi = r - LANE_MARGIN;\n list.sort((a, b) => a.ys / a.n - b.ys / b.n || (a.key < b.key ? -1 : 1));\n list.forEach((ln, i) => {\n ln.x = list.length === 1 || hi <= lo ? (l + r) / 2 : lo + ((hi - lo) * i) / (list.length - 1);\n });\n }\n\n // --- horizontal stretches already taken, then corridor tracks -------------------------\n const taken: HSeg[] = [];\n for (const w of wires) {\n taken.push({ y: w.src.y, xa: w.src.x, xb: lanes.get(w.exit)!.x, src: w.src.key, dst: w.dst.key, track: false });\n taken.push({ y: w.dst.y, xa: lanes.get(w.entry)!.x, xb: w.dst.x, src: w.src.key, dst: w.dst.key, track: false });\n }\n const sameLine = (h: HSeg, w: Wire) => h.src === w.src.key || h.dst === w.dst.key;\n const trackFree = (y: number, xa: number, xb: number, w: Wire) => {\n for (const h of taken) {\n if (Math.min(xb, h.xb) - Math.max(xa, h.xa) <= 0.5) continue;\n const dy = Math.abs(h.y - y);\n if (dy < 0.5 ? !sameLine(h, w) : h.track && dy < TRACK_GAP - 0.5) return false;\n }\n return true;\n };\n const spanOf = (w: Wire): [number, number] => (w.mode === 'far' ? [w.src.col + 1, w.dst.col - 1] : [w.dst.col, w.src.col]);\n const cardFree = (y: number, c0: number, c1: number) => {\n for (let c = c0; c <= c1; c++) for (const b of cols[c]!.boxes) if (y > b.y - CLEARANCE + 1e-6 && y < b.y + b.h + CLEARANCE - 1e-6) return false;\n return true;\n };\n const bandCache = new Map<string, [number, number][]>();\n /** The free horizontal bands between group boxes across sub-columns c0..c1, top to bottom. */\n const bandsOf = (c0: number, c1: number): [number, number][] => {\n const id = `${c0}-${c1}`;\n let bands = bandCache.get(id);\n if (bands) return bands;\n const spans: [number, number][] = [];\n for (let c = c0; c <= c1; c++) for (const b of cols[c]!.boxes) spans.push([b.y - CLEARANCE, b.y + b.h + CLEARANCE]);\n spans.sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n bands = [];\n let end = spans[0]![1];\n for (const [a, b] of spans) {\n if (a >= end) bands.push([end, a]);\n end = Math.max(end, b);\n }\n bandCache.set(id, bands);\n return bands;\n };\n const gap = (avg: number, [lo, hi]: [number, number]) => (avg < lo ? lo - avg : avg > hi ? avg - hi : 0);\n // How many corridor edges prefer each band, so its tracks can be centered on the band.\n const wanted = new Map<string, number>();\n for (const w of wires) {\n if (w.mode === 'next') continue;\n const avg = (w.src.y + w.dst.y) / 2;\n let best: [number, number] | undefined;\n for (const b of bandsOf(...spanOf(w))) if (!best || gap(avg, b) < gap(avg, best)) best = b;\n if (best) wanted.set(`${best[0]}|${best[1]}`, (wanted.get(`${best[0]}|${best[1]}`) ?? 0) + 1);\n }\n const trackYs = new Map<string, number>();\n for (const w of wires) {\n if (w.mode === 'next') continue;\n const [c0, c1] = spanOf(w);\n const avg = (w.src.y + w.dst.y) / 2;\n const near = (a: number, b: number) => Math.abs(a - avg) - Math.abs(b - avg) || a - b;\n // Candidates, best first: a track an edge of the same source or target already uses, then\n // the free bands nearest the ports, then lines above the top group or below the bottom one.\n const candidates: number[] = [];\n for (const h of taken) if (h.track && sameLine(h, w) && !candidates.includes(h.y)) candidates.push(h.y);\n for (const b of [...bandsOf(c0, c1)].sort((p, q) => gap(avg, p) - gap(avg, q) || p[0] - q[0])) {\n const n = Math.min(Math.floor((b[1] - b[0]) / TRACK_GAP) + 1, wanted.get(`${b[0]}|${b[1]}`) ?? 1);\n const slots: number[] = [];\n for (let i = 0; i < n; i++) slots.push((b[0] + b[1]) / 2 + TRACK_GAP * (i - (n - 1) / 2));\n candidates.push(...slots.sort(near));\n }\n const outer: number[] = [];\n for (let k = 0; k <= wires.length; k++) outer.push(minY - OUTSIDE_GAP - TRACK_GAP * k, maxY + OUTSIDE_GAP + TRACK_GAP * k);\n candidates.push(...outer.sort(near));\n const xo = lanes.get(w.exit)!.x;\n const xe = lanes.get(w.entry)!.x;\n const xa = Math.min(xo, xe);\n const xb = Math.max(xo, xe);\n const y = candidates.find((c) => cardFree(c, c0, c1) && trackFree(c, xa, xb, w)) ?? candidates[candidates.length - 1]!;\n trackYs.set(w.edge.id, y);\n taken.push({ y, xa, xb, src: w.src.key, dst: w.dst.key, track: true });\n }\n\n // --- paths ---------------------------------------------------------------------------\n for (const w of wires) {\n const { src, dst } = w;\n const xo = lanes.get(w.exit)!.x;\n const xe = lanes.get(w.entry)!.x;\n const ty = trackYs.get(w.edge.id)!;\n const raw: [number, number][] =\n w.mode === 'next'\n ? [[src.x, src.y], [xo, src.y], [xo, dst.y], [dst.x, dst.y]]\n : [[src.x, src.y], [xo, src.y], [xo, ty], [xe, ty], [xe, dst.y], [dst.x, dst.y]];\n const points = corners(raw);\n result[w.edge.id] = { id: w.edge.id, points, d: roundedPath(points), dir: 'right' };\n }\n return result;\n}\n"],"mappings":";AAAA;AAAA,EACE,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MAAC,UAAK,KAAK,cAAc,WAAU,oBAAmB,eAAY,QAAO,kBAEzE;AAAA,UACA,gBAAAA,MAAC,cAAW,OAAM,YAAW,SAAQ,SAAQ,WAAU,WAAU,SAAS,MAAM,OAAO,IAAI,WAAW,IAAI,GACxG,0BAAAA,MAAC,aAAU,GACb;AAAA,UACA,gBAAAA,MAAC,cAAW,OAAM,WAAU,SAAQ,SAAQ,WAAU,WAAU,SAAS,MAAM,OAAO,WAAW,IAAI,GACnG,0BAAAA,MAAC,YAAS,GACZ;AAAA,UACA,gBAAAA;AAAA,YAAC;AAAA;AAAA,cACC,OAAM;AAAA,cACN,SAAQ;AAAA,cACR,WAAU;AAAA,cACV,SAAS,MAAM;AACb,wBAAQ,UAAU;AAClB,sBAAM,IAAI;AAAA,cACZ;AAAA,cAEA,0BAAAA,MAAC,WAAQ;AAAA;AAAA,UACX;AAAA,UACC,YACC,gBAAAA,MAAC,cAAW,OAAM,mBAAkB,SAAQ,SAAQ,WAAU,WAAU,QAAQ,UAAU,gBAAc,UAAU,SAAS,MAAM,UAAU,CAAC,QAAQ,GAClJ,0BAAAA,MAAC,cAAW,GACd,IACE;AAAA,WACN;AAAA;AAAA;AAAA,EACF;AAEJ;","names":["Fragment","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","useEffect","useRef","useState","jsx","jsx","jsx","jsx","jsxs","Button","jsxs","jsx","IconButton","Card","Input","jsx","jsxs","Select","jsx","jsxs","useState","useEffect","jsxs","jsx","useEffect","useRef","useState","Fragment","jsx","jsxs","jsx","jsx","jsxs","FollowCaption","useEffect","useRef","useState","useRef","useEffect","useState","Fragment","jsx","jsxs","Svg","memo","useEffect","useId","useRef","useState","jsx","jsxs","memo","EdgeLegend","useState","useRef","useId","useEffect","Svg","memo","useCallback","useEffect","useRef","jsx","jsxs","Minimap","memo","useLayoutEffect","useRef","jsx","jsxs","useRef","useLayoutEffect","memo","NodeView","Svg","jsx","jsxs","useRef","useState","useCallback","useMemo","useLayoutEffect","step","useEffect","Fragment"]}
1
+ {"version":3,"sources":["../src/components/canvas/system-canvas.tsx","../src/cn.ts","../src/components/flow.tsx","../src/components/hooks.tsx","../src/components/icons.tsx","../src/components/primitives.tsx","../src/components/canvas/follow-caption.tsx","../src/components/display.tsx","../src/components/canvas/follow.ts","../src/components/canvas/view.ts","../src/components/canvas/icons.tsx","../src/components/canvas/layout.ts","../src/components/canvas/legend.tsx","../src/components/canvas/minimap.tsx","../src/components/canvas/node.tsx","../src/components/canvas/route.ts"],"sourcesContent":["import {\n Fragment,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type FocusEvent as ReactFocusEvent,\n type KeyboardEvent as ReactKeyboardEvent,\n type MouseEvent as ReactMouseEvent,\n type PointerEvent as ReactPointerEvent,\n} from 'react';\nimport { cn } from '../../cn';\nimport { usePrefersReducedMotion } from '../flow';\nimport { IconButton } from '../primitives';\nimport { FollowCaption } from './follow-caption';\nimport { useFollow } from './follow';\nimport { FitIcon, FollowIcon, MinusIcon, PlusIcon } from './icons';\nimport { chooseLayout, layoutCandidates, SCROLL_K, type CanvasLayout } from './layout';\nimport { EdgeLegend } from './legend';\nimport { Minimap, type MinimapHandle } from './minimap';\nimport { hueStyle, NodeView } from './node';\nimport { labelPoint, routeEdges, type Box } from './route';\nimport type { CanvasEdgeKind, CanvasGroup, CanvasHue, CanvasNode, SystemCanvasProps } from './types';\nimport { ANIM_MS, centerOn, clampK, DOUBLE_MS, DOUBLE_PX, DRAG_PX, ease, FIT_PAD, FOLLOW_MS, KEY_PAN, LABEL_K, LOD_K, MIN_K, PHONE_K, PHONE_MAX_W, ZOOM_STEP, zoomAround, type View } from './view';\n\nconst insetFor = (w: number, minimap: boolean) => (minimap && w >= MINIMAP_MIN_W ? TOP_INSET_MINIMAP : TOP_INSET);\nconst NO_KINDS: CanvasEdgeKind[] = [];\n// World-free screen px kept clear at the top for the legend button (12 px offset + 44 px button + gap), and with the minimap (176 x ~130 at top 12) shown.\nconst TOP_INSET = 64;\nconst TOP_INSET_MINIMAP = 150;\nconst MINIMAP_MIN_W = 600;\n// Screen px from either side that the corner overlays (legend, minimap) can cover.\nconst CORNER_W = 200;\nconst initialHidden = (kinds: CanvasEdgeKind[]) => new Set(kinds.filter((k) => k.hidden).map((k) => k.id));\n\n// SystemCanvas: a pannable, zoomable graph-paper canvas of grouped nodes and edges that\n// light up where work is happening. The layout is computed (layoutSystem), never stored.\n//\n// Pan and zoom never go through React state: the view lives in a ref and is written\n// straight to the world layer (`transform`) and the viewport's background-position and\n// background-size, so a drag or a wheel tick re-renders nothing. Motion lives in CSS\n// (src/css/base.css, `nish-canvas-*`), inside `prefers-reduced-motion: no-preference`.\n// =====================================================================================\n// SystemCanvas\n// =====================================================================================\n\n/** A pannable, zoomable graph-paper canvas of grouped nodes joined by edges. Nodes with\n * `active` pulse in their group's hue, edges into them flow, and `heat` leaves a fading\n * glow behind. Drag or scroll to pan, ctrl+scroll or pinch to zoom, arrow keys, `+`, `-`\n * and `0` from the keyboard. */\nexport function SystemCanvas({\n groups,\n edges,\n columns,\n bands,\n layout: layoutMode = 'auto',\n edgeKinds,\n follow,\n onFollowChange,\n minimap = true,\n selected = null,\n onSelect,\n height = '100%',\n label = 'System map',\n className,\n}: SystemCanvasProps) {\n const reduced = usePrefersReducedMotion();\n const viewportRef = useRef<HTMLDivElement>(null);\n const worldRef = useRef<HTMLDivElement>(null);\n const view = useRef<View>({ x: 0, y: 0, k: 1 });\n const target = useRef<View | null>(null); // where a running animation is heading\n const raf = useRef(0);\n const size = useRef({ w: 0, h: 0 });\n const touched = useRef(false); // the viewer moved the view; stop auto-fitting\n const zoomLabelRef = useRef<HTMLSpanElement>(null);\n const miniRef = useRef<MinimapHandle>(null);\n const [labelsOn, setLabelsOn] = useState(true);\n const [hoverId, setHoverId] = useState<string | null>(null);\n const [viewport, setViewport] = useState({ w: 0, h: 0 }); // follow re-flies when this changes\n\n // --- edge kinds: hidden kinds are left out of the layout and the routing ----------\n const kindList = edgeKinds ?? NO_KINDS;\n const kindSig = kindList.map((k) => k.id).join('|');\n const [hiddenState, setHiddenState] = useState(() => ({\n sig: kindSig,\n set: initialHidden(kindList),\n }));\n let hiddenKinds = hiddenState.set;\n if (hiddenState.sig !== kindSig) {\n const next = { sig: kindSig, set: initialHidden(kindList) };\n setHiddenState(next);\n hiddenKinds = next.set;\n }\n const toggleKind = useCallback((id: string) => {\n setHiddenState((s) => {\n const set = new Set(s.set);\n if (!set.delete(id)) set.add(id);\n return { sig: s.sig, set };\n });\n }, []);\n const visibleEdges = useMemo(() => edges.filter((e) => !e.kind || !hiddenKinds.has(e.kind)), [edges, hiddenKinds]);\n const lineOf = useMemo(() => new Map(kindList.map((k) => [k.id, k.line ?? 'solid'] as const)), [kindList]);\n\n // --- follow is controlled when `follow` is set ----------------------------------\n const [internalFollow, setInternalFollow] = useState(false);\n const followOn = follow ?? internalFollow;\n const followRef = useRef(followOn);\n const followProps = useRef({ controlled: follow !== undefined, onFollowChange });\n const setFollow = useCallback((on: boolean) => {\n if (!followProps.current.controlled) setInternalFollow(on);\n followProps.current.onFollowChange?.(on);\n }, []);\n /** The viewer moved the view: stop auto-fitting and stop following. */\n const markMoved = useCallback(() => {\n touched.current = true;\n if (followRef.current) {\n followRef.current = false; // a burst of events in one frame stops follow once\n setFollow(false);\n }\n }, [setFollow]);\n\n const sig = groups.map((g) => `${g.id}:${g.column}:${g.band ?? ''}:${g.nodes.map((n) => n.id).join(',')}`).join('|');\n const visSig = visibleEdges.map((e) => `${e.id}:${e.from}:${e.to}`).join('|');\n // The layout and the viewport size it was picked for (0 until the first measurement).\n // The candidates do not depend on the viewport, so a resize only re-chooses between them.\n const cands = useMemo(() => layoutCandidates(groups, visibleEdges, layoutMode), [sig, visSig, layoutMode]); // eslint-disable-line react-hooks/exhaustive-deps\n const [picked, setPicked] = useState(() => ({ layout: chooseLayout(cands, { w: 0, h: 0 }), w: 0, h: 0 }));\n const layout = picked.layout;\n const latest = useRef({\n cands,\n minimap,\n groups,\n layout,\n vis: visibleEdges,\n mode: layoutMode,\n });\n // Event handlers and effects read the latest props through refs; synced first, before the other layout effects.\n useLayoutEffect(() => {\n followRef.current = followOn;\n followProps.current = { controlled: follow !== undefined, onFollowChange };\n latest.current = { cands, minimap, groups, layout, vis: visibleEdges, mode: layoutMode };\n });\n\n // --- applying a view ---------------------------------------------------------\n const apply = useCallback((v: View) => {\n view.current = v;\n const world = worldRef.current;\n const vp = viewportRef.current;\n if (world) world.style.transform = `translate3d(${v.x}px,${v.y}px,0) scale(${v.k})`;\n if (vp) {\n // Written straight onto the viewport: inherited custom properties would restyle every descendant.\n const maj = `${120 * v.k}px ${120 * v.k}px`;\n const min = `${24 * v.k}px ${24 * v.k}px`;\n vp.style.backgroundPosition = `${v.x}px ${v.y}px`;\n vp.style.backgroundSize = `${maj}, ${maj}, ${min}, ${min}`;\n vp.dataset.grid = v.k < LOD_K ? 'major' : 'both';\n const lod = v.k < LOD_K ? 'far' : 'near';\n if (vp.dataset.lod !== lod) vp.dataset.lod = lod;\n }\n miniRef.current?.setView(v, size.current);\n const zl = zoomLabelRef.current;\n if (zl) {\n const text = `${Math.round(v.k * 100)}%`;\n if (zl.textContent !== text) zl.textContent = text;\n }\n const on = v.k >= LABEL_K;\n setLabelsOn((old) => (old === on ? old : on));\n }, []);\n\n const stop = useCallback(() => {\n cancelAnimationFrame(raf.current);\n raf.current = 0;\n target.current = null;\n }, []);\n\n /** Moves to `v`: a 300 ms ease (`ms`), or at once when `animate` is false or motion is reduced. */\n const go = useCallback(\n (v: View, animate: boolean, ms = ANIM_MS) => {\n cancelAnimationFrame(raf.current);\n if (!animate || reduced) {\n target.current = null;\n apply(v);\n return;\n }\n const from = { ...view.current };\n target.current = v;\n const t0 = performance.now();\n const step = (now: number) => {\n const t = Math.min(1, (now - t0) / ms);\n const e = ease(t);\n // Interpolate zoom in log space so the motion feels even.\n const k = from.k * Math.pow(v.k / from.k, e);\n apply({\n k,\n x: from.x + (v.x - from.x) * e,\n y: from.y + (v.y - from.y) * e,\n });\n if (t < 1) raf.current = requestAnimationFrame(step);\n else {\n raf.current = 0;\n target.current = null;\n apply(v);\n }\n };\n raf.current = requestAnimationFrame(step);\n },\n [apply, reduced],\n );\n\n /** The fitted view: the whole layout with 48 px padding; on a phone (fit below 0.55) the\n * zoom stays 0.55 and the view centers on the first active node, else the first group. */\n const fitView = useCallback((): View => {\n const { w, h } = size.current;\n const { groups: gs, layout: lay, minimap: mini } = latest.current;\n const cw = Math.max(1, lay.width);\n const ch = Math.max(1, lay.height + lay.titleRoom);\n // The legend and minimap sit in the top corners: keep a strip clear for them only when a card\n // of the map, fitted without that strip, would land under one of them.\n const inset = insetFor(w, mini);\n const free = Math.min((w - FIT_PAD * 2) / cw, (h - FIT_PAD * 2) / ch, 1);\n const fx = (w - cw * free) / 2;\n const fy = FIT_PAD + (h - FIT_PAD * 2 - ch * free) / 2 + lay.titleRoom * free;\n const underCorner = Object.values(lay.groups).some((b) => {\n const top0 = fy + b.y * free;\n const left = fx + b.x * free;\n const right = left + b.w * free;\n return top0 < inset && (left < CORNER_W || right > w - CORNER_W);\n });\n const top = underCorner ? inset : FIT_PAD;\n const availH = h - top - FIT_PAD;\n const fit = Math.min((w - FIT_PAD * 2) / cw, availH / ch, 1);\n if (fit >= PHONE_K || (w >= PHONE_MAX_W && fit >= SCROLL_K - 0.05) || gs.length === 0) {\n const k = clampK(Number.isFinite(fit) && fit > 0 ? fit : 1);\n return {\n k,\n x: (w - lay.width * k) / 2,\n y: top + (availH - ch * k) / 2 + lay.titleRoom * k,\n };\n }\n let box: Box | undefined;\n let activeGroup: Box | undefined;\n for (const g of gs) {\n const n = g.nodes.find((node) => node.active);\n if (n) {\n box = lay.nodes[n.id];\n activeGroup = lay.groups[g.id];\n break;\n }\n }\n // Fill the width when the map is narrower than the canvas at the phone zoom (an unfolded Fold).\n const pk = clampK(Math.min(1, Math.max(PHONE_K, (w - 48) / Math.max(1, lay.width))));\n // The map's top edge never drops below the overlay row and its bottom never rises above the\n // bottom padding, so the view never opens on empty canvas above or below the map.\n const pinY = (y: number) => Math.max(Math.min(y, top + lay.titleRoom * pk), h - FIT_PAD - lay.height * pk);\n const centerX = (lay.width * pk <= w - 24 ? (w - lay.width * pk) / 2 : undefined);\n if (!box) {\n // Nothing active: open on the top of the map (the first band), centered across when it fits.\n const first = lay.groups[gs[0]!.id];\n const x = centerX ?? (first ? w / 2 - (first.x + first.w / 2) * pk : FIT_PAD);\n return { k: pk, x, y: top + lay.titleRoom * pk };\n }\n // Keep the box head clear of the overlay row. A node centers x on its group (as follow does) when\n // the group fits, so the group's left cards and title are not cut off.\n const v = centerOn(w, h, pk, box);\n const gb = activeGroup;\n if (centerX !== undefined) v.x = centerX;\n else if (gb && gb.w * pk <= w - 24) v.x = w / 2 - (gb.x + gb.w / 2) * pk;\n return { ...v, y: pinY(Math.max(h / 2, top + (box.h * pk) / 2) - (box.y + box.h / 2) * pk) };\n }, []);\n\n const doFit = useCallback(\n (animate: boolean) => {\n if (size.current.w <= 0 || size.current.h <= 0) return;\n go(fitView(), animate);\n },\n [fitView, go],\n );\n\n // Pick the layout for the current viewport and data. A resize only swaps the layout when the\n // chosen candidate (mode or row width) changes, so a resize inside one candidate re-renders\n // nothing; otherwise it just refits.\n const relayout = useCallback(\n (data: boolean) => {\n const { cands: cs, layout: cur } = latest.current;\n const { w, h } = size.current;\n const next = chooseLayout(cs, { w, h });\n if (!data && next.mode === cur.mode && next.width === cur.width && next.height === cur.height) {\n if (!touched.current && !followRef.current) doFit(false);\n return;\n }\n setPicked({ layout: next, w, h });\n // Publish the size in the same render as the new layout so follow flies once, for the real size.\n if (followRef.current) setViewport((old) => (old.w === w && old.h === h ? old : { w, h }));\n },\n [doFit],\n );\n\n // The first measurement happens before paint; later size changes are throttled to a frame.\n const layoutRaf = useRef(0);\n const settleTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n /** Publishes the measured size to follow's state once a resize settles, also while follow is off, so\n * switching follow on never starts from a stale size. */\n const syncViewport = useCallback(() => {\n const { w, h } = size.current;\n setViewport((old) => (old.w === w && old.h === h ? old : { w, h }));\n }, []);\n useLayoutEffect(() => {\n const vp = viewportRef.current;\n if (!vp) return;\n let first = true;\n const measure = () => {\n const r = vp.getBoundingClientRect();\n size.current = { w: r.width, h: r.height };\n if (first) {\n first = false;\n setViewport({ w: r.width, h: r.height });\n relayout(true);\n return;\n }\n if (layoutRaf.current) return;\n layoutRaf.current = requestAnimationFrame(() => {\n layoutRaf.current = 0;\n relayout(false);\n // The minimap's visibility and view rect follow the new size even when the view stays put.\n miniRef.current?.setView(view.current, size.current);\n // Follow re-flies only once a resize settles; nothing re-renders per frame.\n clearTimeout(settleTimer.current);\n settleTimer.current = setTimeout(syncViewport, 150);\n });\n };\n measure();\n const ro = new ResizeObserver(measure);\n ro.observe(vp);\n return () => {\n ro.disconnect();\n cancelAnimationFrame(layoutRaf.current);\n layoutRaf.current = 0;\n clearTimeout(settleTimer.current);\n };\n }, [relayout, syncViewport]);\n\n // Switching follow on picks up any size change that happened while it was off.\n useEffect(() => {\n if (followOn) syncViewport();\n }, [followOn, syncViewport]);\n\n const firstData = useRef(true);\n useLayoutEffect(() => {\n if (firstData.current) {\n firstData.current = false;\n return;\n }\n relayout(true);\n }, [sig, visSig, layoutMode, relayout]);\n\n // A new layout: the first one fits at once; a different one slides the cards to their new\n // places (data-relayout switches the CSS transition on for a moment) and refits.\n const prevLayout = useRef<CanvasLayout | null>(null);\n const fitted = useRef(false);\n const relayoutTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n useLayoutEffect(() => {\n const prev = prevLayout.current;\n prevLayout.current = layout;\n if (picked.w <= 0 || picked.h <= 0) return; // picked before the first measurement\n if (!fitted.current) {\n fitted.current = true;\n doFit(false);\n return;\n }\n const moved = !prev || prev.mode !== layout.mode || prev.width !== layout.width || prev.height !== layout.height;\n if (!moved) {\n if (!touched.current && !followRef.current) doFit(false);\n return;\n }\n const vp = viewportRef.current;\n if (vp) {\n vp.dataset.relayout = 'true';\n clearTimeout(relayoutTimer.current);\n relayoutTimer.current = setTimeout(() => {\n delete vp.dataset.relayout;\n }, 500);\n }\n stop(); // a running fly would aim at the old layout\n if (!touched.current && !followRef.current) doFit(true);\n }, [layout, picked.w, picked.h, doFit, stop]);\n\n useEffect(() => () => clearTimeout(relayoutTimer.current), []);\n\n useEffect(() => () => cancelAnimationFrame(raf.current), []);\n\n // --- zoom and pan helpers ----------------------------------------------------\n const zoomBy = useCallback(\n (factor: number, animate: boolean) => {\n markMoved();\n const base = target.current ?? view.current;\n const { w, h } = size.current;\n go(zoomAround(base, base.k * factor, w / 2, h / 2), animate);\n },\n [go, markMoved],\n );\n\n // --- wheel (needs a non-passive listener) ------------------------------------\n useEffect(() => {\n const vp = viewportRef.current;\n if (!vp) return;\n const onWheel = (e: WheelEvent) => {\n if ((e.target as Element | null)?.closest('[data-canvas-ui]')) return;\n e.preventDefault();\n stop();\n markMoved();\n const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? size.current.h : 1;\n const v = view.current;\n if (e.ctrlKey) {\n const r = vp.getBoundingClientRect();\n apply(zoomAround(v, v.k * Math.exp(-e.deltaY * unit * 0.0015), e.clientX - r.left, e.clientY - r.top));\n } else {\n apply({ ...v, x: v.x - e.deltaX * unit, y: v.y - e.deltaY * unit });\n }\n };\n vp.addEventListener('wheel', onWheel, { passive: false });\n return () => vp.removeEventListener('wheel', onWheel);\n }, [apply, stop, markMoved]);\n\n // --- pointers: drag, click vs drag, pinch ------------------------------------\n const pointers = useRef(new Map<number, { x: number; y: number }>());\n const gesture = useRef<{\n mode: 'none' | 'pending' | 'pan' | 'pinch';\n startX: number;\n startY: number;\n lastX: number;\n lastY: number;\n pinchDist: number;\n pinchMid: { x: number; y: number };\n pinchView: View;\n }>({\n mode: 'none',\n startX: 0,\n startY: 0,\n lastX: 0,\n lastY: 0,\n pinchDist: 1,\n pinchMid: { x: 0, y: 0 },\n pinchView: { x: 0, y: 0, k: 1 },\n });\n const dragged = useRef(false);\n const lastTap = useRef<{\n t: number;\n x: number;\n y: number;\n el: Element;\n } | null>(null);\n const lastDouble = useRef(0); // when a double-tap last fired, so the browser's own dblclick is ignored\n\n const local = (e: { clientX: number; clientY: number }) => {\n const r = viewportRef.current!.getBoundingClientRect();\n return { x: e.clientX - r.left, y: e.clientY - r.top };\n };\n\n /** A double-click or double-tap: on a group head zoom to the group, on empty canvas zoom in. */\n const doubleAt = (el: Element, p: { x: number; y: number }) => {\n if (el.closest('[data-canvas-ui]') || el.closest('.nish-canvas-slot')) return;\n const { w, h } = size.current;\n const head = el.closest('.nish-canvas-head');\n if (head) {\n const box = latest.current.layout.groups[(head as HTMLElement).dataset.canvasId ?? ''];\n if (!box) return;\n const k = Math.min(1.5, Math.max(MIN_K, Math.min((w - FIT_PAD * 2) / box.w, (h - FIT_PAD * 2) / box.h)));\n markMoved();\n go(centerOn(w, h, k, box), true);\n return;\n }\n markMoved();\n const base = target.current ?? view.current;\n go(zoomAround(base, base.k * 1.5, p.x, p.y), true);\n };\n\n const onDoubleClick = (e: ReactMouseEvent<HTMLDivElement>) => {\n if (performance.now() - lastDouble.current < 600) return;\n doubleAt(e.target as Element, local(e));\n };\n\n const startPinch = () => {\n const pts = [...pointers.current.values()];\n const [a, b] = pts as [{ x: number; y: number }, { x: number; y: number }];\n const g = gesture.current;\n g.mode = 'pinch';\n g.pinchDist = Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));\n g.pinchMid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n g.pinchView = { ...view.current };\n dragged.current = true;\n };\n\n const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (e.pointerType === 'mouse' && e.button !== 0) return;\n if ((e.target as Element).closest('[data-canvas-ui]')) return;\n stop();\n const p = local(e);\n pointers.current.set(e.pointerId, p);\n const vp = viewportRef.current!;\n const g = gesture.current;\n if (pointers.current.size === 1) {\n dragged.current = false;\n g.mode = 'pending';\n g.startX = g.lastX = p.x;\n g.startY = g.lastY = p.y;\n } else if (pointers.current.size === 2) {\n for (const id of pointers.current.keys()) {\n try {\n vp.setPointerCapture(id);\n } catch {\n // The pointer already ended.\n }\n }\n markMoved();\n startPinch();\n }\n };\n\n const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (!pointers.current.has(e.pointerId)) return;\n const p = local(e);\n pointers.current.set(e.pointerId, p);\n const g = gesture.current;\n if (g.mode === 'pinch' && pointers.current.size >= 2) {\n const [a, b] = [...pointers.current.values()] as [{ x: number; y: number }, { x: number; y: number }];\n const dist = Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));\n const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n const s = g.pinchView;\n const k = clampK(s.k * (dist / g.pinchDist));\n // The world point that was under the start midpoint follows the current midpoint.\n const wx = (g.pinchMid.x - s.x) / s.k;\n const wy = (g.pinchMid.y - s.y) / s.k;\n apply({ k, x: mid.x - wx * k, y: mid.y - wy * k });\n return;\n }\n if (g.mode === 'pending') {\n if (Math.hypot(p.x - g.startX, p.y - g.startY) < DRAG_PX) return;\n stop();\n g.mode = 'pan';\n dragged.current = true;\n markMoved();\n setHoverId(null);\n try {\n viewportRef.current!.setPointerCapture(e.pointerId);\n } catch {\n // The pointer already ended.\n }\n viewportRef.current!.dataset.dragging = 'true';\n }\n if (g.mode === 'pan') {\n const v = view.current;\n apply({ ...v, x: v.x + (p.x - g.lastX), y: v.y + (p.y - g.lastY) });\n g.lastX = p.x;\n g.lastY = p.y;\n }\n };\n\n const endPointer = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (!pointers.current.delete(e.pointerId)) return;\n const vp = viewportRef.current!;\n try {\n vp.releasePointerCapture(e.pointerId);\n } catch {\n // Not captured.\n }\n const g = gesture.current;\n if (pointers.current.size === 1 && g.mode === 'pinch') {\n // One finger stays down: carry on as a pan from where it is.\n const [rest] = [...pointers.current.values()] as [{ x: number; y: number }];\n g.mode = 'pan';\n g.lastX = rest.x;\n g.lastY = rest.y;\n } else if (pointers.current.size === 0) {\n if (g.mode === 'pending' && e.pointerType === 'touch' && e.type === 'pointerup') {\n // A touch tap that did not drag; two close together on the same thing are a double-tap.\n const p = local(e);\n const now = performance.now();\n const el = (e.target as Element).closest('[data-canvas-id]') ?? (e.target as Element);\n const lt = lastTap.current;\n if (lt && now - lt.t <= DOUBLE_MS && lt.el === el && Math.hypot(p.x - lt.x, p.y - lt.y) <= DOUBLE_PX) {\n lastTap.current = null;\n lastDouble.current = now;\n doubleAt(e.target as Element, p);\n } else {\n lastTap.current = { t: now, x: p.x, y: p.y, el };\n }\n }\n g.mode = 'none';\n delete vp.dataset.dragging;\n // The click that follows this pointerup is swallowed when the pointer dragged.\n setTimeout(() => {\n dragged.current = false;\n }, 0);\n }\n };\n\n const onClickCapture = (e: { stopPropagation: () => void; preventDefault: () => void }) => {\n if (dragged.current) {\n e.stopPropagation();\n e.preventDefault();\n }\n };\n\n // --- hover focus (mouse and pen only; touch uses selection) -------------------\n const onPointerOver = (e: ReactPointerEvent<HTMLDivElement>) => {\n if (e.pointerType === 'touch' || gesture.current.mode === 'pan' || gesture.current.mode === 'pinch') return;\n if (typeof window.matchMedia === 'function' && !window.matchMedia('(hover: hover)').matches) return;\n const id = (e.target as Element).closest('[data-canvas-id]')?.getAttribute('data-canvas-id') ?? null;\n setHoverId((old) => (old === id ? old : id));\n };\n const onPointerLeave = () => setHoverId(null);\n\n // --- selecting something brings it into view ---------------------------------\n const prevSelected = useRef(selected);\n useEffect(() => {\n if (prevSelected.current === selected) return;\n prevSelected.current = selected;\n if (!selected || followRef.current) return;\n const lay = latest.current.layout;\n const box = lay.nodes[selected] ?? lay.groups[selected];\n const { w, h } = size.current;\n if (!box || w <= 0 || h <= 0) return;\n const v = target.current ?? view.current;\n const left = box.x * v.k + v.x;\n const top = box.y * v.k + v.y;\n const inside = left >= 0 && top >= 0 && left + box.w * v.k <= w && top + box.h * v.k <= h;\n if (inside && v.k >= LOD_K) return;\n const k = clampK(Math.max(v.k, 0.8));\n const next = centerOn(w, h, k, box);\n // On a phone the drawer covers the bottom: use the top 45%.\n if (w < PHONE_MAX_W) next.y = (h * 0.45) / 2 - (box.y + box.h / 2) * k;\n touched.current = true;\n go(next, true);\n }, [selected, go]);\n\n // --- keyboard ----------------------------------------------------------------\n // The viewport is never scrolled by the browser; focus pans the view instead.\n const onScroll = () => {\n const vp = viewportRef.current;\n if (vp && (vp.scrollLeft !== 0 || vp.scrollTop !== 0)) {\n vp.scrollLeft = 0;\n vp.scrollTop = 0;\n }\n };\n\n const onFocusCapture = (e: ReactFocusEvent<HTMLDivElement>) => {\n const vp = viewportRef.current;\n const el = e.target as HTMLElement;\n if (!vp || el === vp) return;\n if (pointers.current.size > 0 || !el.matches(':focus-visible')) return;\n const id = (el.closest('[data-canvas-id]') as HTMLElement | null)?.dataset.canvasId;\n if (!id) return;\n const box = latest.current.layout.nodes[id] ?? latest.current.layout.groups[id];\n if (!box) return;\n const v = view.current;\n const { w, h } = size.current;\n const left = box.x * v.k + v.x;\n const top = box.y * v.k + v.y;\n if (left >= 0 && top >= 0 && left + box.w * v.k <= w && top + box.h * v.k <= h) return;\n markMoved();\n go(centerOn(w, h, v.k, box), true);\n };\n\n const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {\n if (e.altKey || e.metaKey) return;\n if ((e.target as Element).closest('[data-canvas-ui]')) return;\n const v = view.current;\n switch (e.key) {\n case 'ArrowLeft':\n stop();\n markMoved();\n apply({ ...v, x: v.x + KEY_PAN });\n break;\n case 'ArrowRight':\n stop();\n markMoved();\n apply({ ...v, x: v.x - KEY_PAN });\n break;\n case 'ArrowUp':\n stop();\n markMoved();\n apply({ ...v, y: v.y + KEY_PAN });\n break;\n case 'ArrowDown':\n stop();\n markMoved();\n apply({ ...v, y: v.y - KEY_PAN });\n break;\n case '+':\n case '=':\n zoomBy(ZOOM_STEP, true);\n break;\n case '-':\n case '_':\n zoomBy(1 / ZOOM_STEP, true);\n break;\n case '0':\n touched.current = false;\n doFit(true);\n break;\n default:\n return;\n }\n e.preventDefault();\n };\n\n // --- content (re-rendered only when data changes, never on pan or zoom) ------\n const columnIndex = useMemo(() => {\n const order = [...new Set(groups.map((g) => g.column))].sort((a, b) => a - b);\n return new Map(order.map((c, i) => [c, i]));\n }, [sig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const lookup = useMemo(() => {\n const nodes = new Map<string, { group: CanvasGroup; node: CanvasNode }>();\n const grps = new Map<string, CanvasGroup>();\n for (const g of groups) {\n grps.set(g.id, g);\n for (const n of g.nodes) nodes.set(n.id, { group: g, node: n });\n }\n return { nodes, grps };\n }, [groups]);\n\n const headerViews = useMemo(\n () =>\n layout.headers.flatMap((h) => {\n const text = layout.mode === 'bands' ? (bands?.[h.index] ?? columns?.[h.index]) : columns?.[h.index];\n return text ? [{ key: `${layout.mode}:${h.index}`, x: h.x, y: h.y, text }] : [];\n }),\n [layout, bands, columns],\n );\n\n // Routing depends only on the layout and the visible edge ends, so a pan, a zoom or an\n // activity update never recomputes it.\n const routes = useMemo(() => routeEdges(layout, groups, visibleEdges), [layout, visSig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const { edgeViews, ports } = useMemo(() => {\n const hueOf = (id: string): { hue: CanvasHue | undefined; active: boolean } | undefined => {\n const n = lookup.nodes.get(id);\n if (n) return { hue: n.group.hue, active: !!n.node.active };\n const g = lookup.grps.get(id);\n if (g) return { hue: g.hue, active: g.nodes.some((x) => x.active) };\n return undefined;\n };\n const views = visibleEdges.flatMap((edge) => {\n const route = routes[edge.id];\n const to = hueOf(edge.to);\n if (!route || !to) return [];\n const line = edge.dashed ? 'dashed' : ((edge.kind ? lineOf.get(edge.kind) : undefined) ?? 'solid');\n return [\n {\n edge,\n route,\n line,\n mid: labelPoint(route.points),\n hue: to.hue,\n active: to.active,\n },\n ];\n });\n // Quiet edges first so an active edge that shares a trunk with one draws on top.\n views.sort((a, b) => Number(a.active) - Number(b.active));\n // Source ports only: the arrowheads mark where an edge ends.\n const dots = new Map<string, { x: number; y: number; hue: CanvasHue | undefined; active: boolean }>();\n for (const v of views) {\n const p = v.route.points[0]!;\n const key = `${p[0]}|${p[1]}`;\n const old = dots.get(key);\n if (!old || (v.active && !old.active)) dots.set(key, { x: p[0], y: p[1], hue: v.hue, active: v.active });\n }\n return { edgeViews: views, ports: [...dots.entries()] };\n }, [visibleEdges, routes, lookup, lineOf]);\n\n // Focus: the hovered thing, else the selected one. Its edges stay lit, the cards at their\n // other ends stay clear, everything else dims.\n const focus = useMemo(() => {\n const id = hoverId ?? selected;\n if (!id) return null;\n const node = lookup.nodes.get(id);\n const grp = node ? node.group : lookup.grps.get(id);\n if (!grp) return null;\n const mine = new Set<string>(node ? [id] : [id, ...grp.nodes.map((n) => n.id)]);\n const related = new Set<string>([id, grp.id]);\n if (!node) for (const n of grp.nodes) related.add(n.id);\n const addEnd = (eid: string) => {\n related.add(eid);\n const n = lookup.nodes.get(eid);\n if (n) related.add(n.group.id);\n const g = lookup.grps.get(eid);\n if (g) for (const x of g.nodes) related.add(x.id);\n };\n const hot = new Set<string>();\n for (const e of visibleEdges) {\n if (!mine.has(e.from) && !mine.has(e.to)) continue;\n hot.add(e.id);\n addEnd(e.from);\n addEnd(e.to);\n }\n return { related, hot };\n }, [hoverId, selected, lookup, visibleEdges]);\n\n // --- follow --------------------------------------------------------------------\n const fly = useCallback((v: View) => go(v, true, FOLLOW_MS), [go]);\n const { step } = useFollow({\n on: followOn,\n groups,\n layout,\n size: viewport,\n fit: fitView,\n inset: TOP_INSET,\n fly,\n });\n const canFollow = useMemo(() => groups.some((g) => g.nodes.some((n) => n.active !== undefined)), [groups]);\n\n const jumpTo = useCallback(\n (wx: number, wy: number) => {\n stop();\n markMoved();\n const { w, h } = size.current;\n const v = view.current;\n apply({ k: v.k, x: w / 2 - wx * v.k, y: h / 2 - wy * v.k });\n },\n [apply, stop, markMoved],\n );\n\n const layoutKey = `${layout.mode}:${layout.width}`;\n\n return (\n <div\n ref={viewportRef}\n role=\"application\"\n aria-label={label}\n aria-roledescription=\"canvas\"\n tabIndex={0}\n className={cn('nish-canvas', className)}\n style={{ height }}\n data-grid=\"both\"\n data-lod=\"near\"\n data-focus={focus ? 'true' : undefined}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endPointer}\n onPointerCancel={endPointer}\n onPointerOver={onPointerOver}\n onPointerLeave={onPointerLeave}\n onDoubleClick={onDoubleClick}\n onClickCapture={onClickCapture}\n onKeyDown={onKeyDown}\n onScroll={onScroll}\n onFocusCapture={onFocusCapture}\n >\n <div ref={worldRef} className=\"nish-canvas-world\" style={{ width: layout.width, height: layout.height }}>\n {headerViews.map((t) => (\n <div key={t.key} className=\"nish-canvas-coltitle\" style={layout.mode === 'bands' ? { left: t.x, top: t.y, lineHeight: 1, transform: 'translateY(-100%)' } : { left: t.x, top: t.y }}>\n {t.text}\n </div>\n ))}\n\n <svg key={`e${layoutKey}`} className=\"nish-canvas-edges\" width={layout.width} height={layout.height} aria-hidden=\"true\" focusable=\"false\">\n {edgeViews.map(({ edge, route, line, mid, hue, active }) => {\n const hot = focus?.hot.has(edge.id) ?? false;\n const end = route.points[route.points.length - 1]!;\n const [ex, ey] = end;\n const arrow = route.dir === 'down' ? `M${ex} ${ey}L${ex - 3.5} ${ey - 8}L${ex + 3.5} ${ey - 8}Z` : `M${ex} ${ey}L${ex - 8} ${ey - 3.5}L${ex - 8} ${ey + 3.5}Z`;\n return (\n <g key={edge.id} style={hueStyle(hue)} className=\"nish-canvas-edge\" data-active={active || undefined} data-line={line} data-hot={hot || undefined}>\n <path className=\"nish-canvas-edge-line\" d={route.d} fill=\"none\" />\n <path className=\"nish-canvas-arrow\" d={arrow} />\n {active ? <circle className=\"nish-canvas-dot\" r=\"3.5\" style={{ offsetPath: `path(\"${route.d}\")` }} /> : null}\n {edge.label && (labelsOn || hot) ? (\n <text className=\"nish-canvas-edge-label\" x={mid.x} y={mid.y - 6} textAnchor=\"middle\">\n {edge.label}\n </text>\n ) : null}\n </g>\n );\n })}\n </svg>\n\n <svg key={`p${layoutKey}`} className=\"nish-canvas-ports\" width={layout.width} height={layout.height} aria-hidden=\"true\" focusable=\"false\">\n {ports.map(([key, p]) => (\n <circle key={key} className=\"nish-canvas-port\" cx={p.x} cy={p.y} r={3} style={hueStyle(p.hue)} data-active={p.active || undefined} />\n ))}\n </svg>\n\n {groups.map((g) => {\n const box = layout.groups[g.id];\n if (!box) return null;\n const live = g.nodes.some((n) => n.active);\n const delay = (columnIndex.get(g.column) ?? 0) * 80;\n return (\n <Fragment key={g.id}>\n <div\n className=\"nish-canvas-group\"\n style={\n {\n ...hueStyle(g.hue),\n left: box.x,\n top: box.y,\n width: box.w,\n height: box.h,\n '--nish-canvas-delay': `${delay}ms`,\n } as CSSProperties\n }\n data-live={live || undefined}\n data-selected={selected === g.id || undefined}\n data-related={focus?.related.has(g.id) || undefined}\n >\n <span className=\"nish-canvas-band\" aria-hidden=\"true\" />\n <button type=\"button\" className=\"nish-canvas-head\" data-canvas-id={g.id} aria-pressed={selected === g.id} onClick={() => onSelect?.(g.id, 'group')}>\n <span className=\"nish-canvas-headtext\">\n <span className=\"nish-canvas-title\">{g.title}</span>\n {g.subtitle ? <span className=\"nish-canvas-subtitle\">{g.subtitle}</span> : null}\n </span>\n {g.badge ? <span className=\"nish-canvas-badge\">{g.badge}</span> : null}\n </button>\n </div>\n {g.nodes.map((n) => {\n const nb = layout.nodes[n.id];\n if (!nb) return null;\n return (\n <NodeView\n key={n.id}\n node={n}\n groupTitle={g.title}\n hue={g.hue}\n box={nb}\n selected={selected === n.id}\n dim={focus ? !focus.related.has(n.id) : false}\n delay={delay}\n onSelect={onSelect}\n />\n );\n })}\n </Fragment>\n );\n })}\n </div>\n\n <EdgeLegend kinds={kindList} hidden={hiddenKinds} onToggle={toggleKind} />\n {minimap ? <Minimap layout={layout} groups={groups} handleRef={miniRef} onJump={jumpTo} /> : null}\n <FollowCaption step={step} />\n\n <div data-canvas-ui className=\"nish-canvas-controls\">\n <span ref={zoomLabelRef} className=\"nish-canvas-zoom\" aria-hidden=\"true\">\n 100%\n </span>\n <IconButton label=\"Zoom out\" variant=\"ghost\" className=\"size-11\" onClick={() => zoomBy(1 / ZOOM_STEP, true)}>\n <MinusIcon />\n </IconButton>\n <IconButton label=\"Zoom in\" variant=\"ghost\" className=\"size-11\" onClick={() => zoomBy(ZOOM_STEP, true)}>\n <PlusIcon />\n </IconButton>\n <IconButton\n label=\"Fit to screen\"\n variant=\"ghost\"\n className=\"size-11\"\n onClick={() => {\n touched.current = false;\n doFit(true);\n }}\n >\n <FitIcon />\n </IconButton>\n {canFollow ? (\n <IconButton label=\"Follow activity\" variant=\"ghost\" className=\"size-11\" active={followOn} aria-pressed={followOn} onClick={() => setFollow(!followOn)}>\n <FollowIcon />\n </IconButton>\n ) : null}\n </div>\n </div>\n );\n}\n","import { clsx, type ClassValue } from 'clsx';\nimport { extendTailwindMerge } from 'tailwind-merge';\n\n// tailwind-merge has to know the th-* colors and the custom shadows are colors and\n// shadows, or it treats `text-th-hi text-sm` as a conflict and drops one. The same goes\n// for the extra type sizes: without `text: ['2xs', '3xs']` it may read text-2xs as a\n// color and drop text-th-hi next to it. scripts/build.mjs asserts both cases.\nconst twMerge = extendTailwindMerge({\n extend: {\n theme: {\n text: ['2xs', '3xs'],\n },\n classGroups: {\n shadow: [{ shadow: ['card', 'pop', 'modal'] }],\n },\n },\n});\n\n/** Conditional Tailwind classes with conflict resolution. */\nexport function cn(...inputs: ClassValue[]): string {\n return twMerge(clsx(inputs));\n}\n","import {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactElement,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport { cn } from '../cn';\nimport { ago } from '../format';\nimport { useMediaQuery, useNow } from './hooks';\nimport { Tooltip } from './overlay';\nimport { Badge, type BadgeHue } from './primitives';\n\n// Animated components for live views of multi-step work: FlowSteps, StepBar, AgentNode,\n// WorkflowBoard, ActivityFeed, TickerText and AnimatedList.\n//\n// Motion lives in CSS (src/css/base.css, `nish-flow-*`), inside\n// `prefers-reduced-motion: no-preference`, so under reduced motion every state change is\n// instant and nothing loops. Animations run on a state change, never on a re-render with\n// the same data: a component remembers what it showed last and only plays what changed.\n\nconst EASE = 'cubic-bezier(0.22, 1, 0.36, 1)';\n\n/** True while the viewer asks for reduced motion. False on the server and before hydration. */\nexport function usePrefersReducedMotion(): boolean {\n return useMediaQuery('(prefers-reduced-motion: reduce)');\n}\n\nconst warned = new Set<string>();\n\n/** Dev-only console warning, once per message. Bundlers replace `process.env.NODE_ENV`;\n * where nothing does, the ReferenceError is caught and nothing is printed. */\nfunction warnDev(message: string): void {\n if (warned.has(message)) return;\n try {\n if (process.env.NODE_ENV !== 'production') {\n warned.add(message);\n console.warn(message);\n }\n } catch {\n // No process or no console.\n }\n}\n\n/** Plays a one-shot effect on an element when `value` changes (never on mount): sets\n * data-fx to the name `pick` returns, restarts the CSS animation if one was running,\n * and clears it again. The attribute is set on the DOM directly, so a re-render with the\n * same data cannot cut the animation short. */\nfunction useTransitionFx<S extends string>(\n value: S,\n ref: RefObject<HTMLElement | null>,\n pick: (from: S, to: S) => string | null,\n): void {\n const prev = useRef(value);\n useLayoutEffect(() => {\n const from = prev.current;\n prev.current = value;\n if (from === value) return;\n const el = ref.current;\n if (!el) return;\n el.removeAttribute('data-fx');\n const fx = pick(from, value);\n if (!fx) return;\n void el.offsetWidth;\n el.setAttribute('data-fx', fx);\n const timer = setTimeout(() => el.removeAttribute('data-fx'), 700);\n return () => {\n clearTimeout(timer);\n el.removeAttribute('data-fx');\n };\n }, [value, ref, pick]);\n}\n\n/** Ids that appeared after the first render. They stay flagged while they are in `ids`, so\n * an item's enter animation is not cut off by the next render. With `skipFirst` the ids\n * of the first render are never fresh. */\nfunction useFreshIds(ids: string[], skipFirst: boolean): Set<string> {\n const key = ids.join('\\n');\n const [seen, setSeen] = useState(() => ({\n key,\n known: new Set(ids),\n fresh: new Set(skipFirst ? [] : ids),\n }));\n if (seen.key === key) return seen.fresh;\n // The ids changed: derive the next sets during render (React's \"adjust state on a prop\n // change\" pattern), so a new item is flagged on the very render that adds it.\n const fresh = new Set([...seen.fresh].filter((id) => ids.includes(id)));\n for (const id of ids) if (!seen.known.has(id)) fresh.add(id);\n setSeen({ key, known: new Set(ids), fresh });\n return fresh;\n}\n\nfunction CheckSvg({ size, className }: { size: number; className?: string }) {\n return (\n <svg\n className={cn('nish-flow-check', className)}\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={3}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path d=\"M5 12.5l4.5 4.5L19 7.5\" pathLength={1} />\n </svg>\n );\n}\n\nfunction CrossSvg({ size }: { size: number }) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={3}\n strokeLinecap=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path d=\"M6.5 6.5l11 11M17.5 6.5l-11 11\" />\n </svg>\n );\n}\n\n// =====================================================================================\n// FlowSteps\n// =====================================================================================\n\nexport type FlowStepStatus = 'pending' | 'active' | 'done' | 'failed';\n\nexport interface FlowStepItem {\n id: string;\n label: ReactNode;\n status: FlowStepStatus;\n meta?: ReactNode;\n}\n\nexport interface FlowStepsProps {\n steps: FlowStepItem[];\n /** auto: horizontal when the container is at least 640px wide and there are at most 8 steps; else vertical. */\n orientation?: 'auto' | 'vertical' | 'horizontal';\n /** aria-label of the list. Default \"Progress\". */\n label?: string;\n className?: string;\n}\n\nconst NODE_STATUS: Record<FlowStepStatus, string> = {\n pending: 'border-2 border-th-line text-th-hi3',\n active: 'border-2 border-th-accent text-th-hi',\n done: 'bg-th-ok-fill text-th-on-ok',\n failed: 'bg-th-loss-fill text-th-on-loss',\n};\n\nconst STEP_SR: Partial<Record<FlowStepStatus, string>> = { done: ', done', failed: ', failed' };\n\nfunction pickStepFx(from: FlowStepStatus, to: FlowStepStatus): string | null {\n if (to === 'done') return 'done';\n if (to === 'failed') return 'failed';\n return from === to ? null : null;\n}\n\n/** Horizontal labels clamp to two lines; a text label gets its full text as a tooltip\n * (hover on desktop, tap on a phone, focus from the keyboard). */\nfunction withFullText(text: ReactNode, label: ReactElement) {\n if (typeof text !== 'string') return label;\n return (\n <Tooltip tip={text} className=\"nish-flow-label-tip max-w-full min-w-0\">\n {label}\n </Tooltip>\n );\n}\n\nfunction StepRow({\n step,\n index,\n last,\n sweeping,\n}: {\n step: FlowStepItem;\n index: number;\n last: boolean;\n sweeping: boolean;\n}) {\n const nodeRef = useRef<HTMLSpanElement>(null);\n useTransitionFx(step.status, nodeRef, pickStepFx);\n const { status } = step;\n return (\n <li\n className=\"nish-flow-step nish-flow-rise\"\n data-status={status}\n aria-current={status === 'active' ? 'step' : undefined}\n style={{ '--nish-flow-delay': `${Math.min(index * 40, 400)}ms` } as CSSProperties}\n >\n <span\n ref={nodeRef}\n className={cn(\n 'nish-flow-node grid size-7 place-items-center rounded-full text-xs font-medium tabular-nums',\n NODE_STATUS[status],\n )}\n aria-hidden=\"true\"\n >\n {status === 'done' ? (\n <CheckSvg size={16} />\n ) : status === 'failed' ? (\n <CrossSvg size={14} />\n ) : (\n index + 1\n )}\n {status === 'active' ? (\n <>\n <svg className=\"nish-flow-arc text-th-accent\" viewBox=\"0 0 28 28\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"14\" cy=\"14\" r=\"13\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeDasharray=\"20 62\" />\n </svg>\n <span className=\"nish-flow-ripple\" />\n </>\n ) : null}\n </span>\n <span className=\"nish-flow-text\">\n {withFullText(\n step.label,\n <span\n className={cn(\n 'nish-flow-label text-sm',\n status === 'active' ? 'font-medium text-th-hi' : status === 'failed' ? 'text-th-loss' : 'text-th-hi2',\n )}\n >\n {step.label}\n {STEP_SR[status] ? <span className=\"sr-only\">{STEP_SR[status]}</span> : null}\n </span>,\n )}\n {step.meta != null ? <span className=\"nish-flow-meta text-xs text-th-hi3\">{step.meta}</span> : null}\n </span>\n {last ? null : (\n <span\n className=\"nish-flow-conn\"\n data-on={status === 'done'}\n aria-hidden=\"true\"\n style={sweeping ? ({ '--nish-flow-delay': `${index * 60}ms` } as CSSProperties) : undefined}\n >\n <span className=\"nish-flow-fill\" />\n <span className=\"nish-flow-shimmer\" />\n <span className=\"nish-flow-sweep\" />\n </span>\n )}\n </li>\n );\n}\n\n/** A plan as a flow of steps: numbered nodes joined by connectors that fill as steps\n * finish. The active step ripples, a finishing step draws its check, a failing one\n * shakes, and when the last step finishes a sweep runs along the connectors. Vertical on\n * narrow containers, horizontal from 640px (up to 8 steps). */\nexport function FlowSteps({ steps, orientation = 'auto', label = 'Progress', className }: FlowStepsProps) {\n const allDone = steps.length > 0 && steps.every((s) => s.status === 'done');\n const prevAll = useRef<boolean | null>(null);\n const [sweeping, setSweeping] = useState(false);\n useLayoutEffect(() => {\n const was = prevAll.current;\n prevAll.current = allDone;\n if (!allDone) {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- state is synced from a prop/DOM measurement inside the effect (React 19 rule flagged at adoption)\n setSweeping(false);\n return;\n }\n if (was === false && steps.length > 1) {\n setSweeping(true);\n const timer = setTimeout(() => setSweeping(false), steps.length * 60 + 1000);\n return () => clearTimeout(timer);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [allDone]);\n\n const orient = orientation === 'auto' && steps.length > 8 ? 'vertical' : orientation;\n return (\n <div className={cn('nish-flow-steps-box', className)}>\n <ol className=\"nish-flow-steps\" data-orient={orient} data-sweep={sweeping || undefined} aria-label={label}>\n {steps.map((step, i) => (\n <StepRow key={step.id} step={step} index={i} last={i === steps.length - 1} sweeping={sweeping} />\n ))}\n </ol>\n </div>\n );\n}\n\n// =====================================================================================\n// StepBar\n// =====================================================================================\n\nexport interface StepBarProps {\n total: number;\n done: number;\n /** pulses the current segment */\n active?: boolean;\n label?: string;\n className?: string;\n}\n\n/** A compact progress bar of segments, one per step (a continuous bar above 12). Done\n * segments fill in, the current one pulses while `active`. */\nexport function StepBar({ total, done, active = false, label, className }: StepBarProps) {\n const t = Number.isFinite(total) ? Math.max(0, Math.floor(total)) : 0;\n const d = Number.isFinite(done) ? Math.min(t, Math.max(0, Math.floor(done))) : 0;\n const props = {\n role: 'progressbar' as const,\n 'aria-valuemin': 0,\n 'aria-valuemax': t,\n 'aria-valuenow': d,\n 'aria-label': label ?? 'Progress',\n };\n if (t > 12) {\n return (\n <div {...props} className={cn('relative h-1.5 overflow-hidden rounded-full bg-th-line', className)}>\n <div\n className=\"h-full rounded-full bg-th-ok-fill motion-safe:transition-[width] motion-safe:duration-[400ms]\"\n style={{ width: `${(d / t) * 100}%` }}\n />\n {active && d < t ? (\n <div\n className=\"absolute inset-y-0 rounded-full bg-th-accent motion-safe:animate-pulse\"\n style={{ left: `${(d / t) * 100}%`, width: `max(6px, ${100 / t}%)` }}\n />\n ) : null}\n </div>\n );\n }\n return (\n <div {...props} className={cn('flex h-1.5 gap-[3px]', className)}>\n {Array.from({ length: t }, (_, i) => (\n <div key={i} className=\"relative h-full min-w-0 flex-1 overflow-hidden rounded-full bg-th-line\">\n <div\n className={cn(\n 'absolute inset-0 origin-left rounded-full bg-th-ok-fill motion-safe:transition-transform motion-safe:duration-[400ms]',\n i < d ? 'scale-x-100' : 'scale-x-0',\n )}\n />\n {i === d ? (\n <div className={cn('absolute inset-0 rounded-full bg-th-accent', active ? 'motion-safe:animate-pulse' : 'opacity-0')} />\n ) : null}\n </div>\n ))}\n </div>\n );\n}\n\n// =====================================================================================\n// TickerText\n// =====================================================================================\n\nexport interface TickerTextProps {\n text: string;\n as?: 'span' | 'p' | 'div';\n className?: string;\n}\n\n/** One line of text that swaps with a short slide when it changes: the old text rises and\n * fades out while the new text comes up from below. Long text ends in an ellipsis. */\nexport function TickerText({ text, as = 'span', className }: TickerTextProps) {\n const reduced = usePrefersReducedMotion();\n const [state, setState] = useState<{ text: string; prev: string | null }>({ text, prev: null });\n let cur = state;\n if (state.text !== text) {\n cur = { text, prev: reduced ? null : state.text };\n setState(cur);\n }\n const animating = cur.prev !== null;\n useEffect(() => {\n if (!animating) return;\n const timer = setTimeout(() => setState((s) => (s.prev === null ? s : { ...s, prev: null })), 300);\n return () => clearTimeout(timer);\n }, [animating, cur.text]);\n\n const Tag = as;\n return (\n <Tag className={cn('nish-flow-ticker grid min-w-0 overflow-hidden', className)} title={cur.text}>\n {cur.prev !== null ? (\n <span key={`prev:${cur.prev}`} className=\"nish-flow-ticker-out\" aria-hidden=\"true\">\n {cur.prev}\n </span>\n ) : null}\n <span key={cur.text} className={animating ? 'nish-flow-ticker-in' : undefined}>\n {cur.text}\n </span>\n </Tag>\n );\n}\n\n// =====================================================================================\n// AgentNode\n// =====================================================================================\n\nexport type AgentNodeState = 'queued' | 'running' | 'done' | 'failed';\n\nexport interface AgentNodeProps {\n label: string;\n state: AgentNodeState;\n /** Short model name; opus, sonnet, haiku and fable get their own badge hue. */\n model?: string | null;\n activity?: string;\n /** Right-aligned small text, e.g. elapsed time. */\n meta?: ReactNode;\n onClick?: () => void;\n className?: string;\n}\n\nconst STATE_WORD: Record<AgentNodeState, string> = {\n queued: 'Queued',\n running: 'Running',\n done: 'Done',\n failed: 'Failed',\n};\n\nconst AGENT_STATE: Record<AgentNodeState, string> = {\n queued: 'border-dashed border-th-line opacity-70',\n running: 'border-th-accent',\n done: 'border-th-ok-fill/40',\n failed: 'border-th-loss-fill',\n};\n\nconst MODEL_HUE: [string, BadgeHue][] = [\n ['opus', 'violet'],\n ['sonnet', 'sky'],\n ['haiku', 'emerald'],\n ['fable', 'amber'],\n];\n\nfunction modelFamily(model: string): [string, BadgeHue] | undefined {\n const m = model.toLowerCase();\n return MODEL_HUE.find(([name]) => m.includes(name));\n}\n\nfunction ModelBadge({ model }: { model: string }) {\n const family = modelFamily(model);\n return (\n <Badge size=\"xs\" hue={family?.[1]} className=\"shrink-0\">\n {family ? family[0] : model}\n </Badge>\n );\n}\n\nfunction pickAgentFx(from: AgentNodeState, to: AgentNodeState): string | null {\n if (from === to) return null;\n if (to === 'done') return 'done';\n if (to === 'failed') return 'failed';\n return null;\n}\n\nfunction AgentIcon({ state }: { state: AgentNodeState }) {\n if (state === 'running') {\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center text-th-accent\">\n <svg className=\"nish-flow-agent-spin\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"6\" stroke=\"currentColor\" strokeOpacity=\"0.25\" strokeWidth=\"2\" />\n <path d=\"M8 2a6 6 0 0 1 6 6\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </span>\n );\n }\n if (state === 'done') {\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center rounded-full bg-th-ok-fill text-th-on-ok\">\n <CheckSvg size={12} />\n </span>\n );\n }\n if (state === 'failed') {\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center rounded-full bg-th-loss-fill text-th-on-loss\">\n <CrossSvg size={11} />\n </span>\n );\n }\n return (\n <span className=\"nish-flow-agent-icon grid size-5 shrink-0 place-items-center\">\n <span className=\"size-4 rounded-full border-2 border-dashed border-th-ghost\" />\n </span>\n );\n}\n\n/** One agent or task as a card: state icon, label, model badge, a live activity line.\n * A running agent has a comet of accent circling its border; finishing pops the check;\n * failing shakes once. Pass `onClick` to make the card a button. */\nexport function AgentNode({ label, state, model, activity, meta, onClick, className }: AgentNodeProps) {\n const ref = useRef<HTMLElement>(null);\n useTransitionFx(state, ref, pickAgentFx);\n const aria = `${label}: ${STATE_WORD[state]}`;\n const classes = cn(\n 'nish-flow-agent block min-h-16 w-full min-w-0 rounded-xl border bg-th-surface p-3 text-left',\n AGENT_STATE[state],\n onClick &&\n 'cursor-pointer transition-colors hover:bg-th-elevated focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-th-accent',\n className,\n );\n const body = (\n <>\n <span className=\"flex min-w-0 items-start gap-2\">\n <AgentIcon state={state} />\n <span className=\"line-clamp-2 min-w-0 flex-1 text-sm font-medium leading-5 text-th-hi [overflow-wrap:anywhere]\">{label}</span>\n {meta != null ? <span className=\"shrink-0 text-xs leading-5 tabular-nums text-th-hi3\">{meta}</span> : null}\n </span>\n {model || activity ? (\n <span className=\"mt-1.5 flex min-w-0 items-center gap-2\">\n {model ? <ModelBadge model={model} /> : null}\n {activity ? <TickerText as=\"span\" text={activity} className=\"min-w-0 flex-1 text-xs text-th-hi3\" /> : null}\n </span>\n ) : null}\n </>\n );\n if (onClick) {\n return (\n <button type=\"button\" ref={ref as RefObject<HTMLButtonElement | null>} className={classes} data-state={state} aria-label={aria} onClick={onClick}>\n {body}\n </button>\n );\n }\n return (\n <article ref={ref} className={classes} data-state={state} aria-label={aria}>\n {body}\n </article>\n );\n}\n\n// =====================================================================================\n// WorkflowBoard\n// =====================================================================================\n\nexport interface WorkflowBoardPhase {\n id: string;\n title: string;\n detail?: ReactNode;\n model?: string | null;\n}\n\nexport interface WorkflowBoardAgent extends Omit<AgentNodeProps, 'className' | 'onClick'> {\n id: string;\n /** phase id or title */\n phase: string | null;\n}\n\nexport interface WorkflowBoardProps {\n phases: WorkflowBoardPhase[];\n agents: WorkflowBoardAgent[];\n /** aria-label. Default \"Workflow\". */\n label?: string;\n className?: string;\n}\n\ntype PhaseState = 'waiting' | 'pending' | 'active' | 'done';\n\nconst OTHER_ID = '__nish-flow-other__';\n\nfunction phaseState(agents: WorkflowBoardAgent[]): PhaseState {\n if (agents.length === 0) return 'waiting';\n if (agents.some((a) => a.state === 'running')) return 'active';\n if (agents.every((a) => a.state === 'done' || a.state === 'failed')) return 'done';\n return 'pending';\n}\n\nfunction PhaseConnector({ flowing }: { flowing: boolean }) {\n return (\n <svg className=\"nish-flow-phase-conn\" data-flow={flowing} viewBox=\"0 0 24 12\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <path className=\"nish-flow-dashline\" d=\"M1 6h15\" strokeDasharray=\"3 3\" />\n <path d=\"M16 2.5L20.5 6 16 9.5\" />\n </svg>\n );\n}\n\n/** A workflow as columns of phases (stacked on narrow containers), each phase holding its\n * agents as AgentNodes. A phase waits, glows while an agent runs and gets a check when\n * all its agents finish; new agents rise in, staggered. */\nexport function WorkflowBoard({ phases, agents, label = 'Workflow', className }: WorkflowBoardProps) {\n const fresh = useFreshIds(\n agents.map((a) => a.id),\n false,\n );\n const columns = useMemo(() => {\n const byId = new Map<string, WorkflowBoardPhase>();\n const byTitle = new Map<string, WorkflowBoardPhase>();\n for (const p of phases) {\n if (!byId.has(p.id)) byId.set(p.id, p);\n if (!byTitle.has(p.title)) byTitle.set(p.title, p);\n }\n const groups = new Map<string, WorkflowBoardAgent[]>();\n const other: WorkflowBoardAgent[] = [];\n for (const a of agents) {\n const phase = a.phase === null ? undefined : (byId.get(a.phase) ?? byTitle.get(a.phase));\n if (!phase) {\n other.push(a);\n continue;\n }\n const list = groups.get(phase.id);\n if (list) list.push(a);\n else groups.set(phase.id, [a]);\n }\n const cols: { phase: WorkflowBoardPhase; agents: WorkflowBoardAgent[]; state: PhaseState }[] = phases.map((phase) => {\n const list = groups.get(phase.id) ?? [];\n return { phase, agents: list, state: phaseState(list) };\n });\n // Duplicate phase ids share one group; the later column shows the same agents once.\n const seen = new Set<string>();\n for (const c of cols) {\n if (seen.has(c.phase.id)) {\n c.agents = [];\n c.state = 'waiting';\n }\n seen.add(c.phase.id);\n }\n if (other.length) cols.push({ phase: { id: OTHER_ID, title: 'Other' }, agents: other, state: phaseState(other) });\n return cols;\n }, [phases, agents]);\n\n return (\n <section aria-label={label} className={cn('nish-flow-board-box', className)}>\n <div className=\"nish-flow-board\">\n {columns.map((col, ci) => {\n const { phase, state } = col;\n const finished = col.agents.filter((a) => a.state === 'done' || a.state === 'failed').length;\n const total = col.agents.length;\n const next = columns[ci + 1];\n const flowing =\n (state === 'done' || state === 'active') &&\n next !== undefined &&\n (next.state === 'waiting' || next.state === 'pending' || next.state === 'active');\n return (\n <div\n key={phase.id}\n role=\"group\"\n aria-label={phase.title}\n data-state={state}\n className={cn(\n 'nish-flow-phase rounded-xl border bg-th-elevated/40 p-3',\n state === 'active' ? 'border-th-accent/50' : 'border-th-line',\n )}\n >\n <div className={cn('flex min-w-0 items-center gap-2', state === 'waiting' && 'opacity-60')}>\n {state === 'done' ? (\n <span className=\"grid size-4 shrink-0 place-items-center rounded-full bg-th-ok-fill text-th-on-ok\">\n <CheckSvg size={10} />\n </span>\n ) : null}\n <span className={cn('min-w-0 flex-1 truncate text-sm font-medium', state === 'active' ? 'text-th-accent' : 'text-th-hi')}>\n {phase.title}\n </span>\n {phase.model ? <ModelBadge model={phase.model} /> : null}\n <span className=\"shrink-0 text-xs tabular-nums text-th-hi3\">\n {finished}/{total}\n </span>\n </div>\n <div\n className={cn('mt-2 h-1 overflow-hidden rounded-full bg-th-line', state === 'waiting' && 'opacity-60')}\n aria-hidden=\"true\"\n >\n <div\n className=\"h-full rounded-full bg-th-ok-fill motion-safe:transition-[width] motion-safe:duration-500\"\n style={{ width: total ? `${(finished / total) * 100}%` : '0%' }}\n />\n </div>\n {phase.detail != null ? <div className=\"mt-2 text-xs text-th-hi3\">{phase.detail}</div> : null}\n <div className=\"mt-3 flex min-w-0 flex-col gap-2\">\n {total === 0 ? (\n <p className=\"text-xs text-th-hi3\">Waiting</p>\n ) : (\n col.agents.map((a, ai) => {\n const { id, phase: _phase, ...node } = a;\n return (\n <div\n key={id}\n className={fresh.has(id) ? 'nish-flow-rise' : undefined}\n style={fresh.has(id) ? ({ '--nish-flow-delay': `${Math.min(ai * 60, 600)}ms` } as CSSProperties) : undefined}\n >\n <AgentNode {...node} />\n </div>\n );\n })\n )}\n </div>\n {next ? <PhaseConnector flowing={flowing} /> : null}\n </div>\n );\n })}\n </div>\n </section>\n );\n}\n\n// =====================================================================================\n// ActivityFeed\n// =====================================================================================\n\nexport interface ActivityItem {\n id: string;\n at: number;\n text: ReactNode;\n tone?: 'neutral' | 'accent' | 'ok' | 'warn' | 'loss';\n source?: ReactNode;\n}\n\nexport interface ActivityFeedProps {\n items: ActivityItem[];\n /** default 50 */\n max?: number;\n now?: number;\n /** default \"Activity\" */\n label?: string;\n empty?: ReactNode;\n className?: string;\n}\n\nconst FEED_DOT: Record<NonNullable<ActivityItem['tone']>, string> = {\n neutral: 'bg-th-ghost',\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n};\n\n/** A timeline of short updates, newest first. A new update opens its row, fades in and\n * flashes the accent tint. Items present on the first render do not animate. */\nexport function ActivityFeed({ items, max = 50, now, label = 'Activity', empty, className }: ActivityFeedProps) {\n const internalNow = useNow(15000);\n const clock = now ?? internalNow;\n const shown = useMemo(() => [...items].sort((a, b) => b.at - a.at).slice(0, Math.max(0, max)), [items, max]);\n const fresh = useFreshIds(\n shown.map((i) => i.id),\n true,\n );\n if (shown.length === 0) {\n return <div className={cn('text-sm text-th-hi3', className)}>{empty ?? 'No activity yet'}</div>;\n }\n return (\n <ol className={cn('nish-flow-feed', className)} aria-label={label}>\n {shown.map((item) => (\n <li key={item.id} className=\"nish-flow-feed-item\" data-fresh={fresh.has(item.id) || undefined} data-tone={item.tone ?? 'neutral'}>\n <div className=\"nish-flow-feed-inner\">\n <div className=\"nish-flow-feed-row\">\n <span className={cn('nish-flow-feed-dot', FEED_DOT[item.tone ?? 'neutral'])} aria-hidden=\"true\" />\n <div className=\"min-w-0\">\n <div className=\"break-words text-sm text-th-hi2\">{item.text}</div>\n {item.source != null ? <div className=\"break-words text-xs text-th-hi3\">{item.source}</div> : null}\n </div>\n <span className=\"pt-0.5 text-right text-xs tabular-nums text-th-hi3\">{ago(item.at, { now: clock, style: 'short' })}</span>\n </div>\n </div>\n </li>\n ))}\n </ol>\n );\n}\n\n// =====================================================================================\n// AnimatedList\n// =====================================================================================\n\nexport interface AnimatedListProps<T> {\n items: T[];\n getKey: (item: T) => string;\n children: (item: T, phase: 'enter' | 'idle' | 'exit') => ReactNode;\n /** How long a removed item stays to animate out. Default 420. */\n exitMs?: number;\n as?: 'ul' | 'ol' | 'div';\n className?: string;\n itemClassName?: string;\n}\n\ntype ListPhase = 'enter' | 'idle' | 'exit';\ninterface ListEntry<T> {\n key: string;\n item: T;\n phase: ListPhase;\n}\ninterface ListState<T> {\n src: T[];\n reduced: boolean;\n entries: ListEntry<T>[];\n}\n\nconst ENTER_MS = 400;\nconst MOVE_MS = 300;\n\n/** The entries to render for `items`: new keys enter, removed keys stay at their last\n * index as \"exit\" (when animating), a key that comes back during its exit stops exiting.\n * When a key repeats, the first item wins. */\nfunction reconcile<T>(prev: ListEntry<T>[], items: T[], getKey: (item: T) => string, animate: boolean): ListEntry<T>[] {\n const prevMap = new Map(prev.map((e) => [e.key, e]));\n const seen = new Set<string>();\n const next: ListEntry<T>[] = [];\n for (const item of items) {\n const key = getKey(item);\n if (seen.has(key)) {\n warnDev(`AnimatedList: duplicate key \"${key}\"; only the first item with it is shown.`);\n continue;\n }\n seen.add(key);\n const old = prevMap.get(key);\n const phase: ListPhase = !old ? (animate ? 'enter' : 'idle') : old.phase === 'exit' ? 'idle' : old.phase;\n next.push({ key, item, phase: animate ? phase : 'idle' });\n }\n if (animate) {\n // Each exiting entry goes right after the key that preceded it in `prev`.\n prev.forEach((e, i) => {\n if (seen.has(e.key)) return;\n let at = 0;\n if (i > 0) {\n const before = prev[i - 1]!.key;\n const idx = next.findIndex((x) => x.key === before);\n at = idx === -1 ? Math.min(i, next.length) : idx + 1;\n }\n next.splice(at, 0, e.phase === 'exit' ? e : { ...e, phase: 'exit' });\n });\n }\n return next;\n}\n\n/** A list whose items animate: new ones rise in, removed ones fade and close the gap\n * before they are dropped, and the rest slide to their new place (FLIP). The render\n * function gets each item's phase. Under reduced motion changes are instant. */\nexport function AnimatedList<T>({\n items,\n getKey,\n children,\n exitMs = 420,\n as = 'ul',\n className,\n itemClassName,\n}: AnimatedListProps<T>) {\n const reduced = usePrefersReducedMotion();\n const [state, setState] = useState<ListState<T>>(() => ({\n src: items,\n reduced,\n entries: reconcile([], items, getKey, false),\n }));\n let current = state;\n if (state.src !== items || state.reduced !== reduced) {\n current = { src: items, reduced, entries: reconcile(state.entries, items, getKey, !reduced) };\n setState(current);\n }\n const entries = current.entries;\n\n const els = useRef(new Map<string, HTMLElement>());\n const rects = useRef(new Map<string, { x: number; y: number }>());\n const anims = useRef(new Map<string, Animation>());\n const lastKeys = useRef<string | null>(null);\n const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());\n\n // Enter and exit timers: one per entry in that phase.\n useEffect(() => {\n const wanted = new Set<string>();\n for (const e of entries) {\n if (e.phase === 'idle') continue;\n const id = `${e.phase}:${e.key}`;\n wanted.add(id);\n if (timers.current.has(id)) continue;\n timers.current.set(\n id,\n setTimeout(\n () => {\n timers.current.delete(id);\n if (e.phase === 'exit') {\n // Fresh positions for the slide that follows the removal.\n const fresh = new Map<string, { x: number; y: number }>();\n els.current.forEach((el, k) => fresh.set(k, { x: el.offsetLeft, y: el.offsetTop }));\n rects.current = fresh;\n }\n setState((s) => ({\n ...s,\n entries:\n e.phase === 'exit'\n ? s.entries.filter((x) => !(x.key === e.key && x.phase === 'exit'))\n : s.entries.map((x) => (x.key === e.key && x.phase === 'enter' ? { ...x, phase: 'idle' as const } : x)),\n }));\n },\n e.phase === 'exit' ? exitMs : ENTER_MS,\n ),\n );\n }\n timers.current.forEach((timer, id) => {\n if (!wanted.has(id)) {\n clearTimeout(timer);\n timers.current.delete(id);\n }\n });\n }, [entries, exitMs]);\n useEffect(\n () => () => {\n timers.current.forEach((timer) => clearTimeout(timer));\n timers.current.clear();\n },\n [],\n );\n\n // FLIP: items that stayed move from their old place to the new one.\n useLayoutEffect(() => {\n const next = new Map<string, { x: number; y: number }>();\n els.current.forEach((el, k) => next.set(k, { x: el.offsetLeft, y: el.offsetTop }));\n const keyList = entries.map((e) => e.key).join('\\n');\n const reordered = lastKeys.current !== null && lastKeys.current !== keyList;\n lastKeys.current = keyList;\n const live = new Set(entries.map((e) => e.key));\n anims.current.forEach((anim, k) => {\n if (!live.has(k)) {\n anim.cancel();\n anims.current.delete(k);\n }\n });\n // Focus inside an exiting item moves to a staying neighbour.\n const active = typeof document !== 'undefined' ? document.activeElement : null;\n if (active) {\n const ei = entries.findIndex((e) => e.phase === 'exit' && els.current.get(e.key)?.contains(active));\n if (ei !== -1) {\n const target = [...entries.slice(ei + 1), ...entries.slice(0, ei).reverse()].find((e) => e.phase !== 'exit');\n const focusable = target\n ? els.current.get(target.key)?.querySelector<HTMLElement>('a[href], button, input, select, textarea, [tabindex]:not([tabindex=\"-1\"])')\n : null;\n if (focusable) focusable.focus({ preventScroll: true });\n }\n }\n if (!reduced && reordered) {\n for (const e of entries) {\n if (e.phase === 'exit') continue;\n const a = rects.current.get(e.key);\n const b = next.get(e.key);\n const el = els.current.get(e.key);\n if (!a || !b || !el || typeof el.animate !== 'function') continue;\n let dx = a.x - b.x;\n let dy = a.y - b.y;\n const running = anims.current.get(e.key);\n if (running) {\n // Start from where the item is drawn now, not from its layout position.\n const r1 = el.getBoundingClientRect();\n running.cancel();\n anims.current.delete(e.key);\n const r2 = el.getBoundingClientRect();\n dx += r1.left - r2.left;\n dy += r1.top - r2.top;\n }\n if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;\n const anim = el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {\n duration: MOVE_MS,\n easing: EASE,\n });\n anims.current.set(e.key, anim);\n anim.onfinish = () => {\n if (anims.current.get(e.key) === anim) anims.current.delete(e.key);\n };\n }\n }\n rects.current = next;\n }, [entries, reduced]);\n\n const Root = as;\n const Item = as === 'div' ? 'div' : 'li';\n return (\n <Root className={className}>\n {entries.map((e) => (\n <Item\n key={e.key}\n ref={(el: HTMLElement | null) => {\n if (!el) return;\n els.current.set(e.key, el);\n return () => {\n if (els.current.get(e.key) === el) els.current.delete(e.key);\n };\n }}\n className={cn('nish-flow-item', itemClassName)}\n data-phase={e.phase}\n aria-hidden={e.phase === 'exit' || undefined}\n inert={e.phase === 'exit' || undefined}\n style={e.phase === 'exit' ? ({ '--nish-flow-exit-ms': `${exitMs}ms` } as CSSProperties) : undefined}\n >\n <div className=\"nish-flow-item-inner\">{children(e.item, e.phase)}</div>\n </Item>\n ))}\n </Root>\n );\n}\n","import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { cn } from '../cn';\nimport { ago, dateTime } from '../format';\nimport { useLatest } from './latest';\n\n/** True while the CSS media query matches. False on the server and before hydration. */\nexport function useMediaQuery(query: string): boolean {\n const subscribe = useCallback(\n (onChange: () => void) => {\n if (typeof window === 'undefined' || !window.matchMedia) return () => {};\n const mq = window.matchMedia(query);\n mq.addEventListener('change', onChange);\n return () => mq.removeEventListener('change', onChange);\n },\n [query],\n );\n const get = () => typeof window !== 'undefined' && !!window.matchMedia && window.matchMedia(query).matches;\n return useSyncExternalStore(subscribe, get, () => false);\n}\n\nexport type Breakpoint = 'base' | 'sm' | 'md' | 'lg' | 'xl';\n\n/** Tailwind's breakpoints, in px. Phone = below sm; narrow = below md (cover screen and small tablets). */\nexport const BREAKPOINTS = { sm: 640, md: 768, lg: 1024, xl: 1280 } as const;\nexport const PHONE_QUERY = '(max-width: 639.98px)';\nexport const NARROW_QUERY = '(max-width: 767.98px)';\n\nconst BREAKPOINT_QUERIES: [Exclude<Breakpoint, 'base'>, string][] = (['xl', 'lg', 'md', 'sm'] as const).map((name) => [\n name,\n `(min-width: ${BREAKPOINTS[name]}px)`,\n]);\n\n/** True below 640px (the Fold's cover screen, any phone held upright). */\nexport function usePhone(): boolean {\n return useMediaQuery(PHONE_QUERY);\n}\n\n/** True below 768px: where BottomNav shows and NavRail hides. */\nexport function useNarrow(): boolean {\n return useMediaQuery(NARROW_QUERY);\n}\n\nfunction currentBreakpoint(): Breakpoint {\n if (typeof window === 'undefined' || !window.matchMedia) return 'base';\n for (const [name, q] of BREAKPOINT_QUERIES) if (window.matchMedia(q).matches) return name;\n return 'base';\n}\n\nfunction subscribeBreakpoint(onChange: () => void): () => void {\n if (typeof window === 'undefined' || !window.matchMedia) return () => {};\n const lists = BREAKPOINT_QUERIES.map(([, q]) => window.matchMedia(q));\n lists.forEach((l) => l.addEventListener('change', onChange));\n return () => lists.forEach((l) => l.removeEventListener('change', onChange));\n}\n\n/** The largest Tailwind breakpoint the viewport has reached: base, sm (640), md (768), lg (1024) or xl (1280). */\nexport function useBreakpoint(): Breakpoint {\n return useSyncExternalStore(subscribeBreakpoint, currentBreakpoint, () => 'base');\n}\n\n/**\n * Sets document.title to \"title · app\" (or just the app, or just the title) and restores\n * the previous title on unmount. An undefined title with no app leaves the title alone.\n */\nexport function useDocumentTitle(title: string | undefined, o: { app?: string } = {}): void {\n const app = o.app;\n useEffect(() => {\n if (typeof document === 'undefined') return;\n const next = title && app ? `${title} · ${app}` : title || app;\n if (!next) return;\n const previous = document.title;\n document.title = next;\n return () => {\n document.title = previous;\n };\n }, [title, app]);\n}\n\n/** Date.now() that updates every intervalMs, paused while the tab is hidden. */\nexport function useNow(intervalMs = 30000): number {\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (typeof document === 'undefined') return;\n let id: ReturnType<typeof setInterval> | undefined;\n const start = () => {\n if (id === undefined) id = setInterval(() => setNow(Date.now()), intervalMs);\n };\n const stop = () => {\n if (id !== undefined) clearInterval(id);\n id = undefined;\n };\n const onVisibility = () => {\n if (document.visibilityState === 'visible') {\n setNow(Date.now());\n start();\n } else stop();\n };\n if (document.visibilityState !== 'hidden') start();\n document.addEventListener('visibilitychange', onVisibility);\n return () => {\n stop();\n document.removeEventListener('visibilitychange', onVisibility);\n };\n }, [intervalMs]);\n return now;\n}\n\nconst LOCAL_EVENT = 'nish-local-storage';\n\nfunction readStored<T>(key: string, initial: T, raw: boolean): T {\n try {\n const text = window.localStorage.getItem(key);\n if (text === null) return initial;\n return raw ? (text as T) : (JSON.parse(text) as T);\n } catch {\n return initial;\n }\n}\n\n/**\n * State kept in localStorage. JSON by default, the raw string with { raw: true }. Never\n * throws (private mode, quota and bad JSON fall back to the initial value) and follows\n * changes from other tabs and from other hooks on the same key.\n */\nexport function useLocalStorage<T>(\n key: string,\n initial: T,\n o: { raw?: boolean } = {},\n): [T, (next: T | ((prev: T) => T)) => void] {\n const raw = !!o.raw;\n const initialRef = useLatest(initial);\n const [value, setValueState] = useState<T>(() =>\n typeof window === 'undefined' ? initial : readStored(key, initial, raw),\n );\n const valueRef = useLatest(value);\n const instanceRef = useRef<object>({});\n\n useEffect(() => {\n const sync = () => setValueState(readStored(key, initialRef.current, raw));\n sync();\n const onStorage = (e: StorageEvent) => {\n if (e.key === null || e.key === key) sync();\n };\n const onLocal = (e: Event) => {\n const d = (e as CustomEvent<{ key: string; source: object }>).detail;\n if (d && d.key === key && d.source !== instanceRef.current) sync();\n };\n window.addEventListener('storage', onStorage);\n window.addEventListener(LOCAL_EVENT, onLocal);\n return () => {\n window.removeEventListener('storage', onStorage);\n window.removeEventListener(LOCAL_EVENT, onLocal);\n };\n }, [initialRef, key, raw]);\n\n const setValue = useCallback(\n (next: T | ((prev: T) => T)) => {\n const resolved = typeof next === 'function' ? (next as (prev: T) => T)(valueRef.current) : next;\n valueRef.current = resolved;\n setValueState(resolved);\n try {\n window.localStorage.setItem(key, raw ? String(resolved) : JSON.stringify(resolved));\n } catch {\n // Storage unavailable: the value still lives in memory.\n }\n try {\n window.dispatchEvent(new CustomEvent(LOCAL_EVENT, { detail: { key, source: instanceRef.current } }));\n } catch {\n // No window events.\n }\n },\n [key, raw, valueRef],\n );\n\n return [value, setValue];\n}\n\nexport interface RelativeTimeProps {\n /** The moment: a Date, epoch milliseconds or a date string. */\n value: Date | number | string;\n /** \"3m ago\" (short, default) or \"3 minutes ago\" (long). */\n style?: 'short' | 'long';\n /** How often the text refreshes, in milliseconds. Default 30000. */\n refreshMs?: number;\n /** Classes for the time element. */\n className?: string;\n}\n\n/** A self-updating \"3m ago\". The full date and time show on hover and in the dateTime attribute. */\nexport function RelativeTime({ value, style = 'short', refreshMs = 30000, className }: RelativeTimeProps) {\n const now = useNow(refreshMs);\n const d = new Date(value);\n const iso = Number.isNaN(d.getTime()) ? undefined : d.toISOString();\n return (\n <time dateTime={iso} title={dateTime(value)} className={cn('tabular-nums', className)}>\n {ago(value, { now, style })}\n </time>\n );\n}\n","import type { SVGProps } from 'react';\n\n/** The handful of icons the shared components need, inlined so the package does not\n * pin apps to one lucide-react version. 24px grid, 2px stroke, lucide geometry. */\ntype IconProps = SVGProps<SVGSVGElement> & { size?: number };\n\nfunction Svg({ size = 16, children, ...rest }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...rest}\n >\n {children}\n </svg>\n );\n}\n\nexport const XIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </Svg>\n);\n\nexport const CheckCircleIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m9 12 2 2 4-4\" />\n </Svg>\n);\n\nexport const AlertTriangleIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4M12 17h.01\" />\n </Svg>\n);\n\nexport const InfoIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 16v-4M12 8h.01\" />\n </Svg>\n);\n\nexport const RotateIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8\" />\n <path d=\"M21 3v5h-5\" />\n </Svg>\n);\n\nexport const LoaderIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M21 12a9 9 0 1 1-6.22-8.56\" />\n </Svg>\n);\n\nexport const SunIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <path d=\"M12 2v2M12 20v2m-7.07-2.93 1.41-1.41M17.66 6.34l1.41-1.41M2 12h2m16 0h2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41\" />\n </Svg>\n);\n\nexport const MoonIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9\" />\n </Svg>\n);\n\nexport const MonitorIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"20\" height=\"14\" x=\"2\" y=\"3\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </Svg>\n);\n\nexport const ChevronDownIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m6 9 6 6 6-6\" />\n </Svg>\n);\n\nexport const CheckIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M20 6 9 17l-5-5\" />\n </Svg>\n);\n\nexport const ClockIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 6v6l4 2\" />\n </Svg>\n);\n\n/** Three horizontal dots. */\nexport const MoreIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"19\" cy=\"12\" r=\"1\" />\n <circle cx=\"5\" cy=\"12\" r=\"1\" />\n </Svg>\n);\n\nexport const BellIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9\" />\n <path d=\"M10.3 21a1.94 1.94 0 0 0 3.4 0\" />\n </Svg>\n);\n\nexport const SettingsIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </Svg>\n);\n\n/** A panel with its left column and an arrow pointing in: collapse a sidebar. */\nexport const PanelLeftCloseIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M9 3v18\" />\n <path d=\"m16 15-3-3 3-3\" />\n </Svg>\n);\n\n/** A panel with its left column and an arrow pointing out: expand a sidebar. */\nexport const PanelLeftOpenIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M9 3v18\" />\n <path d=\"m14 9 3 3-3 3\" />\n </Svg>\n);\n","import {\n forwardRef,\n useId,\n type ButtonHTMLAttributes,\n type HTMLAttributes,\n type InputHTMLAttributes,\n type ReactNode,\n type Ref,\n type SelectHTMLAttributes,\n} from 'react';\nimport { cn } from '../cn';\nimport { ChevronDownIcon, LoaderIcon } from './icons';\n\n// Controls grow to the 44px tap target on touch screens (pointer-coarse) and stay\n// compact under a mouse, so dense desktop tables keep their density.\n//\n// One recipe per look: each component that also has a class form (buttonClass,\n// iconButtonClass, cardClass, fieldClass, badgeClass) renders exactly that function's\n// output, so an <a>, a router <Link> or a one-off control can match it without copying\n// a class string.\n\n// --- Button -------------------------------------------------------------------------\n\nexport type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger' | 'soft' | 'subtle' | 'link';\nexport type ButtonSize = 'xs' | 'sm' | 'md' | 'lg';\n\nconst BUTTON_VARIANT: Record<ButtonVariant, string> = {\n primary: 'bg-th-accent text-th-on-accent hover:bg-th-accent/90 active:bg-th-accent/80',\n secondary: 'border border-th-line-strong bg-th-surface text-th-hi hover:bg-th-elevated',\n ghost: 'text-th-hi2 hover:bg-th-elevated hover:text-th-hi',\n danger: 'bg-th-loss text-th-on-loss hover:bg-th-loss/90 active:bg-th-loss/80',\n soft: 'bg-th-accent-soft text-th-accent hover:bg-th-accent/20 active:bg-th-accent/25',\n subtle: 'bg-th-elevated text-th-hi hover:bg-th-overlay',\n link: 'h-auto p-0 font-medium text-th-accent underline-offset-2 hover:underline',\n};\n\nconst BUTTON_SIZE: Record<ButtonSize, string> = {\n xs: 'h-6 gap-1 px-2 text-2xs pointer-coarse:min-h-11',\n sm: 'h-7 gap-1.5 px-2.5 text-xs pointer-coarse:min-h-11',\n md: 'h-9 gap-2 px-3.5 text-sm pointer-coarse:min-h-11',\n lg: 'h-11 gap-2 px-5 text-base',\n};\n\n// A link button sits inline in text: it keeps the size's type and gap, but has no\n// height, no padding and no touch growth.\nconst LINK_SIZE: Record<ButtonSize, string> = {\n xs: 'gap-1 text-2xs',\n sm: 'gap-1 text-xs',\n md: 'gap-1.5 text-sm',\n lg: 'gap-2 text-base',\n};\n\nconst BUTTON_BASE =\n 'inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap rounded-lg font-medium transition-[color,background-color,border-color,transform] duration-150';\n\n// Touch press feedback for filled buttons and icon buttons; never on a disabled one.\nconst PRESS = 'pointer-coarse:not-disabled:active:scale-[0.97]';\n\n// A link button's hit area grows to 44px on touch with an invisible ::after, so the\n// layout does not move.\nconst LINK_HIT =\n \"pointer-coarse:relative pointer-coarse:after:absolute pointer-coarse:after:-inset-x-2 pointer-coarse:after:-inset-y-3 pointer-coarse:after:content-['']\";\n\n// Disabled reads as disabled in every theme: a flat, quiet fill and faint text, instead\n// of a dimmed copy of the enabled color. A link only fades its text.\nconst BUTTON_DISABLED =\n 'disabled:pointer-events-none disabled:border disabled:border-th-line disabled:bg-th-elevated disabled:text-th-ghost disabled:shadow-none';\nconst LINK_DISABLED = 'disabled:pointer-events-none disabled:text-th-ghost disabled:no-underline';\n\nexport interface ButtonClassOptions {\n /** Same variants as Button. Default \"secondary\". */\n variant?: ButtonVariant;\n /** Same sizes as Button. Default \"md\". */\n size?: ButtonSize;\n /** Link variant only: skip the 44px touch hit area, for a link inside running text. */\n inline?: boolean;\n /** Extra classes, merged last (tailwind-merge resolves conflicts). */\n className?: string;\n}\n\n/** The classes `<Button>` renders, minus its `disabled:` styles. Use it on `<a>`, router\n * `<Link>`s and `<a download>` so links that look like buttons match them exactly. */\nexport function buttonClass({ variant = 'secondary', size = 'md', inline = false, className }: ButtonClassOptions = {}): string {\n return cn(\n BUTTON_BASE,\n variant === 'link' ? LINK_SIZE[size] : BUTTON_SIZE[size],\n variant === 'link' ? !inline && LINK_HIT : PRESS,\n BUTTON_VARIANT[variant],\n className,\n );\n}\n\nexport interface LinkClassOptions {\n /** accent: the accent color (default). muted: grey text that lights up on hover. */\n tone?: 'accent' | 'muted';\n /** Skip the 44px touch hit area, for a link inside running text. */\n inline?: boolean;\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes for a text link on a router `<Link>` or `<a>`: tone, underline on hover\n * and, on touch screens, a 44px hit area that does not move the layout. */\nexport function linkClass({ tone = 'accent', inline = false, className }: LinkClassOptions = {}): string {\n return cn(\n 'font-medium underline-offset-2 transition-colors duration-150 hover:underline',\n tone === 'accent' ? 'text-th-accent' : 'text-th-hi3 hover:text-th-hi',\n !inline && LINK_HIT,\n className,\n );\n}\n\n/** Classes that hide a row action until its row is hovered or focused, and always show\n * it on touch screens (there is no hover). Put `group` on the row. */\nexport function revealClass(className?: string): string {\n return cn(\n 'opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100',\n className,\n );\n}\n\nexport interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** primary: the one main action in a view. secondary: everything else. ghost:\n * toolbars and quiet actions. danger: destructive actions. soft: an accent action\n * that is not the main one (replaces \"accent outline\" buttons). subtle: a filled,\n * quiet button for dense toolbars and chips on a surface. link: looks like a text\n * link and sits inline in text (no height or padding; on touch screens an invisible\n * 44px hit area, unless `inline`). */\n variant?: ButtonVariant;\n /** xs for dense tool rows (24px), sm for dense rows and toolbars, lg for a page's\n * main call to action. xs, sm and md grow to 44px on touch screens. */\n size?: ButtonSize;\n /** Link variant only: skip the 44px touch hit area, for a link inside running text. */\n inline?: boolean;\n /** Shows a spinner and disables the button. */\n loading?: boolean;\n /** Icon before the label (16px for md and lg, 12–14px for xs and sm). Replaced by the\n * spinner while loading. */\n icon?: ReactNode;\n}\n\n/** The standard button. Defaults to type=\"button\", so it never submits a form by\n * accident; pass type=\"submit\" for the one that should. */\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(\n { variant = 'secondary', size = 'md', inline = false, loading = false, icon, className, children, disabled, type = 'button', ...rest },\n ref,\n) {\n return (\n <button\n ref={ref}\n type={type}\n disabled={disabled || loading}\n aria-busy={loading || undefined}\n className={buttonClass({\n variant,\n size,\n inline,\n className: cn(variant === 'link' ? LINK_DISABLED : BUTTON_DISABLED, className),\n })}\n {...rest}\n >\n {loading ? <LoaderIcon size={size === 'xs' || size === 'sm' ? 12 : 14} className=\"animate-spin\" /> : icon}\n {children}\n </button>\n );\n});\n\n// --- IconButton ---------------------------------------------------------------------\n\nexport type IconButtonSize = '2xs' | 'xs' | 'sm' | 'md';\nexport type IconButtonVariant = 'ghost' | 'subtle' | 'soft';\n\nconst ICON_SIZE: Record<IconButtonSize, string> = {\n '2xs': 'size-5 rounded',\n xs: 'size-6 rounded-md',\n sm: 'size-7 rounded-lg',\n md: 'size-9 rounded-lg',\n};\n\nconst ICON_VARIANT: Record<IconButtonVariant, { idle: string; active: string }> = {\n ghost: { idle: 'text-th-hi3 hover:bg-th-elevated hover:text-th-hi', active: 'bg-th-elevated text-th-hi' },\n subtle: { idle: 'bg-th-elevated text-th-hi hover:bg-th-overlay', active: 'bg-th-overlay text-th-hi' },\n soft: { idle: 'bg-th-accent-soft text-th-accent hover:bg-th-accent/20', active: 'bg-th-accent/25 text-th-accent' },\n};\n\nconst ICON_DANGER = 'hover:bg-th-loss-soft hover:text-th-loss active:bg-th-loss-soft active:text-th-loss';\n\nexport interface IconButtonClassOptions {\n /** Same sizes as IconButton. Default \"md\". */\n size?: IconButtonSize;\n /** Same variants as IconButton. Default \"ghost\". */\n variant?: IconButtonVariant;\n /** Same tones as IconButton. Default \"neutral\". */\n tone?: 'neutral' | 'danger';\n /** The pressed look (IconButton also sets aria-pressed; set it yourself on a link). */\n active?: boolean;\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes `<IconButton>` renders. Use it on an icon-only `<a>` or router `<Link>`,\n * and give that element an aria-label. */\nexport function iconButtonClass({\n size = 'md',\n variant = 'ghost',\n tone = 'neutral',\n active = false,\n className,\n}: IconButtonClassOptions = {}): string {\n return cn(\n 'inline-flex shrink-0 items-center justify-center transition-[color,background-color,border-color,transform] duration-150',\n PRESS,\n 'disabled:pointer-events-none disabled:bg-transparent disabled:text-th-ghost',\n 'pointer-coarse:min-h-11 pointer-coarse:min-w-11',\n ICON_SIZE[size],\n ICON_VARIANT[variant].idle,\n active && ICON_VARIANT[variant].active,\n tone === 'danger' && ICON_DANGER,\n active && tone === 'danger' && 'bg-th-loss-soft text-th-loss',\n className,\n );\n}\n\nexport interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** Required: an icon-only button needs a name for screen readers and tooltips. It is\n * also the title, so tests that query by title keep working. */\n label: string;\n /** 2xs: 20px (row-level reveal actions, 22px widget title bars), xs: 24px (dense\n * headers), sm: 28px, md: 36px. All grow to 44px on touch screens. */\n size?: IconButtonSize;\n /** Pressed state for toggles (sets aria-pressed). */\n active?: boolean;\n /** ghost: no fill until hover (default). subtle: a quiet filled square for toolbars on\n * a surface. soft: an accent tint for the highlighted action. */\n variant?: IconButtonVariant;\n /** danger: hover and pressed turn loss-red, for delete and remove actions. */\n tone?: 'neutral' | 'danger';\n}\n\n/** A square button holding only an icon, with its label as aria-label and title. */\nexport const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton(\n { label, size = 'md', active = false, variant = 'ghost', tone = 'neutral', className, children, type = 'button', ...rest },\n ref,\n) {\n return (\n <button\n ref={ref}\n type={type}\n aria-label={label}\n title={label}\n aria-pressed={active || undefined}\n className={iconButtonClass({ size, variant, tone, active, className })}\n {...rest}\n >\n {children}\n </button>\n );\n});\n\n// --- Card and CardHeader ------------------------------------------------------------\n\nexport type CardPadding = 'none' | 'sm' | 'md' | 'lg';\nexport type CardElement = 'div' | 'section' | 'article' | 'aside' | 'li';\n\nconst CARD_PADDING: Record<CardPadding, string> = {\n none: '',\n sm: 'p-3',\n md: 'p-4 sm:p-5',\n lg: 'p-6',\n};\n\nexport interface CardClassOptions {\n /** Inner padding. Default \"md\". */\n padding?: CardPadding;\n /** Kept from v0.2: false is the same as padding=\"none\". */\n padded?: boolean;\n /** Hover styles for cards that are links or buttons. */\n interactive?: boolean;\n /** surface: the bordered panel (default). inset: a quiet elevated box for use inside\n * another card. */\n variant?: 'surface' | 'inset';\n /** Extra classes, merged last. */\n className?: string;\n}\n\nconst resolvePadding = (padding: CardPadding | undefined, padded: boolean | undefined): CardPadding =>\n padding ?? (padded === false ? 'none' : 'md');\n\n/** The classes `<Card>` renders. Use it on a router `<Link>` or `<a>` that is a whole\n * card: `<Link className={cardClass({ interactive: true })}>`. */\nexport function cardClass({ padding, padded, interactive = false, variant = 'surface', className }: CardClassOptions = {}): string {\n const inset = variant === 'inset';\n return cn(\n inset ? 'rounded-lg border border-transparent bg-th-elevated' : 'rounded-xl border border-th-line bg-th-surface shadow-card',\n CARD_PADDING[resolvePadding(padding, padded)],\n interactive &&\n (inset\n ? 'transition-colors duration-150 hover:bg-th-overlay'\n : 'transition-colors duration-150 hover:border-th-line-strong hover:bg-th-elevated/60'),\n className,\n );\n}\n\nexport interface CardHeaderProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {\n /** The card's heading. */\n title: ReactNode;\n /** A quieter line under the title. */\n description?: ReactNode;\n /** Right-aligned slot: a Button, an IconButton, a Badge, a Segmented. It wraps under\n * the title on narrow cards. */\n action?: ReactNode;\n /** A small icon before the title (16px). */\n icon?: ReactNode;\n /** The heading level. Default \"h2\". */\n as?: 'h2' | 'h3' | 'h4';\n /** A bottom border and its own padding (px-4 py-3), for unpadded cards whose content\n * runs edge to edge (tables, lists, widgets). */\n divided?: boolean;\n /** id for the heading element, so a section can point aria-labelledby at it. */\n titleId?: string;\n}\n\n/** The header row of a card: title, optional description and icon, and an action slot. */\nexport function CardHeader({\n title,\n description,\n action,\n icon,\n as: Heading = 'h2',\n divided = false,\n titleId,\n className,\n ...rest\n}: CardHeaderProps) {\n return (\n <div\n className={cn(\n 'flex flex-wrap items-center justify-between gap-x-3 gap-y-2',\n divided && 'border-b border-th-line px-4 py-3',\n className,\n )}\n {...rest}\n >\n <div className=\"flex min-w-0 items-start gap-2\">\n {icon ? (\n <span className=\"mt-0.5 inline-flex shrink-0 text-th-hi3\" aria-hidden=\"true\">\n {icon}\n </span>\n ) : null}\n <div className=\"min-w-0\">\n <Heading id={titleId} className=\"text-sm font-semibold text-th-hi\">\n {title}\n </Heading>\n {description ? <p className=\"mt-0.5 text-xs text-th-hi3\">{description}</p> : null}\n </div>\n </div>\n {action ? <div className=\"flex shrink-0 flex-wrap items-center gap-2\">{action}</div> : null}\n </div>\n );\n}\n\nexport interface CardProps extends Omit<HTMLAttributes<HTMLElement>, 'title'> {\n /** The element to render. Use section or article for a titled region, li inside a list. */\n as?: CardElement;\n /** Inner padding: sm p-3, md p-4 (p-5 from 640px; the default), lg p-6, none for\n * tables and lists that run edge to edge. Use this, not className=\"p-3\", which would\n * keep md's sm:p-5. */\n padding?: CardPadding;\n /** Kept from v0.2: false is the same as padding=\"none\". padding wins when both are set. */\n padded?: boolean;\n /** Hover styles for cards that are links or buttons. */\n interactive?: boolean;\n /** surface: the bordered panel with the card shadow (default). inset: bg-th-elevated,\n * no border color, no shadow and rounded-lg, for a box inside another card. */\n variant?: 'surface' | 'inset';\n /** Renders a CardHeader first. On an unpadded card the header is divided (its own\n * padding and a bottom border). */\n title?: ReactNode;\n /** The header's description; only with title. */\n description?: ReactNode;\n /** The header's right-aligned action slot; only with title. */\n action?: ReactNode;\n}\n\n/** The surface panel every widget, table and form sits in. */\nexport const Card = forwardRef<HTMLElement, CardProps>(function Card(\n { as = 'div', padding, padded, interactive = false, variant = 'surface', title, description, action, className, children, ...rest },\n ref,\n) {\n const Tag = as as 'div';\n const pad = resolvePadding(padding, padded);\n const headingId = useId();\n const region = title != null && (as === 'section' || as === 'article' || as === 'aside');\n return (\n <Tag\n ref={ref as Ref<HTMLDivElement>}\n aria-labelledby={region && !rest['aria-label'] && !rest['aria-labelledby'] ? headingId : undefined}\n className={cardClass({ padding: pad, interactive, variant, className })}\n {...rest}\n >\n {title != null ? (\n <CardHeader\n title={title}\n description={description}\n action={action}\n titleId={headingId}\n divided={pad === 'none'}\n className={pad === 'none' ? undefined : 'mb-3'}\n />\n ) : null}\n {children}\n </Tag>\n );\n});\n\n// --- Badge --------------------------------------------------------------------------\n\nexport type BadgeTone = 'neutral' | 'accent' | 'ok' | 'loss' | 'warn' | 'info' | 'on-accent';\ntype Tone = BadgeTone;\nexport type BadgeHue = 'emerald' | 'indigo' | 'amber' | 'lime' | 'rose' | 'sky' | 'violet' | 'teal';\n\nconst BADGE_TONE: Record<Tone, string> = {\n neutral: 'border-th-line bg-th-elevated text-th-hi2',\n accent: 'border-th-accent/30 bg-th-accent-soft text-th-accent',\n ok: 'border-th-ok/30 bg-th-ok-soft text-th-ok',\n loss: 'border-th-loss/30 bg-th-loss-soft text-th-loss',\n warn: 'border-th-warn/30 bg-th-warn-soft text-th-warn',\n info: 'border-th-info/30 bg-th-info-soft text-th-info',\n // A label on a solid accent fill (inside a primary Button or an accent link).\n 'on-accent': 'border-transparent bg-th-on-accent/20 text-th-on-accent',\n};\n\n// Full literal class names, so Tailwind's scanner finds every one.\nconst BADGE_HUE: Record<BadgeHue, string> = {\n emerald: 'border-th-emerald/30 bg-th-emerald-soft text-th-hi',\n indigo: 'border-th-indigo/30 bg-th-indigo-soft text-th-hi',\n amber: 'border-th-amber/30 bg-th-amber-soft text-th-hi',\n lime: 'border-th-lime/30 bg-th-lime-soft text-th-hi',\n rose: 'border-th-rose/30 bg-th-rose-soft text-th-hi',\n sky: 'border-th-sky/30 bg-th-sky-soft text-th-hi',\n violet: 'border-th-violet/30 bg-th-violet-soft text-th-hi',\n teal: 'border-th-teal/30 bg-th-teal-soft text-th-hi',\n};\n\n// The dot is StatusDot's xs recipe (6px, the tone's -fill).\nconst DOT_TONE: Record<Tone, string> = {\n neutral: 'bg-th-ghost',\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n loss: 'bg-th-loss-fill',\n warn: 'bg-th-warn-fill',\n info: 'bg-th-info-fill',\n 'on-accent': 'bg-th-on-accent',\n};\n\nconst DOT_HUE: Record<BadgeHue, string> = {\n emerald: 'bg-th-emerald',\n indigo: 'bg-th-indigo',\n amber: 'bg-th-amber',\n lime: 'bg-th-lime',\n rose: 'bg-th-rose',\n sky: 'bg-th-sky',\n violet: 'bg-th-violet',\n teal: 'bg-th-teal',\n};\n\nexport interface BadgeClassOptions {\n /** Same tones as Badge. Default \"neutral\". */\n tone?: Tone;\n /** Same hues as Badge; overrides tone. */\n hue?: BadgeHue;\n /** Same sizes as Badge. Default \"sm\". */\n size?: 'xs' | 'sm';\n /** Same variants as Badge. Default \"pill\". */\n variant?: 'pill' | 'tag';\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes `<Badge>` renders (without the dot), for a badge-shaped link or a\n * label inside a third-party renderer. */\nexport function badgeClass({ tone = 'neutral', hue, size = 'sm', variant = 'pill', className }: BadgeClassOptions = {}): string {\n return cn(\n 'inline-flex items-center gap-1 whitespace-nowrap rounded-full border font-medium',\n size === 'xs' ? 'px-1.5 py-0 text-3xs leading-4' : 'px-2 py-0.5 text-xs leading-4',\n hue ? BADGE_HUE[hue] : BADGE_TONE[tone],\n variant === 'tag' && 'rounded-sm border-transparent font-semibold uppercase tracking-wide',\n className,\n );\n}\n\nexport interface BadgeProps extends HTMLAttributes<HTMLSpanElement> {\n /** Text on its own soft tint; every tone clears 4.5:1 in every theme. on-accent: a\n * small label inside a solid accent fill (a primary Button, an accent link), in the\n * on-accent color over a 20% on-accent tint. It has no hover state; pair a short\n * label with sr-only text that says what it means. */\n tone?: Tone;\n /** A color with no meaning (stores, categories, tags): the hue's soft tint with hi\n * text, so it reads in every theme. Overrides tone. */\n hue?: BadgeHue;\n /** sm: the default 12px pill. xs: 10px text for dense rows and table cells. */\n size?: 'xs' | 'sm';\n /** pill: rounded (default). tag: square corners, no border, bold uppercase, for\n * tag-shaped labels (\"CALL\", \"NEW\"). */\n variant?: 'pill' | 'tag';\n /** A leading 6px status dot in the tone's fill (or the hue). Pair it with text that\n * says the state; the dot itself is hidden from screen readers. */\n dot?: boolean;\n}\n\n/** A small status pill: counts, states, tags. */\nexport function Badge({ tone = 'neutral', hue, size = 'sm', variant = 'pill', dot = false, className, children, ...rest }: BadgeProps) {\n return (\n <span className={badgeClass({ tone, hue, size, variant, className })} {...rest}>\n {dot ? (\n <span aria-hidden=\"true\" className={cn('inline-block size-1.5 shrink-0 rounded-full', hue ? DOT_HUE[hue] : DOT_TONE[tone])} />\n ) : null}\n {children}\n </span>\n );\n}\n\n// --- Fields: Input, Select (and the shared FIELD recipe) -----------------------------\n\nexport type FieldSize = 'xs' | 'sm' | 'md';\n\n/** The field look without size: border, fill, hover, focus ring, disabled and invalid.\n * Internal to the package (Textarea in forms.tsx builds on it); apps use fieldClass(). */\nexport const FIELD =\n 'w-full min-w-0 rounded-lg border border-th-line-strong bg-th-elevated text-th-hi placeholder:text-th-ghost ' +\n 'transition-colors duration-150 hover:border-th-hi3/60 focus:border-th-accent focus:outline-none focus:ring-2 focus:ring-th-accent/25 ' +\n 'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-th-loss';\n\n// Touch screens always get 16px text (text-base), so iOS does not zoom on focus. Under a\n// mouse the size's own text size applies at every width, so a narrow popout window\n// driven by a mouse keeps its dense text.\n// Padding is split into pl and pr, so a slot or a select chevron can replace one side\n// without fighting a px class.\nconst FIELD_SIZE: Record<FieldSize, { box: string; pad: string; text: string }> = {\n xs: { box: 'h-7 pointer-coarse:min-h-11', pad: 'pl-2 pr-2', text: 'text-2xs pointer-coarse:text-base' },\n sm: { box: 'h-8 pointer-coarse:min-h-11', pad: 'pl-2.5 pr-2.5', text: 'text-xs pointer-coarse:text-base' },\n md: { box: 'h-9 pointer-coarse:min-h-11', pad: 'pl-3 pr-3', text: 'text-sm pointer-coarse:text-base' },\n};\n\nconst FIELD_INVALID = 'border-th-loss hover:border-th-loss';\n\nexport interface FieldClassOptions {\n /** md h-9 (default), sm h-8, xs h-7. All grow to 44px on touch screens. */\n size?: FieldSize;\n /** The red invalid border, for elements that do not set aria-invalid themselves. */\n invalid?: boolean;\n /** Extra classes, merged last. */\n className?: string;\n}\n\n/** The classes `<Input>` renders: the shared field look at a size. Use it for a one-off\n * control (a date input, a contenteditable) instead of copying a class string. */\nexport function fieldClass({ size = 'md', invalid = false, className }: FieldClassOptions = {}): string {\n const s = FIELD_SIZE[size];\n return cn(FIELD, s.box, s.pad, s.text, invalid && FIELD_INVALID, className);\n}\n\nexport interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> {\n /** Red border and aria-invalid. Pair it with an error message tied by aria-describedby. */\n invalid?: boolean;\n /** md h-9 (default), sm h-8 with 12px text, xs h-7 with 11px text. Touch screens\n * always get 16px text and a 44px height. (Replaces the native size attribute; set a width with\n * className instead.) */\n size?: FieldSize;\n /** A decorative slot inside the left edge: a search icon, a \"$\" prefix. It ignores\n * pointer events, so clicks reach the input. */\n leading?: ReactNode;\n /** A slot inside the right edge that may be interactive: a clear IconButton, a unit\n * suffix. */\n trailing?: ReactNode;\n /** Classes for the wrapper span that holds the slots (only rendered with leading or\n * trailing). className stays on the input. */\n wrapperClassName?: string;\n}\n\n/** Text input. 16px text on touch screens so iOS does not zoom the page on focus. */\nexport const Input = forwardRef<HTMLInputElement, InputProps>(function Input(\n { invalid, size = 'md', leading, trailing, wrapperClassName, className, ...rest },\n ref,\n) {\n const input = (\n <input\n ref={ref}\n aria-invalid={invalid || undefined}\n className={fieldClass({ size, className: cn(leading != null && 'pl-8', trailing != null && 'pr-8', className) })}\n {...rest}\n />\n );\n if (leading == null && trailing == null) return input;\n return (\n <span className={cn('relative inline-flex w-full min-w-0 items-center', wrapperClassName)}>\n {leading != null ? (\n <span className=\"pointer-events-none absolute inset-y-0 left-0 flex w-8 items-center justify-center text-sm text-th-hi2\">\n {leading}\n </span>\n ) : null}\n {input}\n {trailing != null ? (\n <span className=\"absolute inset-y-0 right-0 flex min-w-8 items-center justify-center pr-0.5 text-sm text-th-hi2\">{trailing}</span>\n ) : null}\n </span>\n );\n});\n\nconst SELECT_SIZE: Record<FieldSize, { pad: string; chevron: string; icon: number }> = {\n xs: { pad: 'pl-2 pr-6', chevron: 'right-1.5', icon: 12 },\n sm: { pad: 'pl-2.5 pr-7', chevron: 'right-2', icon: 13 },\n md: { pad: 'pl-3 pr-8', chevron: 'right-2.5', icon: 14 },\n};\n\nexport interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'> {\n /** Red border and aria-invalid. */\n invalid?: boolean;\n /** md h-9 (default), sm h-8, xs h-7, the same as Input. Touch screens get 16px text\n * and a 44px height. (Replaces the native size attribute, which turns a select into a list box.) */\n size?: FieldSize;\n /** Classes for the inner <select> itself. className sizes the wrapper (width, margin);\n * use this instead of reaching in with [&>select]:… */\n selectClassName?: string;\n}\n\n/** Native select (keeps the platform picker on phones) with the shared field look. */\nexport const Select = forwardRef<HTMLSelectElement, SelectProps>(function Select(\n { invalid, size = 'md', selectClassName, className, children, ...rest },\n ref,\n) {\n const s = SELECT_SIZE[size];\n return (\n <span className={cn('relative inline-flex w-full min-w-0', className)}>\n <select\n ref={ref}\n aria-invalid={invalid || undefined}\n className={fieldClass({ size, className: cn('appearance-none', s.pad, selectClassName) })}\n {...rest}\n >\n {children}\n </select>\n <ChevronDownIcon size={s.icon} className={cn('pointer-events-none absolute top-1/2 -translate-y-1/2 text-th-hi3', s.chevron)} />\n </span>\n );\n});\n\n// --- Label --------------------------------------------------------------------------\n\n/** Small uppercase label for form fields and section headings. */\nexport function Label({ className, ...rest }: HTMLAttributes<HTMLSpanElement>) {\n return <span className={cn('text-xs font-medium uppercase tracking-wider text-th-hi3', className)} {...rest} />;\n}\n","import { memo } from 'react';\nimport { StatusDot } from '../display';\nimport { TickerText } from '../flow';\nimport type { FollowStep } from './follow';\n\n/** The pill at the bottom left of the canvas saying what follow mode is looking at. */\nexport const FollowCaption = memo(function FollowCaption({ step }: { step: FollowStep | null }) {\n if (!step) return null;\n const only = step.targets.length === 1 ? step.targets[0]! : null;\n const text =\n step.mode === 'idle'\n ? 'Following · waiting for activity'\n : only\n ? `Following · ${only.group} › ${only.label}`\n : `Following ${step.targets.length} active pieces`;\n return (\n <div\n data-canvas-ui\n role=\"status\"\n aria-live=\"polite\"\n className=\"absolute bottom-[68px] left-3 z-10 flex max-w-[min(420px,calc(100%-24px))] items-center gap-2 rounded-xl border border-th-line bg-th-surface px-3 py-2 text-xs text-th-hi shadow-card min-[600px]:bottom-3\"\n >\n <StatusDot tone=\"accent\" pulse={step.mode !== 'idle'} />\n <div className=\"min-w-0\">\n <div className=\"truncate\">{text}</div>\n {only?.note ? <TickerText as=\"div\" text={only.note} className=\"truncate text-th-ghost\" /> : null}\n </div>\n </div>\n );\n});\n","import {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n type HTMLAttributes,\n type ReactNode,\n type SVGProps,\n} from 'react';\nimport { cn } from '../cn';\nimport { sparklineGeometry } from '../sparkline-path';\nimport { Skeleton } from './feedback';\nimport { AlertTriangleIcon, CheckCircleIcon, ChevronDownIcon, InfoIcon, XIcon } from './icons';\nimport { useHeightVar, useStuck } from './layout-vars';\nimport { DropdownMenu, Tooltip } from './overlay';\nimport { Badge, Button, Card, IconButton, type ButtonProps } from './primitives';\nimport { ThemeToggle } from './theme-toggle';\n\n// Read-only display pieces: notices, status marks, numbers, meters, small charts,\n// headers. Every color is a role; fills (*-fill) for marks, plain roles for text.\n\n// --- icons only this file needs (24px grid, 2px stroke, lucide geometry) -------------\n\ntype IconProps = SVGProps<SVGSVGElement> & { size?: number };\n\nfunction Svg({ size = 16, children, ...rest }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...rest}\n >\n {children}\n </svg>\n );\n}\n\nconst CopyIcon = (p: IconProps) => (\n <Svg {...p}>\n <rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" />\n <path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\" />\n </Svg>\n);\n\nconst CheckIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M20 6 9 17l-5-5\" />\n </Svg>\n);\n\nconst ChevronRightIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m9 18 6-6-6-6\" />\n </Svg>\n);\n\n// --- shared tone maps -----------------------------------------------------------------\n\n/** Status tones shared by the display components. */\nexport type StatusTone = 'ok' | 'warn' | 'loss' | 'info' | 'accent' | 'neutral';\n\n/** Solid fills for marks (dots, bars, meters). */\nconst FILL: Record<StatusTone, string> = {\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n info: 'bg-th-info-fill',\n accent: 'bg-th-accent',\n neutral: 'bg-th-ghost',\n};\n\n// =====================================================================================\n// Callout\n// =====================================================================================\n\nexport type CalloutTone = 'neutral' | 'accent' | 'info' | 'ok' | 'warn' | 'loss';\n\n// box: translucent tint that sits in the flow. bar: the same tint flattened onto the page\n// background (-soft-solid), so content scrolling under a sticky bar never shows through.\nconst CALLOUT_TONE: Record<CalloutTone, { box: string; bar: string; icon: string }> = {\n neutral: { box: 'border-th-line bg-th-elevated', bar: 'border-th-line bg-th-elevated', icon: 'text-th-hi3' },\n accent: { box: 'border-th-accent/30 bg-th-accent-soft', bar: 'border-th-accent/30 bg-th-accent-soft-solid', icon: 'text-th-accent' },\n info: { box: 'border-th-info/30 bg-th-info-soft', bar: 'border-th-info/30 bg-th-info-soft-solid', icon: 'text-th-info' },\n ok: { box: 'border-th-ok/30 bg-th-ok-soft', bar: 'border-th-ok/30 bg-th-ok-soft-solid', icon: 'text-th-ok' },\n warn: { box: 'border-th-warn/30 bg-th-warn-soft', bar: 'border-th-warn/30 bg-th-warn-soft-solid', icon: 'text-th-warn' },\n loss: { box: 'border-th-loss/30 bg-th-loss-soft', bar: 'border-th-loss/30 bg-th-loss-soft-solid', icon: 'text-th-loss' },\n};\n\nconst CALLOUT_CLAMP = { 1: 'line-clamp-1', 2: 'line-clamp-2', 3: 'line-clamp-3' } as const;\n\nfunction defaultCalloutIcon(tone: CalloutTone, size: number): ReactNode {\n if (tone === 'ok') return <CheckCircleIcon size={size} />;\n if (tone === 'warn' || tone === 'loss') return <AlertTriangleIcon size={size} />;\n return <InfoIcon size={size} />;\n}\n\nexport interface CalloutProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title' | 'onClick'> {\n /** What kind of notice: info and accent for news, ok for success, warn for something to\n * check, loss for a failure. neutral is a plain grey note. */\n tone?: CalloutTone;\n /** Leading icon. Defaults by tone (Info, CheckCircle or AlertTriangle); false hides it. */\n icon?: ReactNode | false;\n /** A short bold first line. */\n title?: ReactNode;\n /** The body text. */\n children?: ReactNode;\n /** Usually one small Button or link, shown after the text. */\n action?: ReactNode;\n /** Adds a Dismiss button that calls this. */\n onDismiss?: () => void;\n /** box: a rounded tinted box in the flow (default). bar: full width with square\n * corners and no side borders, for a sticky page-level alert. */\n variant?: 'box' | 'bar';\n /** Tighter padding and xs text, for widgets and table cells. */\n compact?: boolean;\n /** Announce it when it appears: role=\"alert\" for loss, role=\"status\" otherwise.\n * Leave it off for notices that are part of the page from the start. */\n live?: boolean;\n /** Sticks under the app header (`top: var(--nish-header-h)`), above page content. Pair\n * with variant=\"bar\". */\n sticky?: boolean;\n /** Limits the body to 1, 2 or 3 lines with an ellipsis, instead of growing. */\n clamp?: 1 | 2 | 3;\n /** Makes the icon, title and text one link (at least 44px tall) with a trailing\n * chevron. `action` and the dismiss button stay separate controls beside it. */\n href?: string;\n /** Like href, but a button. */\n onClick?: () => void;\n /** Shows a \"+{count}\" badge after the title, for \"and 3 more\" notices. */\n count?: number;\n}\n\n/** An inline notice: a tinted box with an icon, an optional title, text and an action.\n * variant=\"bar\" is opaque, so it can stick under the header without content showing\n * through. */\nexport function Callout({\n tone = 'info',\n icon,\n title,\n children,\n action,\n onDismiss,\n variant = 'box',\n compact = false,\n live = false,\n sticky = false,\n clamp,\n href,\n onClick,\n count,\n className,\n ...rest\n}: CalloutProps) {\n const t = CALLOUT_TONE[tone];\n const shown = icon === false ? null : (icon ?? defaultCalloutIcon(tone, compact ? 14 : 16));\n const interactive = href != null || onClick != null;\n const iconEl = shown ? <span className={cn('shrink-0', compact ? 'mt-px' : 'mt-0.5', t.icon)}>{shown}</span> : null;\n const text = (\n <div className=\"min-w-0 flex-1 basis-60\">\n {title || count != null ? (\n <p className=\"flex items-center gap-2 font-medium leading-snug text-th-hi\">\n {title ? <span className=\"min-w-0\">{title}</span> : null}\n {count != null ? (\n <Badge tone={tone} aria-label={`${count} more`} className=\"shrink-0\">\n +{count}\n </Badge>\n ) : null}\n </p>\n ) : null}\n {children ? (\n <div className={cn('leading-snug text-th-hi2', title || count != null ? 'mt-0.5' : null, clamp && CALLOUT_CLAMP[clamp])}>\n {children}\n </div>\n ) : null}\n </div>\n );\n const actionEl = action ? <div className=\"flex shrink-0 items-center gap-2\">{action}</div> : null;\n const dismissEl = onDismiss ? (\n <IconButton label=\"Dismiss\" size=\"xs\" onClick={onDismiss} className=\"-my-0.5 -mr-1\">\n <XIcon size={14} />\n </IconButton>\n ) : null;\n const chevron = <ChevronDownIcon size={16} className=\"-rotate-90 shrink-0 self-center text-th-hi3\" />;\n const hit = cn(\n 'flex min-h-11 min-w-0 flex-1 items-start text-left outline-none focus-visible:ring-2 focus-visible:ring-th-accent/40',\n compact ? 'gap-2' : 'gap-3',\n // Pull the padding of the row into the link so the whole row is the target.\n compact ? '-my-2 py-2' : '-my-3 py-3',\n );\n return (\n <div\n role={live ? (tone === 'loss' ? 'alert' : 'status') : undefined}\n className={cn(\n 'flex border',\n variant === 'bar' && action ? 'items-center' : 'items-start',\n compact ? 'gap-2 px-3 py-2 text-xs' : 'gap-3 px-4 py-3 text-sm',\n variant === 'bar' ? 'w-full rounded-none border-x-0' : 'rounded-xl',\n variant === 'bar' ? t.bar : t.box,\n sticky && 'sticky top-[var(--nish-header-h,0px)] z-20',\n className,\n )}\n {...rest}\n >\n {interactive ? (\n <>\n {href != null ? (\n <a href={href} className={hit}>\n {iconEl}\n <span className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2\">{text}</span>\n {chevron}\n </a>\n ) : (\n <button type=\"button\" onClick={onClick} className={hit}>\n {iconEl}\n <span className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2\">{text}</span>\n {chevron}\n </button>\n )}\n {actionEl}\n {dismissEl}\n </>\n ) : (\n <>\n {iconEl}\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2\">\n {text}\n {actionEl}\n </div>\n {dismissEl}\n </>\n )}\n </div>\n );\n}\n\n// =====================================================================================\n// StatusDot\n// =====================================================================================\n\nconst DOT_SIZE = { xs: 'size-1.5', sm: 'size-2', md: 'size-2.5', lg: 'size-3.5' } as const;\n\nconst HALO: Record<StatusTone, string> = {\n ok: 'ring-4 ring-th-ok-fill/25',\n warn: 'ring-4 ring-th-warn-fill/25',\n loss: 'ring-4 ring-th-loss-fill/25',\n info: 'ring-4 ring-th-info-fill/25',\n accent: 'ring-4 ring-th-accent/25',\n neutral: 'ring-4 ring-th-ghost/25',\n};\n\nexport interface StatusDotProps {\n /** ok, warn, loss and info use the status fills; accent the accent; neutral the ghost grey. */\n tone: StatusTone;\n /** xs 6px, sm 8px (default), md 10px, lg 14px. */\n size?: keyof typeof DOT_SIZE;\n /** Gently pulses the opacity, for \"live\" or \"running\". Still under reduced motion. */\n pulse?: boolean;\n /** A soft ring around the dot, for a header status. */\n halo?: boolean;\n /** The accessible name read by screen readers (\"Up\", \"Degraded\"; role=\"img\"). Without it the\n * dot is aria-hidden, so always pair it with visible text then. */\n label?: string;\n className?: string;\n}\n\n/** A small round status mark. Color is never the only signal: give it a label or\n * put text beside it. */\nexport function StatusDot({ tone, size = 'sm', pulse = false, halo = false, label, className }: StatusDotProps) {\n return (\n <span\n role={label ? 'img' : undefined}\n aria-label={label}\n aria-hidden={label ? undefined : true}\n className={cn(\n 'inline-block shrink-0 rounded-full',\n DOT_SIZE[size],\n FILL[tone],\n halo && HALO[tone],\n pulse && 'motion-safe:animate-pulse',\n className,\n )}\n />\n );\n}\n\n// =====================================================================================\n// Stat, StatGrid, signTone\n// =====================================================================================\n\n/** ok for a positive number, loss for a negative one, neutral for zero or nothing.\n * Replaces `n >= 0 ? gain : loss` ternaries. */\nexport function signTone(n: number | null | undefined): 'ok' | 'loss' | 'neutral' {\n if (n == null || Number.isNaN(n) || n === 0) return 'neutral';\n return n > 0 ? 'ok' : 'loss';\n}\n\nconst STAT_VALUE_SIZE = { sm: 'text-base', md: 'text-xl', lg: 'text-2xl' } as const;\nconst STAT_SKELETON = { sm: 'h-6', md: 'h-7', lg: 'h-8' } as const;\nconst STAT_TONE = { ok: 'text-th-ok', loss: 'text-th-loss', warn: 'text-th-warn', neutral: 'text-th-hi' } as const;\n\n// Set by StatGrid so each Stat renders a <div> of <dt>/<dd> inside its <dl>.\nconst InStatGrid = createContext(false);\n\nexport interface StatProps {\n /** What the number is: \"Open positions\", \"Uptime (30d)\". */\n label: ReactNode;\n /** The number, already formatted (\"$12,480\", \"99.95%\"). */\n value: ReactNode;\n /** A quiet line under the value: a change, a date, a unit. */\n sub?: ReactNode;\n /** Colors the value: ok for gains, loss for losses, warn for attention. Use\n * signTone(n) for signed numbers. */\n tone?: 'ok' | 'loss' | 'warn' | 'neutral';\n /** An explanation shown in a tooltip on the label (dotted underline). */\n tip?: ReactNode;\n /** Value size: sm 16px, md 20px (default), lg 24px. */\n size?: keyof typeof STAT_VALUE_SIZE;\n /** card: a small Card (default). inset: a grey box for use inside a card. plain: no box. */\n variant?: 'card' | 'inset' | 'plain';\n /** Skeleton bars of the same size instead of the value and sub. */\n loading?: boolean;\n className?: string;\n}\n\n/** One labelled number. Inside a StatGrid it is a row of the grid's <dl>; on its own it\n * renders its own <dl>. */\nexport function Stat({\n label,\n value,\n sub,\n tone = 'neutral',\n tip,\n size = 'md',\n variant = 'card',\n loading = false,\n className,\n}: StatProps) {\n const inGrid = useContext(InStatGrid);\n // hi3 clears 4.5:1 on bg and surface only; on the elevated inset box the quiet text is hi2.\n const quiet = variant === 'inset' ? 'text-th-hi2' : 'text-th-hi3';\n const body = (\n <>\n <dt className={cn('text-xs', quiet)}>\n {tip ? (\n <Tooltip tip={tip} variant=\"hint\">\n {label}\n </Tooltip>\n ) : (\n label\n )}\n </dt>\n {loading ? (\n <dd className=\"mt-1\" aria-busy=\"true\">\n <Skeleton className={cn('w-24', STAT_SKELETON[size])} />\n {sub ? <Skeleton className=\"mt-1.5 h-3 w-16\" /> : null}\n </dd>\n ) : (\n <>\n <dd\n className={cn(\n 'mt-0.5 font-semibold tabular-nums tracking-tight [overflow-wrap:anywhere]',\n STAT_VALUE_SIZE[size],\n STAT_TONE[tone],\n )}\n >\n {value}\n </dd>\n {sub ? <dd className={cn('mt-0.5 text-xs', quiet)}>{sub}</dd> : null}\n </>\n )}\n </>\n );\n const Box = inGrid ? 'div' : 'dl';\n if (variant === 'card') {\n return (\n <Card padding=\"sm\" className={cn('min-w-0', className)}>\n {inGrid ? body : <dl>{body}</dl>}\n </Card>\n );\n }\n return <Box className={cn('min-w-0', variant === 'inset' && 'rounded-lg bg-th-elevated p-3', className)}>{body}</Box>;\n}\n\nconst GRID_BASE = { 1: 'grid-cols-1', 2: 'grid-cols-2', 3: 'grid-cols-3', 4: 'grid-cols-4' } as const;\nconst GRID_MD = {\n 2: 'md:grid-cols-2',\n 3: 'md:grid-cols-3',\n 4: 'md:grid-cols-4',\n 5: 'md:grid-cols-5',\n 6: 'md:grid-cols-6',\n} as const;\n\nexport interface StatGridProps {\n /** Columns on phones (base, default 2) and from 768px (md, default 4). */\n cols?: { base?: keyof typeof GRID_BASE; md?: keyof typeof GRID_MD };\n /** Stat elements. */\n children: ReactNode;\n className?: string;\n}\n\n/** A responsive grid of Stats, rendered as one <dl>. */\nexport function StatGrid({ cols, children, className }: StatGridProps) {\n return (\n <dl className={cn('grid gap-3', GRID_BASE[cols?.base ?? 2], GRID_MD[cols?.md ?? 4], className)}>\n <InStatGrid.Provider value={true}>{children}</InStatGrid.Provider>\n </dl>\n );\n}\n\n// =====================================================================================\n// Meter, toneFor\n// =====================================================================================\n\n/** ok, warn or loss for a value against two thresholds. When loss is above warn, higher\n * is worse (disk use: { warn: 75, loss: 90 }). When loss is below warn, lower is worse\n * (battery: { warn: 30, loss: 10 }). */\nexport function toneFor(value: number, t: { warn: number; loss: number }): 'ok' | 'warn' | 'loss' {\n if (t.loss >= t.warn) return value >= t.loss ? 'loss' : value >= t.warn ? 'warn' : 'ok';\n return value <= t.loss ? 'loss' : value <= t.warn ? 'warn' : 'ok';\n}\n\ntype ChartTone = `chart-${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8}`;\nexport type MeterTone = 'accent' | 'ok' | 'warn' | 'loss' | 'info' | 'neutral' | ChartTone;\n\nconst METER_FILL: Record<MeterTone, string> = {\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n info: 'bg-th-info-fill',\n neutral: 'bg-th-hi3',\n 'chart-1': 'bg-th-chart-1',\n 'chart-2': 'bg-th-chart-2',\n 'chart-3': 'bg-th-chart-3',\n 'chart-4': 'bg-th-chart-4',\n 'chart-5': 'bg-th-chart-5',\n 'chart-6': 'bg-th-chart-6',\n 'chart-7': 'bg-th-chart-7',\n 'chart-8': 'bg-th-chart-8',\n};\n\nconst METER_THICK = { xs: 'h-1', sm: 'h-1.5', md: 'h-2.5' } as const;\nconst METER_THICK_V = { xs: 'w-1', sm: 'w-1.5', md: 'w-2.5' } as const;\n\nexport interface MeterProps {\n /** The current value, between min and max (clamped). */\n value: number;\n /** Default 0. */\n min?: number;\n /** Default 100. */\n max?: number;\n /** Accessible name: what is being measured (\"Disk used\"). Required, since the bar has no text. */\n label: string;\n /** Fill color. Overrides thresholds. Default: from thresholds, else accent. neutral:\n * a gray fill for a quantity with no status meaning (swap, a share of a total). */\n tone?: MeterTone;\n /** Picks ok, warn or loss from the value (see toneFor) when tone is not given. */\n thresholds?: { warn: number; loss: number };\n /** Bar thickness: xs 4px, sm 6px (default), md 10px. */\n size?: keyof typeof METER_THICK;\n /** vertical fills from the bottom; give the meter a height (className=\"h-16\"). */\n orientation?: 'horizontal' | 'vertical';\n /** Track color: elevated on a surface (default), overlay when the meter sits on an\n * elevated box. */\n track?: 'elevated' | 'overlay';\n /** meter: a measurement (role=\"meter\"). progress: work being done (role=\"progressbar\"). */\n kind?: 'meter' | 'progress';\n /** Shows the rounded percentage beside a horizontal bar. */\n showValue?: boolean;\n className?: string;\n}\n\n/** A thin bar showing how full something is: disk, quota, progress, a score. */\nexport function Meter({\n value,\n min = 0,\n max = 100,\n label,\n tone,\n thresholds,\n size = 'sm',\n orientation = 'horizontal',\n track = 'elevated',\n kind = 'meter',\n showValue = false,\n className,\n}: MeterProps) {\n const span = max - min || 1;\n const clamped = Math.min(Math.max(value, min), max);\n const pct = ((clamped - min) / span) * 100;\n const resolved: MeterTone = tone ?? (thresholds ? toneFor(clamped, thresholds) : 'accent');\n const vertical = orientation === 'vertical';\n const bar = (\n <div\n role={kind === 'progress' ? 'progressbar' : 'meter'}\n aria-label={label}\n aria-valuemin={min}\n aria-valuemax={max}\n aria-valuenow={clamped}\n aria-valuetext={`${Math.round(pct)}%`}\n className={cn(\n 'relative shrink-0 overflow-hidden rounded-full',\n track === 'overlay' ? 'bg-th-overlay' : 'bg-th-elevated',\n vertical ? cn('h-full', METER_THICK_V[size]) : cn('w-full', METER_THICK[size]),\n !showValue && className,\n )}\n >\n <div\n className={cn(\n 'absolute rounded-full duration-300 ease-out motion-reduce:transition-none',\n vertical ? 'inset-x-0 bottom-0 transition-[height]' : 'inset-y-0 left-0 transition-[width]',\n METER_FILL[resolved],\n )}\n style={vertical ? { height: `${pct}%` } : { width: `${pct}%` }}\n />\n </div>\n );\n if (!showValue || vertical) return bar;\n return (\n <div className={cn('flex w-full items-center gap-2', className)}>\n {bar}\n <span aria-hidden=\"true\" className=\"w-9 shrink-0 text-right text-xs tabular-nums text-th-hi3\">\n {Math.round(pct)}%\n </span>\n </div>\n );\n}\n\n// =====================================================================================\n// Sparkline\n// =====================================================================================\n\nexport type SparklineTone = ChartTone | 'accent' | 'ok' | 'warn' | 'loss' | 'info';\n\nconst SPARK_TONE: Record<SparklineTone, string> = {\n accent: 'text-th-accent',\n ok: 'text-th-ok-fill',\n warn: 'text-th-warn-fill',\n loss: 'text-th-loss-fill',\n info: 'text-th-info-fill',\n 'chart-1': 'text-th-chart-1',\n 'chart-2': 'text-th-chart-2',\n 'chart-3': 'text-th-chart-3',\n 'chart-4': 'text-th-chart-4',\n 'chart-5': 'text-th-chart-5',\n 'chart-6': 'text-th-chart-6',\n 'chart-7': 'text-th-chart-7',\n 'chart-8': 'text-th-chart-8',\n};\n\nexport interface SparklineProps {\n /** The series, oldest first. null leaves a gap (a missed check, a closed market). */\n values: (number | null)[];\n /** Accessible name, ideally with the trend: \"Response time, last 24 hours, 120 to 180 ms\". */\n label: string;\n /** Line color. Default chart-1. */\n tone?: SparklineTone;\n /** Width in px. Default 120; pass className=\"w-full\" to stretch it. */\n width?: number;\n /** Height in px. Default 28. */\n height?: number;\n /** Shades the area under the line. */\n fill?: boolean;\n /** Bottom of the scale. Default: the smallest value. */\n min?: number;\n /** Top of the scale. Default: the largest value. */\n max?: number;\n className?: string;\n}\n\n/** A tiny line chart with no axes, for a trend beside a number. Plain SVG, no chart\n * library. Gaps at nulls; a flat dashed line when there is no data. */\nexport function Sparkline({\n values,\n label,\n tone = 'chart-1',\n width = 120,\n height = 28,\n fill = false,\n min,\n max,\n className,\n}: SparklineProps) {\n const { empty, lines, areas, baseline } = sparklineGeometry(values, width, height, min, max);\n\n return (\n <svg\n role=\"img\"\n aria-label={empty ? `${label}: no data` : label}\n width={width}\n height={height}\n viewBox={`0 0 ${width} ${height}`}\n preserveAspectRatio=\"none\"\n className={cn('block shrink-0 overflow-visible', empty ? 'text-th-line-strong' : SPARK_TONE[tone], className)}\n >\n {empty ? (\n <path\n d={baseline}\n stroke=\"currentColor\"\n strokeWidth={1.5}\n strokeDasharray=\"3 3\"\n vectorEffect=\"non-scaling-stroke\"\n />\n ) : (\n <>\n {fill ? areas.map((d, i) => <path key={`a${i}`} d={d} fill=\"currentColor\" fillOpacity={0.15} />) : null}\n {lines.map((d, i) => (\n <path\n key={i}\n d={d}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={1.5}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n vectorEffect=\"non-scaling-stroke\"\n />\n ))}\n </>\n )}\n </svg>\n );\n}\n\n// =====================================================================================\n// Disclosure\n// =====================================================================================\n\nexport interface DisclosureProps {\n /** The always-visible row that opens and closes it. */\n summary: ReactNode;\n /** What it reveals. */\n children: ReactNode;\n /** Starts open (uncontrolled). */\n defaultOpen?: boolean;\n /** Controlled open state; pair it with onOpenChange. */\n open?: boolean;\n /** Called with the new state when the reader toggles it. */\n onOpenChange?: (open: boolean) => void;\n /** plain: a bare row (default). card: a bordered surface box. */\n variant?: 'plain' | 'card';\n className?: string;\n}\n\n/** Show-more on native <details>/<summary>: keyboard and find-in-page work for free,\n * with a chevron that turns when open. */\nexport function Disclosure({\n summary,\n children,\n defaultOpen = false,\n open,\n onOpenChange,\n variant = 'plain',\n className,\n}: DisclosureProps) {\n const card = variant === 'card';\n return (\n <details\n // Uncontrolled, React writes defaultOpen once and the element owns the state after;\n // controlled, React writes it whenever `open` changes.\n open={open ?? defaultOpen}\n onToggle={(e) => {\n const now = e.currentTarget.open;\n // Skip the toggle event React's own write of `open` causes.\n if (open === undefined || now !== open) onOpenChange?.(now);\n }}\n className={cn(\n 'group',\n card && 'rounded-xl border border-th-line bg-th-surface shadow-card',\n className,\n )}\n >\n <summary\n className={cn(\n 'flex cursor-pointer list-none items-center gap-2 rounded-lg text-sm font-medium text-th-hi select-none',\n '[&::-webkit-details-marker]:hidden hover:text-th-hi pointer-coarse:min-h-11',\n card ? 'px-4 py-3' : 'py-1.5',\n )}\n >\n <ChevronRightIcon\n size={14}\n className=\"shrink-0 text-th-hi3 transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none\"\n />\n <span className=\"min-w-0 flex-1\">{summary}</span>\n </summary>\n <div className={cn('text-sm text-th-hi2', card ? 'border-t border-th-line px-4 py-3' : 'pb-2 pl-6 pt-1')}>\n {children}\n </div>\n </details>\n );\n}\n\n// =====================================================================================\n// Kbd\n// =====================================================================================\n\n/** A keyboard key or shortcut, e.g. <Kbd>⌘K</Kbd>. */\nexport function Kbd({ className, ...rest }: HTMLAttributes<HTMLElement>) {\n return (\n <kbd\n className={cn(\n 'inline-flex min-w-[1.5em] items-center justify-center rounded border border-th-line-strong bg-th-elevated px-1.5 font-mono text-2xs leading-4 text-th-hi2',\n className,\n )}\n {...rest}\n />\n );\n}\n\n// =====================================================================================\n// copyText, CopyButton\n// =====================================================================================\n\n/** Copies text to the clipboard. Uses the Clipboard API, falling back to a hidden\n * textarea for insecure origins and old browsers. Resolves true when it worked. */\nexport async function copyText(text: string): Promise<boolean> {\n try {\n if (typeof navigator !== 'undefined' && navigator.clipboard && window.isSecureContext) {\n await navigator.clipboard.writeText(text);\n return true;\n }\n } catch {\n // permission denied or not focused: try the fallback\n }\n if (typeof document === 'undefined') return false;\n const ta = document.createElement('textarea');\n ta.value = text;\n ta.setAttribute('readonly', '');\n ta.style.position = 'fixed';\n ta.style.top = '-1000px';\n ta.style.opacity = '0';\n const active = document.activeElement as HTMLElement | null;\n document.body.appendChild(ta);\n ta.select();\n let ok = false;\n try {\n ok = document.execCommand('copy');\n } catch {\n ok = false;\n }\n ta.remove();\n active?.focus?.();\n return ok;\n}\n\nconst COPIED_MS = 1_500;\n\nexport interface CopyButtonProps {\n /** What lands on the clipboard. */\n text: string;\n /** Button text, and the accessible name when iconOnly. Default \"Copy\". */\n label?: string;\n /** Shown for 1.5s after a copy and announced politely. Default \"Copied\". */\n copiedLabel?: string;\n /** A square IconButton instead of a labelled Button. */\n iconOnly?: boolean;\n /** Button size (or IconButton size when iconOnly). Default sm. */\n size?: 'sm' | 'md';\n /** Button variant when not iconOnly. Default secondary. */\n variant?: ButtonProps['variant'];\n /** Called after each copy attempt with whether it worked. */\n onCopy?: (ok: boolean) => void;\n className?: string;\n}\n\n/** Copies text with one click, shows \"Copied\" for 1.5s and tells screen readers. */\nexport function CopyButton({\n text,\n label = 'Copy',\n copiedLabel = 'Copied',\n iconOnly = false,\n size = 'sm',\n variant = 'secondary',\n onCopy,\n className,\n}: CopyButtonProps) {\n const [copied, setCopied] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => () => {\n if (timer.current) clearTimeout(timer.current);\n }, []);\n const onClick = async () => {\n const ok = await copyText(text);\n onCopy?.(ok);\n if (!ok) return;\n setCopied(true);\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(() => setCopied(false), COPIED_MS);\n };\n const iconSize = size === 'sm' ? 14 : 16;\n const icon = copied ? <CheckIcon size={iconSize} className=\"text-th-ok\" /> : <CopyIcon size={iconSize} />;\n return (\n <>\n {iconOnly ? (\n <IconButton label={copied ? copiedLabel : label} size={size} onClick={onClick} className={className}>\n {icon}\n </IconButton>\n ) : (\n <Button variant={variant} size={size} icon={icon} onClick={onClick} className={className}>\n {copied ? copiedLabel : label}\n </Button>\n )}\n <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {copied ? copiedLabel : ''}\n </span>\n </>\n );\n}\n\n// =====================================================================================\n// PageHeader\n// =====================================================================================\n\nexport interface PageHeaderProps {\n /** The page's title. */\n title: ReactNode;\n /** One sentence under the title. */\n description?: ReactNode;\n /** A small line above the title (a section or a breadcrumb). */\n eyebrow?: ReactNode;\n /** A back link above everything, e.g. the app's own\n * <Link className={buttonClass({ variant: 'link' })}>← Jobs</Link>. */\n back?: ReactNode;\n /** Buttons on the right; they wrap under the title on phones. */\n actions?: ReactNode;\n /** Heading level. Default h1. */\n as?: 'h1' | 'h2';\n /** Sticks under the app header (`top: var(--nish-header-h)`) with an opaque background\n * while the page scrolls; a bottom border appears once it is stuck. */\n sticky?: boolean;\n /** Sticky only: under 640px, once stuck, hide the description and show the title as\n * one truncated line, so the bar stays short. Default true. */\n collapseWhenStuck?: boolean;\n className?: string;\n}\n\n/** The title block at the top of a page: optional back link and eyebrow, the title,\n * a description and actions. */\nexport function PageHeader({\n title,\n description,\n eyebrow,\n back,\n actions,\n as: H = 'h1',\n sticky = false,\n collapseWhenStuck = true,\n className,\n}: PageHeaderProps) {\n const ref = useRef<HTMLElement>(null);\n const stuck = useStuck(ref) && sticky;\n const collapsed = stuck && collapseWhenStuck;\n return (\n <header\n ref={ref}\n className={cn(\n 'flex flex-col gap-2',\n sticky &&\n cn(\n 'sticky top-[var(--nish-header-h,0px)] z-20 -mx-[var(--nish-page-gutter,1rem)] border-b bg-th-bg px-[var(--nish-page-gutter,1rem)] py-3',\n stuck ? 'border-th-line' : 'border-transparent',\n ),\n className,\n )}\n >\n {back ? <div className=\"text-sm\">{back}</div> : null}\n <div className=\"flex flex-wrap items-end justify-between gap-x-4 gap-y-3\">\n <div className=\"min-w-0 flex-1 basis-64\">\n {eyebrow ? <p className=\"mb-1 text-xs font-medium uppercase tracking-wider text-th-hi3\">{eyebrow}</p> : null}\n <H\n className={cn(\n 'text-2xl font-semibold tracking-tight text-th-hi [overflow-wrap:anywhere]',\n collapsed && 'max-sm:truncate max-sm:text-base max-sm:[overflow-wrap:normal]',\n )}\n >\n {title}\n </H>\n {description ? <p className={cn('mt-1 text-sm text-th-hi2', collapsed && 'max-sm:hidden')}>{description}</p> : null}\n </div>\n {actions ? <div className=\"flex flex-wrap items-center gap-2\">{actions}</div> : null}\n </div>\n </header>\n );\n}\n\n// =====================================================================================\n// AppHeader\n// =====================================================================================\n\nexport interface AppHeaderProps {\n /** The app's name, shown as the wordmark. */\n name: ReactNode;\n /** An icon before the name, drawn in the accent color. */\n icon?: ReactNode;\n /** Replaces the icon and name, and their home link, with your own node (a profile\n * switcher, a wordmark with a subtitle). It is not wrapped in a link; `name` stays for\n * screen readers. */\n brand?: ReactNode;\n /** Where the \"← nish.software\" pill goes. Default https://nish.software. */\n hubHref?: string;\n /** Buttons before the theme toggle. */\n actions?: ReactNode;\n /** A second row of nav links (use tabClass on each, aria-current on the active one). */\n nav?: ReactNode;\n /** Replaces the default <ThemeToggle />; false hides it. */\n themeToggle?: ReactNode | false;\n /** Sticks to the top of the page. Default true. */\n sticky?: boolean;\n /** Classes for the inner rows, e.g. \"mx-auto max-w-6xl\" to match the page width. */\n innerClassName?: string;\n /** Makes the icon and name one link home (a 44px target), e.g. \"/\". */\n homeHref?: string;\n /** Under 640px show only the icon; the name stays for screen readers, so the pill,\n * actions and theme toggle fit on one row. Needs an icon. */\n hideNameBelow?: 'sm';\n /** Names the nav row's <nav> landmark (\"Trackers\"), so several navs on a page can be\n * told apart. */\n navLabel?: string;\n /** Under 480px the hub pill shrinks to its arrow (.nish-pill-link--compact), for\n * headers with a long name. */\n compactPill?: boolean;\n /** Frosted glass (`bg-th-bg/80 backdrop-blur-xl`) where the browser supports\n * backdrop-filter. Off by default: the header is opaque. */\n glass?: boolean;\n /** Extra MenuItems. From 640px they render after `actions`; under 640px they collapse\n * into a \"More actions\" kebab menu, so the row never wraps. */\n overflowActions?: ReactNode;\n className?: string;\n}\n\n/** A 3-dot \"more\" icon for the overflow kebab. */\nfunction MoreVerticalIcon({ size = 18 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\">\n <circle cx=\"12\" cy=\"5\" r=\"1.8\" />\n <circle cx=\"12\" cy=\"12\" r=\"1.8\" />\n <circle cx=\"12\" cy=\"19\" r=\"1.8\" />\n </svg>\n );\n}\n\n/** The shared app header: the hub pill, the wordmark, actions and the theme toggle,\n * with an optional nav row. Opaque by default (glass is opt-in), safe-area aware. A\n * sticky header publishes its height as `--nish-header-h` for the rest of the layout. */\nexport function AppHeader({\n name,\n icon,\n brand,\n hubHref = 'https://nish.software',\n actions,\n nav,\n themeToggle,\n sticky = true,\n innerClassName,\n homeHref,\n hideNameBelow,\n navLabel,\n compactPill = false,\n glass = false,\n overflowActions,\n className,\n}: AppHeaderProps) {\n const ref = useRef<HTMLElement>(null);\n useHeightVar(ref, '--nish-header-h', sticky);\n const stuck = useStuck(ref) && sticky;\n // From sm the overflow actions sit in the header row, outside any menu: MenuItem renders\n // as a menu row (role=menuitem, tabIndex -1), so make them ordinary tabbable buttons.\n const inlineActionsRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n inlineActionsRef.current?.querySelectorAll<HTMLElement>('[role=\"menuitem\"]').forEach((el) => {\n el.removeAttribute('role');\n el.tabIndex = el.getAttribute('aria-disabled') === 'true' ? -1 : 0;\n });\n });\n const toggle = themeToggle === false ? null : (themeToggle ?? <ThemeToggle />);\n const hideName = hideNameBelow === 'sm' && icon != null;\n const mark = (\n <>\n {icon ? <span className=\"shrink-0 text-th-accent [&>svg]:size-5\">{icon}</span> : null}\n <span className={cn('truncate', hideName && 'max-sm:sr-only')}>{name}</span>\n </>\n );\n const markClass = 'inline-flex min-w-0 items-center gap-2 text-xl font-bold tracking-tight text-th-hi';\n return (\n <header\n ref={ref}\n className={cn(\n 'border-b border-th-line pl-[env(safe-area-inset-left)] pr-[env(safe-area-inset-right)] pt-[env(safe-area-inset-top)]',\n glass ? 'bg-th-bg supports-[backdrop-filter]:bg-th-bg/80 supports-[backdrop-filter]:backdrop-blur-xl' : 'bg-th-bg',\n sticky && 'sticky top-0 z-30 transition-shadow',\n stuck && 'shadow-[var(--nish-shadow-card)]',\n className,\n )}\n >\n <div\n className={cn(\n '@container/header flex min-h-14 flex-nowrap items-center gap-2 px-[var(--nish-page-gutter,1rem)] py-2 sm:gap-3',\n innerClassName,\n )}\n >\n {compactPill ? (\n <a className=\"nish-pill-link nish-pill-link--compact\" href={hubHref} title=\"Back to nish.software\">\n ← <span className=\"nish-pill-link-label\">nish.software</span>\n </a>\n ) : (\n <a\n className=\"nish-pill-link @max-[400px]/header:min-w-11 @max-[400px]/header:justify-center @max-[400px]/header:px-1.5 @max-[400px]/header:[&_.nish-pill-link-label]:sr-only\"\n href={hubHref}\n title=\"Back to nish.software\"\n >\n ← <span className=\"nish-pill-link-label\">nish.software</span>\n </a>\n )}\n {brand != null ? (\n <div className=\"flex min-w-0 items-center\">\n <span className=\"sr-only\">{name}</span>\n {brand}\n </div>\n ) : homeHref != null ? (\n <a href={homeHref} className={cn(markClass, 'min-h-11 min-w-11 rounded-lg', hideName && 'max-sm:justify-center')}>\n {mark}\n </a>\n ) : (\n <span className={markClass}>{mark}</span>\n )}\n <div className=\"ml-auto flex shrink-0 items-center gap-2\">\n {actions}\n {overflowActions ? (\n <>\n <div ref={inlineActionsRef} className=\"hidden items-center gap-2 sm:flex [&>button]:w-auto\">\n {overflowActions}\n </div>\n <div className=\"sm:hidden\">\n <DropdownMenu\n align=\"end\"\n trigger={\n <IconButton label=\"More actions\">\n <MoreVerticalIcon />\n </IconButton>\n }\n >\n {overflowActions}\n </DropdownMenu>\n </div>\n </>\n ) : null}\n {toggle}\n </div>\n </div>\n {nav ? (\n <nav\n aria-label={navLabel}\n className={cn('nish-no-scrollbar -mb-px flex gap-6 overflow-x-auto px-[var(--nish-page-gutter,1rem)]', innerClassName)}\n >\n {nav}\n </nav>\n ) : null}\n </header>\n );\n}\n\n// =====================================================================================\n// SectionHeader\n// =====================================================================================\n\nexport interface SectionHeaderProps {\n /** The section's title. */\n title: ReactNode;\n /** id for the heading, so the section can point aria-labelledby at it. */\n id?: string;\n /** Heading level. Default h2. */\n as?: 'h1' | 'h2' | 'h3';\n /** Quiet text on the right (\"Updated 2 min ago\", \"3 of 12\"). */\n meta?: ReactNode;\n /** A control on the right, after meta (a Button, a Segmented, a link). */\n action?: ReactNode;\n className?: string;\n}\n\n/** The heading row of a section inside a page: the title, with optional meta text\n * and an action on the right. Smaller than PageHeader, larger than CardHeader. */\nexport function SectionHeader({ title, id, as: H = 'h2', meta, action, className }: SectionHeaderProps) {\n return (\n <div className={cn('mb-3 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1', className)}>\n <H id={id} className=\"min-w-0 text-lg font-semibold tracking-tight text-th-hi [overflow-wrap:anywhere]\">\n {title}\n </H>\n {meta != null || action != null ? (\n <div className=\"flex items-center gap-3\">\n {meta != null ? <span className=\"text-sm text-th-hi3\">{meta}</span> : null}\n {action}\n </div>\n ) : null}\n </div>\n );\n}\n\n// =====================================================================================\n// KeyValueList\n// =====================================================================================\n\nexport interface KeyValueItem {\n /** React key; unique in the list. */\n key: string;\n /** The left side: a name, often with a StatusDot or an icon. */\n label: ReactNode;\n /** The right side: a value, a Badge, a status. */\n value: ReactNode;\n /** Let the row wrap instead of staying on one line; it grows taller than 44px (32px\n * dense) when the text wraps. Both the `ul` and `dl` forms.\n * - `true` or `'anywhere'`: a long value with no spaces (a path, a URL, an id). The value\n * cell may shrink and breaks anywhere (`break-all`); the label keeps its width.\n * - `'words'`: prose (a phrase-long status or error). Both cells wrap at word breaks,\n * labels first: the label keeps its one-line width up to 60% of the row\n * (`shrink-0 max-w-[calc(60%-0.75rem)]`), so a short label never wraps one word per\n * line, and the value takes the rest, at least 40% (`min-w-0 flex-1 text-right`). A\n * word splits only when it alone is wider than its cell (`overflow-wrap: anywhere`).\n * Without `wrap` the value keeps its full width, so keep it short. */\n wrap?: boolean | 'anywhere' | 'words';\n}\n\nexport interface KeyValueListProps {\n items: KeyValueItem[];\n /** Rows 32px tall instead of 44px, for dense panels. */\n dense?: boolean;\n /** ul: a list of rows (default). dl: a description list with dt and dd, for label\n * and value pairs that read as \"name: value\". */\n as?: 'ul' | 'dl';\n className?: string;\n}\n\n/** Label and value rows with dividers: services and their status, runner details,\n * vitals. Each row is at least 44px tall (32px dense); an item with `wrap` lets its row\n * wrap and grow: `true`/`'anywhere'` for a path or URL, `'words'` for prose. */\nexport function KeyValueList({ items, dense = false, as = 'ul', className }: KeyValueListProps) {\n // A wrapping row gets vertical padding so wrapped lines clear the dividers; a single\n // line still fits inside the 44px (32px dense) minimum, so its height is unchanged.\n const row = (wrap: KeyValueItem['wrap']) =>\n cn(\n 'flex min-w-0 items-center justify-between gap-3 border-b border-th-line last:border-b-0',\n dense ? 'min-h-8' : 'min-h-11',\n wrap && (dense ? 'py-1' : 'py-2'),\n );\n // Cell widths per mode. None: the value keeps its width. anywhere: the value shrinks and\n // breaks anywhere, the label keeps its width. words: both wrap at word breaks; the label\n // does not shrink below its one-line width until it reaches 60% of the row (so a flex\n // shrink never tips \"Earnings Calendar\" onto two lines), and the value fills the rest.\n const labelCls = (wrap: KeyValueItem['wrap']) =>\n wrap === 'words'\n ? 'min-w-0 shrink-0 max-w-[calc(60%_-_0.75rem)] [overflow-wrap:anywhere]'\n : wrap\n ? 'shrink-0'\n : 'min-w-0';\n const valueCls = (wrap: KeyValueItem['wrap']) =>\n wrap === 'words' ? 'min-w-0 flex-1 [overflow-wrap:anywhere]' : wrap ? 'min-w-0 break-all' : 'shrink-0';\n if (as === 'dl') {\n return (\n <dl className={cn('grid text-sm text-th-hi', className)}>\n {items.map((it) => (\n <div key={it.key} className={row(it.wrap)}>\n <dt className={cn('text-th-hi2', labelCls(it.wrap))}>{it.label}</dt>\n <dd className={cn('m-0 text-right', valueCls(it.wrap))}>{it.value}</dd>\n </div>\n ))}\n </dl>\n );\n }\n return (\n <ul className={cn('grid text-sm text-th-hi', className)}>\n {items.map((it) => (\n <li key={it.key} className={row(it.wrap)}>\n <span className={cn('flex items-center gap-2', labelCls(it.wrap))}>{it.label}</span>\n <span className={cn('flex items-center justify-end gap-2 text-right', valueCls(it.wrap))}>\n {it.value}\n </span>\n </li>\n ))}\n </ul>\n );\n}\n\n// =====================================================================================\n// ChartLegend\n// =====================================================================================\n\nexport type ChartLegendTone = ChartTone | 'accent' | 'ok' | 'warn' | 'loss' | 'info';\n\n// Full literal class names, so Tailwind's scanner finds every one. Marks use -fill.\nconst LEGEND_FILL: Record<ChartLegendTone, string> = {\n 'chart-1': 'bg-th-chart-1',\n 'chart-2': 'bg-th-chart-2',\n 'chart-3': 'bg-th-chart-3',\n 'chart-4': 'bg-th-chart-4',\n 'chart-5': 'bg-th-chart-5',\n 'chart-6': 'bg-th-chart-6',\n 'chart-7': 'bg-th-chart-7',\n 'chart-8': 'bg-th-chart-8',\n accent: 'bg-th-accent',\n ok: 'bg-th-ok-fill',\n warn: 'bg-th-warn-fill',\n loss: 'bg-th-loss-fill',\n info: 'bg-th-info-fill',\n};\n\nexport interface ChartLegendItem {\n /** The series name. */\n label: string;\n /** The series color, the same role the chart draws it in. */\n tone: ChartLegendTone;\n}\n\nexport interface ChartLegendProps {\n items: ChartLegendItem[];\n /** line: a short 3px x 10px stroke, for line charts (default). dot: an 8px dot, for\n * bars and points. */\n marker?: 'line' | 'dot';\n /** Accessible name of the list. Default \"Legend\". */\n label?: string;\n className?: string;\n}\n\n/** The key for a multi-series chart (uPlot and canvas charts draw none of their own):\n * each series' color mark and name. The marks are decorative; the names carry it. */\nexport function ChartLegend({ items, marker = 'line', label = 'Legend', className }: ChartLegendProps) {\n return (\n <ul aria-label={label} className={cn('flex flex-wrap gap-x-4 gap-y-1 text-xs text-th-hi2', className)}>\n {items.map((it) => (\n <li key={it.label} className=\"inline-flex items-center gap-1.5\">\n <i\n aria-hidden=\"true\"\n className={cn('inline-block shrink-0', marker === 'dot' ? 'size-2 rounded-full' : 'h-0.75 w-2.5 rounded-sm', LEGEND_FILL[it.tone])}\n />\n {it.label}\n </li>\n ))}\n </ul>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { CanvasGroup } from './types';\nimport type { CanvasLayout } from './layout';\nimport type { Box } from './route';\nimport { centerOn, clampK, type View } from './view';\n\nexport interface FollowTarget {\n id: string;\n label: string;\n group: string;\n note?: string;\n box: Box;\n /** The node's group box; on a phone the camera centers x on it so the group is not cut off. */\n groupBox?: Box;\n at: number;\n}\n\nexport interface FollowStep {\n /** 'all': every active node is in view (`targets`); 'one': visiting a single node (`targets` holds just that one); 'idle': nothing active. */\n view: View;\n targets: FollowTarget[];\n mode: 'all' | 'one' | 'idle';\n}\n\nconst CYCLE_MS = 6000;\nconst BBOX_PAD = 80;\nconst VIEW_PAD = 96; // 2 x FIT_PAD\nconst PHONE_W = 600;\nconst PHONE_TOP = 0.45;\n\n/** Active nodes newest first (activeAt desc, missing = 0; ties keep layout order: group order, then node order). */\nexport function followTargets(groups: CanvasGroup[], layout: CanvasLayout): FollowTarget[] {\n const out: FollowTarget[] = [];\n for (const g of groups) {\n for (const n of g.nodes) {\n const box = layout.nodes[n.id];\n if (!n.active || !box) continue;\n out.push({ id: n.id, label: n.label, group: g.title, note: n.note, box, groupBox: layout.groups[g.id], at: n.activeAt ?? 0 });\n }\n }\n // Array.prototype.sort is stable, so equal times keep layout order.\n return out.sort((a, b) => b.at - a.at);\n}\n\n/** `view` for centering a world rect at zoom `k`; on a phone the center sits in the top 45% of the viewport (the drawer may cover the rest). */\nfunction place(w: number, h: number, k: number, box: Box, groupBox?: Box, top = 0): View {\n const v = centerOn(w, h, k, box);\n if (w >= PHONE_W) return v;\n // Never let the box head slide under the overlay row (`top` px): center at max(22.5% of h, top + half the box).\n const y = Math.max((h * PHONE_TOP) / 2, top + (box.h * k) / 2) - (box.y + box.h / 2) * k;\n // Center x on the node's group when the group fits the width, so its title and left cards stay on screen.\n if (groupBox && groupBox.w * k <= w - 24) return { ...v, x: w / 2 - (groupBox.x + groupBox.w / 2) * k, y };\n return { ...v, y };\n}\n\n/** The view for step `i` (0-based) of following `targets` in a w x h viewport. */\nexport function followStep(targets: FollowTarget[], i: number, w: number, h: number, fit: View, top = 0): FollowStep {\n if (targets.length === 0) return { mode: 'idle', view: fit, targets: [] };\n const phone = w < PHONE_W;\n const single = phone ? 0.8 : 1;\n if (targets.length === 1) {\n return { mode: 'all', targets, view: place(w, h, single, targets[0]!.box, targets[0]!.groupBox, top) };\n }\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (const t of targets) {\n x0 = Math.min(x0, t.box.x);\n y0 = Math.min(y0, t.box.y);\n x1 = Math.max(x1, t.box.x + t.box.w);\n y1 = Math.max(y1, t.box.y + t.box.h);\n }\n const bbox: Box = { x: x0 - BBOX_PAD, y: y0 - BBOX_PAD, w: x1 - x0 + 2 * BBOX_PAD, h: y1 - y0 + 2 * BBOX_PAD };\n const kAll = Math.min((w - VIEW_PAD) / bbox.w, (h - VIEW_PAD) / bbox.h, 1.1);\n if (kAll >= (phone ? 0.55 : 0.75)) {\n return { mode: 'all', targets, view: place(w, h, clampK(kAll), bbox, undefined, top) };\n }\n const target = targets[((i % targets.length) + targets.length) % targets.length]!;\n return { mode: 'one', targets: [target], view: place(w, h, single, target.box, target.groupBox, top) };\n}\n\n// Sorted, so a reorder by activeAt alone (same set of ids) does not count as a change and re-fly.\nexport const followSignature = (targets: FollowTarget[]) => targets.map((t) => t.id).sort().join('|');\nconst captionKey = (targets: FollowTarget[]) => targets.map((t) => `${t.id}:${t.label}:${t.group}:${t.note ?? ''}`).join('|');\n\n/** While `on`, flies the camera to the active nodes: on switch-on, when the set of active ids\n * changes, when the layout or viewport changes, and every 6 s while visiting one at a time.\n * Data polls that leave the active ids alone do not fly. */\nexport function useFollow(o: {\n on: boolean;\n groups: CanvasGroup[];\n layout: CanvasLayout;\n size: { w: number; h: number };\n fit: () => View;\n /** Height in px of the overlay row (legend) a phone view keeps clear. */\n inset?: number;\n fly: (v: View) => void;\n}): { step: FollowStep | null } {\n const { on, groups, layout, size } = o;\n const latest = useRef(o);\n useEffect(() => {\n latest.current = o;\n });\n const index = useRef(0);\n /** The piece shown in 'one' mode, by id. */\n const visiting = useRef<string | null>(null);\n const [step, setStep] = useState<FollowStep | null>(null);\n\n const targets = on ? followTargets(groups, layout) : [];\n const sig = followSignature(targets);\n const caption = captionKey(targets);\n\n // The visiting index restarts only when follow turns on or the active ids change, not on a resize or relayout.\n const indexKey = useRef('');\n useEffect(() => {\n if (!on) {\n indexKey.current = '';\n return;\n }\n const key = sig;\n if (indexKey.current !== key) {\n indexKey.current = key;\n index.current = 0;\n visiting.current = null;\n }\n let timer: ReturnType<typeof setInterval> | undefined;\n const run = (advance: boolean) => {\n const cur = latest.current;\n const ts = followTargets(cur.groups, cur.layout);\n // The order is newest first, so it shifts as activity times change: find the piece being\n // visited by id, not by its old position, and step to the one after it.\n const at = visiting.current ? ts.findIndex((t) => t.id === visiting.current) : -1;\n index.current = at < 0 ? 0 : advance ? at + 1 : at;\n const next = followStep(ts, index.current, cur.size.w, cur.size.h, cur.fit(), cur.inset ?? 0);\n visiting.current = next.mode === 'one' ? (next.targets[0]?.id ?? null) : null;\n setStep(next);\n cur.fly(next.view);\n if (next.mode === 'one' && timer === undefined) timer = setInterval(() => run(true), CYCLE_MS);\n if (next.mode !== 'one' && timer !== undefined) {\n clearInterval(timer);\n timer = undefined;\n }\n };\n run(false);\n return () => {\n if (timer !== undefined) clearInterval(timer);\n };\n }, [on, sig, layout, size.w, size.h]);\n\n // Keep the caption's text fresh when a poll changes a note without changing which ids are active.\n useEffect(() => {\n if (!on) return;\n const cur = latest.current;\n const ts = followTargets(cur.groups, cur.layout);\n setStep((prev) => {\n if (!prev || prev.mode === 'idle') return prev;\n // 'one' keeps showing the piece the view is on (by id), with its fresh note; 'all' shows every active piece.\n const fresh = prev.mode === 'one' ? ts.filter((t) => t.id === visiting.current) : ts;\n if (fresh.length === 0 || captionKey(prev.targets) === captionKey(fresh)) return prev;\n return { ...prev, targets: fresh };\n });\n }, [on, caption]);\n\n return { step: on ? step : null };\n}\n","// View math: a view is the world-to-screen transform, screen = world * k + (x, y).\n\nexport interface View {\n x: number;\n y: number;\n k: number;\n}\n\nexport const MIN_K = 0.3;\nexport const MAX_K = 2;\nexport const PHONE_K = 0.55;\nexport const PHONE_MAX_W = 600; // viewports narrower than this keep the readable phone zoom when fit is small\nexport const FIT_PAD = 48;\nexport const TITLE_ROOM = 36; // world px above y=0 taken by the column titles\nexport const LABEL_K = 0.8;\nexport const ANIM_MS = 300;\nexport const FOLLOW_MS = 700; // follow mode's fly\nexport const LOD_K = 0.6; // below this zoom the cards drop their details\nexport const DOUBLE_MS = 300; // two taps this close make a double-tap\nexport const DOUBLE_PX = 10;\nexport const DRAG_PX = 4;\nexport const KEY_PAN = 48;\nexport const ZOOM_STEP = 1.25;\n\nexport const clampK = (k: number) => Math.min(MAX_K, Math.max(MIN_K, k));\nexport const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);\n\n/** The view after zooming to `k` while keeping the world point under (px, py) fixed. */\nexport function zoomAround(v: View, k: number, px: number, py: number): View {\n const nk = clampK(k);\n const r = nk / v.k;\n return { k: nk, x: px - (px - v.x) * r, y: py - (py - v.y) * r };\n}\n\nexport function centerOn(w: number, h: number, k: number, box: { x: number; y: number; w: number; h: number }): View {\n return { k, x: w / 2 - (box.x + box.w / 2) * k, y: h / 2 - (box.y + box.h / 2) * k };\n}\n","import type { ReactNode, SVGProps } from 'react';\nimport type { CanvasNodeKind } from './types';\n\nexport function Svg({ children, ...rest }: SVGProps<SVGSVGElement>) {\n return (\n <svg\n width={16}\n height={16}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...rest}\n >\n {children}\n </svg>\n );\n}\n\nexport const KIND_ICON: Record<CanvasNodeKind, ReactNode> = {\n ui: (\n <>\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M3 9h18\" />\n </>\n ),\n service: (\n <>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"7\" rx=\"2\" />\n <rect x=\"3\" y=\"14\" width=\"18\" height=\"7\" rx=\"2\" />\n <path d=\"M7 6.5h.01M7 17.5h.01\" />\n </>\n ),\n worker: (\n <>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n <path d=\"M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4\" />\n </>\n ),\n library: (\n <>\n <path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\" />\n <path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\" />\n </>\n ),\n infra: <path d=\"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z\" />,\n data: (\n <>\n <ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\" />\n <path d=\"M3 5v14a9 3 0 0 0 18 0V5\" />\n <path d=\"M3 12a9 3 0 0 0 18 0\" />\n </>\n ),\n tool: <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z\" />,\n docs: (\n <>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <path d=\"M14 2v6h6M8 13h8M8 17h5\" />\n </>\n ),\n};\n\nexport const PlusIcon = () => (\n <Svg>\n <path d=\"M12 5v14M5 12h14\" />\n </Svg>\n);\nexport const MinusIcon = () => (\n <Svg>\n <path d=\"M5 12h14\" />\n </Svg>\n);\nexport const FitIcon = () => (\n <Svg>\n <path d=\"M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3\" />\n <rect x=\"8\" y=\"8\" width=\"8\" height=\"8\" rx=\"1\" />\n </Svg>\n);\nexport const FollowIcon = () => (\n <Svg>\n <circle cx=\"12\" cy=\"12\" r=\"7\" />\n <path d=\"M12 2v3M12 19v3M2 12h3M19 12h3\" />\n <circle cx=\"12\" cy=\"12\" r=\"1.5\" fill=\"currentColor\" />\n </Svg>\n);\n","import type { CanvasEdge, CanvasGroup, CanvasLayoutMode } from \"./types\";\nimport { FIT_PAD, PHONE_K, PHONE_MAX_W } from \"./view\";\n\n// =====================================================================================\n// Layout\n// =====================================================================================\n\nexport interface CanvasLayout {\n mode: \"columns\" | \"bands\";\n width: number;\n height: number;\n /** World px above y = 0 taken by the headers: 36 in \"columns\" (titles sit above the cards), 0 in \"bands\" (titles sit inside). */\n titleRoom: number;\n /** Top-left of each column's (\"columns\") or band's (\"bands\") title, world px; `index` is the column or band value. */\n headers: { index: number; x: number; y: number }[];\n groups: Record<string, { x: number; y: number; w: number; h: number }>;\n nodes: Record<string, { x: number; y: number; w: number; h: number }>;\n}\n\nexport const NODE_W = 172;\nexport const NODE_H = 56;\nexport const NODE_GAP = 12;\nexport const GROUP_PAD = 16;\nexport const GROUP_HEAD = 52;\nexport const MIN_COLUMN_STEP = 420;\nexport const CHANNEL_EDGE = 60; // width of the routing channel left of the first and right of the last sub-column\nexport const GROUP_GAP_X = 56; // \"bands\": horizontal gap between groups in a row\nexport const BAND_TITLE = 40; // \"bands\": extra room above a band's first row for its title\n\nconst GAP_MIN = 72; // \"bands\": smallest and largest gap between two rows\nconst GAP_MAX = 240;\nconst COLUMN_TITLE_ROOM = 36;\n\n/** Where every group and node sits, in world units (px at zoom 1). Pure and deterministic.\n *\n * \"columns\" (default): columns are the distinct `column` values in ascending order, groups\n * stack in the order given, nodes sit in a 2-column grid inside their group (1 column for a\n * group of one), and each column is centered against the tallest. The first sub-column starts\n * 60 px in and `width` includes 60 px after the last, which is room for the edge lanes\n * outside the cards.\n *\n * \"bands\": bands are the distinct `band ?? column` values in ascending order, stacked top to\n * bottom; each band wraps its groups (by `column`, then input order) into rows no wider than\n * `width`. The gaps between rows grow with the number of edge ends that need lanes there. */\nexport interface LayoutOptions {\n /** Default \"columns\". */\n mode?: \"columns\" | \"bands\";\n /** \"bands\" only: the widest a row of groups may get, world px (at least one group per row). */\n width?: number;\n /** \"bands\" only: used to size the gaps between rows for the edge lanes. */\n edges?: CanvasEdge[];\n columnGap?: number;\n rowGap?: number;\n}\n\ninterface Size {\n w: number;\n h: number;\n cols: number;\n}\n\nfunction sizeGroups(groups: CanvasGroup[]): Map<string, Size> {\n const sized = new Map<string, Size>();\n for (const g of groups) {\n const cols = g.nodes.length > 1 ? 2 : 1;\n const rows = Math.ceil(g.nodes.length / cols);\n const w = GROUP_PAD * 2 + cols * NODE_W + (cols - 1) * NODE_GAP;\n const h =\n GROUP_HEAD +\n GROUP_PAD +\n (rows > 0 ? rows * NODE_H + (rows - 1) * NODE_GAP : 0);\n sized.set(g.id, { w, h, cols });\n }\n return sized;\n}\n\nfunction placeGroup(\n out: CanvasLayout,\n g: CanvasGroup,\n s: Size,\n x: number,\n y: number,\n) {\n out.groups[g.id] = { x, y, w: s.w, h: s.h };\n g.nodes.forEach((n, i) => {\n out.nodes[n.id] = {\n x: x + GROUP_PAD + (i % s.cols) * (NODE_W + NODE_GAP),\n y: y + GROUP_HEAD + Math.floor(i / s.cols) * (NODE_H + NODE_GAP),\n w: NODE_W,\n h: NODE_H,\n };\n });\n}\n\ninterface Row {\n band: number;\n firstOfBand: boolean;\n list: CanvasGroup[];\n w: number;\n h: number;\n}\n\nfunction layoutBands(\n groups: CanvasGroup[],\n width: number,\n edges: CanvasEdge[],\n): CanvasLayout {\n const out: CanvasLayout = {\n mode: \"bands\",\n width: 0,\n height: 0,\n titleRoom: 0,\n headers: [],\n groups: {},\n nodes: {},\n };\n if (groups.length === 0) return out;\n const sized = sizeGroups(groups);\n const bandOf = (g: CanvasGroup) => g.band ?? g.column;\n const bandIds = [...new Set(groups.map(bandOf))].sort((a, b) => a - b);\n\n // Rows, filled greedily left to right; a row always holds at least one group.\n const rows: Row[] = [];\n for (const band of bandIds) {\n const members = groups\n .map((g, i) => ({ g, i }))\n .filter((m) => bandOf(m.g) === band)\n .sort((a, b) => a.g.column - b.g.column || a.i - b.i)\n .map((m) => m.g);\n let cur: Row | null = null;\n for (const g of members) {\n const s = sized.get(g.id)!;\n if (cur && cur.w + GROUP_GAP_X + s.w <= width) {\n cur.list.push(g);\n cur.w += GROUP_GAP_X + s.w;\n cur.h = Math.max(cur.h, s.h);\n } else {\n cur = { band, firstOfBand: cur === null, list: [g], w: s.w, h: s.h };\n rows.push(cur);\n }\n }\n }\n\n // Which row every group and node is in.\n const rowOf = new Map<string, number>();\n rows.forEach((r, ri) => {\n for (const g of r.list) {\n rowOf.set(g.id, ri);\n for (const n of g.nodes) rowOf.set(n.id, ri);\n }\n });\n\n // Edge ends that need a lane in the gap between row r and r + 1, counted by distinct id per\n // direction: the source end just below its row, the target end just above its row.\n const ends: Set<string>[] = Array.from(\n { length: Math.max(0, rows.length - 1) },\n () => new Set<string>(),\n );\n for (const e of edges) {\n const s = rowOf.get(e.from);\n const t = rowOf.get(e.to);\n if (s === undefined || t === undefined || s === t) continue;\n if (s < t) {\n ends[s]!.add(`df:${e.from}`);\n ends[t - 1]!.add(`dt:${e.to}`);\n } else {\n ends[s - 1]!.add(`uf:${e.from}`);\n ends[t]!.add(`ut:${e.to}`);\n }\n }\n\n const widest = rows.reduce((m, r) => Math.max(m, r.w), 0);\n out.width = CHANNEL_EDGE + widest + CHANNEL_EDGE;\n let y = CHANNEL_EDGE + BAND_TITLE;\n rows.forEach((r, ri) => {\n if (ri > 0) {\n const gap = Math.min(\n GAP_MAX,\n Math.max(GAP_MIN, 40 + 8 * ends[ri - 1]!.size),\n );\n y += gap + (r.firstOfBand ? BAND_TITLE : 0);\n }\n let x = CHANNEL_EDGE + (widest - r.w) / 2;\n r.list.forEach((g, gi) => {\n const s = sized.get(g.id)!;\n placeGroup(out, g, s, x, y);\n if (r.firstOfBand && gi === 0)\n out.headers.push({ index: r.band, x, y: y - 12 }); // the header's bottom edge sits here (see system-canvas.tsx), clear of arrowheads\n x += s.w + GROUP_GAP_X;\n });\n if (ri === rows.length - 1) out.height = y + r.h + CHANNEL_EDGE;\n y += r.h;\n });\n return out;\n}\n\nexport function layoutSystem(\n groups: CanvasGroup[],\n o: LayoutOptions = {},\n): CanvasLayout {\n if (o.mode === \"bands\")\n return layoutBands(groups, o.width ?? 0, o.edges ?? []);\n const columnGap = o.columnGap ?? 120;\n const rowGap = o.rowGap ?? 40;\n const columns = [...new Set(groups.map((g) => g.column))].sort(\n (a, b) => a - b,\n );\n const sized = sizeGroups(groups);\n const stackHeight = (list: CanvasGroup[]) =>\n list.reduce((sum, g) => sum + sized.get(g.id)!.h, 0) +\n Math.max(0, list.length - 1) * rowGap;\n const whole = columns.map((c) => groups.filter((g) => g.column === c));\n const sorted = whole.map(stackHeight).sort((a, b) => a - b);\n const median =\n sorted.length === 0 ? 0 : sorted[Math.floor(sorted.length / 2)]!;\n // A column taller than 1.5x the median wraps into 2 or 3 sub-columns (order kept) so the whole\n // map stays close to the viewport's aspect ratio.\n const members: CanvasGroup[][] = [];\n for (const list of whole) {\n const h = stackHeight(list);\n const parts =\n median > 0 && list.length > 1\n ? Math.min(3, list.length, Math.ceil(h / (median * 1.5)))\n : 1;\n if (parts <= 1) {\n members.push(list);\n continue;\n }\n const goal = h / parts;\n let cur: CanvasGroup[] = [];\n let cuts = 0;\n for (const g of list) {\n if (\n cur.length > 0 &&\n cuts < parts - 1 &&\n stackHeight(cur) + rowGap + sized.get(g.id)!.h / 2 > goal\n ) {\n members.push(cur);\n cur = [];\n cuts++;\n }\n cur.push(g);\n }\n members.push(cur);\n }\n const heights = members.map(stackHeight);\n const tallest = heights.reduce((m, h) => Math.max(m, h), 0);\n\n const out: CanvasLayout = {\n mode: \"columns\",\n width: 0,\n height: tallest,\n titleRoom: COLUMN_TITLE_ROOM,\n headers: [],\n groups: {},\n nodes: {},\n };\n let x = members.length > 0 ? CHANNEL_EDGE : 0;\n members.forEach((list, ci) => {\n const widest = list.reduce((m, g) => Math.max(m, sized.get(g.id)!.w), 0);\n let y = (tallest - heights[ci]!) / 2;\n for (const g of list) {\n placeGroup(out, g, sized.get(g.id)!, x, y);\n y += sized.get(g.id)!.h + rowGap;\n }\n out.width = Math.max(out.width, x + widest);\n x += Math.max(MIN_COLUMN_STEP, widest + columnGap);\n });\n if (members.length > 0) out.width += CHANNEL_EDGE;\n for (const c of columns) {\n const boxes = groups\n .filter((g) => g.column === c)\n .map((g) => out.groups[g.id]!);\n out.headers.push({\n index: c,\n x: Math.min(...boxes.map((b) => b.x)),\n y: Math.min(...boxes.map((b) => b.y)) - COLUMN_TITLE_ROOM,\n });\n }\n return out;\n}\n\n/** Layouts that do not depend on the viewport: every bands candidate (the row width that fits the\n * n widest groups side by side, n = 1..most groups in a band) and, in \"auto\", the columns layout. */\nexport interface LayoutCandidates {\n mode: CanvasLayoutMode;\n bands: CanvasLayout[];\n columns: CanvasLayout | null;\n}\n\nexport function layoutCandidates(\n groups: CanvasGroup[],\n edges: CanvasEdge[],\n mode: CanvasLayoutMode = \"auto\",\n): LayoutCandidates {\n if (mode === \"columns\")\n return {\n mode,\n bands: [],\n columns: layoutSystem(groups, { mode: \"columns\" }),\n };\n const sized = sizeGroups(groups);\n const widths = groups.map((g) => sized.get(g.id)!.w).sort((a, b) => b - a);\n const perBand = new Map<number, number>();\n for (const g of groups) {\n const b = g.band ?? g.column;\n perBand.set(b, (perBand.get(b) ?? 0) + 1);\n }\n const maxN = Math.max(0, ...perBand.values());\n const rowWidths: number[] = [];\n let sum = 0;\n for (let n = 1; n <= maxN; n++) {\n sum += widths[n - 1]!;\n rowWidths.push(sum + (n - 1) * GROUP_GAP_X);\n }\n if (rowWidths.length === 0) rowWidths.push(0);\n return {\n mode,\n bands: [...new Set(rowWidths)].map((width) =>\n layoutSystem(groups, { mode: \"bands\", width, edges }),\n ),\n columns: mode === \"auto\" ? layoutSystem(groups, { mode: \"columns\" }) : null,\n };\n}\n\n// Only canvases narrower than this are treated as phones (one readable column at the phone zoom).\n// From 480 to 600 px the best-scoring candidate is used unless it would fit below the phone zoom.\nconst PHONE_LAYOUT_W = 480;\n// Below this best score a canvas 600 px or wider also gets the fits-across layout.\nexport const SCROLL_K = 0.35;\n\n/** Picks from `layoutCandidates` for a viewport. Cheap, so it can run on every resize. */\nexport function chooseLayout(\n c: LayoutCandidates,\n viewport: { w: number; h: number },\n): CanvasLayout {\n if (c.mode === \"columns\") return c.columns!;\n const candidates = c.bands;\n if (viewport.w <= 0 || viewport.h <= 0) return candidates[0]!;\n const score = (l: CanvasLayout) => {\n if (l.width <= 0 || l.height <= 0) return 1;\n return Math.min(\n (viewport.w - 2 * FIT_PAD) / l.width,\n (viewport.h - 2 * FIT_PAD) / (l.height + l.titleRoom),\n 1,\n );\n };\n const scores = candidates.map(score);\n const top = Math.max(...scores);\n let best = 0; // ties (within 0.005 of the top score) go to the larger row width\n scores.forEach((s, i) => {\n if (top - s < 0.005) best = i;\n });\n // fitView keeps the phone zoom (PHONE_K) below PHONE_MAX_W when the fit is smaller, so below\n // PHONE_MAX_W use the same threshold here: the widest candidate that fits at the phone zoom.\n // From PHONE_MAX_W up the same happens when even the best candidate would open below\n // SCROLL_K (fitView's overlay insets make the real fit a little smaller than this score):\n // a readable map that fits across and scrolls down beats a whole map too small to read.\n if (\n viewport.w < PHONE_LAYOUT_W ||\n top < (viewport.w < PHONE_MAX_W ? PHONE_K : SCROLL_K)\n ) {\n let pick = candidates[0]!;\n for (const x of candidates) if (x.width * PHONE_K <= viewport.w - 24) pick = x;\n return pick;\n }\n const bands = candidates[best]!;\n if (c.mode === \"bands\" || !c.columns) return bands;\n return score(c.columns) > scores[best]! ? c.columns : bands;\n}\n\n/** The layout to show in a viewport of `viewport` px. \"columns\" and \"bands\" use that mode;\n * \"auto\" picks whichever candidate shows the map biggest. Pure and deterministic. */\nexport function pickLayout(\n groups: CanvasGroup[],\n edges: CanvasEdge[],\n viewport: { w: number; h: number },\n mode: CanvasLayoutMode = \"auto\",\n): CanvasLayout {\n return chooseLayout(layoutCandidates(groups, edges, mode), viewport);\n}\n","import { memo, useEffect, useId, useRef, useState } from 'react';\nimport { cn } from '../../cn';\nimport { Svg } from './icons';\nimport type { CanvasEdgeKind } from './types';\n\nconst DASH: Record<NonNullable<CanvasEdgeKind['line']>, { dash?: string; width: number; cap?: 'round' }> = {\n solid: { width: 1.75 },\n dashed: { dash: '6 5', width: 1.75 },\n dotted: { dash: '0.5 6', width: 2.25, cap: 'round' },\n};\n\nfunction Sample({ line }: { line: CanvasEdgeKind['line'] }) {\n const d = DASH[line ?? 'solid'];\n return (\n <svg width={28} height={10} viewBox=\"0 0 28 10\" aria-hidden=\"true\" focusable=\"false\" className=\"shrink-0\">\n <line x1={2} y1={5} x2={26} y2={5} stroke=\"currentColor\" strokeWidth={d.width} strokeDasharray={d.dash} strokeLinecap={d.cap} />\n </svg>\n );\n}\n\n/** The \"Lines\" button and its panel: one row per edge kind to show or hide it. */\nexport const EdgeLegend = memo(function EdgeLegend({ kinds, hidden, onToggle }: { kinds: CanvasEdgeKind[]; hidden: ReadonlySet<string>; onToggle: (id: string) => void }) {\n const [open, setOpen] = useState(false);\n const rootRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const panelId = useId();\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: PointerEvent) => {\n if (!rootRef.current?.contains(e.target as Node)) setOpen(false);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n e.stopPropagation();\n setOpen(false);\n buttonRef.current?.focus();\n };\n document.addEventListener('pointerdown', onDown, true);\n document.addEventListener('keydown', onKey, true);\n return () => {\n document.removeEventListener('pointerdown', onDown, true);\n document.removeEventListener('keydown', onKey, true);\n };\n }, [open]);\n\n if (kinds.length === 0) return null;\n const nHidden = kinds.filter((k) => hidden.has(k.id)).length;\n\n return (\n <div ref={rootRef} data-canvas-ui className=\"absolute left-3 top-3 z-[5] flex flex-col items-start gap-1.5\">\n <button\n ref={buttonRef}\n type=\"button\"\n aria-expanded={open}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen((o) => !o)}\n className=\"inline-flex h-11 items-center gap-2 rounded-xl border border-th-line bg-th-surface px-3 text-sm text-th-hi shadow-pop outline-none hover:bg-th-elevated focus-visible:ring-2 focus-visible:ring-th-accent\"\n >\n <Svg>\n <path d=\"M3 6h18M3 12h18M3 18h18\" />\n </Svg>\n <span>Lines</span>\n {nHidden > 0 ? <span className=\"text-th-hi3\">· {nHidden} hidden</span> : null}\n </button>\n {open ? (\n <div id={panelId} role=\"menu\" aria-label=\"Lines\" className=\"overflow-hidden rounded-xl border border-th-line bg-th-surface shadow-pop\" style={{ width: 'min(240px, calc(100vw - 24px))' }}>\n {kinds.map((k) => {\n const on = !hidden.has(k.id);\n return (\n <button\n key={k.id}\n type=\"button\"\n role=\"menuitemcheckbox\"\n aria-checked={on}\n onClick={() => onToggle(k.id)}\n className={cn(\n 'flex h-11 w-full items-center gap-3 px-3 text-left text-sm outline-none hover:bg-th-elevated focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-th-accent',\n on ? 'text-th-hi' : 'text-th-hi3',\n )}\n >\n <Sample line={k.line} />\n <span className=\"min-w-0 flex-1 truncate\">{k.label}</span>\n <span aria-hidden=\"true\" className={cn('relative h-5 w-9 shrink-0 rounded-full border transition-colors', on ? 'border-th-accent bg-th-accent' : 'border-th-line-strong bg-th-elevated')}>\n <span className={cn('absolute top-0.5 size-3.5 rounded-full transition-all', on ? 'left-[18px] bg-th-on-accent' : 'left-0.5 bg-th-hi3')} />\n </span>\n </button>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n});\n","import { memo, useCallback, useEffect, useImperativeHandle, useRef, type PointerEvent as ReactPointerEvent, type RefObject } from 'react';\nimport type { CanvasLayout } from './layout';\nimport type { CanvasGroup } from './types';\nimport type { View } from './view';\n\nexport interface MinimapHandle {\n setView(v: View, size: { w: number; h: number }): void;\n}\n\nconst MAP_W = 176;\nconst MAP_MAX_H = 132;\nconst MAP_MIN_H = 60;\nconst MIN_CANVAS_W = 600;\n\nconst hueVar = (hue: string | undefined, soft: boolean) => (hue ? `var(--nish-${hue}${soft ? '-soft' : ''})` : soft ? 'var(--nish-accent-soft)' : 'var(--nish-accent)');\n\n/** A small overview of the whole map with the current view drawn on it. Click or drag to move the view. */\nexport const Minimap = memo(function Minimap({\n layout,\n groups,\n handleRef,\n onJump,\n}: {\n layout: CanvasLayout;\n groups: CanvasGroup[];\n handleRef: RefObject<MinimapHandle | null>;\n onJump: (worldX: number, worldY: number) => void;\n}) {\n const wrapRef = useRef<HTMLDivElement>(null);\n const svgRef = useRef<SVGSVGElement>(null);\n const rectRef = useRef<SVGRectElement>(null);\n const last = useRef<{ v: View; size: { w: number; h: number } } | null>(null);\n\n const totalH = layout.height + layout.titleRoom;\n const ok = layout.width > 0 && totalH > 0;\n const s = ok ? Math.min(MAP_W / layout.width, MAP_MAX_H / totalH) : 1;\n const mapH = ok ? Math.min(MAP_MAX_H, Math.max(MAP_MIN_H, (MAP_W * totalH) / layout.width)) : MAP_MIN_H;\n const ox = (MAP_W - layout.width * s) / 2;\n const oy = (mapH - totalH * s) / 2;\n\n const draw = useCallback(() => {\n const cur = last.current;\n const wrap = wrapRef.current;\n const rect = rectRef.current;\n if (!cur || !wrap || !rect) return;\n const { v, size } = cur;\n wrap.style.display = size.w < MIN_CANVAS_W ? 'none' : '';\n const x0 = Math.max(0, ox + (-v.x / v.k) * s);\n const y0 = Math.max(0, oy + (-v.y / v.k + layout.titleRoom) * s);\n const x1 = Math.min(MAP_W, ox + ((-v.x + size.w) / v.k) * s);\n const y1 = Math.min(mapH, oy + ((-v.y + size.h) / v.k + layout.titleRoom) * s);\n rect.setAttribute('x', String(x0));\n rect.setAttribute('y', String(y0));\n rect.setAttribute('width', String(Math.max(0, x1 - x0)));\n rect.setAttribute('height', String(Math.max(0, y1 - y0)));\n }, [ox, oy, s, mapH, layout.titleRoom]);\n\n useImperativeHandle(\n handleRef,\n () => ({\n setView(v, size) {\n last.current = { v, size };\n draw();\n },\n }),\n [draw],\n );\n\n // The scale changed with a new layout: redraw the view rect from the last view.\n useEffect(() => {\n draw();\n }, [draw]);\n\n const jump = (e: ReactPointerEvent<SVGSVGElement>) => {\n const svg = svgRef.current;\n if (!svg || !ok) return;\n const box = svg.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return;\n const px = ((e.clientX - box.left) / box.width) * MAP_W;\n const py = ((e.clientY - box.top) / box.height) * mapH;\n onJump((px - ox) / s, (py - oy) / s - layout.titleRoom);\n };\n\n return (\n <div\n ref={wrapRef}\n data-canvas-ui\n aria-hidden=\"true\"\n className=\"nish-canvas-minimap absolute right-3 top-3 z-[5] overflow-hidden rounded-xl border border-th-line bg-th-surface shadow-pop\"\n style={{ display: 'none' }}\n >\n <svg\n ref={svgRef}\n width={MAP_W}\n height={mapH}\n viewBox={`0 0 ${MAP_W} ${mapH}`}\n className=\"block cursor-pointer touch-none\"\n onPointerDown={(e) => {\n if (e.button !== 0) return;\n e.currentTarget.setPointerCapture(e.pointerId);\n jump(e);\n }}\n onPointerMove={(e) => {\n if (e.currentTarget.hasPointerCapture(e.pointerId)) jump(e);\n }}\n onPointerUp={(e) => {\n if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);\n }}\n >\n {groups.map((g) => {\n const b = layout.groups[g.id];\n if (!b) return null;\n return (\n <rect\n key={g.id}\n x={ox + b.x * s}\n y={oy + (b.y + layout.titleRoom) * s}\n width={b.w * s}\n height={b.h * s}\n rx={3}\n fill={hueVar(g.hue, true)}\n stroke={hueVar(g.hue, false)}\n strokeWidth={1}\n />\n );\n })}\n {groups.map((g) =>\n g.nodes.map((n) => {\n const b = layout.nodes[n.id];\n if (!n.active || !b) return null;\n return <circle key={n.id} cx={ox + (b.x + b.w / 2) * s} cy={oy + (b.y + b.h / 2 + layout.titleRoom) * s} r={3} fill={hueVar(g.hue, false)} />;\n }),\n )}\n <rect ref={rectRef} x={0} y={0} width={0} height={0} fill=\"var(--nish-accent)\" fillOpacity={0.1} stroke=\"var(--nish-accent)\" strokeWidth={1} />\n </svg>\n </div>\n );\n});\n","import { memo, useLayoutEffect, useRef, type CSSProperties } from 'react';\nimport { TickerText } from '../flow';\nimport { KIND_ICON, Svg } from './icons';\nimport type { CanvasHue, CanvasNode } from './types';\n\nexport function hueStyle(hue: CanvasHue | undefined): CSSProperties {\n return {\n '--c': hue ? `var(--nish-${hue})` : 'var(--nish-accent)',\n '--c-soft': hue ? `var(--nish-${hue}-soft)` : 'var(--nish-accent-soft)',\n } as CSSProperties;\n}\n\ninterface NodeViewProps {\n node: CanvasNode;\n groupTitle: string;\n hue: CanvasHue | undefined;\n box: { x: number; y: number; w: number; h: number };\n selected: boolean;\n /** Hover or selection focus is on something else: fade this card. */\n dim: boolean;\n delay: number;\n onSelect: ((id: string, type: 'node' | 'group') => void) | undefined;\n}\n\nexport const clamp01 = (n: number | undefined) => (n == null || !Number.isFinite(n) ? 0 : Math.min(1, Math.max(0, n)));\n\n/** Plays a one-time \"ping\" when `active` turns on after mount. Sets data-fx on the DOM so a\n * re-render with the same data cannot cut it short. */\nfunction usePing(active: boolean) {\n const ref = useRef<HTMLButtonElement>(null);\n const prev = useRef(active);\n useLayoutEffect(() => {\n const was = prev.current;\n prev.current = active;\n const el = ref.current;\n if (!el || was || !active) return;\n el.removeAttribute('data-fx');\n void el.offsetWidth;\n el.setAttribute('data-fx', 'ping');\n const timer = setTimeout(() => el.removeAttribute('data-fx'), 450);\n return () => clearTimeout(timer);\n }, [active]);\n return ref;\n}\n\nexport const NodeView = memo(\n function NodeView({ node, groupTitle, hue, box, selected, dim, delay, onSelect }: NodeViewProps) {\n const active = !!node.active;\n const heat = clamp01(node.heat);\n const ref = usePing(active);\n const count = node.count ?? 0;\n const style: CSSProperties = {\n ...hueStyle(hue),\n left: box.x,\n top: box.y,\n width: box.w,\n height: box.h,\n '--nish-canvas-delay': `${delay}ms`,\n } as CSSProperties;\n // The afterglow is drawn by the card (`.nish-canvas-node[data-heat]` in base.css), whose rounded\n // corners and border the slot does not have; the slot only carries the values.\n if (!active && heat > 0) {\n const vars = style as Record<string, string>;\n vars['--nish-canvas-heat-line'] = `color-mix(in srgb, var(--c) ${Math.round(heat * 70)}%, var(--nish-line))`;\n vars['--nish-canvas-heat-glow'] = `0 0 ${Math.round(6 + heat * 16)}px color-mix(in srgb, var(--c) ${Math.round(heat * 60)}%, transparent)`;\n }\n const aria = `${node.label}, ${groupTitle}${active ? (node.note ? `, active: ${node.note}` : ', active') : ''}`;\n return (\n <div className=\"nish-canvas-slot\" style={style} data-active={active || undefined} data-dim={dim || undefined}>\n <button\n ref={ref}\n type=\"button\"\n className=\"nish-canvas-node\"\n data-canvas-id={node.id}\n data-active={active || undefined}\n data-selected={selected || undefined}\n data-heat={heat > 0 || undefined}\n aria-label={aria}\n title={node.detail || undefined}\n aria-pressed={selected}\n onClick={() => onSelect?.(node.id, 'node')}\n >\n {node.kind ? (\n <span className=\"nish-canvas-icon\" aria-hidden=\"true\">\n <Svg>{KIND_ICON[node.kind]}</Svg>\n </span>\n ) : null}\n <span className=\"nish-canvas-text\">\n <span className=\"nish-canvas-label\">{node.label}</span>\n {active && node.note ? (\n <span className=\"nish-canvas-note\" aria-hidden=\"true\">\n <TickerText text={node.note} as=\"span\" />\n </span>\n ) : node.detail ? (\n <span className=\"nish-canvas-detail\">{node.detail}</span>\n ) : null}\n </span>\n {count > 1 ? <span className=\"nish-canvas-count\">{count}</span> : null}\n {active ? <span className=\"nish-canvas-live\" aria-hidden=\"true\" /> : null}\n </button>\n </div>\n );\n },\n (a, b) =>\n a.groupTitle === b.groupTitle &&\n a.hue === b.hue &&\n a.selected === b.selected &&\n a.dim === b.dim &&\n a.delay === b.delay &&\n a.onSelect === b.onSelect &&\n a.box.x === b.box.x &&\n a.box.y === b.box.y &&\n a.node.id === b.node.id &&\n a.node.label === b.node.label &&\n a.node.kind === b.node.kind &&\n a.node.detail === b.node.detail &&\n a.node.active === b.node.active &&\n a.node.note === b.node.note &&\n a.node.count === b.node.count &&\n Math.round(clamp01(a.node.heat) * 100) === Math.round(clamp01(b.node.heat) * 100),\n);\n","import type { CanvasEdge, CanvasGroup } from './types';\nimport { CHANNEL_EDGE, NODE_GAP, type CanvasLayout } from './layout';\n\nexport interface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nexport interface RoutedEdge {\n id: string;\n /** The corners of the line, source port first. Every segment is horizontal or vertical. */\n points: [number, number][];\n /** The same line as an SVG path with rounded corners; also valid for CSS `offset-path`. */\n d: string;\n /** Direction of travel of the last segment: \"right\" in \"columns\", \"down\" in \"bands\". */\n dir: 'right' | 'down';\n}\n\nconst LANE_MARGIN = 16; // a lane keeps this far from the cards on both sides of its channel\nconst TRACK_GAP = 8; // distance between corridor tracks\nconst CLEARANCE = 8; // distance a corridor track keeps from group boxes\nconst OUTSIDE_GAP = 24; // first track above the top group or below the bottom group\nconst CORNER_R = 6;\n\ninterface Port {\n key: string;\n x: number;\n y: number;\n col: number;\n}\n\ninterface Wire {\n edge: CanvasEdge;\n src: Port;\n dst: Port;\n mode: 'next' | 'far' | 'back';\n exit: string;\n entry: string;\n}\n\ninterface Lane {\n key: string;\n ys: number;\n n: number;\n x: number;\n}\n\n/** A horizontal stretch some edge already occupies; `track` marks corridor tracks. */\ninterface HSeg {\n y: number;\n xa: number;\n xb: number;\n src: string;\n dst: string;\n track: boolean;\n}\n\n/** `pts` as an SVG path whose corners are quarter arcs of radius 6 (less on short segments). */\nfunction roundedPath(pts: [number, number][]): string {\n const f = (v: number) => String(Math.round(v * 100) / 100);\n let d = `M${f(pts[0]![0])} ${f(pts[0]![1])}`;\n for (let i = 1; i < pts.length - 1; i++) {\n const [ax, ay] = pts[i - 1]!;\n const [bx, by] = pts[i]!;\n const [cx, cy] = pts[i + 1]!;\n const r = Math.min(CORNER_R, (Math.abs(bx - ax) + Math.abs(by - ay)) / 2, (Math.abs(cx - bx) + Math.abs(cy - by)) / 2);\n const ux = Math.sign(bx - ax);\n const uy = Math.sign(by - ay);\n const vx = Math.sign(cx - bx);\n const vy = Math.sign(cy - by);\n d += `L${f(bx - ux * r)} ${f(by - uy * r)}A${f(r)} ${f(r)} 0 0 ${ux * vy - uy * vx > 0 ? 1 : 0} ${f(bx + vx * r)} ${f(by + vy * r)}`;\n }\n const last = pts[pts.length - 1]!;\n return `${d}L${f(last[0])} ${f(last[1])}`;\n}\n\n/** Drops repeated points and the middle point of three in a row, so only corners stay. */\nfunction corners(pts: [number, number][]): [number, number][] {\n const out: [number, number][] = [];\n for (const p of pts) {\n const prev = out[out.length - 1];\n if (prev && prev[0] === p[0] && prev[1] === p[1]) continue;\n const before = out[out.length - 2];\n if (prev && before && ((before[0] === prev[0] && prev[0] === p[0]) || (before[1] === prev[1] && prev[1] === p[1]))) out.pop();\n out.push(p);\n }\n return out;\n}\n\n/** Where an edge label sits: the middle of the longest segment. */\nexport function labelPoint(pts: [number, number][]): { x: number; y: number } {\n let best = { x: pts[0]![0], y: pts[0]![1] };\n let len = -1;\n for (let i = 1; i < pts.length; i++) {\n const [ax, ay] = pts[i - 1]!;\n const [bx, by] = pts[i]!;\n const l = Math.abs(bx - ax) + Math.abs(by - ay);\n if (l > len) {\n len = l;\n best = { x: (ax + bx) / 2, y: (ay + by) / 2 };\n }\n }\n return best;\n}\n\nconst flip = (b: Box): Box => ({ x: b.y, y: b.x, w: b.h, h: b.w });\n\n/** Routes every edge as an orthogonal line (horizontal and vertical segments, rounded corners)\n * from the right border of its source card to the left border of its target card. A node\n * attaches at its own center height, a group at its card's middle. Group boxes are clustered\n * into sub-columns by x; the gaps between them (and 60 px outside the first and last) are\n * channels, where vertical lanes run: one lane per source port (edges from a port share a\n * trunk) and one per target port (edges into a port merge). An edge to a sub-column further\n * right than the next travels along a horizontal corridor free of cards; backward edges and\n * edges inside one sub-column do the same, mirrored. Two edges share a line only at a shared\n * source or target port. Pure and deterministic; the result is keyed by edge id and skips\n * edges with an unknown end. In a \"bands\" layout the same router runs on the transposed layout\n * (x and y swapped) and the points are swapped back: lines leave the bottom border of the\n * source card and enter the top border of the target card, and `dir` is \"down\". */\nexport function routeEdges(layout: CanvasLayout, groups: CanvasGroup[], edges: CanvasEdge[]): Record<string, RoutedEdge> {\n if (layout.mode !== 'bands') return routeColumns(layout, groups, edges);\n const t: CanvasLayout = { ...layout, mode: 'columns', width: layout.height, height: layout.width, groups: {}, nodes: {} };\n for (const id of Object.keys(layout.groups)) t.groups[id] = flip(layout.groups[id]!);\n for (const id of Object.keys(layout.nodes)) t.nodes[id] = flip(layout.nodes[id]!);\n // An edge between two nodes of one group would loop around the whole card through the outer\n // corridors. Draw a short connector between the two cards inside the group instead.\n const groupOf = new Map<string, string>();\n for (const g of groups) for (const n of g.nodes) groupOf.set(n.id, g.id);\n const inside: CanvasEdge[] = [];\n const outside: CanvasEdge[] = [];\n for (const e of edges) {\n const g = groupOf.get(e.from);\n (g !== undefined && g === groupOf.get(e.to) ? inside : outside).push(e);\n }\n const routed = routeColumns(t, groups, outside);\n const result: Record<string, RoutedEdge> = {};\n for (const e of inside) {\n const a = layout.nodes[e.from];\n const b = layout.nodes[e.to];\n if (!a || !b || e.from === e.to) continue;\n let points: [number, number][];\n let dir: 'right' | 'down';\n if (b.y >= a.y + a.h) {\n // Target below: bottom border to top border, with a bend in the gap when not aligned.\n const ax = a.x + a.w / 2;\n const bx = b.x + b.w / 2;\n if (b.y <= a.y + a.h + NODE_GAP + 1) {\n const my = (a.y + a.h + b.y) / 2;\n points = corners([[ax, a.y + a.h], [ax, my], [bx, my], [bx, b.y]]);\n } else {\n // Rows are not adjacent: a straight drop would cross the cards in between. Leave a's\n // bottom, jog into the column gutter in the gap below a, run down it, then jog to b's\n // center in the gap above b.\n const gb = layout.groups[groupOf.get(e.from)!];\n const hasRightColumn = !!gb && gb.x + gb.w - (a.x + a.w) > NODE_GAP + 20;\n const gx = hasRightColumn ? a.x + a.w + NODE_GAP / 2 : a.x - NODE_GAP / 2;\n const y1 = a.y + a.h + NODE_GAP / 2;\n const y2 = b.y - NODE_GAP / 2;\n points = corners([[ax, a.y + a.h], [ax, y1], [gx, y1], [gx, y2], [bx, y2], [bx, b.y]]);\n }\n dir = 'down';\n } else if (b.x >= a.x + a.w && Math.abs(b.y - a.y) < 1) {\n // Same row, target to the right: right border to left border.\n const cy = a.y + a.h / 2;\n points = [[a.x + a.w, cy], [b.x, cy]];\n dir = 'right';\n } else {\n // Upward or leftward links inside a group have no clean short route; the link is left out.\n continue;\n }\n result[e.id] = { id: e.id, points, d: roundedPath(points), dir };\n }\n for (const id of Object.keys(routed)) {\n const points = routed[id]!.points.map(([x, y]): [number, number] => [y, x]);\n result[id] = { id, points, d: roundedPath(points), dir: 'down' };\n }\n return result;\n}\n\nfunction routeColumns(layout: CanvasLayout, groups: CanvasGroup[], edges: CanvasEdge[]): Record<string, RoutedEdge> {\n const result: Record<string, RoutedEdge> = {};\n const cards: { id: string; box: Box }[] = [];\n for (const g of groups) {\n const box = layout.groups[g.id];\n if (box) cards.push({ id: g.id, box });\n }\n if (cards.length === 0) return result;\n\n // --- sub-columns and channels ----------------------------------------------------\n const colX = [...new Set(cards.map((c) => c.box.x))].sort((a, b) => a - b);\n const cols = colX.map((x) => ({ x, right: x, boxes: [] as Box[] }));\n const colOf = new Map<string, number>();\n for (const { id, box } of cards) {\n const ci = colX.indexOf(box.x);\n colOf.set(id, ci);\n cols[ci]!.right = Math.max(cols[ci]!.right, box.x + box.w);\n cols[ci]!.boxes.push(box);\n }\n /** Channel j is left of sub-column j; channel 0 and channel `cols.length` are the outer ones. */\n const channelOf = (j: number): [number, number] => {\n if (j <= 0) return [cols[0]!.x - CHANNEL_EDGE, cols[0]!.x];\n if (j >= cols.length) return [cols[cols.length - 1]!.right, cols[cols.length - 1]!.right + CHANNEL_EDGE];\n return [cols[j - 1]!.right, cols[j]!.x];\n };\n const minY = cards.reduce((m, c) => Math.min(m, c.box.y), Infinity);\n const maxY = cards.reduce((m, c) => Math.max(m, c.box.y + c.box.h), -Infinity);\n\n // --- ports and wires ---------------------------------------------------------------\n const groupOfNode = new Map<string, string>();\n for (const g of groups) for (const n of g.nodes) groupOfNode.set(n.id, g.id);\n const portOf = (id: string, side: 'o' | 'i'): Port | undefined => {\n const nb = layout.nodes[id];\n const gid = nb ? groupOfNode.get(id) : id;\n const gb = gid ? layout.groups[gid] : undefined;\n if (!gid || !gb || !colOf.has(gid)) return undefined;\n const y = nb ? nb.y + nb.h / 2 : gb.y + gb.h / 2;\n return { key: `${side}|${gid}|${y}`, x: side === 'o' ? gb.x + gb.w : gb.x, y, col: colOf.get(gid)! };\n };\n const fanOut = new Map<string, number>();\n const wires: Wire[] = [];\n for (const edge of edges) {\n const src = portOf(edge.from, 'o');\n const dst = portOf(edge.to, 'i');\n if (!src || !dst) continue;\n fanOut.set(src.key, (fanOut.get(src.key) ?? 0) + 1);\n wires.push({ edge, src, dst, mode: dst.col === src.col + 1 ? 'next' : dst.col > src.col ? 'far' : 'back', exit: '', entry: '' });\n }\n\n // --- lanes -------------------------------------------------------------------------\n const lanes = new Map<string, Lane>();\n const inChannel = new Map<number, Lane[]>();\n const lane = (channel: number, key: string, w: Wire): string => {\n const id = `${channel}|${key}`;\n let l = lanes.get(id);\n if (!l) {\n l = { key: id, ys: 0, n: 0, x: 0 };\n lanes.set(id, l);\n const list = inChannel.get(channel);\n if (list) list.push(l);\n else inChannel.set(channel, [l]);\n }\n l.ys += (w.src.y + w.dst.y) / 2;\n l.n++;\n return id;\n };\n for (const w of wires) {\n if (w.mode === 'next') {\n // One vertical in the channel between the two sub-columns: the source trunk when the\n // source fans out, else the target's merge lane.\n w.exit = w.entry = lane(w.dst.col, fanOut.get(w.src.key)! > 1 ? w.src.key : w.dst.key, w);\n } else {\n w.exit = lane(w.src.col + 1, w.src.key, w);\n w.entry = lane(w.dst.col, w.dst.key, w);\n }\n }\n // Lanes spread evenly over the channel minus the margins, ordered by the average height of\n // their edges (6 px apart or more while they fit; more lanes than that share the width evenly).\n for (const [channel, list] of inChannel) {\n const [l, r] = channelOf(channel);\n const lo = l + LANE_MARGIN;\n const hi = r - LANE_MARGIN;\n list.sort((a, b) => a.ys / a.n - b.ys / b.n || (a.key < b.key ? -1 : 1));\n list.forEach((ln, i) => {\n ln.x = list.length === 1 || hi <= lo ? (l + r) / 2 : lo + ((hi - lo) * i) / (list.length - 1);\n });\n }\n\n // --- horizontal stretches already taken, then corridor tracks -------------------------\n const taken: HSeg[] = [];\n for (const w of wires) {\n taken.push({ y: w.src.y, xa: w.src.x, xb: lanes.get(w.exit)!.x, src: w.src.key, dst: w.dst.key, track: false });\n taken.push({ y: w.dst.y, xa: lanes.get(w.entry)!.x, xb: w.dst.x, src: w.src.key, dst: w.dst.key, track: false });\n }\n const sameLine = (h: HSeg, w: Wire) => h.src === w.src.key || h.dst === w.dst.key;\n const trackFree = (y: number, xa: number, xb: number, w: Wire) => {\n for (const h of taken) {\n if (Math.min(xb, h.xb) - Math.max(xa, h.xa) <= 0.5) continue;\n const dy = Math.abs(h.y - y);\n if (dy < 0.5 ? !sameLine(h, w) : h.track && dy < TRACK_GAP - 0.5) return false;\n }\n return true;\n };\n const spanOf = (w: Wire): [number, number] => (w.mode === 'far' ? [w.src.col + 1, w.dst.col - 1] : [w.dst.col, w.src.col]);\n const cardFree = (y: number, c0: number, c1: number) => {\n for (let c = c0; c <= c1; c++) for (const b of cols[c]!.boxes) if (y > b.y - CLEARANCE + 1e-6 && y < b.y + b.h + CLEARANCE - 1e-6) return false;\n return true;\n };\n const bandCache = new Map<string, [number, number][]>();\n /** The free horizontal bands between group boxes across sub-columns c0..c1, top to bottom. */\n const bandsOf = (c0: number, c1: number): [number, number][] => {\n const id = `${c0}-${c1}`;\n let bands = bandCache.get(id);\n if (bands) return bands;\n const spans: [number, number][] = [];\n for (let c = c0; c <= c1; c++) for (const b of cols[c]!.boxes) spans.push([b.y - CLEARANCE, b.y + b.h + CLEARANCE]);\n spans.sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n bands = [];\n let end = spans[0]![1];\n for (const [a, b] of spans) {\n if (a >= end) bands.push([end, a]);\n end = Math.max(end, b);\n }\n bandCache.set(id, bands);\n return bands;\n };\n const gap = (avg: number, [lo, hi]: [number, number]) => (avg < lo ? lo - avg : avg > hi ? avg - hi : 0);\n // How many corridor edges prefer each band, so its tracks can be centered on the band.\n const wanted = new Map<string, number>();\n for (const w of wires) {\n if (w.mode === 'next') continue;\n const avg = (w.src.y + w.dst.y) / 2;\n let best: [number, number] | undefined;\n for (const b of bandsOf(...spanOf(w))) if (!best || gap(avg, b) < gap(avg, best)) best = b;\n if (best) wanted.set(`${best[0]}|${best[1]}`, (wanted.get(`${best[0]}|${best[1]}`) ?? 0) + 1);\n }\n const trackYs = new Map<string, number>();\n for (const w of wires) {\n if (w.mode === 'next') continue;\n const [c0, c1] = spanOf(w);\n const avg = (w.src.y + w.dst.y) / 2;\n const near = (a: number, b: number) => Math.abs(a - avg) - Math.abs(b - avg) || a - b;\n // Candidates, best first: a track an edge of the same source or target already uses, then\n // the free bands nearest the ports, then lines above the top group or below the bottom one.\n const candidates: number[] = [];\n for (const h of taken) if (h.track && sameLine(h, w) && !candidates.includes(h.y)) candidates.push(h.y);\n for (const b of [...bandsOf(c0, c1)].sort((p, q) => gap(avg, p) - gap(avg, q) || p[0] - q[0])) {\n const n = Math.min(Math.floor((b[1] - b[0]) / TRACK_GAP) + 1, wanted.get(`${b[0]}|${b[1]}`) ?? 1);\n const slots: number[] = [];\n for (let i = 0; i < n; i++) slots.push((b[0] + b[1]) / 2 + TRACK_GAP * (i - (n - 1) / 2));\n candidates.push(...slots.sort(near));\n }\n const outer: number[] = [];\n for (let k = 0; k <= wires.length; k++) outer.push(minY - OUTSIDE_GAP - TRACK_GAP * k, maxY + OUTSIDE_GAP + TRACK_GAP * k);\n candidates.push(...outer.sort(near));\n const xo = lanes.get(w.exit)!.x;\n const xe = lanes.get(w.entry)!.x;\n const xa = Math.min(xo, xe);\n const xb = Math.max(xo, xe);\n const y = candidates.find((c) => cardFree(c, c0, c1) && trackFree(c, xa, xb, w)) ?? candidates[candidates.length - 1]!;\n trackYs.set(w.edge.id, y);\n taken.push({ y, xa, xb, src: w.src.key, dst: w.dst.key, track: true });\n }\n\n // --- paths ---------------------------------------------------------------------------\n for (const w of wires) {\n const { src, dst } = w;\n const xo = lanes.get(w.exit)!.x;\n const xe = lanes.get(w.entry)!.x;\n const ty = trackYs.get(w.edge.id)!;\n const raw: [number, number][] =\n w.mode === 'next'\n ? [[src.x, src.y], [xo, src.y], [xo, dst.y], [dst.x, dst.y]]\n : [[src.x, src.y], [xo, src.y], [xo, ty], [xe, ty], [xe, dst.y], [dst.x, dst.y]];\n const points = corners(raw);\n result[w.edge.id] = { id: w.edge.id, points, d: roundedPath(points), dir: 'right' };\n }\n return result;\n}\n"],"mappings":";AAAA;AAAA,EACE,YAAAA;AAAA,EACA,eAAAC;AAAA,EACA,aAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,WAAAC;AAAA,EACA,UAAAC;AAAA,EACA,YAAAC;AAAA,OAMK;;;ACbP,SAAS,YAA6B;AACtC,SAAS,2BAA2B;AAMpC,IAAM,UAAU,oBAAoB;AAAA,EAClC,QAAQ;AAAA,IACN,OAAO;AAAA,MACL,MAAM,CAAC,OAAO,KAAK;AAAA,IACrB;AAAA,IACA,aAAa;AAAA,MACX,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,OAAO,OAAO,EAAE,CAAC;AAAA,IAC/C;AAAA,EACF;AACF,CAAC;AAGM,SAAS,MAAM,QAA8B;AAClD,SAAO,QAAQ,KAAK,MAAM,CAAC;AAC7B;;;ACrBA;AAAA,EACE,aAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA,YAAAC;AAAA,OAKK;;;ACVP,SAAS,aAAa,WAAW,QAAQ,UAAU,4BAA4B;AAkM3E;AA5LG,SAAS,cAAc,OAAwB;AACpD,QAAM,YAAY;AAAA,IAChB,CAAC,aAAyB;AACxB,UAAI,OAAO,WAAW,eAAe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AAA;AAAA,EACF;AAEJ;","names":["Fragment","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","useEffect","useRef","useState","jsx","jsx","jsx","jsx","jsxs","Button","jsxs","jsx","IconButton","Card","Input","jsx","jsxs","Select","jsx","jsxs","useState","useEffect","jsxs","jsx","useEffect","useRef","useState","Fragment","jsx","jsxs","jsx","jsx","jsxs","FollowCaption","useEffect","useRef","useState","useRef","useEffect","useState","Fragment","jsx","jsxs","Svg","memo","useEffect","useId","useRef","useState","jsx","jsxs","memo","EdgeLegend","useState","useRef","useId","useEffect","Svg","memo","useCallback","useEffect","useRef","jsx","jsxs","Minimap","memo","useLayoutEffect","useRef","jsx","jsxs","useRef","useLayoutEffect","memo","NodeView","Svg","jsx","jsxs","useRef","useState","useCallback","useMemo","useLayoutEffect","step","useEffect","Fragment"]}