{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "project-index",
  "title": "Project index",
  "description": "Project index is a production-ready galleries component from BJORK UI, packaged for shadcn registries.",
  "dependencies": [
    "clsx",
    "framer-motion",
    "next-themes",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "components/bjork-ui/galleries/project-index.tsx",
      "content": "\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type CSSProperties,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type ReactNode,\n} from \"react\";\nimport { AnimatePresence, motion } from \"framer-motion\";\nimport {\n  GlowRules,\n  type GlowRulesHandle,\n} from \"@/components/bjork-ui/misc/glow-rules\";\nimport { MediaStage } from \"@/components/bjork-ui/galleries/project-index-media\";\nimport {\n  BJORK_PALETTE,\n  type BjorkTone,\n} from \"@/components/bjork-ui/_core/palette\";\nimport { useBjorkTone } from \"@/components/bjork-ui/_core/tone\";\nimport { useVisibleLoop } from \"@/components/bjork-ui/_core/loop\";\nimport { ease, springs } from \"@/components/bjork-ui/_core/motion\";\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------------------------------\n * Types\n * ---------------------------------------------------------------------------------------------- */\n\nexport interface ProjectIndexMedia {\n  type: \"image\" | \"video\";\n  src: string;\n  /** Still frame for videos. Shown until the first frame decodes, and instead of the video under reduced motion. */\n  poster?: string;\n  alt: string;\n  /** Focal point for cover cropping, 0 to 1 from the top-left. Default [0.5, 0.5]. */\n  focal?: [number, number];\n}\n\nexport interface ProjectIndexItem {\n  id: string;\n  title: string;\n  href: string;\n  client?: string;\n  year: number | string;\n  /** What you did. The headline of the card. */\n  role: string;\n  services: string[];\n  /** One true number about the work. Leave it out rather than invent one. */\n  outcome?: { value: string; label: string };\n  category?: { label: string; color?: string };\n  media: ProjectIndexMedia;\n  /** Tints the row slab and index. Defaults to the index accent. */\n  accent?: string;\n  disabled?: boolean;\n}\n\nexport interface ProjectIndexProps {\n  items: ProjectIndexItem[];\n  heading?: ReactNode;\n  tone?: BjorkTone;\n  /** Accent for every row without its own. */\n  accent?: string;\n  /** `corner` docks the card at the bottom right; `follow` lets it lean toward the hovered row. */\n  cardPlacement?: \"corner\" | \"follow\";\n  /** `dissolve` is a WebGL grain dissolve; it falls back to `crossfade` without WebGL. */\n  mediaTransition?: \"dissolve\" | \"crossfade\" | \"none\";\n  /** Hover time before the card rises, in ms. Default 90. */\n  dwellMs?: number;\n  /** `auto` uses the expanding list on touch screens and under 900 px. */\n  layout?: \"auto\" | \"hover\" | \"expand\";\n  showIndexNumbers?: boolean;\n  /** Show the item count beside the heading. Default true. */\n  showCount?: boolean;\n  /** Label of the card's call to action. Default \"Open project\". */\n  openLabel?: string;\n  /** Opens links in a new tab. */\n  target?: \"_self\" | \"_blank\";\n  renderRowEnd?: (item: ProjectIndexItem, active: boolean) => ReactNode;\n  renderCardBody?: (item: ProjectIndexItem) => ReactNode;\n  renderCardFooter?: (item: ProjectIndexItem) => ReactNode;\n  onActiveChange?: (item: ProjectIndexItem | null) => void;\n  /** Opens the card on this item at mount, as if it were hovered. Useful for previews and pinned states. */\n  defaultActiveId?: string;\n  className?: string;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Tokens\n * ---------------------------------------------------------------------------------------------- */\n\nconst ROW_H = 72;\nconst EASE_OUT = \"cubic-bezier(0.23,1,0.32,1)\";\nconst SPEED_GATE = 1.5; // px per ms\nconst SETTLE_MS = 60;\nconst GRACE_MS = 160;\n\nfunction tokens(tone: BjorkTone) {\n  const p = BJORK_PALETTE[tone];\n  const dark = tone === \"dark\";\n  return {\n    dark,\n    text: p.text,\n    // Titles dim to these when another row is active. Both stay above 4.5:1 on the index background.\n    dim: dark ? 0.56 : 0.66,\n    meta: dark ? \"rgba(237,237,237,0.6)\" : \"rgba(23,23,23,0.64)\",\n    faint: dark ? \"rgba(237,237,237,0.42)\" : \"rgba(23,23,23,0.5)\",\n    hair: dark ? \"rgba(255,255,255,0.1)\" : \"rgba(23,23,23,0.1)\",\n    card: dark ? \"rgba(18,18,20,0.86)\" : \"rgba(255,252,246,0.9)\",\n    cardBorder: dark ? \"rgba(255,255,255,0.08)\" : \"rgba(23,23,23,0.08)\",\n    cardShadow: dark\n      ? \"0 40px 90px -20px rgba(0,0,0,0.75), 0 12px 24px -12px rgba(0,0,0,0.5)\"\n      : \"0 30px 60px -24px rgba(66,52,33,0.28), 0 10px 20px -12px rgba(66,52,33,0.16)\",\n    inner: dark\n      ? \"inset 0 1px 0 rgba(255,255,255,0.06)\"\n      : \"inset 0 1px 0 rgba(255,255,255,0.9)\",\n    mediaBg: dark ? \"#0d0d0e\" : \"#ece6da\",\n    accent: p.accent,\n    accentInk: p.accentInk,\n    glow: dark ? \"#ffffff\" : \"#5b3f22\",\n  };\n}\ntype Tokens = ReturnType<typeof tokens>;\n\n/** Accent as ink: on light backgrounds, darken it so small text keeps its contrast. */\nfunction inkFor(accent: string, t: Tokens) {\n  return t.dark\n    ? `color-mix(in oklab, ${accent} 58%, #ffffff)`\n    : `color-mix(in oklab, ${accent} 62%, #1a120c)`;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks\n * ---------------------------------------------------------------------------------------------- */\n\nfunction useMedia(query: string, server = false) {\n  return useSyncExternalStore(\n    (cb) => {\n      if (typeof window === \"undefined\") return () => {};\n      const mq = window.matchMedia(query);\n      mq.addEventListener(\"change\", cb);\n      return () => mq.removeEventListener(\"change\", cb);\n    },\n    () => window.matchMedia(query).matches,\n    () => server,\n  );\n}\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\n\n/* ------------------------------------------------------------------------------------------------\n * Small parts\n * ---------------------------------------------------------------------------------------------- */\n\nfunction pad(n: number) {\n  return String(n).padStart(2, \"0\");\n}\n\n/** A field that swaps its value in place. Only changed values move; the old one leaves as the new one arrives. */\nfunction Swap({\n  value,\n  dir,\n  delay,\n  intro,\n  reduce,\n  className,\n  style,\n  children,\n}: {\n  value: string;\n  dir: number;\n  delay: number;\n  intro: boolean;\n  reduce: boolean;\n  className?: string;\n  style?: CSSProperties;\n  children: ReactNode;\n}) {\n  const from = reduce\n    ? { opacity: 0 }\n    : intro\n      ? { opacity: 0, y: 8, filter: \"blur(4px)\" }\n      : { opacity: 0, y: 6 * dir, filter: \"blur(0px)\" };\n  return (\n    <span className={cn(\"grid\", className)} style={style}>\n      <AnimatePresence initial={true}>\n        <motion.span\n          key={value}\n          className=\"col-start-1 row-start-1 block min-w-0\"\n          initial={from}\n          animate={{\n            opacity: 1,\n            y: 0,\n            filter: \"blur(0px)\",\n            transition: reduce\n              ? { duration: 0.15 }\n              : {\n                  duration: intro ? 0.26 : 0.22,\n                  delay: delay / 1000,\n                  ease: ease.out,\n                },\n          }}\n          exit={{\n            opacity: 0,\n            y: reduce ? 0 : -6 * dir,\n            transition: { duration: 0.12, ease: ease.out },\n          }}\n        >\n          {children}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\n/** Characters roll vertically when they change, in the direction of travel. */\nfunction Roll({\n  value,\n  dir,\n  reduce,\n}: {\n  value: string;\n  dir: number;\n  reduce: boolean;\n}) {\n  const chars = value.split(\"\");\n  return (\n    <span className=\"inline-flex tabular-nums\" aria-hidden>\n      {chars.map((c, i) => (\n        <span\n          key={i}\n          className=\"relative inline-grid overflow-hidden\"\n          style={{ height: \"1em\", lineHeight: 1 }}\n        >\n          <AnimatePresence initial={false}>\n            <motion.span\n              key={c}\n              className=\"col-start-1 row-start-1 block\"\n              initial={reduce ? false : { y: `${dir > 0 ? 100 : -100}%` }}\n              animate={{\n                y: \"0%\",\n                transition: { duration: 0.42, delay: i * 0.03, ease: ease.out },\n              }}\n              exit={{\n                y: `${dir > 0 ? -100 : 100}%`,\n                transition: { duration: 0.42, delay: i * 0.03, ease: ease.out },\n              }}\n            >\n              {c === \" \" ? \" \" : c}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n      ))}\n    </span>\n  );\n}\n\nfunction CategoryMark({\n  category,\n  t,\n}: {\n  category?: ProjectIndexItem[\"category\"];\n  t: Tokens;\n}) {\n  if (!category) return null;\n  return (\n    <span className=\"inline-flex items-center gap-2\">\n      <span\n        aria-hidden\n        className=\"size-1.5 shrink-0 rounded-full\"\n        style={{ background: category.color ?? t.faint }}\n      />\n      <span>{category.label}</span>\n    </span>\n  );\n}\n\n/** Stacked stills for the crossfade mode, and the reduced-motion path. Videos play only while active. */\nfunction DomMedia({\n  items,\n  index,\n  reduce,\n  mode,\n  open,\n}: {\n  items: ProjectIndexItem[];\n  index: number;\n  reduce: boolean;\n  mode: \"crossfade\" | \"none\";\n  open: boolean;\n}) {\n  const ms = mode === \"none\" ? 0 : reduce ? 150 : 300;\n  return (\n    <>\n      {items.map((item, i) => {\n        const m = item.media;\n        const active = i === index;\n        const still = m.type === \"image\" ? m.src : m.poster;\n        const pos = `${(m.focal?.[0] ?? 0.5) * 100}% ${(m.focal?.[1] ?? 0.5) * 100}%`;\n        return (\n          <div\n            key={item.id}\n            className=\"absolute inset-0\"\n            style={{\n              opacity: active ? 1 : 0,\n              transform: active || reduce ? \"scale(1)\" : \"scale(1.04)\",\n              transition: `opacity ${ms}ms ${EASE_OUT}, transform ${ms}ms ${EASE_OUT}`,\n              zIndex: active ? 1 : 0,\n            }}\n          >\n            {still && (\n              // eslint-disable-next-line @next/next/no-img-element\n              <img\n                src={still}\n                alt=\"\"\n                className=\"size-full object-cover\"\n                style={{ objectPosition: pos }}\n                decoding=\"async\"\n              />\n            )}\n            {m.type === \"video\" && active && open && !reduce && (\n              <video\n                src={m.src}\n                poster={m.poster}\n                muted\n                loop\n                playsInline\n                autoPlay\n                className=\"absolute inset-0 size-full object-cover\"\n                style={{ objectPosition: pos }}\n              />\n            )}\n          </div>\n        );\n      })}\n    </>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hover layout\n * ---------------------------------------------------------------------------------------------- */\n\ninterface CardState {\n  open: boolean;\n  index: number;\n  /** Content changes since the card opened. 0 means the fields play their rise. */\n  changes: number;\n  dir: number;\n  /** Bumps on every open so the fields remount and rise again. */\n  openId: number;\n}\n\nfunction HoverIndex(props: ProjectIndexProps & { t: Tokens; reduce: boolean }) {\n  const {\n    items,\n    t,\n    reduce,\n    accent,\n    cardPlacement = \"corner\",\n    mediaTransition = \"dissolve\",\n    dwellMs = 90,\n    showIndexNumbers = true,\n    openLabel = \"Open project\",\n    target,\n    renderRowEnd,\n    renderCardBody,\n    renderCardFooter,\n    onActiveChange,\n    defaultActiveId,\n  } = props;\n\n  const defaultIndex = defaultActiveId\n    ? items.findIndex((x) => x.id === defaultActiveId)\n    : -1;\n  const uid = useId();\n  const wrapRef = useRef<HTMLDivElement>(null);\n  const glowRef = useRef<GlowRulesHandle>(null);\n  const rowRefs = useRef<(HTMLLIElement | null)[]>([]);\n  const linkRefs = useRef<(HTMLAnchorElement | null)[]>([]);\n  const endRefs = useRef<(HTMLSpanElement | null)[]>([]);\n  const cardDockRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const mediaBoxRef = useRef<HTMLDivElement>(null);\n  const stageRef = useRef<MediaStage | null>(null);\n\n  const [hover, setHover] = useState(defaultIndex);\n  // Where the slab sits. It keeps its row while fading out, and appears in place (jump) when nothing was active.\n  const [slab, setSlab] = useState({\n    index: Math.max(0, defaultIndex),\n    jump: true,\n  });\n  const [focusIndex, setFocusIndex] = useState(Math.max(0, defaultIndex));\n  const [card, setCard] = useState<CardState>({\n    open: defaultIndex >= 0,\n    index: Math.max(0, defaultIndex),\n    changes: 0,\n    dir: 1,\n    openId: defaultIndex >= 0 ? 1 : 0,\n  });\n  const [geom, setGeom] = useState({\n    width: 0,\n    rowTops: [] as number[],\n    rowH: ROW_H,\n  });\n  const [stageOk, setStageOk] = useState<boolean | null>(null);\n\n  // Live copies for event handlers.\n  const live = useRef({\n    hover: defaultIndex,\n    hoverStart: 0,\n    lastFastAt: 0,\n    lastMove: { x: 0, y: 0, t: 0 },\n    speed: 0,\n    gate: 0 as ReturnType<typeof setTimeout> | 0,\n    grace: 0 as ReturnType<typeof setTimeout> | 0,\n    card,\n    pointerY: 0,\n  });\n  useEffect(() => {\n    live.current.card = card;\n  }, [card]);\n\n  const useShader =\n    mediaTransition === \"dissolve\" && !reduce && stageOk !== false;\n  const domMode: \"crossfade\" | \"none\" =\n    mediaTransition === \"none\" ? \"none\" : \"crossfade\";\n\n  /* Geometry ----------------------------------------------------------------------------------- */\n\n  useEffect(() => {\n    const wrap = wrapRef.current;\n    if (!wrap) return;\n    const read = () => {\n      const width = wrap.clientWidth;\n      const rowTops = rowRefs.current.map((r) => r?.offsetTop ?? 0);\n      const rowH = rowRefs.current[0]?.offsetHeight ?? ROW_H;\n      setGeom((g) =>\n        g.width === width &&\n        g.rowH === rowH &&\n        g.rowTops.join() === rowTops.join()\n          ? g\n          : { width, rowTops, rowH },\n      );\n    };\n    const ro = new ResizeObserver(read);\n    ro.observe(wrap);\n    read();\n    return () => ro.disconnect();\n  }, [items.length]);\n\n  const cardW = Math.round(Math.min(400, Math.max(300, geom.width * 0.34)));\n  const inset = 16;\n\n  // A default active row also gets its light, as if the pointer rested on it.\n  useEffect(() => {\n    if (defaultIndex < 0) return;\n    const raf = requestAnimationFrame(() => {\n      const row = rowRefs.current[defaultIndex];\n      if (row)\n        glowRef.current?.pointAt(\n          Math.min(row.offsetWidth * 0.3, 320),\n          row.offsetTop + row.offsetHeight / 2,\n        );\n    });\n    return () => cancelAnimationFrame(raf);\n    // Mount only.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  /* Media stage -------------------------------------------------------------------------------- */\n\n  const loop = useVisibleLoop(\n    wrapRef,\n    () => {\n      const stage = stageRef.current;\n      if (!stage) return false;\n      return stage.frame(performance.now());\n    },\n    { enabled: useShader },\n  );\n\n  useEffect(() => {\n    if (mediaTransition !== \"dissolve\" || reduce) return;\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const stage = MediaStage.create(canvas);\n    stageRef.current = stage;\n    // Reporting the result is the point of this effect: it decides between the canvas and the DOM stack.\n    setStageOk(!!stage);\n    if (!stage) return;\n    const box = mediaBoxRef.current;\n    const ro = new ResizeObserver(() => {\n      if (!box) return;\n      const dpr = Math.min(2, window.devicePixelRatio || 1);\n      stage.resize(\n        Math.round(box.clientWidth * dpr),\n        Math.round(box.clientHeight * dpr),\n      );\n      loop.wake();\n    });\n    if (box) ro.observe(box);\n    // Warm every still so the first rise never shows an empty frame.\n    items.forEach((it) => stage.preload(it.media));\n    const c = live.current.card;\n    if (c.open && items[c.index])\n      stage.show(items[c.index].media, 1, true).then(() => loop.wake());\n    const onVis = () => {\n      if (document.visibilityState === \"hidden\") stage.pauseVideos();\n      else if (live.current.card.open) stage.resumeVideo();\n    };\n    document.addEventListener(\"visibilitychange\", onVis);\n    return () => {\n      ro.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVis);\n      stage.dispose();\n      stageRef.current = null;\n    };\n    // items identity changes should not rebuild the GL context; media is looked up by index at show time.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [mediaTransition, reduce, loop]);\n\n  const showMedia = useCallback(\n    (index: number, dir: number, instant: boolean) => {\n      const stage = stageRef.current;\n      const item = items[index];\n      if (!stage || !item) return;\n      stage.show(item.media, dir, instant).then(() => loop.wake());\n      loop.wake();\n    },\n    [items, loop],\n  );\n\n  /* Card control ------------------------------------------------------------------------------- */\n\n  const emit = useCallback(\n    (item: ProjectIndexItem | null) => {\n      onActiveChange?.(item);\n    },\n    [onActiveChange],\n  );\n\n  const openCard = useCallback(\n    (index: number) => {\n      const c = live.current.card;\n      if (c.open && c.index === index) return;\n      const dir = c.open ? Math.sign(index - c.index) || 1 : 1;\n      const next: CardState = c.open\n        ? { ...c, index, dir, changes: c.changes + 1 }\n        : { open: true, index, dir: 1, changes: 0, openId: c.openId + 1 };\n      live.current.card = next;\n      setCard(next);\n      showMedia(index, dir, !c.open);\n      emit(items[index] ?? null);\n    },\n    [emit, items, showMedia],\n  );\n\n  const closeCard = useCallback(() => {\n    const c = live.current.card;\n    if (!c.open) return;\n    const next = { ...c, open: false };\n    live.current.card = next;\n    setCard(next);\n    emit(null);\n    // Let the sink finish before stopping video.\n    setTimeout(() => {\n      if (!live.current.card.open) stageRef.current?.pauseVideos();\n    }, 320);\n  }, [emit]);\n\n  const clearGate = () => {\n    const l = live.current;\n    if (l.gate) clearTimeout(l.gate);\n    l.gate = 0;\n  };\n\n  const evaluateRef = useRef<() => void>(() => {});\n  // The gate: the card rises only after the dwell, and only once the pointer has slowed down.\n  // While open, content follows the same speed gate with a shorter dwell, so fast sweeps never flash.\n  const evaluate = useCallback(() => {\n    const l = live.current;\n    l.gate = 0;\n    const target = l.hover;\n    if (target < 0 || items[target]?.disabled) return;\n    const now = performance.now();\n    const settled = now - l.lastFastAt >= SETTLE_MS;\n    const c = l.card;\n    const dwell = c.open ? Math.min(60, dwellMs) : dwellMs;\n    if (c.open && c.index === target) return;\n    if (now - l.hoverStart >= dwell && settled) {\n      openCard(target);\n      return;\n    }\n    l.gate = setTimeout(() => evaluateRef.current(), 16);\n  }, [dwellMs, items, openCard]);\n  useEffect(() => {\n    evaluateRef.current = evaluate;\n  }, [evaluate]);\n\n  const enterRow = useCallback(\n    (i: number) => {\n      const l = live.current;\n      if (l.grace) {\n        clearTimeout(l.grace);\n        l.grace = 0;\n      }\n      if (l.hover === i) return;\n      setSlab({ index: i, jump: l.hover < 0 });\n      l.hover = i;\n      l.hoverStart = performance.now();\n      setHover(i);\n      clearGate();\n      evaluate();\n    },\n    [evaluate],\n  );\n\n  const leaveList = useCallback(() => {\n    const l = live.current;\n    clearGate();\n    l.hover = -1;\n    setHover(-1);\n    if (l.grace) clearTimeout(l.grace);\n    l.grace = setTimeout(() => {\n      l.grace = 0;\n      closeCard();\n    }, GRACE_MS);\n  }, [closeCard]);\n\n  useEffect(() => {\n    const l = live.current;\n    return () => {\n      if (l.gate) clearTimeout(l.gate);\n      if (l.grace) clearTimeout(l.grace);\n    };\n  }, []);\n\n  /* Rows under the card fade their row ends so nothing reads through the glass. -------------- */\n\n  useEffect(() => {\n    const dock = cardDockRef.current;\n    if (!card.open || !dock) {\n      endRefs.current.forEach((el) => el?.removeAttribute(\"data-covered\"));\n      return;\n    }\n    let raf = 0;\n    const update = () => {\n      raf = 0;\n      const r = dock.getBoundingClientRect();\n      rowRefs.current.forEach((row, i) => {\n        const end = endRefs.current[i];\n        if (!row || !end) return;\n        const b = row.getBoundingClientRect();\n        const covered = b.bottom > r.top + 4 && b.top < r.bottom - 4;\n        if (covered) end.setAttribute(\"data-covered\", \"\");\n        else end.removeAttribute(\"data-covered\");\n      });\n    };\n    const schedule = () => {\n      if (!raf) raf = requestAnimationFrame(update);\n    };\n    update();\n    window.addEventListener(\"scroll\", schedule, {\n      passive: true,\n      capture: true,\n    });\n    window.addEventListener(\"resize\", schedule);\n    return () => {\n      if (raf) cancelAnimationFrame(raf);\n      window.removeEventListener(\"scroll\", schedule, { capture: true });\n      window.removeEventListener(\"resize\", schedule);\n    };\n  }, [card.open, geom]);\n\n  /* Keyboard ----------------------------------------------------------------------------------- */\n\n  const focusRow = (i: number) => {\n    const n = items.length;\n    const next = (i + n) % n;\n    linkRefs.current[next]?.focus();\n  };\n\n  const onKeyDown = (e: ReactKeyboardEvent<HTMLUListElement>) => {\n    const current = linkRefs.current.findIndex(\n      (el) => el === document.activeElement,\n    );\n    if (current < 0) return;\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      focusRow(current + 1);\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      focusRow(current - 1);\n    } else if (e.key === \"Home\") {\n      e.preventDefault();\n      focusRow(0);\n    } else if (e.key === \"End\") {\n      e.preventDefault();\n      focusRow(items.length - 1);\n    } else if (e.key === \"Escape\") {\n      if (live.current.card.open) {\n        e.preventDefault();\n        closeCard();\n      }\n    }\n  };\n\n  /* Derived ------------------------------------------------------------------------------------ */\n\n  const activeIndex = hover;\n  const cardItem = items[card.index];\n  const accentOf = (item?: ProjectIndexItem) =>\n    item?.accent ?? accent ?? t.accent;\n  const slabAccent = accentOf(items[slab.index]);\n  const slabY = geom.rowTops[slab.index] ?? 0;\n\n  const tether =\n    card.open && !reduce && geom.width > 0\n      ? {\n          x: geom.width - inset - cardW - 24,\n          y: (geom.rowTops[card.index] ?? 0) + geom.rowH / 2,\n          width: Math.max(220, geom.width * 0.32),\n          height: geom.rowH * 0.62,\n          intensity: t.dark ? 0.55 : 0.5,\n        }\n      : null;\n\n  // Follow mode: the card leans toward the hovered row, a few px at most.\n  const followY = (() => {\n    if (cardPlacement !== \"follow\" || !card.open || reduce) return 0;\n    const rows = geom.rowTops.length;\n    if (!rows) return 0;\n    const centre = (rows - 1) / 2;\n    return Math.max(-24, Math.min(24, (card.index - centre) * 6));\n  })();\n\n  const describe = (item: ProjectIndexItem) =>\n    [\n      item.role,\n      item.services.join(\", \"),\n      item.client,\n      String(item.year),\n      item.outcome ? `${item.outcome.value} ${item.outcome.label}` : \"\",\n    ]\n      .filter(Boolean)\n      .join(\". \");\n\n  return (\n    <div\n      ref={wrapRef}\n      className=\"relative\"\n      onPointerMove={(e) => {\n        if (e.pointerType === \"touch\") return;\n        const l = live.current;\n        const now = performance.now();\n        const dt = now - l.lastMove.t;\n        if (dt > 0 && dt < 100) {\n          const v =\n            Math.hypot(e.clientX - l.lastMove.x, e.clientY - l.lastMove.y) / dt;\n          l.speed = l.speed * 0.6 + v * 0.4;\n          if (l.speed > SPEED_GATE) l.lastFastAt = now;\n        }\n        l.lastMove = { x: e.clientX, y: e.clientY, t: now };\n      }}\n      onPointerLeave={(e) => {\n        if (e.pointerType === \"touch\") return;\n        leaveList();\n      }}\n    >\n      <GlowRules\n        ref={glowRef}\n        selector=\"[data-pi-row]\"\n        tone={t.dark ? \"dark\" : \"light\"}\n        color={t.glow}\n        ruleColor={t.hair}\n        radius={[0.4, 100]}\n        lerp={0.12}\n        quantize={4}\n        tether={tether}\n        drawIn\n      >\n        {/* The slab: one element that travels between rows. */}\n        <motion.div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-x-0 top-0\"\n          style={{ height: geom.rowH, zIndex: 0 }}\n          initial={false}\n          animate={{ y: slabY, opacity: activeIndex >= 0 ? 1 : 0 }}\n          transition={{\n            y: reduce || slab.jump ? { duration: 0 } : springs.snappy,\n            opacity: {\n              duration: activeIndex >= 0 ? 0.12 : 0.2,\n              ease: \"easeOut\",\n            },\n          }}\n        >\n          <div\n            className=\"absolute inset-0\"\n            style={{\n              backgroundColor: `color-mix(in srgb, ${slabAccent} ${t.dark ? 14 : 10}%, transparent)`,\n              WebkitMaskImage:\n                \"linear-gradient(90deg, #000 0%, rgba(0,0,0,0.5) 30%, transparent 72%)\",\n              maskImage:\n                \"linear-gradient(90deg, #000 0%, rgba(0,0,0,0.5) 30%, transparent 72%)\",\n              transition: slab.jump ? \"none\" : \"background-color 220ms ease\",\n            }}\n          />\n          <div\n            className=\"absolute bottom-[1px] left-0 top-[1px] w-[2px] origin-center\"\n            style={{\n              background: slabAccent,\n              transform: `scaleY(${activeIndex >= 0 ? 1 : 0})`,\n              transition: `transform 180ms ${EASE_OUT}${slab.jump ? \"\" : \", background-color 220ms ease\"}`,\n            }}\n          />\n        </motion.div>\n\n        <ul\n          role=\"list\"\n          className=\"relative m-0 list-none p-0\"\n          style={{ zIndex: 0 }}\n          onKeyDown={onKeyDown}\n        >\n          {items.map((item, i) => {\n            const active = i === activeIndex;\n            const dimmed = activeIndex >= 0 && !active;\n            const descId = `${uid}-d${i}`;\n            const ink = inkFor(accentOf(item), t);\n            return (\n              <motion.li\n                key={item.id}\n                ref={(el) => {\n                  rowRefs.current[i] = el;\n                }}\n                data-pi-row=\"\"\n                className=\"relative\"\n                initial={reduce ? { opacity: 0 } : { opacity: 0, y: 24 }}\n                whileInView={{ opacity: 1, y: 0 }}\n                viewport={{ once: true, margin: \"0px 0px -8% 0px\" }}\n                transition={{\n                  duration: reduce ? 0.2 : 0.6,\n                  delay: reduce ? 0 : i * 0.04,\n                  ease: ease.out,\n                }}\n              >\n                <a\n                  ref={(el) => {\n                    linkRefs.current[i] = el;\n                  }}\n                  href={item.disabled ? undefined : item.href}\n                  target={target}\n                  rel={target === \"_blank\" ? \"noreferrer\" : undefined}\n                  aria-disabled={item.disabled || undefined}\n                  aria-describedby={descId}\n                  tabIndex={i === focusIndex ? 0 : -1}\n                  className={cn(\n                    \"group/row relative grid items-center px-4 no-underline outline-none\",\n                    \"rounded-[2px] focus-visible:shadow-[inset_0_0_0_1px_var(--pi-ring)]\",\n                    item.disabled ? \"cursor-default\" : \"cursor-pointer\",\n                  )}\n                  style={\n                    {\n                      height: ROW_H,\n                      gridTemplateColumns: showIndexNumbers\n                        ? \"48px minmax(0,1fr) auto\"\n                        : \"minmax(0,1fr) auto\",\n                      color: t.text,\n                      \"--pi-ring\": `color-mix(in srgb, ${accentOf(item)} 45%, transparent)`,\n                    } as CSSProperties\n                  }\n                  onPointerEnter={(e) => {\n                    if (e.pointerType === \"touch\") return;\n                    enterRow(i);\n                  }}\n                  onFocus={(e) => {\n                    setFocusIndex(i);\n                    // Keyboard runs the same choreography, without the dwell.\n                    if (!e.currentTarget.matches(\":focus-visible\")) return;\n                    const l = live.current;\n                    if (l.grace) {\n                      clearTimeout(l.grace);\n                      l.grace = 0;\n                    }\n                    clearGate();\n                    setSlab({ index: i, jump: l.hover < 0 });\n                    l.hover = i;\n                    setHover(i);\n                    if (!item.disabled) openCard(i);\n                  }}\n                  onBlur={(e) => {\n                    const next = e.relatedTarget as Node | null;\n                    if (next && wrapRef.current?.contains(next)) return;\n                    leaveList();\n                  }}\n                  onClick={(e) => {\n                    if (item.disabled) e.preventDefault();\n                  }}\n                >\n                  {showIndexNumbers && (\n                    <span\n                      className=\"font-mono text-[12px] tabular-nums tracking-[0.02em]\"\n                      style={{\n                        color: active ? ink : t.faint,\n                        transition: \"color 200ms ease\",\n                      }}\n                    >\n                      {pad(i + 1)}\n                    </span>\n                  )}\n                  <span\n                    className=\"truncate font-medium leading-none tracking-[-0.015em]\"\n                    style={{\n                      fontSize: \"clamp(20px, 2vw, 28px)\",\n                      opacity: dimmed ? t.dim : item.disabled ? t.dim : 1,\n                      transform: `translate3d(${active && !reduce ? 12 : 0}px,0,0)`,\n                      transition: `opacity 200ms ease, transform 220ms ${EASE_OUT}`,\n                    }}\n                  >\n                    {item.title}\n                  </span>\n                  <span\n                    ref={(el) => {\n                      endRefs.current[i] = el;\n                    }}\n                    className=\"flex items-center gap-6 font-mono text-[12px] tabular-nums tracking-[0.02em] transition-opacity duration-200 data-[covered]:opacity-0\"\n                    style={{ color: t.meta }}\n                  >\n                    {renderRowEnd ? (\n                      renderRowEnd(item, active)\n                    ) : (\n                      <>\n                        <CategoryMark category={item.category} t={t} />\n                        <span>{item.year}</span>\n                      </>\n                    )}\n                  </span>\n                  <span id={descId} className=\"sr-only\">\n                    {describe(item)}\n                  </span>\n                </a>\n              </motion.li>\n            );\n          })}\n        </ul>\n      </GlowRules>\n\n      {/* The dossier rail: a column on the right whose card docks at the bottom, and to the viewport bottom on long lists. */}\n      <div\n        aria-hidden\n        className=\"pointer-events-none absolute bottom-0 top-0 flex flex-col justify-end\"\n        style={{ right: inset, width: cardW, zIndex: 2, paddingBottom: inset }}\n      >\n        <div ref={cardDockRef} className=\"sticky\" style={{ bottom: 24 }}>\n          <motion.div\n            initial={false}\n            animate={{ y: followY }}\n            transition={{ type: \"spring\", stiffness: 170, damping: 26 }}\n          >\n            <Dossier\n              card={card}\n              item={cardItem}\n              items={items}\n              t={t}\n              reduce={reduce}\n              width={cardW}\n              useShader={useShader}\n              domMode={domMode}\n              canvasRef={canvasRef}\n              mediaBoxRef={mediaBoxRef}\n              openLabel={openLabel}\n              accent={accentOf(cardItem)}\n              renderCardBody={renderCardBody}\n              renderCardFooter={renderCardFooter}\n            />\n          </motion.div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------\n * The card\n * ---------------------------------------------------------------------------------------------- */\n\nfunction Dossier({\n  card,\n  item,\n  items,\n  t,\n  reduce,\n  width,\n  useShader,\n  domMode,\n  canvasRef,\n  mediaBoxRef,\n  openLabel,\n  accent,\n  renderCardBody,\n  renderCardFooter,\n}: {\n  card: CardState;\n  item?: ProjectIndexItem;\n  items: ProjectIndexItem[];\n  t: Tokens;\n  reduce: boolean;\n  width: number;\n  useShader: boolean;\n  domMode: \"crossfade\" | \"none\";\n  canvasRef: React.RefObject<HTMLCanvasElement | null>;\n  mediaBoxRef: React.RefObject<HTMLDivElement | null>;\n  openLabel: string;\n  accent: string;\n  renderCardBody?: (item: ProjectIndexItem) => ReactNode;\n  renderCardFooter?: (item: ProjectIndexItem) => ReactNode;\n}) {\n  const open = card.open;\n  const intro = card.changes === 0;\n  const dir = card.dir;\n  const R = 14;\n\n  // Rise: the card slides up out of a slot whose lower edge is the card's docked bottom edge,\n  // so its top arrives first and the fields can follow top to bottom. It sinks back the same way.\n  const shell = reduce\n    ? {\n        open: {\n          opacity: 1,\n          y: \"0%\",\n          transition: { duration: 0.15, y: { duration: 0 } },\n        },\n        closed: {\n          opacity: 0,\n          y: \"0%\",\n          transition: { duration: 0.15, y: { duration: 0 } },\n        },\n      }\n    : {\n        open: {\n          opacity: 1,\n          y: \"0%\",\n          transition: { duration: 0.56, ease: ease.out },\n        },\n        closed: {\n          opacity: 1,\n          y: \"101%\",\n          transition: { duration: 0.3, ease: ease.inOut },\n        },\n      };\n  const shadow = {\n    open: {\n      opacity: 1,\n      transition: {\n        duration: reduce ? 0.15 : 0.5,\n        ease: ease.out,\n        delay: reduce ? 0 : 0.12,\n      },\n    },\n    closed: {\n      opacity: 0,\n      transition: { duration: reduce ? 0.15 : 0.2, ease: ease.inOut },\n    },\n  };\n  const zoom = {\n    open: {\n      scale: 1,\n      transition: { duration: reduce ? 0 : 0.7, ease: ease.out },\n    },\n    closed: {\n      scale: reduce ? 1 : 1.12,\n      transition: { duration: 0, delay: 0.32 },\n    },\n  };\n  const ink = inkFor(accent, t);\n  const index = items.findIndex((x) => x.id === item?.id);\n\n  const field = (k: number) => (intro ? 160 + k * 40 : k * 30);\n\n  return (\n    <motion.div\n      className=\"relative\"\n      style={{ width }}\n      initial=\"closed\"\n      animate={open ? \"open\" : \"closed\"}\n    >\n      {/* Shadow lives outside the clip so the rise does not crop it. */}\n      <motion.div\n        variants={shadow}\n        className=\"absolute inset-0\"\n        style={{ borderRadius: R, boxShadow: t.cardShadow }}\n      />\n      {/* The slot. Its bottom edge is where the card docks; the card rises out of it. */}\n      <div className=\"relative overflow-hidden\" style={{ borderRadius: R }}>\n        <motion.div\n          variants={shell}\n          className=\"relative overflow-hidden\"\n          style={{\n            borderRadius: R,\n            background: t.card,\n            backdropFilter: \"blur(14px) saturate(1.2)\",\n            WebkitBackdropFilter: \"blur(14px) saturate(1.2)\",\n            boxShadow: `${t.inner}, inset 0 0 0 1px ${t.cardBorder}`,\n            willChange: \"transform\",\n          }}\n        >\n          <div className=\"p-[6px]\">\n            <div\n              ref={mediaBoxRef}\n              className=\"relative w-full overflow-hidden\"\n              style={{\n                aspectRatio: \"16 / 10\",\n                borderRadius: R - 6,\n                background: t.mediaBg,\n              }}\n            >\n              <motion.div variants={zoom} className=\"absolute inset-0\">\n                {useShader ? (\n                  <canvas\n                    ref={canvasRef}\n                    className=\"absolute inset-0 size-full\"\n                  />\n                ) : (\n                  <DomMedia\n                    items={items}\n                    index={card.index}\n                    reduce={reduce}\n                    mode={domMode}\n                    open={open}\n                  />\n                )}\n              </motion.div>\n              {/* Hairline inside the media edge, so light stills do not bleed into a light card. */}\n              <div\n                className=\"pointer-events-none absolute inset-0\"\n                style={{\n                  borderRadius: R - 6,\n                  boxShadow: `inset 0 0 0 1px ${t.dark ? \"rgba(255,255,255,0.06)\" : \"rgba(23,23,23,0.06)\"}`,\n                }}\n              />\n            </div>\n          </div>\n\n          {item && (\n            <div\n              key={card.openId}\n              className=\"px-4 pb-4 pt-3\"\n              style={{ color: t.text }}\n            >\n              {renderCardBody ? (\n                renderCardBody(item)\n              ) : (\n                <>\n                  <div\n                    className=\"flex items-center justify-between font-mono text-[11px] uppercase tracking-[0.12em]\"\n                    style={{ color: t.meta }}\n                  >\n                    <Swap\n                      value={`${item.client ?? item.category?.label ?? \"\"}·${item.year}`}\n                      dir={dir}\n                      delay={field(0)}\n                      intro={intro}\n                      reduce={reduce}\n                      className=\"min-w-0\"\n                    >\n                      <span className=\"flex min-w-0 items-center gap-2\">\n                        <span\n                          aria-hidden\n                          className=\"size-1.5 shrink-0 rounded-full\"\n                          style={{ background: item.category?.color ?? accent }}\n                        />\n                        <span className=\"truncate\">\n                          {item.client ?? item.category?.label}\n                        </span>\n                        <span aria-hidden style={{ color: t.faint }}>\n                          /\n                        </span>\n                        <span className=\"tabular-nums\">{item.year}</span>\n                      </span>\n                    </Swap>\n                    <span className=\"tabular-nums\" style={{ color: t.faint }}>\n                      <Roll value={pad(index + 1)} dir={dir} reduce={reduce} />\n                      <span className=\"px-[3px]\">/</span>\n                      {pad(items.length)}\n                    </span>\n                  </div>\n\n                  <Swap\n                    value={`t:${item.title}`}\n                    dir={dir}\n                    delay={field(1)}\n                    intro={intro}\n                    reduce={reduce}\n                    className=\"mt-3\"\n                  >\n                    <span className=\"block truncate text-[19px] font-medium leading-[1.15] tracking-[-0.015em]\">\n                      {item.title}\n                    </span>\n                  </Swap>\n                  <Swap\n                    value={`r:${item.role}`}\n                    dir={dir}\n                    delay={field(2)}\n                    intro={intro}\n                    reduce={reduce}\n                    className=\"mt-1\"\n                  >\n                    <span\n                      className=\"block truncate text-[14px] leading-[1.3]\"\n                      style={{ color: t.meta }}\n                    >\n                      {item.role}\n                    </span>\n                  </Swap>\n\n                  <Swap\n                    value={`s:${item.services.join(\"|\")}`}\n                    dir={dir}\n                    delay={field(3)}\n                    intro={intro}\n                    reduce={reduce}\n                    className=\"mt-3\"\n                    style={{ minHeight: 36 }}\n                  >\n                    <span\n                      className=\"line-clamp-2 text-[12.5px] leading-[18px]\"\n                      style={{ color: t.faint }}\n                    >\n                      {item.services.map((s, k) => (\n                        <span key={s}>\n                          {k > 0 && (\n                            <span aria-hidden className=\"opacity-60\">\n                              {\" \\u2009/\\u2009 \"}\n                            </span>\n                          )}\n                          <span\n                            className=\"whitespace-nowrap\"\n                            style={{ color: t.meta }}\n                          >\n                            {s}\n                          </span>\n                        </span>\n                      ))}\n                    </span>\n                  </Swap>\n\n                  <div\n                    className=\"mt-4 flex items-end justify-between gap-4 border-t pt-3\"\n                    style={{ borderColor: t.hair, minHeight: 52 }}\n                  >\n                    {renderCardFooter ? (\n                      renderCardFooter(item)\n                    ) : (\n                      <>\n                        <Swap\n                          value={`o:${item.outcome?.value ?? \"\"}:${item.outcome?.label ?? \"\"}`}\n                          dir={dir}\n                          delay={field(4)}\n                          intro={intro}\n                          reduce={reduce}\n                          className=\"min-w-0\"\n                        >\n                          {item.outcome ? (\n                            <span className=\"flex min-w-0 items-baseline gap-2\">\n                              <span\n                                className=\"text-[28px] font-medium leading-none tracking-[-0.03em] tabular-nums\"\n                                style={{ color: t.text }}\n                              >\n                                {item.outcome.value}\n                              </span>\n                              <span\n                                className=\"line-clamp-2 max-w-[150px] text-[12px] leading-[1.25]\"\n                                style={{ color: t.meta }}\n                              >\n                                {item.outcome.label}\n                              </span>\n                            </span>\n                          ) : (\n                            <span className=\"block h-[28px]\" />\n                          )}\n                        </Swap>\n                        <Swap\n                          value=\"cta\"\n                          dir={dir}\n                          delay={field(5)}\n                          intro={intro}\n                          reduce={reduce}\n                          className=\"shrink-0\"\n                        >\n                          <span\n                            className=\"flex shrink-0 items-center gap-2 pb-[2px] text-[12px]\"\n                            style={{ color: ink }}\n                          >\n                            {openLabel}\n                            <kbd\n                              className=\"inline-grid h-[18px] min-w-[18px] place-items-center rounded-[5px] px-1 font-mono text-[10px] leading-none\"\n                              style={{\n                                color: t.meta,\n                                boxShadow: `inset 0 0 0 1px ${t.hair}`,\n                              }}\n                            >\n                              ↵\n                            </kbd>\n                          </span>\n                        </Swap>\n                      </>\n                    )}\n                  </div>\n                </>\n              )}\n            </div>\n          )}\n        </motion.div>\n      </div>\n    </motion.div>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Expanding layout (touch and narrow screens)\n * ---------------------------------------------------------------------------------------------- */\n\nfunction ExpandMedia({\n  media,\n  open,\n  reduce,\n  t,\n}: {\n  media: ProjectIndexMedia;\n  open: boolean;\n  reduce: boolean;\n  t: Tokens;\n}) {\n  const ref = useRef<HTMLVideoElement>(null);\n  useEffect(() => {\n    const v = ref.current;\n    if (!v) return;\n    if (!open || reduce) {\n      v.pause();\n      return;\n    }\n    // Autoplay once most of the frame is on screen; pause when it scrolls away.\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (e.intersectionRatio >= 0.6) v.play().catch(() => {});\n        else v.pause();\n      },\n      { threshold: [0, 0.6, 1] },\n    );\n    io.observe(v);\n    return () => io.disconnect();\n  }, [open, reduce]);\n\n  const pos = `${(media.focal?.[0] ?? 0.5) * 100}% ${(media.focal?.[1] ?? 0.5) * 100}%`;\n  return (\n    <div\n      className=\"relative w-full overflow-hidden rounded-[10px]\"\n      style={{ aspectRatio: \"16 / 10\", background: t.mediaBg }}\n    >\n      {media.type === \"video\" ? (\n        <video\n          ref={ref}\n          src={open ? media.src : undefined}\n          poster={media.poster}\n          muted\n          loop\n          playsInline\n          preload=\"none\"\n          controls={reduce}\n          aria-label={media.alt}\n          className=\"size-full object-cover\"\n          style={{ objectPosition: pos }}\n        />\n      ) : (\n        // eslint-disable-next-line @next/next/no-img-element\n        <img\n          src={media.src}\n          alt={media.alt}\n          loading=\"lazy\"\n          decoding=\"async\"\n          className=\"size-full object-cover\"\n          style={{ objectPosition: pos }}\n        />\n      )}\n    </div>\n  );\n}\n\nfunction ExpandIndex(\n  props: ProjectIndexProps & { t: Tokens; reduce: boolean },\n) {\n  const {\n    items,\n    t,\n    reduce,\n    accent,\n    showIndexNumbers = true,\n    openLabel = \"Open project\",\n    target,\n    onActiveChange,\n    renderCardBody,\n  } = props;\n  const uid = useId();\n  const [openIndex, setOpenIndex] = useState(-1);\n  const btnRefs = useRef<(HTMLButtonElement | null)[]>([]);\n\n  const toggle = (i: number) => {\n    const next = openIndex === i ? -1 : i;\n    setOpenIndex(next);\n    onActiveChange?.(next >= 0 ? items[next] : null);\n  };\n\n  const onKeyDown = (e: ReactKeyboardEvent<HTMLUListElement>) => {\n    const current = btnRefs.current.findIndex(\n      (el) => el === document.activeElement,\n    );\n    if (current < 0) return;\n    const n = items.length;\n    const go = (i: number) => btnRefs.current[(i + n) % n]?.focus();\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      go(current + 1);\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      go(current - 1);\n    } else if (e.key === \"Home\") {\n      e.preventDefault();\n      go(0);\n    } else if (e.key === \"End\") {\n      e.preventDefault();\n      go(n - 1);\n    } else if (e.key === \"Escape\" && openIndex >= 0) {\n      e.preventDefault();\n      setOpenIndex(-1);\n      onActiveChange?.(null);\n    }\n  };\n\n  return (\n    <GlowRules\n      selector=\"[data-pi-row]\"\n      tone={t.dark ? \"dark\" : \"light\"}\n      ruleColor={t.hair}\n      color={t.glow}\n      drawIn\n    >\n      <ul role=\"list\" className=\"m-0 list-none p-0\" onKeyDown={onKeyDown}>\n        {items.map((item, i) => {\n          const open = i === openIndex;\n          const panelId = `${uid}-p${i}`;\n          const ink = inkFor(item.accent ?? accent ?? t.accent, t);\n          return (\n            <motion.li\n              key={item.id}\n              data-pi-row=\"\"\n              initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16 }}\n              whileInView={{ opacity: 1, y: 0 }}\n              viewport={{ once: true }}\n              transition={{\n                duration: reduce ? 0.2 : 0.5,\n                delay: reduce ? 0 : i * 0.04,\n                ease: ease.out,\n              }}\n            >\n              <button\n                ref={(el) => {\n                  btnRefs.current[i] = el;\n                }}\n                type=\"button\"\n                aria-expanded={open}\n                aria-controls={panelId}\n                onClick={() => toggle(i)}\n                className=\"grid w-full items-center gap-0 px-1 text-left outline-none focus-visible:rounded-[4px] focus-visible:shadow-[inset_0_0_0_1px_var(--pi-ring)] active:opacity-80\"\n                style={\n                  {\n                    minHeight: 64,\n                    gridTemplateColumns: showIndexNumbers\n                      ? \"36px minmax(0,1fr) auto\"\n                      : \"minmax(0,1fr) auto\",\n                    color: t.text,\n                    \"--pi-ring\": `color-mix(in srgb, ${item.accent ?? accent ?? t.accent} 45%, transparent)`,\n                  } as CSSProperties\n                }\n              >\n                {showIndexNumbers && (\n                  <span\n                    className=\"font-mono text-[11px] tabular-nums\"\n                    style={{\n                      color: open ? ink : t.faint,\n                      transition: \"color 200ms ease\",\n                    }}\n                  >\n                    {pad(i + 1)}\n                  </span>\n                )}\n                <span className=\"min-w-0\">\n                  <span className=\"block truncate text-[19px] font-medium leading-tight tracking-[-0.015em]\">\n                    {item.title}\n                  </span>\n                </span>\n                <span\n                  className=\"flex items-center gap-3 pl-3 font-mono text-[11px] tabular-nums\"\n                  style={{ color: t.meta }}\n                >\n                  {item.year}\n                  <span\n                    aria-hidden\n                    className=\"relative block size-3\"\n                    style={{\n                      transform: `rotate(${open ? 45 : 0}deg)`,\n                      transition: reduce\n                        ? \"none\"\n                        : `transform 320ms ${EASE_OUT}`,\n                    }}\n                  >\n                    <span\n                      className=\"absolute left-0 top-1/2 h-px w-3 -translate-y-1/2\"\n                      style={{ background: \"currentColor\" }}\n                    />\n                    <span\n                      className=\"absolute left-1/2 top-0 h-3 w-px -translate-x-1/2\"\n                      style={{ background: \"currentColor\" }}\n                    />\n                  </span>\n                </span>\n              </button>\n              <div\n                id={panelId}\n                role=\"region\"\n                aria-label={item.title}\n                className=\"grid\"\n                style={{\n                  gridTemplateRows: open ? \"1fr\" : \"0fr\",\n                  transition: reduce\n                    ? \"none\"\n                    : `grid-template-rows 320ms ${EASE_OUT}`,\n                }}\n                inert={!open}\n              >\n                <div className=\"min-h-0 overflow-hidden\">\n                  <div\n                    className=\"pb-5 pt-1\"\n                    style={{\n                      opacity: open ? 1 : 0,\n                      transform: open || reduce ? \"none\" : \"translateY(-6px)\",\n                      transition: reduce\n                        ? \"opacity 150ms ease\"\n                        : `opacity 260ms ease ${open ? 80 : 0}ms, transform 320ms ${EASE_OUT}`,\n                    }}\n                  >\n                    <ExpandMedia\n                      media={item.media}\n                      open={open}\n                      reduce={reduce}\n                      t={t}\n                    />\n                    {renderCardBody ? (\n                      <div className=\"mt-4\">{renderCardBody(item)}</div>\n                    ) : (\n                      <dl className=\"mt-4 grid grid-cols-[88px_minmax(0,1fr)] gap-x-3 gap-y-2 text-[13px] leading-snug\">\n                        <dt\n                          className=\"font-mono text-[10.5px] uppercase tracking-[0.12em]\"\n                          style={{ color: t.faint, paddingTop: 2 }}\n                        >\n                          Role\n                        </dt>\n                        <dd className=\"m-0\" style={{ color: t.text }}>\n                          {item.role}\n                        </dd>\n                        <dt\n                          className=\"font-mono text-[10.5px] uppercase tracking-[0.12em]\"\n                          style={{ color: t.faint, paddingTop: 2 }}\n                        >\n                          Work\n                        </dt>\n                        <dd className=\"m-0\" style={{ color: t.meta }}>\n                          {item.services.join(\" / \")}\n                        </dd>\n                        {item.category && (\n                          <>\n                            <dt\n                              className=\"font-mono text-[10.5px] uppercase tracking-[0.12em]\"\n                              style={{ color: t.faint, paddingTop: 2 }}\n                            >\n                              Kind\n                            </dt>\n                            <dd className=\"m-0\" style={{ color: t.meta }}>\n                              <CategoryMark category={item.category} t={t} />\n                            </dd>\n                          </>\n                        )}\n                        {item.outcome && (\n                          <>\n                            <dt\n                              className=\"font-mono text-[10.5px] uppercase tracking-[0.12em]\"\n                              style={{ color: t.faint, paddingTop: 6 }}\n                            >\n                              Outcome\n                            </dt>\n                            <dd className=\"m-0 flex items-baseline gap-2\">\n                              <span\n                                className=\"text-[24px] font-medium leading-none tracking-[-0.03em] tabular-nums\"\n                                style={{ color: t.text }}\n                              >\n                                {item.outcome.value}\n                              </span>\n                              <span style={{ color: t.meta }}>\n                                {item.outcome.label}\n                              </span>\n                            </dd>\n                          </>\n                        )}\n                      </dl>\n                    )}\n                    {!item.disabled && (\n                      <a\n                        href={item.href}\n                        target={target}\n                        rel={target === \"_blank\" ? \"noreferrer\" : undefined}\n                        tabIndex={open ? 0 : -1}\n                        className=\"mt-5 inline-flex h-10 items-center gap-2 rounded-full px-4 text-[13px] font-medium no-underline outline-none transition-transform duration-150 active:scale-[0.97] focus-visible:shadow-[inset_0_0_0_1px_currentColor]\"\n                        style={{\n                          color: ink,\n                          background: `color-mix(in srgb, ${item.accent ?? accent ?? t.accent} ${t.dark ? 14 : 12}%, transparent)`,\n                        }}\n                      >\n                        {openLabel}\n                        <span aria-hidden>→</span>\n                      </a>\n                    )}\n                  </div>\n                </div>\n              </div>\n            </motion.li>\n          );\n        })}\n      </ul>\n    </GlowRules>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Root\n * ---------------------------------------------------------------------------------------------- */\n\n/**\n * A ledger of work. Titles sit on the left; on hover a dossier card rises from the bottom right\n * and stays put while you move between rows, dissolving its media and swapping only the fields\n * that change. Hairline rules catch a soft light under the pointer. Touch screens get an\n * expanding list instead.\n */\nexport function ProjectIndex(props: ProjectIndexProps) {\n  const {\n    items,\n    heading,\n    tone,\n    layout = \"auto\",\n    showCount = true,\n    className,\n  } = props;\n  const resolved = useBjorkTone(tone);\n  const t = useMemo(() => tokens(resolved), [resolved]);\n  const reduce = useMedia(REDUCED);\n  const narrow = useMedia(\n    \"(hover: none), (pointer: coarse), (max-width: 899px)\",\n  );\n  const expand = layout === \"expand\" || (layout === \"auto\" && narrow);\n\n  return (\n    <section\n      className={cn(\"relative w-full\", className)}\n      style={{ color: t.text }}\n    >\n      {(heading || showCount) && (\n        <div className=\"flex items-baseline justify-between gap-4 px-1 pb-5 md:px-4\">\n          <div className=\"min-w-0 text-[15px] font-medium tracking-[-0.01em]\">\n            {heading}\n          </div>\n          {showCount && (\n            <span\n              className=\"font-mono text-[11px] tabular-nums tracking-[0.08em]\"\n              style={{ color: t.faint }}\n            >\n              ({pad(items.length)})\n            </span>\n          )}\n        </div>\n      )}\n      {expand ? (\n        <ExpandIndex {...props} t={t} reduce={reduce} />\n      ) : (\n        <HoverIndex {...props} t={t} reduce={reduce} />\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/galleries/project-index.tsx"
    },
    {
      "path": "components/bjork-ui/misc/glow-rules.tsx",
      "content": "\"use client\";\n\nimport {\n  forwardRef,\n  useCallback,\n  useEffect,\n  useImperativeHandle,\n  useRef,\n  type CSSProperties,\n  type HTMLAttributes,\n  type ReactNode,\n} from \"react\";\nimport {\n  BJORK_PALETTE,\n  type BjorkTone,\n} from \"@/components/bjork-ui/_core/palette\";\nimport { useBjorkTone } from \"@/components/bjork-ui/_core/tone\";\nimport { cn } from \"@/lib/utils\";\n\nexport type GlowRulesAxis = \"rows\" | \"cols\" | \"grid\";\n\nexport interface GlowRulesTether {\n  /** Centre of the second light, in px from the container's top-left. */\n  x: number;\n  y: number;\n  /** Half-width of the light in px. Default 360. */\n  width?: number;\n  /** Half-height of the light in px. Default 56. */\n  height?: number;\n  /** 0 to 1. Default 1. */\n  intensity?: number;\n}\n\nexport interface GlowRulesProps extends Omit<\n  HTMLAttributes<HTMLDivElement>,\n  \"color\"\n> {\n  children?: ReactNode;\n  /** Elements whose edges become rules. Matched inside the container. Default `\"li\"`. */\n  selector?: string;\n  /** `rows` draws horizontal rules, `cols` vertical rules, `grid` both. Default `\"rows\"`. */\n  axis?: GlowRulesAxis;\n  /** Light size: [half-width as a share of the container, half-height in px]. Default `[0.4, 100]`. */\n  radius?: [number, number];\n  /** Share of the remaining distance the light covers per 60 Hz frame. Default 0.12. */\n  lerp?: number;\n  /** Snaps the light to this grid (px) so style writes stay rare. Default 4. */\n  quantize?: number;\n  /** Light colour. Defaults to white on dark and warm ink on light. */\n  color?: string;\n  /** Peak opacity of the light, 0 to 1. Default 1 on dark, 0.85 on light. */\n  intensity?: number;\n  /** Colour of the resting rules. `false` hides them, so the light only shows where you already draw borders. */\n  ruleColor?: string | false;\n  /** Blend for the light. `auto` uses screen on dark and multiply on light. */\n  blend?: \"auto\" | CSSProperties[\"mixBlendMode\"];\n  /** Draw a rule above the first item and below the last. Default true. */\n  outerEdges?: boolean;\n  /** Keyboard focus inside a matched element moves the light there. Default true. */\n  followFocus?: boolean;\n  /** A second light pinned to a point, e.g. to lead the eye toward a card. */\n  tether?: GlowRulesTether | null;\n  /** Draws the rules in from the left the first time they are measured. Default false. */\n  drawIn?: boolean;\n  /** Turns the light off without unmounting. */\n  disabled?: boolean;\n  tone?: BjorkTone;\n}\n\nexport interface GlowRulesHandle {\n  /** Re-measures the rules. Call after a change the observers cannot see, such as a transform-free reflow. */\n  measure: () => void;\n  /** Moves the light to a point (container px) and shows it, as keyboard focus does. */\n  pointAt: (x: number, y: number) => void;\n  /** Hides the light. */\n  release: () => void;\n  element: HTMLDivElement | null;\n}\n\nconst FADE_MS = 350;\n\nfunction offsetWithin(el: HTMLElement, root: HTMLElement) {\n  // offsetTop/Left ignore transforms, so entrance animations on the items do not drag the rules around.\n  let x = 0;\n  let y = 0;\n  let node: HTMLElement | null = el;\n  while (node && node !== root) {\n    x += node.offsetLeft;\n    y += node.offsetTop;\n    const parent = node.offsetParent as HTMLElement | null;\n    if (!parent || !root.contains(parent)) {\n      if (parent !== root) {\n        // root is not an offsetParent of this chain: fall back to layout rects.\n        const a = el.getBoundingClientRect();\n        const b = root.getBoundingClientRect();\n        return {\n          x: a.left - b.left,\n          y: a.top - b.top,\n          w: el.offsetWidth,\n          h: el.offsetHeight,\n        };\n      }\n    }\n    node = parent;\n  }\n  return { x, y, w: el.offsetWidth, h: el.offsetHeight };\n}\n\nfunction prefersReducedMotion() {\n  return (\n    typeof window !== \"undefined\" &&\n    window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n  );\n}\n\n/**\n * Hairline rules that catch a soft light under the pointer. One overlay draws every rule:\n * the rules are 1 px mask layers measured from the matched children, the light is a single\n * radial gradient behind that mask. The pointer is eased and quantised; the loop sleeps when settled.\n */\nexport const GlowRules = forwardRef<GlowRulesHandle, GlowRulesProps>(\n  function GlowRules(\n    {\n      children,\n      selector = \"li\",\n      axis = \"rows\",\n      radius = [0.4, 100],\n      lerp = 0.12,\n      quantize = 4,\n      color,\n      intensity,\n      ruleColor,\n      blend = \"auto\",\n      outerEdges = true,\n      followFocus = true,\n      tether = null,\n      drawIn = false,\n      disabled = false,\n      tone,\n      className,\n      style,\n      onPointerMove,\n      onPointerEnter,\n      onPointerLeave,\n      onFocus,\n      onBlur,\n      ...rest\n    },\n    ref,\n  ) {\n    const resolved = useBjorkTone(tone);\n    const palette = BJORK_PALETTE[resolved];\n    const isDark = resolved === \"dark\";\n    const lightColor = color ?? (isDark ? \"#ffffff\" : \"#6b4a2b\");\n    const peak = intensity ?? (isDark ? 1 : 0.85);\n    const rules = ruleColor === undefined ? palette.hair : ruleColor;\n    const mixBlend =\n      blend === \"auto\" ? (isDark ? \"screen\" : \"multiply\") : blend;\n\n    const rootRef = useRef<HTMLDivElement>(null);\n    const layersRef = useRef<HTMLDivElement>(null);\n    const glowRef = useRef<HTMLDivElement>(null);\n    const tetherRef = useRef<HTMLDivElement>(null);\n    const drawnRef = useRef(false);\n\n    // Pointer state lives in refs; React never re-renders for it.\n    const state = useRef({\n      tx: -9999,\n      ty: -9999,\n      x: -9999,\n      y: -9999,\n      lastX: NaN,\n      lastY: NaN,\n      raf: 0,\n      last: 0,\n      pointerInside: false,\n      focusInside: false,\n      snapNext: true,\n      // Tether light: eased toward its target in the same loop.\n      hx: NaN,\n      hy: NaN,\n      htx: NaN,\n      hty: NaN,\n      hLastX: NaN,\n      hLastY: NaN,\n    });\n    const optsRef = useRef({ lerp, quantize });\n    useEffect(() => {\n      optsRef.current = { lerp, quantize };\n    }, [lerp, quantize]);\n\n    const write = useCallback((x: number, y: number) => {\n      const el = glowRef.current;\n      if (!el) return;\n      el.style.setProperty(\"--gr-x\", `${x}px`);\n      el.style.setProperty(\"--gr-y\", `${y}px`);\n    }, []);\n\n    const tick = useCallback(\n      (now: number) => {\n        const s = state.current;\n        s.raf = 0;\n        const dt = s.last ? Math.min(64, now - s.last) : 16.7;\n        s.last = now;\n        const reduce = prefersReducedMotion();\n        const { lerp: l, quantize: q } = optsRef.current;\n        const k =\n          s.snapNext || reduce\n            ? 1\n            : 1 - Math.pow(1 - Math.min(1, Math.max(0.001, l)), dt / 16.667);\n        s.snapNext = false;\n        s.x += (s.tx - s.x) * k;\n        s.y += (s.ty - s.y) * k;\n        const step = Math.max(1, q);\n        const qx = Math.round(s.x / step) * step;\n        const qy = Math.round(s.y / step) * step;\n        if (qx !== s.lastX || qy !== s.lastY) {\n          write(qx, qy);\n          s.lastX = qx;\n          s.lastY = qy;\n        }\n        let tetherMoving = false;\n        if (!Number.isNaN(s.htx)) {\n          if (Number.isNaN(s.hx) || reduce) {\n            s.hx = s.htx;\n            s.hy = s.hty;\n          } else {\n            // A touch slower than the pointer light, so the tether trails it.\n            const kt = 1 - Math.pow(1 - 0.16, dt / 16.667);\n            s.hx += (s.htx - s.hx) * kt;\n            s.hy += (s.hty - s.hy) * kt;\n          }\n          const hx = Math.round(s.hx);\n          const hy = Math.round(s.hy);\n          if (hx !== s.hLastX || hy !== s.hLastY) {\n            tetherRef.current?.style.setProperty(\"--gt-x\", `${hx}px`);\n            tetherRef.current?.style.setProperty(\"--gt-y\", `${hy}px`);\n            s.hLastX = hx;\n            s.hLastY = hy;\n          }\n          tetherMoving =\n            Math.abs(s.htx - s.hx) > 0.5 || Math.abs(s.hty - s.hy) > 0.5;\n        }\n        if (\n          tetherMoving ||\n          Math.abs(s.tx - s.x) > 0.5 ||\n          Math.abs(s.ty - s.y) > 0.5\n        ) {\n          s.raf = requestAnimationFrame(tick);\n        } else {\n          s.last = 0;\n        }\n      },\n      [write],\n    );\n\n    const kick = useCallback(() => {\n      const s = state.current;\n      if (!s.raf) s.raf = requestAnimationFrame(tick);\n    }, [tick]);\n\n    const setOn = useCallback(\n      (on: boolean) => {\n        const el = glowRef.current;\n        if (!el) return;\n        el.style.opacity = on && !disabled ? String(peak) : \"0\";\n      },\n      [disabled, peak],\n    );\n\n    const measure = useCallback(() => {\n      const root = rootRef.current;\n      const layers = layersRef.current;\n      if (!root || !layers) return;\n      let items: HTMLElement[] = [];\n      try {\n        items = Array.from(root.querySelectorAll<HTMLElement>(selector)).filter(\n          (el) => el.offsetParent !== null || el.getClientRects().length > 0,\n        );\n      } catch {\n        items = [];\n      }\n      const images: string[] = [];\n      const sizes: string[] = [];\n      const positions: string[] = [];\n      const push = (x: number, y: number, w: number, h: number) => {\n        images.push(\"linear-gradient(#000,#000)\");\n        sizes.push(`${Math.round(w)}px ${Math.round(h)}px`);\n        positions.push(`${Math.round(x)}px ${Math.round(y)}px`);\n      };\n      const boxes = items.map((el) => offsetWithin(el, root));\n      const near = (a: number, b: number) => Math.abs(a - b) <= 1.5;\n      const overlapX = (a: (typeof boxes)[number], b: (typeof boxes)[number]) =>\n        a.x < b.x + b.w - 1 && b.x < a.x + a.w - 1;\n      const overlapY = (a: (typeof boxes)[number], b: (typeof boxes)[number]) =>\n        a.y < b.y + b.h - 1 && b.y < a.y + a.h - 1;\n      const seen = new Set<string>();\n      const line = (x: number, y: number, w: number, h: number) => {\n        const key = `${Math.round(x)}:${Math.round(y)}:${Math.round(w)}:${Math.round(h)}`;\n        if (seen.has(key)) return;\n        seen.add(key);\n        push(x, y, w, h);\n      };\n      if (axis === \"rows\" || axis === \"grid\") {\n        boxes.forEach((b) => {\n          // Top edge, unless it is the outer edge and outer edges are off.\n          const hasAbove = boxes.some(\n            (o) => o !== b && near(o.y + o.h, b.y) && overlapX(o, b),\n          );\n          if (outerEdges || hasAbove) line(b.x, b.y, b.w, 1);\n          // Bottom edge only where nothing sits directly below, so shared edges draw once.\n          const hasBelow = boxes.some(\n            (o) => o !== b && near(o.y, b.y + b.h) && overlapX(o, b),\n          );\n          if (outerEdges && !hasBelow) line(b.x, b.y + b.h - 1, b.w, 1);\n        });\n      }\n      if (axis === \"cols\" || axis === \"grid\") {\n        boxes.forEach((b) => {\n          const hasLeft = boxes.some(\n            (o) => o !== b && near(o.x + o.w, b.x) && overlapY(o, b),\n          );\n          if (outerEdges || hasLeft) line(b.x, b.y, 1, b.h);\n          const hasRight = boxes.some(\n            (o) => o !== b && near(o.x, b.x + b.w) && overlapY(o, b),\n          );\n          if (outerEdges && !hasRight) line(b.x + b.w - 1, b.y, 1, b.h);\n        });\n      }\n      const mask = images.length\n        ? images.join(\",\")\n        : \"linear-gradient(transparent,transparent)\";\n      layers.style.setProperty(\"--gr-mask\", mask);\n      layers.style.setProperty(\"--gr-mask-size\", sizes.join(\",\") || \"0 0\");\n      layers.style.setProperty(\"--gr-mask-pos\", positions.join(\",\") || \"0 0\");\n      if (drawIn && !drawnRef.current && images.length) {\n        drawnRef.current = true;\n        if (!prefersReducedMotion()) {\n          layers.animate(\n            [\n              { clipPath: \"inset(0 100% 0 0)\" },\n              { clipPath: \"inset(0 0% 0 0)\" },\n            ],\n            {\n              duration: 700,\n              easing: \"cubic-bezier(0.23,1,0.32,1)\",\n              fill: \"both\",\n            },\n          );\n        }\n      }\n    }, [selector, axis, outerEdges, drawIn]);\n\n    // Measure on size and structure changes. Observing every matched item catches rows that grow.\n    useEffect(() => {\n      const root = rootRef.current;\n      if (!root) return;\n      let frame = 0;\n      const schedule = () => {\n        if (frame) return;\n        frame = requestAnimationFrame(() => {\n          frame = 0;\n          measure();\n          observeItems();\n        });\n      };\n      const ro = new ResizeObserver(schedule);\n      const observed = new Set<Element>();\n      const observeItems = () => {\n        let items: Element[] = [];\n        try {\n          items = Array.from(root.querySelectorAll(selector));\n        } catch {\n          items = [];\n        }\n        for (const el of items) {\n          if (!observed.has(el)) {\n            observed.add(el);\n            ro.observe(el);\n          }\n        }\n      };\n      ro.observe(root);\n      observeItems();\n      const mo = new MutationObserver(schedule);\n      mo.observe(root, { childList: true, subtree: true });\n      schedule();\n      if (typeof document !== \"undefined\" && document.fonts?.ready) {\n        document.fonts.ready.then(schedule).catch(() => {});\n      }\n      return () => {\n        if (frame) cancelAnimationFrame(frame);\n        ro.disconnect();\n        mo.disconnect();\n      };\n    }, [measure, selector]);\n\n    useEffect(() => {\n      const s = state.current;\n      return () => {\n        if (s.raf) cancelAnimationFrame(s.raf);\n      };\n    }, []);\n\n    useEffect(() => {\n      setOn(state.current.pointerInside || state.current.focusInside);\n    }, [setOn]);\n\n    // Tether: keep the last position while it fades out, ease to new positions while it is on.\n    const tetherX = tether?.x;\n    const tetherY = tether?.y;\n    const tetherOn = tether != null && !disabled;\n    const tetherAlpha = (tether?.intensity ?? 1) * peak;\n    useEffect(() => {\n      const el = tetherRef.current;\n      if (!el) return;\n      const s = state.current;\n      if (tetherOn && tetherX != null && tetherY != null) {\n        const wasOff = el.style.opacity === \"0\" || el.style.opacity === \"\";\n        s.htx = tetherX;\n        s.hty = tetherY;\n        if (wasOff) {\n          // Appearing: start in place rather than sliding from the last row.\n          s.hx = NaN;\n          s.hy = NaN;\n        }\n        el.style.opacity = String(tetherAlpha);\n        kick();\n      } else {\n        el.style.opacity = \"0\";\n      }\n    }, [tetherOn, tetherX, tetherY, tetherAlpha, kick]);\n\n    const pointAt = useCallback(\n      (x: number, y: number) => {\n        const s = state.current;\n        const wasOff = !(s.pointerInside || s.focusInside);\n        s.tx = x;\n        s.ty = y;\n        if (wasOff && s.x < -9000) s.snapNext = true;\n        s.focusInside = true;\n        setOn(true);\n        kick();\n      },\n      [kick, setOn],\n    );\n\n    const release = useCallback(() => {\n      state.current.focusInside = false;\n      setOn(state.current.pointerInside);\n    }, [setOn]);\n\n    useImperativeHandle(\n      ref,\n      () => ({ measure, pointAt, release, element: rootRef.current }),\n      [measure, pointAt, release],\n    );\n\n    // Works inside scaled parents: layout px = screen px / scale.\n    const toLocal = (clientX: number, clientY: number) => {\n      const el = rootRef.current!;\n      const r = el.getBoundingClientRect();\n      const sx = el.offsetWidth ? r.width / el.offsetWidth : 1;\n      const sy = el.offsetHeight ? r.height / el.offsetHeight : 1;\n      return {\n        x: (clientX - r.left) / (sx || 1),\n        y: (clientY - r.top) / (sy || 1),\n      };\n    };\n\n    const [rx, ry] = radius;\n    const glowBg = `radial-gradient(ellipse ${Math.max(1, rx * 100)}% ${ry}px at var(--gr-x, -9999px) var(--gr-y, -9999px), ${lightColor} 0%, color-mix(in srgb, ${lightColor} 55%, transparent) 38%, transparent 100%)`;\n    const tetherBg = `radial-gradient(ellipse ${tether?.width ?? 360}px ${tether?.height ?? 56}px at var(--gt-x, -9999px) var(--gt-y, -9999px), ${lightColor} 0%, color-mix(in srgb, ${lightColor} 40%, transparent) 45%, transparent 100%)`;\n\n    const maskStyle: CSSProperties = {\n      WebkitMaskImage: \"var(--gr-mask)\",\n      maskImage: \"var(--gr-mask)\",\n      WebkitMaskSize: \"var(--gr-mask-size)\",\n      maskSize: \"var(--gr-mask-size)\",\n      WebkitMaskPosition: \"var(--gr-mask-pos)\",\n      maskPosition: \"var(--gr-mask-pos)\",\n      WebkitMaskRepeat: \"no-repeat\",\n      maskRepeat: \"no-repeat\",\n    };\n\n    return (\n      <div\n        ref={rootRef}\n        className={cn(\"relative\", className)}\n        style={style}\n        data-glow-rules=\"\"\n        onPointerMove={(e) => {\n          onPointerMove?.(e);\n          if (disabled || e.pointerType === \"touch\") return;\n          const s = state.current;\n          const p = toLocal(e.clientX, e.clientY);\n          s.tx = p.x;\n          s.ty = p.y;\n          if (!s.pointerInside) {\n            s.pointerInside = true;\n            // First contact: start the light under the pointer instead of sweeping in from the last spot.\n            if (!s.focusInside) s.snapNext = true;\n            setOn(true);\n          }\n          kick();\n        }}\n        onPointerEnter={(e) => {\n          onPointerEnter?.(e);\n          if (disabled || e.pointerType === \"touch\") return;\n          const s = state.current;\n          const p = toLocal(e.clientX, e.clientY);\n          s.tx = p.x;\n          s.ty = p.y;\n          s.pointerInside = true;\n          if (!s.focusInside) s.snapNext = true;\n          setOn(true);\n          kick();\n        }}\n        onPointerLeave={(e) => {\n          onPointerLeave?.(e);\n          state.current.pointerInside = false;\n          setOn(state.current.focusInside);\n        }}\n        onFocus={(e) => {\n          onFocus?.(e);\n          if (!followFocus || disabled) return;\n          const target = e.target as HTMLElement;\n          let item: HTMLElement | null = null;\n          try {\n            item = target.closest<HTMLElement>(selector);\n          } catch {\n            item = null;\n          }\n          if (!item || !rootRef.current?.contains(item)) return;\n          if (!target.matches(\":focus-visible\")) return;\n          const b = offsetWithin(item, rootRef.current);\n          // Light the left third of the item, where the eye starts reading.\n          pointAt(b.x + Math.min(b.w * 0.3, 320), b.y + b.h / 2);\n        }}\n        onBlur={(e) => {\n          onBlur?.(e);\n          const next = e.relatedTarget as Node | null;\n          if (next && rootRef.current?.contains(next)) return;\n          release();\n        }}\n        {...rest}\n      >\n        {children}\n        <div\n          ref={layersRef}\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0\"\n          style={{ zIndex: 1 }}\n        >\n          {rules !== false && (\n            <div\n              className=\"absolute inset-0\"\n              style={{ ...maskStyle, background: rules }}\n            />\n          )}\n          <div\n            ref={glowRef}\n            className=\"absolute inset-0\"\n            style={{\n              ...maskStyle,\n              background: glowBg,\n              mixBlendMode: mixBlend,\n              opacity: 0,\n              transition: `opacity ${FADE_MS}ms ease`,\n            }}\n          />\n          <div\n            ref={tetherRef}\n            className=\"absolute inset-0\"\n            style={{\n              ...maskStyle,\n              background: tetherBg,\n              mixBlendMode: mixBlend,\n              opacity: 0,\n              transition: `opacity ${FADE_MS}ms ease`,\n            }}\n          />\n        </div>\n      </div>\n    );\n  },\n);\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/misc/glow-rules.tsx"
    },
    {
      "path": "components/bjork-ui/_core/palette.ts",
      "content": "export type BjorkTone = \"dark\" | \"light\";\n\n// Canvas, WebGL and SVG attribute colours. DOM code uses the CSS tokens with these as fallbacks.\nexport const BJORK_PALETTE = {\n  dark: {\n    bg: \"#050505\", stage: \"#111111\", surface: \"#121212\", raised: \"#161616\", active: \"#202020\",\n    border: \"#232323\", borderStrong: \"#343434\",\n    text: \"#ededed\", textMedium: \"rgba(237,237,237,0.72)\", textMuted: \"rgba(237,237,237,0.6)\",\n    textSoft: \"rgba(237,237,237,0.5)\", textFaint: \"rgba(237,237,237,0.22)\", hair: \"rgba(237,237,237,0.12)\",\n    accent: \"#ec5c13\", accentInk: \"#ec5c13\", accentFill: \"#b84a12\", accentSoft: \"rgba(236,92,19,0.12)\", accentMuted: \"rgba(236,92,19,0.24)\",\n    accentFg: \"#fff2ea\", success: \"#4cc38a\", warning: \"#f2b544\", error: \"#ff5c4d\",\n  },\n  light: {\n    bg: \"#f7f5ef\", stage: \"#f7f5ef\", surface: \"#fffcf6\", raised: \"#f5efe3\", active: \"#efe7d8\",\n    border: \"#eee6db\", borderStrong: \"#e1d7c8\",\n    text: \"#171717\", textMedium: \"rgba(23,23,23,0.78)\", textMuted: \"rgba(23,23,23,0.68)\",\n    textSoft: \"rgba(23,23,23,0.62)\", textFaint: \"rgba(23,23,23,0.22)\", hair: \"rgba(23,23,23,0.10)\",\n    accent: \"#ec7d43\", accentInk: \"#b4531f\", accentFill: \"#ec7d43\", accentSoft: \"rgba(236,125,67,0.10)\", accentMuted: \"rgba(236,125,67,0.20)\",\n    accentFg: \"#3f2112\", success: \"#1f8a55\", warning: \"#a86b00\", error: \"#c8361f\",\n  },\n} as const;\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/palette.ts"
    },
    {
      "path": "components/bjork-ui/_core/tone.ts",
      "content": "\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport type { BjorkTone } from \"./palette\";\n\nconst subscribeNoop = () => () => {};\nconst getMounted = () => true;\nconst getServerMounted = () => false;\n\n/**\n * Resolves the tone for a component. An explicit `tone` always wins.\n * Otherwise it follows next-themes' resolved theme, but only after mount,\n * so the server render and first client render agree on dark.\n */\nexport function useBjorkTone(tone?: BjorkTone): BjorkTone {\n  const { resolvedTheme } = useTheme();\n  const mounted = useSyncExternalStore(subscribeNoop, getMounted, getServerMounted);\n  if (tone) return tone;\n  if (!mounted) return \"dark\";\n  return resolvedTheme === \"light\" ? \"light\" : \"dark\";\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/tone.ts"
    },
    {
      "path": "lib/utils.ts",
      "content": "import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n",
      "type": "registry:lib",
      "target": "@lib/utils.ts"
    },
    {
      "path": "components/bjork-ui/galleries/project-index-media.ts",
      "content": "// Media stage for Project Index: one WebGL canvas that dissolves between images and videos.\n// No dependencies. Falls back (create() returns null) when WebGL is unavailable.\n\nexport interface StageMedia {\n  type: \"image\" | \"video\";\n  src: string;\n  poster?: string;\n  focal?: [number, number];\n}\n\ninterface Tex {\n  tex: WebGLTexture;\n  w: number;\n  h: number;\n  focal: [number, number];\n  /** Canvas-space buffer: no cover fitting. */\n  screen?: boolean;\n}\n\ninterface VideoEntry {\n  el: HTMLVideoElement;\n  tex: WebGLTexture;\n  ready: boolean;\n  fresh: boolean;\n  used: number;\n}\n\nconst VERT = `\nattribute vec2 aPos;\nvarying vec2 vUv;\nvoid main() {\n  vUv = aPos * 0.5 + 0.5;\n  gl_Position = vec4(aPos, 0.0, 1.0);\n}`;\n\n// Grain dissolve. The front sweeps in the direction of travel, broken up by a low-frequency\n// fbm and a fine sand grain; pixels near the front are pushed along the sweep and lifted a touch.\nconst FRAG = `\nprecision highp float;\nvarying vec2 vUv;\nuniform sampler2D uA;\nuniform sampler2D uB;\nuniform vec4 uFitA; // xy scale, zw offset\nuniform vec4 uFitB;\nuniform float uP;\nuniform float uDir;\nuniform float uSeed;\nuniform float uTime;\nuniform float uZoom;\nuniform vec2 uRes;\nuniform float uGrain;\n\nfloat hash(vec2 p) {\n  p = fract(p * vec2(123.34, 456.21));\n  p += dot(p, p + 45.32);\n  return fract(p.x * p.y);\n}\nfloat noise(vec2 p) {\n  vec2 i = floor(p);\n  vec2 f = fract(p);\n  vec2 u = f * f * (3.0 - 2.0 * f);\n  return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),\n             mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);\n}\nfloat fbm(vec2 p) {\n  float v = 0.0;\n  float a = 0.5;\n  for (int i = 0; i < 4; i++) {\n    v += a * noise(p);\n    p *= 2.03;\n    a *= 0.5;\n  }\n  return v;\n}\nvec3 sampleFit(sampler2D t, vec4 fit, vec2 uv) {\n  vec2 c = (uv - 0.5) / uZoom + 0.5;\n  vec2 st = c * fit.xy + fit.zw;\n  return texture2D(t, clamp(st, 0.0, 1.0)).rgb;\n}\nvoid main() {\n  vec2 uv = vUv;\n  float p = uP;\n  // Low-frequency shape of the front plus fine grain in device pixels (about 2 px sand).\n  float n = fbm(uv * vec2(3.0, 5.0) + uSeed);\n  float g = hash(floor(uv * uRes / 2.0) + uSeed * 31.0);\n  float along = uDir > 0.0 ? uv.y : 1.0 - uv.y;    // 0 where the new media enters\n  float edge = along * 0.72 + n * 0.2 + g * 0.08;\n  float m = p * 1.24 - 0.12;\n  float t = smoothstep(edge - 0.06, edge + 0.06, m);\n  // Grains just ahead of the front fall in early, like sand ahead of a wave.\n  // ahead: 0 far in front of the front, 1 at the front itself.\n  float ahead = smoothstep(edge - 0.1, edge, m);\n  float scatter = step(g, ahead * ahead * 0.5);\n  t = max(t, scatter);\n  float front = smoothstep(0.22, 0.0, abs(m - edge));\n  vec2 push = vec2(0.0, -uDir) * 0.035 * front * (n - 0.35);\n  vec3 a = sampleFit(uA, uFitA, uv + push * t);\n  vec3 b = sampleFit(uB, uFitB, uv - push * (1.0 - t));\n  vec3 col = mix(a, b, t);\n  // A faint lift along the front, and film grain that only lives during the move.\n  col += front * 0.06 * (1.0 - abs(p * 2.0 - 1.0));\n  float live = sin(p * 3.14159);\n  col += (hash(uv * uRes + floor(uTime * 24.0)) - 0.5) * 0.07 * live * uGrain;\n  gl_FragColor = vec4(col, 1.0);\n}`;\n\nfunction compile(gl: WebGLRenderingContext, type: number, src: string) {\n  const sh = gl.createShader(type)!;\n  gl.shaderSource(sh, src);\n  gl.compileShader(sh);\n  if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {\n    const log = gl.getShaderInfoLog(sh);\n    gl.deleteShader(sh);\n    throw new Error(log ?? \"shader\");\n  }\n  return sh;\n}\n\nfunction program(gl: WebGLRenderingContext, frag: string) {\n  const p = gl.createProgram()!;\n  gl.attachShader(p, compile(gl, gl.VERTEX_SHADER, VERT));\n  gl.attachShader(p, compile(gl, gl.FRAGMENT_SHADER, frag));\n  gl.bindAttribLocation(p, 0, \"aPos\");\n  gl.linkProgram(p);\n  if (!gl.getProgramParameter(p, gl.LINK_STATUS))\n    throw new Error(gl.getProgramInfoLog(p) ?? \"link\");\n  return p;\n}\n\nconst easeInOut = (t: number) =>\n  t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;\n\nexport class MediaStage {\n  private gl: WebGLRenderingContext;\n  private prog: WebGLProgram;\n  private u: Record<string, WebGLUniformLocation | null> = {};\n  private images = new Map<string, Promise<Tex>>();\n  private videos = new Map<string, VideoEntry>();\n  private fbos: { fb: WebGLFramebuffer; tex: WebGLTexture }[] = [];\n  private fboIndex = 0;\n  private a: Tex | null = null;\n  private b: Tex | null = null;\n  private bVideo: VideoEntry | null = null;\n  private aVideo: VideoEntry | null = null;\n  private progress = 1;\n  private dir = 1;\n  private seed = 0;\n  private start = 0;\n  private token = 0;\n  private dirty = true;\n  zoom = 1;\n  duration = 420;\n  maxVideos = 3;\n\n  static create(canvas: HTMLCanvasElement): MediaStage | null {\n    try {\n      const gl = canvas.getContext(\"webgl\", {\n        alpha: false,\n        antialias: false,\n        premultipliedAlpha: false,\n        preserveDrawingBuffer: false,\n      });\n      if (!gl) return null;\n      return new MediaStage(canvas, gl);\n    } catch {\n      return null;\n    }\n  }\n\n  private constructor(\n    private canvas: HTMLCanvasElement,\n    gl: WebGLRenderingContext,\n  ) {\n    this.gl = gl;\n    this.prog = program(gl, FRAG);\n    for (const name of [\n      \"uA\",\n      \"uB\",\n      \"uFitA\",\n      \"uFitB\",\n      \"uP\",\n      \"uDir\",\n      \"uSeed\",\n      \"uTime\",\n      \"uZoom\",\n      \"uRes\",\n      \"uGrain\",\n    ]) {\n      this.u[name] = gl.getUniformLocation(this.prog, name);\n    }\n    const buf = gl.createBuffer();\n    gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n    gl.bufferData(\n      gl.ARRAY_BUFFER,\n      new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),\n      gl.STATIC_DRAW,\n    );\n    gl.enableVertexAttribArray(0);\n    gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n  }\n\n  resize(w: number, h: number) {\n    if (this.canvas.width === w && this.canvas.height === h) return;\n    this.canvas.width = w;\n    this.canvas.height = h;\n    // Old buffers are the wrong size now.\n    const gl = this.gl;\n    for (const f of this.fbos) {\n      gl.deleteFramebuffer(f.fb);\n      gl.deleteTexture(f.tex);\n    }\n    this.fbos = [];\n    if (this.a?.screen) this.a = this.b;\n    this.dirty = true;\n  }\n\n  private newTexture() {\n    const gl = this.gl;\n    const tex = gl.createTexture()!;\n    gl.bindTexture(gl.TEXTURE_2D, tex);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    gl.texImage2D(\n      gl.TEXTURE_2D,\n      0,\n      gl.RGBA,\n      1,\n      1,\n      0,\n      gl.RGBA,\n      gl.UNSIGNED_BYTE,\n      new Uint8Array([0, 0, 0, 255]),\n    );\n    return tex;\n  }\n\n  loadImage(src: string, focal: [number, number] = [0.5, 0.5]): Promise<Tex> {\n    const key = src;\n    const hit = this.images.get(key);\n    if (hit) return hit.then((t) => ({ ...t, focal }));\n    const p = new Promise<Tex>((resolve, reject) => {\n      const img = new Image();\n      img.crossOrigin = \"anonymous\";\n      img.decoding = \"async\";\n      img.onload = () => {\n        const gl = this.gl;\n        const tex = this.newTexture();\n        gl.bindTexture(gl.TEXTURE_2D, tex);\n        gl.texImage2D(\n          gl.TEXTURE_2D,\n          0,\n          gl.RGBA,\n          gl.RGBA,\n          gl.UNSIGNED_BYTE,\n          img,\n        );\n        resolve({ tex, w: img.naturalWidth, h: img.naturalHeight, focal });\n      };\n      img.onerror = () => reject(new Error(`image ${src}`));\n      img.src = src;\n    });\n    p.catch(() => this.images.delete(key));\n    this.images.set(key, p);\n    return p;\n  }\n\n  /** Warms the cache without showing anything. */\n  preload(media: StageMedia) {\n    const still = media.type === \"image\" ? media.src : media.poster;\n    if (still) this.loadImage(still).catch(() => {});\n  }\n\n  private videoFor(media: StageMedia): VideoEntry {\n    const v = this.videos.get(media.src);\n    if (v) {\n      v.used = performance.now();\n      return v;\n    }\n    const el = document.createElement(\"video\");\n    el.muted = true;\n    el.loop = true;\n    el.playsInline = true;\n    el.crossOrigin = \"anonymous\";\n    el.preload = \"auto\";\n    el.setAttribute(\"muted\", \"\");\n    el.setAttribute(\"playsinline\", \"\");\n    el.src = media.src;\n    const entry: VideoEntry = {\n      el,\n      tex: this.newTexture(),\n      ready: false,\n      fresh: false,\n      used: performance.now(),\n    };\n    const onFrame = () => {\n      entry.ready = true;\n      entry.fresh = true;\n      this.dirty = true;\n      const rvfc = (\n        el as HTMLVideoElement & {\n          requestVideoFrameCallback?: (cb: () => void) => number;\n        }\n      ).requestVideoFrameCallback;\n      if (rvfc) rvfc.call(el, onFrame);\n    };\n    const rvfc = (\n      el as HTMLVideoElement & {\n        requestVideoFrameCallback?: (cb: () => void) => number;\n      }\n    ).requestVideoFrameCallback;\n    if (rvfc) rvfc.call(el, onFrame);\n    else el.addEventListener(\"timeupdate\", onFrame);\n    this.videos.set(media.src, entry);\n    // Keep at most maxVideos alive, dropping the least recently used that is not on screen.\n    if (this.videos.size > this.maxVideos) {\n      const victims = [...this.videos.entries()]\n        .filter(\n          ([, e]) => e !== this.bVideo && e !== this.aVideo && e !== entry,\n        )\n        .sort((x, y) => x[1].used - y[1].used);\n      const [key, victim] = victims[0] ?? [];\n      if (key && victim) {\n        victim.el.pause();\n        victim.el.removeAttribute(\"src\");\n        victim.el.load();\n        this.gl.deleteTexture(victim.tex);\n        this.videos.delete(key);\n      }\n    }\n    return entry;\n  }\n\n  private fit(t: Tex): [number, number, number, number] {\n    if (t.screen) return [1, 1, 0, 0];\n    const cw = this.canvas.width;\n    const ch = this.canvas.height;\n    const ca = cw / Math.max(1, ch);\n    const ta = t.w / Math.max(1, t.h);\n    let sx = 1;\n    let sy = 1;\n    if (ta > ca) sx = ca / ta;\n    else sy = ta / ca;\n    const [fx, fy] = t.focal;\n    // Offset toward the focal point (focal y is top-down; texture space is bottom-up).\n    const ox = (1 - sx) * fx;\n    const oy = (1 - sy) * (1 - fy);\n    return [sx, sy, ox, oy];\n  }\n\n  /** Captures what is on screen into a buffer so a new transition can start from it. */\n  private snapshot(time: number): Tex | null {\n    const gl = this.gl;\n    const w = this.canvas.width;\n    const h = this.canvas.height;\n    if (!this.fbos.length) {\n      for (let i = 0; i < 2; i++) {\n        const tex = this.newTexture();\n        gl.bindTexture(gl.TEXTURE_2D, tex);\n        gl.texImage2D(\n          gl.TEXTURE_2D,\n          0,\n          gl.RGBA,\n          w,\n          h,\n          0,\n          gl.RGBA,\n          gl.UNSIGNED_BYTE,\n          null,\n        );\n        const fb = gl.createFramebuffer()!;\n        gl.bindFramebuffer(gl.FRAMEBUFFER, fb);\n        gl.framebufferTexture2D(\n          gl.FRAMEBUFFER,\n          gl.COLOR_ATTACHMENT0,\n          gl.TEXTURE_2D,\n          tex,\n          0,\n        );\n        this.fbos.push({ fb, tex });\n      }\n      gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n    }\n    // Never render into the buffer we are reading from.\n    let slot = this.fbos[this.fboIndex];\n    if (this.a?.tex === slot.tex) {\n      this.fboIndex = 1 - this.fboIndex;\n      slot = this.fbos[this.fboIndex];\n    }\n    gl.bindFramebuffer(gl.FRAMEBUFFER, slot.fb);\n    this.draw(time, true);\n    gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n    this.fboIndex = 1 - this.fboIndex;\n    return { tex: slot.tex, w, h, focal: [0.5, 0.5], screen: true };\n  }\n\n  /**\n   * Shows media. `dir` is +1 when moving down the list and -1 when moving up.\n   * `instant` swaps without a transition (first open, reduced motion).\n   */\n  async show(media: StageMedia, dir: number, instant: boolean) {\n    const token = ++this.token;\n    const focal = media.focal ?? [0.5, 0.5];\n    let next: Tex | null = null;\n    let video: VideoEntry | null = null;\n    if (media.type === \"video\") {\n      video = this.videoFor(media);\n      video.el.play().catch(() => {});\n      if (video.ready)\n        next = {\n          tex: video.tex,\n          w: video.el.videoWidth,\n          h: video.el.videoHeight,\n          focal,\n        };\n      else if (media.poster)\n        next = await this.loadImage(media.poster, focal).catch(() => null);\n      if (!next) {\n        // No poster and no frame yet: wait for the first frame.\n        await new Promise<void>((res) => {\n          const done = () => res();\n          video!.el.addEventListener(\"loadeddata\", done, { once: true });\n          setTimeout(done, 1500);\n        });\n        next = {\n          tex: video.tex,\n          w: video.el.videoWidth || 16,\n          h: video.el.videoHeight || 10,\n          focal,\n        };\n      }\n    } else {\n      next = await this.loadImage(media.src, focal).catch(() => null);\n    }\n    if (token !== this.token || !next) return;\n\n    // Pause the video we are leaving once it is no longer needed.\n    const leaving = this.bVideo;\n    const now = performance.now();\n    if (instant || !this.b) {\n      this.a = null;\n      this.b = next;\n      this.aVideo = null;\n      this.bVideo = video;\n      this.progress = 1;\n    } else {\n      const inFlight = this.progress < 1;\n      this.a = inFlight ? this.snapshot(now) : this.b;\n      this.aVideo = inFlight ? null : leaving;\n      this.b = next;\n      this.bVideo = video;\n      this.dir = dir >= 0 ? 1 : -1;\n      this.seed = Math.random() * 10;\n      this.progress = 0;\n      this.start = now;\n    }\n    if (leaving && leaving !== video && leaving !== this.aVideo)\n      leaving.el.pause();\n    this.dirty = true;\n  }\n\n  pauseVideos() {\n    for (const v of this.videos.values()) v.el.pause();\n  }\n\n  resumeVideo() {\n    this.bVideo?.el.play().catch(() => {});\n  }\n\n  get transitioning() {\n    return this.progress < 1;\n  }\n\n  /** True while there is a reason to keep drawing. */\n  get busy() {\n    return (\n      this.progress < 1 ||\n      this.dirty ||\n      (!!this.bVideo && !this.bVideo.el.paused)\n    );\n  }\n\n  private upload(v: VideoEntry | null) {\n    if (!v || !v.fresh || v.el.readyState < 2) return;\n    const gl = this.gl;\n    gl.bindTexture(gl.TEXTURE_2D, v.tex);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, v.el);\n    v.fresh = false;\n  }\n\n  /** Draws a frame. Returns true while it needs more frames. */\n  frame(time: number): boolean {\n    if (!this.b) return false;\n    if (this.progress < 1) {\n      this.progress = Math.min(1, (time - this.start) / this.duration);\n      if (this.progress >= 1) {\n        if (this.aVideo && this.aVideo !== this.bVideo) this.aVideo.el.pause();\n        this.a = null;\n        this.aVideo = null;\n      }\n      // Every step of a transition draws, including the one that lands on 1.\n      this.dirty = true;\n    }\n    // Swap the poster for live video once the first frame exists.\n    if (this.bVideo?.ready && this.b.tex !== this.bVideo.tex) {\n      this.b = {\n        tex: this.bVideo.tex,\n        w: this.bVideo.el.videoWidth,\n        h: this.bVideo.el.videoHeight,\n        focal: this.b.focal,\n      };\n    }\n    const videoFresh = !!(this.bVideo?.fresh || this.aVideo?.fresh);\n    if (!this.dirty && this.progress >= 1 && !videoFresh) return this.busy;\n    this.upload(this.bVideo);\n    this.upload(this.aVideo);\n    this.draw(time, false);\n    this.dirty = false;\n    return this.busy;\n  }\n\n  markDirty() {\n    this.dirty = true;\n  }\n\n  private draw(time: number, toBuffer: boolean) {\n    const gl = this.gl;\n    const b = this.b!;\n    const a = this.a ?? b;\n    const p = this.a ? easeInOut(this.progress) : 1;\n    gl.viewport(0, 0, this.canvas.width, this.canvas.height);\n    gl.useProgram(this.prog);\n    gl.activeTexture(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, a.tex);\n    gl.uniform1i(this.u.uA, 0);\n    gl.activeTexture(gl.TEXTURE1);\n    gl.bindTexture(gl.TEXTURE_2D, b.tex);\n    gl.uniform1i(this.u.uB, 1);\n    gl.uniform4fv(this.u.uFitA, this.fit(a));\n    gl.uniform4fv(this.u.uFitB, this.fit(b));\n    gl.uniform1f(this.u.uP, p);\n    gl.uniform1f(this.u.uDir, this.dir);\n    gl.uniform1f(this.u.uSeed, this.seed);\n    gl.uniform1f(this.u.uTime, time / 1000);\n    gl.uniform1f(this.u.uZoom, this.zoom);\n    gl.uniform2f(this.u.uRes, this.canvas.width, this.canvas.height);\n    gl.uniform1f(this.u.uGrain, toBuffer ? 0 : 1);\n    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n  }\n\n  dispose() {\n    this.token++;\n    const gl = this.gl;\n    for (const v of this.videos.values()) {\n      v.el.pause();\n      v.el.removeAttribute(\"src\");\n      v.el.load();\n      gl.deleteTexture(v.tex);\n    }\n    this.videos.clear();\n    for (const p of this.images.values())\n      p.then((t) => gl.deleteTexture(t.tex)).catch(() => {});\n    this.images.clear();\n    for (const f of this.fbos) {\n      gl.deleteFramebuffer(f.fb);\n      gl.deleteTexture(f.tex);\n    }\n    gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n  }\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/galleries/project-index-media.ts"
    },
    {
      "path": "components/bjork-ui/_core/loop.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, type RefObject } from \"react\";\n\nexport interface VisibleLoopOptions {\n  enabled?: boolean;\n  fpsCap?: number;\n  rootMargin?: string;\n}\n\n/**\n * Runs `frame(dt, t)` on requestAnimationFrame while the element is near the viewport,\n * the tab is visible and `enabled` is not false. Return `false` from `frame` to go idle\n * until `wake()` is called. Writes `data-loop` on the element: running, idle or paused.\n */\nexport function useVisibleLoop(\n  ref: RefObject<HTMLElement | null>,\n  frame: (dt: number, t: number) => boolean | void,\n  opts?: VisibleLoopOptions,\n): { wake: () => void } {\n  const enabled = opts?.enabled !== false;\n  const fpsCap = opts?.fpsCap ?? 0;\n  const rootMargin = opts?.rootMargin ?? \"96px\";\n\n  const frameRef = useRef(frame);\n  useEffect(() => {\n    frameRef.current = frame;\n  }, [frame]);\n\n  const wakeRef = useRef<() => void>(() => {});\n  const wake = useCallback(() => wakeRef.current(), []);\n\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof window === \"undefined\") return;\n\n    let wants = true; // false once the frame callback returns false\n    let inView = false;\n    let raf = 0;\n    let last = 0;\n    let t = 0;\n    const minFrame = fpsCap > 0 ? 1000 / fpsCap : 0;\n\n    const canRun = () => enabled && inView && document.visibilityState === \"visible\";\n    const stop = () => {\n      if (raf) cancelAnimationFrame(raf);\n      raf = 0;\n    };\n\n    const update = () => {\n      if (!enabled) {\n        stop();\n        el.dataset.loop = \"paused\";\n        return;\n      }\n      if (!wants) {\n        stop();\n        el.dataset.loop = \"idle\";\n        return;\n      }\n      if (!canRun()) {\n        stop();\n        el.dataset.loop = \"paused\";\n        return;\n      }\n      el.dataset.loop = \"running\";\n      if (!raf) {\n        last = performance.now();\n        raf = requestAnimationFrame(tick);\n      }\n    };\n\n    const tick = (now: number) => {\n      raf = 0;\n      if (!canRun() || !wants) {\n        update();\n        return;\n      }\n      const elapsed = now - last;\n      if (minFrame && elapsed < minFrame - 0.5) {\n        raf = requestAnimationFrame(tick);\n        return;\n      }\n      last = now;\n      const dt = Math.min(0.05, Math.max(0, elapsed / 1000));\n      t += dt;\n      const keep = frameRef.current(dt, t);\n      if (keep === false) {\n        wants = false;\n        update();\n        return;\n      }\n      raf = requestAnimationFrame(tick);\n    };\n\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        inView = entry.isIntersecting;\n        update();\n      },\n      { rootMargin },\n    );\n    observer.observe(el);\n\n    const onVisibility = () => update();\n    document.addEventListener(\"visibilitychange\", onVisibility);\n\n    wakeRef.current = () => {\n      wants = true;\n      update();\n    };\n\n    update();\n\n    return () => {\n      stop();\n      observer.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVisibility);\n      wakeRef.current = () => {};\n    };\n  }, [ref, enabled, fpsCap, rootMargin]);\n\n  return useMemo(() => ({ wake }), [wake]);\n}\n\n// matchMedia based check. False on the server.\nexport function isCoarsePointer(): boolean {\n  if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return false;\n  return window.matchMedia(\"(pointer: coarse)\").matches;\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/loop.ts"
    },
    {
      "path": "components/bjork-ui/_core/motion.ts",
      "content": "// Shared springs, easings and durations. Components import these instead of inventing values.\n\nexport const springs = {\n  press: { type: \"spring\", stiffness: 500, damping: 30, mass: 0.6 },\n  snappy: { type: \"spring\", stiffness: 400, damping: 25, mass: 1 },\n  standard: { type: \"spring\", stiffness: 300, damping: 30, mass: 0.8 },\n  soft: { type: \"spring\", stiffness: 200, damping: 25, mass: 1.2 },\n  settle: { type: \"spring\", stiffness: 380, damping: 30, mass: 0.8 },\n  blurIn: { type: \"spring\", stiffness: 400, damping: 28, mass: 0.6 },\n} as const;\n\nexport const ease = {\n  out: [0.23, 1, 0.32, 1],\n  inOut: [0.77, 0, 0.175, 1],\n  drawer: [0.32, 0.72, 0, 1],\n} as const;\n\nexport const easeCss = {\n  out: \"cubic-bezier(0.23,1,0.32,1)\",\n  inOut: \"cubic-bezier(0.77,0,0.175,1)\",\n  drawer: \"cubic-bezier(0.32,0.72,0,1)\",\n} as const;\n\nexport const durations = { press: 140, tooltip: 160, menu: 200, panel: 280 } as const; // ms\n\n// Cubic bezier easing for canvas and rAF code. Returns progress y for input x in [0, 1].\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {\n  const cx = 3 * x1;\n  const bx = 3 * (x2 - x1) - cx;\n  const ax = 1 - cx - bx;\n  const cy = 3 * y1;\n  const by = 3 * (y2 - y1) - cy;\n  const ay = 1 - cy - by;\n  const sampleX = (s: number) => ((ax * s + bx) * s + cx) * s;\n  const sampleY = (s: number) => ((ay * s + by) * s + cy) * s;\n  const sampleDX = (s: number) => (3 * ax * s + 2 * bx) * s + cx;\n\n  const solveX = (x: number) => {\n    let s = x;\n    for (let i = 0; i < 8; i++) {\n      const err = sampleX(s) - x;\n      if (Math.abs(err) < 1e-6) return s;\n      const d = sampleDX(s);\n      if (Math.abs(d) < 1e-6) break;\n      s -= err / d;\n    }\n    let lo = 0;\n    let hi = 1;\n    s = x;\n    while (lo < hi) {\n      const v = sampleX(s);\n      if (Math.abs(v - x) < 1e-6) return s;\n      if (x > v) lo = s;\n      else hi = s;\n      s = (lo + hi) / 2;\n      if (hi - lo < 1e-7) break;\n    }\n    return s;\n  };\n\n  return (t: number) => {\n    if (t <= 0) return 0;\n    if (t >= 1) return 1;\n    return sampleY(solveX(t));\n  };\n}\n",
      "type": "registry:component",
      "target": "@components/bjork-ui/_core/motion.ts"
    }
  ],
  "cssVars": {
    "light": {
      "bjork-bg": "#f7f3ea",
      "bjork-surface": "#fffcf6",
      "bjork-surface-muted": "rgba(250, 246, 237, 0.94)",
      "bjork-surface-hover": "#f5efe3",
      "bjork-surface-active": "#efe7d8",
      "bjork-panel": "#f8f2e7",
      "bjork-menu": "rgba(255, 252, 246, 0.98)",
      "bjork-field": "rgba(255, 252, 246, 0.96)",
      "bjork-field-muted": "rgba(248, 242, 231, 0.82)",
      "bjork-field-inset": "rgba(239, 231, 216, 0.72)",
      "bjork-error-bg": "#fff0e8",
      "bjork-text": "#171717",
      "bjork-text-strong": "rgba(23, 23, 23, 0.9)",
      "bjork-text-medium": "rgba(23, 23, 23, 0.78)",
      "bjork-text-muted": "rgba(23, 23, 23, 0.68)",
      "bjork-text-soft": "rgba(23, 23, 23, 0.62)",
      "bjork-text-faint": "rgba(23, 23, 23, 0.22)",
      "bjork-inverted-text": "#fff8f0",
      "bjork-border": "#eee6db",
      "bjork-border-muted": "#f5ede2",
      "bjork-border-strong": "#e1d7c8",
      "bjork-thumb": "#a49b8e",
      "bjork-track": "#ded6ca",
      "bjork-accent": "#ec7d43",
      "bjork-accent-hover": "#f0935f",
      "bjork-accent-soft": "rgba(236, 125, 67, 0.1)",
      "bjork-accent-muted": "rgba(236, 125, 67, 0.2)",
      "bjork-accent-badge": "rgba(236, 125, 67, 0.16)",
      "bjork-accent-badge-foreground": "#8d421d",
      "bjork-accent-foreground": "#3f2112",
      "bjork-accent-fill": "#ec7d43",
      "bjork-accent-fill-hover": "#f0935f",
      "bjork-shadow-surface": "inset 0 7px 14px rgba(88, 72, 49, 0.045), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.92), inset 1px 0 0 rgba(88, 72, 49, 0.026), inset -1px 0 0 rgba(255, 255, 255, 0.68), 0 14px 22px -9px rgba(66, 52, 33, 0.11)",
      "bjork-shadow-soft": "inset 0 1px 0 rgba(88, 72, 49, 0.045), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.86)",
      "bjork-shadow-panel": "inset 0 1px 0 rgba(88, 72, 49, 0.04), inset 1px 0 0 rgba(88, 72, 49, 0.024), inset -1px 0 0 rgba(255, 255, 255, 0.64), 0 18px 38px -30px rgba(66, 52, 33, 0.2)",
      "bjork-shadow-menu": "inset 0 1px 0 rgba(88, 72, 49, 0.04), inset 0 12px 24px rgba(88, 72, 49, 0.022), inset 1px 0 0 rgba(88, 72, 49, 0.024), inset -1px 0 0 rgba(255, 255, 255, 0.62), 0 22px 44px -26px rgba(66, 52, 33, 0.22)",
      "bjork-shadow-inset": "inset 0 1px 10px rgba(88, 72, 49, 0.12), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.72)",
      "bjork-ring-offset": "#f7f3ea"
    },
    "dark": {
      "bjork-bg": "#111111",
      "bjork-surface": "#121212",
      "bjork-surface-muted": "rgba(22, 22, 22, 0.92)",
      "bjork-surface-hover": "#161616",
      "bjork-surface-active": "#202020",
      "bjork-panel": "#0d0d0d",
      "bjork-menu": "rgba(18, 18, 18, 0.98)",
      "bjork-field": "rgba(18, 18, 18, 0.95)",
      "bjork-field-muted": "rgba(18, 18, 18, 0.55)",
      "bjork-field-inset": "rgba(9, 9, 9, 0.75)",
      "bjork-error-bg": "#130d0a",
      "bjork-text": "#ededed",
      "bjork-text-strong": "rgba(237, 237, 237, 0.9)",
      "bjork-text-medium": "rgba(237, 237, 237, 0.72)",
      "bjork-text-muted": "rgba(237, 237, 237, 0.6)",
      "bjork-text-soft": "rgba(237, 237, 237, 0.5)",
      "bjork-text-faint": "rgba(237, 237, 237, 0.22)",
      "bjork-inverted-text": "#080808",
      "bjork-border": "#232323",
      "bjork-border-muted": "#1c1c1c",
      "bjork-border-strong": "#343434",
      "bjork-thumb": "#626262",
      "bjork-track": "#090909",
      "bjork-accent": "#ec5c13",
      "bjork-accent-hover": "#f07832",
      "bjork-accent-soft": "rgba(236, 92, 19, 0.12)",
      "bjork-accent-muted": "rgba(236, 92, 19, 0.24)",
      "bjork-accent-badge": "#b84a12",
      "bjork-accent-badge-foreground": "#fff2ea",
      "bjork-accent-foreground": "#fff2ea",
      "bjork-accent-fill": "#b84a12",
      "bjork-accent-fill-hover": "#a84a14",
      "bjork-shadow-surface": "inset 0 7px 14px rgba(255, 255, 255, 0.03), inset 0 0.5px 0.5px rgba(255, 255, 255, 0.06), 0 14px 20px -6px rgba(0, 0, 0, 0.45)",
      "bjork-shadow-soft": "inset 0 1px 0 rgba(255, 255, 255, 0.045)",
      "bjork-shadow-panel": "inset 0 1px 0 rgba(255, 255, 255, 0.035), 0 18px 36px -28px rgba(0, 0, 0, 0.9)",
      "bjork-shadow-menu": "inset 0 1px 0 rgba(255, 255, 255, 0.055), inset 0 12px 24px rgba(255, 255, 255, 0.018), inset 0 -18px 26px rgba(0, 0, 0, 0.24), 0 22px 42px -22px rgba(0, 0, 0, 0.9)",
      "bjork-shadow-inset": "inset 0 1px 10px rgba(0, 0, 0, 0.45)",
      "bjork-ring-offset": "#080808"
    }
  },
  "css": {
    ".bjork-range": {
      "box-shadow": "inset 0 1px 1px rgba(255, 255, 255, 0.04), 0 0 14px rgba(189, 69, 20, 0.06)"
    },
    ".bjork-range::-webkit-slider-thumb": {
      "appearance": "none",
      "width": "16px",
      "height": "8px",
      "border": "0",
      "border-radius": "999px",
      "background": "var(--bjork-thumb)",
      "box-shadow": "inset 0 1px 0 rgba(255, 255, 255, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.42)"
    },
    ".bjork-range::-moz-range-thumb": {
      "width": "16px",
      "height": "8px",
      "border": "0",
      "border-radius": "999px",
      "background": "var(--bjork-thumb)",
      "box-shadow": "inset 0 1px 0 rgba(255, 255, 255, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.42)"
    },
    ".bjork-layered-button-accent, .bjork-layered-button-raised": {
      "position": "relative",
      "isolation": "isolate",
      "appearance": "none",
      "overflow": "hidden",
      "border": "0",
      "border-radius": "13px",
      "box-shadow": "inset 0 1px 0 #ffffff38, 0 4px 6px -1px #0000001a, 0 2px 4px -2px #0000001a",
      "transition": "filter 150ms ease-out, box-shadow 150ms ease-out"
    },
    ".bjork-layered-button-accent::after, .bjork-layered-button-raised::after": {
      "position": "absolute",
      "inset": "0",
      "pointer-events": "none",
      "content": "\"\"",
      "border": "1.5px solid transparent",
      "border-radius": "inherit",
      "background": "linear-gradient(#ffffffb8, #0000003d 41% 75%, #ffffff47) border-box",
      "mix-blend-mode": "overlay",
      "-webkit-mask-image": "linear-gradient(#000, #000), linear-gradient(#000, #000)",
      "mask-image": "linear-gradient(#000, #000), linear-gradient(#000, #000)",
      "-webkit-mask-clip": "padding-box, border-box",
      "mask-clip": "padding-box, border-box",
      "-webkit-mask-origin": "padding-box, border-box",
      "mask-origin": "padding-box, border-box",
      "-webkit-mask-composite": "xor",
      "mask-composite": "exclude"
    },
    ".bjork-layered-button-accent": {
      "color": "oklch(100% 0 0)",
      "text-shadow": "0 -1px #00000040",
      "background": "radial-gradient(ellipse at -20px top, rgba(255, 255, 255, 0.14), transparent), linear-gradient(180deg, #ec5c13 0%, #ec5c13 62%, color-mix(in oklab, #ec5c13 84%, black 16%) 100%)"
    },
    ".bjork-layered-button-raised": {
      "color": "oklch(100% 0 0)",
      "text-shadow": "0 -1px #00000026",
      "background": "radial-gradient(ellipse at -20px top, #ffffff38, #fff0), linear-gradient(180deg, oklch(0.1881 0.006 265), oklch(0.5493 0.0081 265))"
    },
    ".dark .bjork-layered-button-raised": {
      "color": "oklch(0.2574 0.0056 265)",
      "text-shadow": "0 -1px #00000026",
      "background": "radial-gradient(ellipse at -20px top, #ffffff38, #fff0), linear-gradient(180deg, color-mix(in oklab, oklch(0.9674 0.0013 265) 80%, oklch(0.2574 0.0056 265) 20%), color-mix(in oklab, oklch(0.669 0.0107 265) 80%, oklch(0.2574 0.0056 265) 20%))"
    },
    "@media (hover: hover)": {
      ".bjork-layered-button-accent:hover": {
        "filter": "brightness(1.08) saturate(1.04)"
      },
      ".bjork-layered-button-raised:hover": {
        "filter": "brightness(1.08) contrast(0.9)"
      }
    }
  },
  "meta": {
    "collection": "Galleries",
    "registryUrl": "https://ui.isaiahbjork.com/project-index.json",
    "installCommand": "npx shadcn@latest add https://ui.isaiahbjork.com/project-index.json"
  },
  "type": "registry:component"
}