{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "zoom-canvas",
  "type": "registry:ui",
  "title": "Zoom Canvas",
  "description": "The zoom-canvas primitive.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/zoom-canvas.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/zoom-canvas.tsx",
      "content": "/// <reference path=\"../css.d.ts\" />\nimport { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type Ref } from 'react';\nimport { cn } from '../lib/utils';\nimport {\n  DEFAULT_ASPECT, IDENTITY, MIN_PICTURE, cameraAt, cardAt, ease, layoutLevel, levelBox, pictureRadius, planFlight, resolvePath, within, worthDrawing,\n  type Aff, type Cam, type Flight,\n} from './zoom-canvas.maths';\nimport './zoom-canvas.css';\n\nexport { fitColumns } from './zoom-canvas.maths';\n\n/** One card. With `items` its picture is the level they make; without, the host's `picture` (drawn at the panel's size) or its name. */\nexport interface ZoomItem { id: string; title: string; items?: ZoomItem[]; picture?: ReactNode }\n\n/** What a host can do with a canvas it holds a ref to. Paths are ids from the top, `[]` is the top level. */\nexport interface ZoomCanvasHandle {\n  /** Fly down or up to the level or card at a path, one flight; false when it was not there or the camera was already moving. */\n  flyTo: (path: string[]) => Promise<boolean>;\n  /** One level out. */\n  out: () => Promise<boolean>;\n  /** The top level. */\n  home: () => Promise<boolean>;\n  /** Where the camera rests (the last rest while it moves). */\n  readonly path: string[];\n}\n\nexport interface ZoomCanvasProps {\n  items: ZoomItem[];\n  /** Names the region for assistive tech. */\n  label: string;\n  /** Where the camera starts. */\n  defaultPath?: string[];\n  /** The camera has come to rest on a level or card: the nodes from the top to it (empty on the top level). The host draws its\n   *  breadcrumb from this. */\n  onRest?: (path: ZoomItem[]) => void;\n  /** Laid over the panel while the camera rests on a path that returns something (a leaf's real page, say). Esc still flies out. */\n  renderOverlay?: (path: ZoomItem[]) => ReactNode;\n  /** The panel's corner radius in px; every picture on the way in has the same corners once it fills the panel. */\n  radius?: number;\n  /** Picture width over height; 16:10 like the directory's cards. A panel taller than that shows pictures as tall as the panel. */\n  aspect?: number;\n  /** One flight, in ms (none under reduced motion). */\n  duration?: number;\n  /** A picture smaller than this on screen is left plain. */\n  minPicture?: number;\n  className?: string;\n  style?: CSSProperties;\n  ref?: Ref<ZoomCanvasHandle>;\n}\n\n/** How much pinch (wheel with ctrl or meta, as a trackpad pinch arrives) makes one step in or out: a pinch is a step, never a zoom. */\nconst PINCH_STEP = 36;\nconst SEP = '\\u0001';\nconst key = (ids: readonly string[]) => ids.join(SEP);\nconst PANEL = 'var(--kh-panel-bg, var(--kh-surface))';\n\ninterface Seen { cam: Cam; view: { W: number; H: number } }\ninterface Scene {\n  W: number; H: number; aspect: number; radius: number; minPicture: number;\n  seen: Seen[];\n  register: (path: string[], el: HTMLElement | null) => void;\n}\n\n/** A level: W by H laid out by the maths, each card absolutely placed so the camera and the markup agree to the pixel. */\nfunction Level({ items, path, aff, scene, live, onOpen }: { items: ZoomItem[]; path: string[]; aff: Aff; scene: Scene; live: boolean; onOpen?: (id: string) => void }) {\n  const { W, H, aspect, radius } = scene;\n  const lay = useMemo(() => layoutLevel(items.length, W, H, aspect), [items.length, W, H, aspect]);\n  const box = levelBox(W, H, aspect);\n  return (\n    <ul className=\"relative m-0 list-none p-0\" style={{ width: W, height: live ? lay.height : Math.max(lay.height, box.H) }}>\n      {items.map((item, i) => {\n        const b = lay.boxes[i]!, pic = lay.pictures[i]!;\n        const ids = [...path, item.id];\n        const child = within(aff, pic, W);\n        const drawn = scene.seen.some((s) => worthDrawing(pic, aff, s.cam, s.view, scene.minPicture));\n        const k = pic.w / W;\n        return (\n          <li key={item.id} className=\"absolute m-0 min-w-0 p-0\" style={{ left: b.x, top: b.y, width: b.w, height: b.h }}>\n            <article className=\"group relative flex h-full flex-col rounded-kh-lg border border-kh-line bg-kh-surface p-[6px] transition-colors duration-(--kh-dur) hover:border-kh-line-strong\">\n              <div ref={(el) => scene.register(ids, el)} className=\"kh-zoom-pic shrink-0\" style={{ width: pic.w, height: pic.h, borderRadius: pictureRadius(radius, pic.w, W) }}>\n                {drawn && (\n                  <div inert aria-hidden className=\"pointer-events-none absolute left-0 top-0 origin-top-left overflow-clip\" style={{ width: box.W, height: box.H, transform: `scale(${k})`, background: PANEL }}>\n                    {item.items?.length\n                      ? <Level items={item.items} path={ids} aff={child} scene={scene} live={false} />\n                      : (item.picture ?? <Plain title={item.title} />)}\n                  </div>\n                )}\n              </div>\n              <div className=\"flex h-[33px] min-w-0 items-center px-1.5\">\n                <button type=\"button\" tabIndex={live ? 0 : -1} onClick={live ? () => onOpen?.(item.id) : undefined}\n                  className=\"min-w-0 truncate rounded-kh-sm text-kh-small font-medium text-kh-ink after:absolute after:inset-0 after:content-[''] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\">\n                  {item.title}\n                </button>\n              </div>\n            </article>\n          </li>\n        );\n      })}\n    </ul>\n  );\n}\n\n/** A leaf with no picture of its own: its name, large, on the panel. */\nfunction Plain({ title }: { title: string }) {\n  return <div className=\"flex h-full w-full items-center justify-center p-[10%] text-center text-kh-ink\" style={{ fontSize: 56, fontWeight: 600, lineHeight: 1.1 }}>{title}</div>;\n}\n\nconst levelOf = (items: ZoomItem[], ids: string[]): ZoomItem[] => {\n  const hit = resolvePath(items, ids);\n  return (hit && hit.length ? hit[hit.length - 1]!.items : items) ?? [];\n};\n\n/** The library as nested cards, each card's picture the level it opens, drawn live and scaled in. A click (or Enter) flies the camera one\n *  level into a card, Esc, a pinch out or `out()` flies back, and it always rests on a whole level at scale 1, so text stays sharp at any\n *  depth: the camera is rooted on the level it rests on, and re-rooted when it lands. It steps level by level and never pans or zooms\n *  freely. The host draws leaves (`picture`), the breadcrumb (`onRest`) and the page a leaf opens (`renderOverlay`). Give it a height. */\nexport function ZoomCanvas({ items, label, defaultPath, onRest, renderOverlay, radius = 14, aspect = DEFAULT_ASPECT, duration = 520, minPicture = MIN_PICTURE, className, style, ref }: ZoomCanvasProps) {\n  const view = useRef<HTMLDivElement>(null);\n  const world = useRef<HTMLDivElement>(null);\n  const wrap = useRef<HTMLElement>(null);\n  const [size, setSize] = useState<{ W: number; H: number } | null>(null);\n  const [at, setAt] = useState<string[]>(() => defaultPath ?? []);\n  const [flight, setFlight] = useState<(Flight & { from: string[]; to: string[]; resolve: (ok: boolean) => void }) | null>(null);\n  const pictures = useRef(new Map<string, HTMLElement>());\n  const scrollNext = useRef(0);\n  const focusNext = useRef(false);\n  const pinch = useRef({ sum: 0, at: 0 });\n\n  // The latest of everything the handlers read, so they are stable.\n  const now = { items, at, size, aspect, flight, onRest, duration };\n  const live = useRef(now);\n  live.current = now;\n\n  useLayoutEffect(() => {\n    const el = view.current;\n    if (!el) return;\n    const measure = () => setSize((was) => (was && was.W === el.clientWidth && was.H === el.clientHeight ? was : { W: el.clientWidth, H: el.clientHeight }));\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  const flyTo = useCallback((to: string[]) => new Promise<boolean>((resolve) => {\n    const { items, at, size, aspect, flight } = live.current;\n    if (!size || flight || to.length === at.length && to.every((id, i) => id === at[i])) return resolve(!flight && !!size);\n    if (!resolvePath(items, to)) return resolve(false);\n    const plan = planFlight(items, at, to, size.W, size.H, { aspect, scroll: view.current?.scrollTop ?? 0 });\n    if (!plan) return resolve(false);\n    setFlight({ ...plan, from: at, to, resolve });\n  }), []);\n  const out = useCallback(() => flyTo(live.current.at.slice(0, -1)), [flyTo]);\n  useImperativeHandle(ref, () => ({ flyTo, out, home: () => flyTo([]), get path() { return live.current.at; } }), [flyTo, out]);\n\n  const apply = (c: Cam | null) => { if (world.current) world.current.style.transform = c ? `translate(${c.x}px, ${c.y}px) scale(${c.k})` : 'none'; };\n\n  // A flight: the camera moves from where it was to the target level, then the target becomes the root and the camera is at rest.\n  useLayoutEffect(() => {\n    const f = flight, sz = live.current.size, v = view.current;\n    if (!f || !sz || !v) return;\n    v.style.overflow = 'hidden';\n    v.scrollTop = 0;\n    apply(f.start);\n    // Rings: those of the pictures we fly into fade out as we arrive; those of the one we fly out of fade in as we leave.\n    const ring = (ids: string[], on: boolean) => { const out: HTMLElement[] = []; for (let i = f.root.length + 1; i <= ids.length; i++) { const el = pictures.current.get(key(ids.slice(0, i))); if (el) { if (on) el.setAttribute('data-landing', ''); out.push(el); } } return out; };\n    const marked = ring(f.to, true);\n    const leaving = ring(f.from, true);\n    requestAnimationFrame(() => requestAnimationFrame(() => { for (const el of leaving) el.removeAttribute('data-landing'); }));\n    const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n    const ms = reduced ? 0 : live.current.duration;\n    const t0 = performance.now();\n    let raf = 0;\n    const land = () => {\n      apply(f.end);\n      // The picture the camera has come to, measured as it lands, for a host that wants to see it fill the panel (and for tests).\n      const el = f.to.length > f.root.length ? pictures.current.get(key(f.to)) : undefined;\n      if (el && wrap.current) {\n        const r = el.getBoundingClientRect(), vr = v.getBoundingClientRect();\n        const radiusPx = (parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0) * (r.width / el.offsetWidth);\n        wrap.current.dispatchEvent(new CustomEvent('kh-zoom-land', { detail: { path: f.to, picture: r, view: vr, radius: radiusPx } }));\n      }\n      scrollNext.current = f.endScroll;\n      focusNext.current = true;\n      setAt(f.to);\n      setFlight(null);\n      f.resolve(true);\n    };\n    const step = (t: number) => {\n      const p = ms ? Math.min(1, (t - t0) / ms) : 1;\n      if (p >= 1) return land();\n      apply(cameraAt(f.start, f.end, ease(p), sz.W, sz.H));\n      raf = requestAnimationFrame(step);\n    };\n    raf = requestAnimationFrame(step);\n    return () => { cancelAnimationFrame(raf); for (const el of [...marked, ...leaving]) el.removeAttribute('data-landing'); };\n  }, [flight]);\n\n  // At rest: the level is the root at scale 1 (sharp), scrolls if it is taller than the panel, and the host is told.\n  useLayoutEffect(() => {\n    const v = view.current;\n    if (flight || !size || !v) return;\n    apply(null);\n    v.style.overflow = '';\n    v.scrollTop = scrollNext.current;\n    scrollNext.current = 0;\n    if (focusNext.current) { focusNext.current = false; v.focus({ preventScroll: true }); }\n    live.current.onRest?.(resolvePath(live.current.items, at) ?? []);\n  }, [at, !!size, !flight]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const step = (dy: number, x: number, y: number) => {\n    if (live.current.flight) return;\n    const t = performance.now();\n    if (t - pinch.current.at > 220) pinch.current.sum = 0;\n    pinch.current = { sum: pinch.current.sum + dy, at: t };\n    if (pinch.current.sum <= -PINCH_STEP) {\n      pinch.current.sum = 0;\n      const { items, at, size, aspect } = live.current, v = view.current;\n      if (!size || !v) return;\n      const kids = levelOf(items, at), r = v.getBoundingClientRect();\n      const i = cardAt(layoutLevel(kids.length, size.W, size.H, aspect), x - r.left, y - r.top, v.scrollTop);\n      if (i >= 0) void flyTo([...at, kids[i]!.id]);\n    } else if (pinch.current.sum >= PINCH_STEP) { pinch.current.sum = 0; void out(); }\n  };\n  // A pinch is a step; two-finger scroll still scrolls a level taller than the panel.\n  useEffect(() => {\n    const el = view.current;\n    if (!el) return;\n    const wheel = (e: WheelEvent) => { if (e.ctrlKey || e.metaKey) { e.preventDefault(); step(e.deltaY, e.clientX, e.clientY); } };\n    el.addEventListener('wheel', wheel, { passive: false });\n    return () => el.removeEventListener('wheel', wheel);\n  }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (e.key !== 'Escape' || e.defaultPrevented || !live.current.at.length || (e.target as Element).closest('input, textarea, select, [role=\"dialog\"]')) return;\n    e.preventDefault();\n    void out();\n  };\n\n  const register = useCallback((ids: string[], el: HTMLElement | null) => { if (el) pictures.current.set(key(ids), el); else pictures.current.delete(key(ids)); }, []);\n\n  const rootIds = flight ? flight.root : at;\n  const rootItems = useMemo(() => levelOf(items, rootIds), [items, key(rootIds)]); // eslint-disable-line react-hooks/exhaustive-deps\n  const scene: Scene | null = useMemo(() => {\n    if (!size) return null;\n    const lay = layoutLevel(rootItems.length, size.W, size.H, aspect);\n    const seen: Seen[] = flight\n      ? [flight.start, cameraAt(flight.start, flight.end, 0.5, size.W, size.H), flight.end].map((cam) => ({ cam, view: size }))\n      : [{ cam: { x: 0, y: 0, k: 1 }, view: { W: size.W, H: Math.max(size.H, lay.height) } }];\n    return { W: size.W, H: size.H, aspect, radius, minPicture, seen, register };\n  }, [size, rootItems, aspect, radius, minPicture, flight, register]);\n\n  const here = resolvePath(items, at) ?? [];\n  const rootNode = resolvePath(items, rootIds)?.at(-1);\n  const leaf = !!rootNode && !rootNode.items?.length;\n  const overlay = !flight && size && renderOverlay && at.length ? renderOverlay(here) : null;\n  const title = here.length ? here[here.length - 1]!.title : label;\n\n  return (\n    <section ref={wrap} aria-label={label} data-zoom-path={at.join('/')} onKeyDown={onKeyDown}\n      className={cn('relative min-h-0 overflow-hidden', className)} style={size ? { ...style, borderRadius: radius } : style}>\n      <div ref={view} tabIndex={-1} className=\"kh-zoom-view absolute inset-0 touch-pan-y overflow-y-auto overflow-x-hidden bg-[var(--kh-panel-bg,var(--kh-surface))]\">\n        <div ref={world} className=\"relative origin-top-left\" style={{ width: size?.W, height: size ? layoutLevel(rootItems.length, size.W, size.H, aspect).height : undefined }}>\n          {scene && (leaf\n            ? <div className=\"overflow-clip\" style={{ width: scene.W, height: scene.H }}>{rootNode!.picture ?? <Plain title={rootNode!.title} />}</div>\n            : <Level items={rootItems} path={rootIds} aff={IDENTITY} scene={scene} live={!flight} onOpen={(id) => void flyTo([...at, id])} />)}\n        </div>\n      </div>\n      {overlay && <div className=\"absolute inset-0 z-10 overflow-y-auto\" style={{ background: PANEL }}>{overlay}</div>}\n      <p className=\"kh-zoom-sr\" role=\"status\" aria-live=\"polite\">{flight ? '' : title}</p>\n    </section>\n  );\n}\n"
    },
    {
      "path": "src/ui/zoom-canvas.css",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/zoom-canvas.css",
      "content": "/* ZoomCanvas: each card's picture is the level it opens. The ring is drawn over the picture (not on it) so the level inside\n   reaches the picture's edge; the card the camera is flying into lets it go, so the level fills the panel edge to edge. */\n.kh-zoom-pic { position:relative; overflow:clip; }\n.kh-zoom-pic::after { content:''; position:absolute; inset:0; border-radius:inherit; box-shadow:inset 0 0 0 1px var(--kh-line); pointer-events:none; transition:opacity 450ms ease; }\n.kh-zoom-pic[data-landing]::after { opacity:0; }\n.kh-zoom-view { outline:none; }\n.kh-zoom-sr { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; }\n@media (prefers-reduced-motion: reduce) { .kh-zoom-pic::after { transition:none; } }\n"
    },
    {
      "path": "src/ui/zoom-canvas.maths.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/zoom-canvas.maths.ts",
      "content": "// The layout and camera maths of ZoomCanvas, as pure functions (no DOM, no React) so they are tested alone and the component only\n// draws what they say. Every level of the tree is laid out in its own panel space (W by H layout pixels); a card's picture is the\n// child level drawn at that same size and scaled by picture width over W. A camera is the transform of the world (the level the\n// camera is rooted on) onto the screen: screen = cam.xy + cam.k * world.\n\nexport interface Rect { x: number; y: number; w: number; h: number }\n/** Screen position of the world origin, and how much the world is scaled. */\nexport interface Cam { x: number; y: number; k: number }\n/** Where a level sits in its root level's coordinates: its origin, and how much it is scaled down. */\nexport interface Aff { x: number; y: number; s: number }\n/** The minimal tree the maths needs. */\nexport interface Node { id: string; items?: readonly Node[] }\n\nexport const IDENTITY: Aff = { x: 0, y: 0, s: 1 };\n/** A picture smaller than this on screen is left plain: nothing there could be seen, and the levels below stop there. */\nexport const MIN_PICTURE = 12;\n/** A card around its picture: 7 px (1 border, 6 padding) each side, and a name row of 33 px under the picture. */\nexport const CARD_W = 14;\nexport const LABEL_H = 47;\n/** The smallest card worth reading when a level cannot fit its panel and scrolls. */\nexport const MIN_CARD = 220;\n/** Directory cards show a 16:10 picture. */\nexport const DEFAULT_ASPECT = 1.6;\n\nexport const padOf = (W: number) => (W >= 768 ? 32 : 24);\nexport const gapOf = (W: number) => (W <= 640 ? 12 : 20);\n\n/** The picture's width over height: the card's own (16:10), or the panel's when the panel is taller than that, so that the level a\n *  card shows always covers the panel it will fill when the camera lands on it. */\nexport const pictureAspect = (W: number, H: number, aspect = DEFAULT_ASPECT) => Math.min(aspect, W / H);\n\n/** Columns that make the cards as large as they can be with every card in view; when no count fits, as many as keep a card\n *  readable, and the level scrolls (`card` is then undefined and the columns share the width). */\nexport function fitColumns(n: number, W: number, H: number, aspect = DEFAULT_ASPECT): { cols: number; card?: number } {\n  const pad = padOf(W), gap = gapOf(W), aw = W - 2 * pad, ah = H - 2 * pad;\n  // For each count a card is as wide as the width allows and as tall as the height allows, whichever is less. A last row at most\n  // half full does not count (one card alone under five). When height is the limit the grid is narrower than the panel and centred.\n  let best: { cols: number; card: number } | undefined;\n  for (let c = 1; c <= n; c++) {\n    const r = Math.ceil(n / c), last = n - (r - 1) * c;\n    if (r > 1 && last * 2 <= c) continue;\n    const byWidth = (aw - gap * (c - 1)) / c, byHeight = ((ah - gap * (r - 1)) / r - LABEL_H) * aspect + CARD_W;\n    const card = Math.floor(Math.min(byWidth, byHeight));\n    if (!best || card > best.card) best = { cols: c, card };\n  }\n  if (best && best.card >= MIN_CARD * 0.75) return best;\n  return { cols: Math.max(1, Math.min(n, Math.floor((aw + gap) / (MIN_CARD + gap)))) };\n}\n\nexport interface Layout {\n  cols: number;\n  /** Card width, border and padding included. */\n  card: number;\n  /** One card's box and its picture, in the level's panel coordinates, in item order. */\n  boxes: Rect[];\n  pictures: Rect[];\n  /** The level's full height: more than H when it scrolls. */\n  height: number;\n}\n\n/** Where n cards sit on a level of W by H. */\nexport function layoutLevel(n: number, W: number, H: number, aspect = DEFAULT_ASPECT): Layout {\n  const ea = pictureAspect(W, H, aspect);\n  const pad = padOf(W), gap = gapOf(W), aw = W - 2 * pad;\n  const fit = fitColumns(n, W, H, ea);\n  const cols = fit.cols;\n  const card = fit.card ?? (aw - gap * (cols - 1)) / cols;\n  const x0 = pad + (aw - (cols * card + gap * (cols - 1))) / 2;\n  const picW = card - CARD_W, picH = picW / ea, cardH = picH + LABEL_H;\n  const boxes: Rect[] = [], pictures: Rect[] = [];\n  for (let i = 0; i < n; i++) {\n    const x = x0 + (i % cols) * (card + gap), y = pad + Math.floor(i / cols) * (cardH + gap);\n    boxes.push({ x, y, w: card, h: cardH });\n    pictures.push({ x: x + CARD_W / 2, y: y + CARD_W / 2, w: picW, h: picH });\n  }\n  const rows = Math.ceil(n / cols);\n  return { cols, card, boxes, pictures, height: n ? 2 * pad + rows * cardH + (rows - 1) * gap : H };\n}\n\n/** The size a level is drawn at inside a picture: the panel's width, and the height the picture's aspect gives (never under H). */\nexport const levelBox = (W: number, H: number, aspect = DEFAULT_ASPECT) => ({ W, H: W / pictureAspect(W, H, aspect) });\n\n/** A card's picture corners: the panel's radius times picture width over panel width, so that once the camera has scaled the picture\n *  up to the panel it has the panel's own corners, at any depth. */\nexport const pictureRadius = (panelRadius: number, picW: number, W: number) => (panelRadius * picW) / W;\n\n/** The level inside a picture: its origin and scale in the root's coordinates, given its parent level's. */\nexport const within = (parent: Aff, pic: Rect, W: number): Aff => ({ x: parent.x + parent.s * pic.x, y: parent.y + parent.s * pic.y, s: (parent.s * pic.w) / W });\n\n/** The camera that shows a level (positioned by `aff` in the root) scrolled by `scroll` panel pixels, filling the panel exactly. */\nexport const cameraFor = (aff: Aff, scroll = 0): Cam => ({ k: 1 / aff.s, x: 0 - aff.x / aff.s, y: 0 - aff.y / aff.s - scroll });\n\n/** Flying into a card: the camera that makes a picture rect (in root coordinates) fill a view W wide, from its top-left. */\nexport const fitCamera = (pic: Rect, W: number): Cam => ({ k: W / pic.w, x: (-pic.x * W) / pic.w, y: (-pic.y * W) / pic.w });\n\nconst find = (items: readonly Node[] | undefined, id: string) => items?.findIndex((x) => x.id === id) ?? -1;\n\n/** The nodes a path of ids names, or null when an id is not there. */\nexport function resolvePath<T extends Node>(items: readonly T[], ids: readonly string[]): T[] | null {\n  const out: T[] = [];\n  let level: readonly T[] | undefined = items;\n  for (const id of ids) {\n    const at = find(level, id);\n    if (at < 0) return null;\n    out.push(level![at]!);\n    level = out[out.length - 1]!.items as readonly T[] | undefined;\n  }\n  return out;\n}\n\n/** Where the level at `ids` sits within the level at `from` (a prefix of it), and the card pictures on the way. */\nexport function levelAt(items: readonly Node[], from: readonly string[], ids: readonly string[], W: number, H: number, aspect = DEFAULT_ASPECT): Aff | null {\n  const base = resolvePath(items, from);\n  if (!base || from.some((id, i) => ids[i] !== id)) return null;\n  let level: readonly Node[] = base.length ? base[base.length - 1]!.items ?? [] : items;\n  let aff = IDENTITY;\n  for (const id of ids.slice(from.length)) {\n    const at = find(level, id);\n    if (at < 0) return null;\n    aff = within(aff, layoutLevel(level.length, W, H, aspect).pictures[at]!, W);\n    level = level[at]!.items ?? [];\n  }\n  return aff;\n}\n\n/** The leading ids two paths share. */\nexport function commonPrefix(a: readonly string[], b: readonly string[]): string[] {\n  const out: string[] = [];\n  while (out.length < a.length && out.length < b.length && a[out.length] === b[out.length]) out.push(a[out.length]!);\n  return out;\n}\n\nexport interface Flight {\n  /** The level drawn as the world during the flight: the deepest level that holds both ends. */\n  root: string[];\n  start: Cam;\n  end: Cam;\n  /** How far the level the camera ends on is scrolled (flying out puts the card we left in view). */\n  endScroll: number;\n}\n\n/** A flight from the level at `from` to the level at `to`: the camera rooted on the deepest level that holds both, so flying in\n *  is the camera moving to a card, flying out is it moving back, and the picture of the level it comes from stays drawn. */\nexport function planFlight(items: readonly Node[], from: readonly string[], to: readonly string[], W: number, H: number, o: { aspect?: number; scroll?: number } = {}): Flight | null {\n  const { aspect = DEFAULT_ASPECT, scroll = 0 } = o;\n  const root = commonPrefix(from, to);\n  const a = levelAt(items, root, from, W, H, aspect), b = levelAt(items, root, to, W, H, aspect);\n  if (!a || !b) return null;\n  // Arriving on the level we flew out of: put the card we left in view.\n  let endScroll = 0;\n  if (to.length === root.length && from.length > root.length) {\n    const level = resolvePath(items, root)!, kids = (level.length ? level[level.length - 1]!.items : items) ?? [];\n    const lay = layoutLevel(kids.length, W, H, aspect), at = find(kids, from[root.length]!);\n    if (at >= 0 && lay.height > H) endScroll = Math.max(0, Math.min(lay.height - H, lay.boxes[at]!.y + lay.boxes[at]!.h / 2 - H / 2));\n  }\n  return { root, start: cameraFor(a, scroll), end: cameraFor(b, endScroll), endScroll };\n}\n\n/** The camera at progress t of a flight: the middle of what is seen moves in a line and the zoom changes evenly in log, so the flight\n *  neither swoops nor crawls. */\nexport function cameraAt(start: Cam, end: Cam, t: number, W: number, H: number): Cam {\n  const seen = (c: Cam) => ({ cx: (W / 2 - c.x) / c.k, cy: (H / 2 - c.y) / c.k, lk: Math.log(c.k) });\n  const a = seen(start), b = seen(end);\n  const k = Math.exp(a.lk + (b.lk - a.lk) * t), cx = a.cx + (b.cx - a.cx) * t, cy = a.cy + (b.cy - a.cy) * t;\n  return { k, x: W / 2 - cx * k, y: H / 2 - cy * k };\n}\nexport const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);\n\n/** Whether a picture (a rect in a level at `aff`) is worth drawing under a camera: big enough on screen, and not further than half a\n *  view from what is seen (`h` is the height seen: a level at rest counts as seen whole). */\nexport function worthDrawing(pic: Rect, aff: Aff, cam: Cam, view: { W: number; H: number }, minPicture = MIN_PICTURE): boolean {\n  const k = cam.k * aff.s;\n  if (pic.w * k < minPicture) return false;\n  const x = cam.x + cam.k * aff.x + k * pic.x, y = cam.y + cam.k * aff.y + k * pic.y;\n  return x + pic.w * k >= -view.W / 2 && x <= view.W * 1.5 && y + pic.h * k >= -view.H / 2 && y <= view.H * 1.5;\n}\n\n/** The card (by index) a pointer at (x, y) is over on a level at scale 1, scrolled by `scroll`. */\nexport function cardAt(layout: Layout, x: number, y: number, scroll = 0): number {\n  return layout.boxes.findIndex((b) => x >= b.x && x <= b.x + b.w && y + scroll >= b.y && y + scroll <= b.y + b.h);\n}\n"
    }
  ]
}
