{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "background-05",
  "title": "Flickering grid",
  "description": "Small squares that flicker under a low ceiling behind a hero, where a new word surfaces from the grid square by square.",
  "dependencies": [
    "not showing"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/background/background-05.tsx",
      "content": "'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\n\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport {\n  PRESS_LEAD_MS,\n  pressedSolidOf,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport { DemoBand } from './_parts/demo-band';\nimport { AT_REST, NEXT_FRAME } from './_parts/frame-loop';\nimport { DEFAULT_HUE } from './_parts/hue';\nimport { clamp, smoothstep, towards } from './_parts/math';\nimport { randomOf } from './_parts/seeded';\nimport type { Scene } from './_parts/stage';\nimport { StageCanvas, type StageHandle } from './_parts/stage-canvas';\nimport { wipeSurface, type Inks, type Surface } from './_parts/surface';\n\nconst DEFAULT_SQUARE = 4;\n\nconst DEFAULT_GAP = 4;\n\n/** A square outside the word never gets darker than this: the grid stays a texture behind text. */\nconst DEFAULT_CEILING = 0.3;\n\n/** A square of the word sits between these two, so the word reads by opacity alone. */\nconst WORD_FLOOR = 0.55;\n\nconst WORD_CEILING = 0.9;\n\nconst FLICKER_MS = 520;\n\n/** The share of the squares that start a flicker each second: a few at a time. */\nconst FLICKER_RATE = 0.04;\n\n/** A new word surfaces over this long: each of its squares starts at its own moment. */\nconst WORD_SPREAD_MS = 700;\n\n/** The word is set this tall, as a share of the rows, and narrowed to fit this share of the columns. */\nconst WORD_HEIGHT_SHARE = 0.44;\n\nconst WORD_WIDTH_SHARE = 0.86;\n\nconst WORD_WEIGHT = 600;\n\n/** How much ink a pixel of the word needs for its square to belong to the word, out of 255. */\nconst INK_THRESHOLD = 110;\n\nconst ALPHA_OFFSET = 3;\n\nconst CHANNELS = 4;\n\n/** Below this a square is not drawn at all. */\nconst FAINT = 0.004;\n\nconst SEED = 20261112;\n\nconst NO_INKS: Inks = { hue: 'transparent', line: 'transparent' };\n\ntype GridOptions = {\n  size: number;\n  gap: number;\n  maxOpacity: number;\n  wordAt: number;\n};\n\ntype Grid = {\n  square: number;\n  gap: number;\n  pitch: number;\n  /** The margin wiped around a square, so no rim is left on a screen of uneven density. */\n  bleed: number;\n  ceiling: number;\n  wordAt: number;\n  isStill: boolean;\n  inks: Inks;\n  family: string;\n  columns: number;\n  rows: number;\n  offsetX: number;\n  offsetY: number;\n  level: Float32Array;\n  from: Float32Array;\n  to: Float32Array;\n  startsAt: Float64Array;\n  isBusy: Uint8Array;\n  /** The squares in the middle of a flicker, packed at the start of the list. */\n  busy: Int32Array;\n  busyCount: number;\n  isWord: Uint8Array;\n  word: string;\n  hasShownWord: boolean;\n  /** Flickers owed by the rate and not started yet: the rate rarely gives a whole number a frame. */\n  owed: number;\n  random: () => number;\n};\n\nfunction wholePixelsOf(length: number) {\n  const rounded = Math.round(length);\n  return Math.max(1, rounded);\n}\n\nfunction gridOf({ size, gap, maxOpacity, wordAt }: GridOptions): Grid {\n  const square = wholePixelsOf(size);\n  const space = wholePixelsOf(gap);\n  const halfSpace = space / 2;\n  return {\n    square,\n    gap: space,\n    pitch: square + space,\n    bleed: Math.min(1, halfSpace),\n    ceiling: clamp(maxOpacity, 0, 1),\n    wordAt: clamp(wordAt, 0, 1),\n    isStill: false,\n    inks: NO_INKS,\n    family: 'sans-serif',\n    columns: 0,\n    rows: 0,\n    offsetX: 0,\n    offsetY: 0,\n    level: new Float32Array(0),\n    from: new Float32Array(0),\n    to: new Float32Array(0),\n    startsAt: new Float64Array(0),\n    isBusy: new Uint8Array(0),\n    busy: new Int32Array(0),\n    busyCount: 0,\n    isWord: new Uint8Array(0),\n    word: '',\n    hasShownWord: false,\n    owed: 0,\n    random: randomOf(SEED),\n  };\n}\n\n/** A level for one square: high inside the word, low and mostly dim outside it. */\nfunction levelFor(grid: Grid, index: number) {\n  const roll = grid.random();\n  const isInWord = grid.isWord[index] === 1;\n  if (isInWord) {\n    const span = WORD_CEILING - WORD_FLOOR;\n    const lift = roll * span;\n    return WORD_FLOOR + lift;\n  }\n  const dim = roll * roll;\n  return dim * grid.ceiling;\n}\n\nfunction fontOf(grid: Grid, pixels: number) {\n  return `${WORD_WEIGHT} ${pixels}px ${grid.family}`;\n}\n\n/**\n * The word, as one pixel a square: it is drawn as text on a sheet as large as the grid, in the\n * face the canvas inherits, and a square belongs to the word where its pixel took enough ink.\n */\nfunction readWord(grid: Grid) {\n  const { columns, rows, word } = grid;\n  const count = columns * rows;\n  const mask = new Uint8Array(count);\n  const hasNoWord = word === '';\n  if (hasNoWord || count === 0) {\n    return mask;\n  }\n  const sheet = document.createElement('canvas');\n  sheet.width = columns;\n  sheet.height = rows;\n  const pen = sheet.getContext('2d');\n  if (!pen) {\n    return mask;\n  }\n  const tallest = rows * WORD_HEIGHT_SHARE;\n  const widest = columns * WORD_WIDTH_SHARE;\n  const centreX = columns / 2;\n  const centreY = rows * grid.wordAt;\n  pen.font = fontOf(grid, tallest);\n  const measured = pen.measureText(word).width;\n  const width = Math.max(1, measured);\n  const room = widest / width;\n  const fit = Math.min(1, room);\n  const fitted = tallest * fit;\n  pen.font = fontOf(grid, fitted);\n  pen.textAlign = 'center';\n  pen.textBaseline = 'middle';\n  pen.fillText(word, centreX, centreY);\n  const pixels = pen.getImageData(0, 0, columns, rows).data;\n  for (let index = 0; index < count; index += 1) {\n    const firstChannel = index * CHANNELS;\n    const alphaAt = firstChannel + ALPHA_OFFSET;\n    const hasInk = pixels[alphaAt] > INK_THRESHOLD;\n    mask[index] = Number(hasInk);\n  }\n  return mask;\n}\n\n/** Starts a square on its way to a new level. A square already on its way heads for the new one. */\nfunction beginFlicker(grid: Grid, index: number, startsAt: number) {\n  grid.from[index] = grid.level[index];\n  grid.to[index] = levelFor(grid, index);\n  grid.startsAt[index] = startsAt;\n  const isListed = grid.isBusy[index] === 1;\n  if (isListed) {\n    return;\n  }\n  grid.isBusy[index] = 1;\n  grid.busy[grid.busyCount] = index;\n  grid.busyCount += 1;\n}\n\nfunction settleLevels(grid: Grid) {\n  for (let index = 0; index < grid.level.length; index += 1) {\n    grid.level[index] = levelFor(grid, index);\n  }\n  grid.busyCount = 0;\n  grid.isBusy.fill(0);\n}\n\n/**\n * The squares that enter or leave the word change level. The first word, and any word under\n * reduced motion, is there at once. A later word surfaces: each square starts at its own moment.\n */\nfunction takeWord(grid: Grid, now: number) {\n  const mask = readWord(grid);\n  const isAtOnce = grid.isStill || !grid.hasShownWord;\n  grid.hasShownWord = true;\n  for (let index = 0; index < mask.length; index += 1) {\n    const hasChanged = mask[index] !== grid.isWord[index];\n    grid.isWord[index] = mask[index];\n    if (hasChanged && isAtOnce) {\n      grid.level[index] = levelFor(grid, index);\n    }\n    if (hasChanged && !isAtOnce) {\n      const delay = grid.random() * WORD_SPREAD_MS;\n      const startsAt = now + delay;\n      beginFlicker(grid, index, startsAt);\n    }\n  }\n}\n\nfunction countAlong(length: number, grid: Grid) {\n  const roomy = length + grid.gap;\n  const count = Math.floor(roomy / grid.pitch);\n  return Math.max(0, count);\n}\n\n/** The grid is centred in the box on whole pixels, so every square has crisp edges. */\nfunction offsetOf(length: number, count: number, grid: Grid) {\n  const pitched = count * grid.pitch;\n  const spanned = pitched - grid.gap;\n  const spare = length - spanned;\n  return Math.floor(spare / 2);\n}\n\nfunction layGrid(grid: Grid, surface: Surface, isStill: boolean) {\n  const columns = countAlong(surface.width, grid);\n  const rows = countAlong(surface.height, grid);\n  const count = columns * rows;\n  grid.columns = columns;\n  grid.rows = rows;\n  grid.offsetX = offsetOf(surface.width, columns, grid);\n  grid.offsetY = offsetOf(surface.height, rows, grid);\n  grid.isStill = isStill;\n  grid.family = getComputedStyle(surface.canvas).fontFamily;\n  grid.level = new Float32Array(count);\n  grid.from = new Float32Array(count);\n  grid.to = new Float32Array(count);\n  grid.startsAt = new Float64Array(count);\n  grid.isBusy = new Uint8Array(count);\n  grid.busy = new Int32Array(count);\n  grid.busyCount = 0;\n  grid.owed = 0;\n  grid.random = randomOf(SEED);\n  grid.isWord = readWord(grid);\n  settleLevels(grid);\n}\n\nfunction paintSquare(pen: CanvasRenderingContext2D, grid: Grid, index: number) {\n  const column = index % grid.columns;\n  const row = Math.floor(index / grid.columns);\n  const across = column * grid.pitch;\n  const down = row * grid.pitch;\n  const x = grid.offsetX + across;\n  const y = grid.offsetY + down;\n  const rim = grid.bleed * 2;\n  const wiped = grid.square + rim;\n  const wipedX = x - grid.bleed;\n  const wipedY = y - grid.bleed;\n  pen.clearRect(wipedX, wipedY, wiped, wiped);\n  const level = grid.level[index];\n  if (level < FAINT) {\n    return;\n  }\n  pen.globalAlpha = level;\n  pen.fillRect(x, y, grid.square, grid.square);\n}\n\nfunction drawGrid(grid: Grid, surface: Surface) {\n  const { pen } = surface;\n  wipeSurface(surface);\n  pen.fillStyle = grid.inks.hue;\n  for (let index = 0; index < grid.level.length; index += 1) {\n    paintSquare(pen, grid, index);\n  }\n}\n\n/** A few squares, picked at random, start towards a new level. One already on its way is left alone. */\nfunction startFlickers(grid: Grid, seconds: number, now: number) {\n  const count = grid.level.length;\n  const perSecond = count * FLICKER_RATE;\n  grid.owed += perSecond * seconds;\n  while (grid.owed >= 1) {\n    grid.owed -= 1;\n    const roll = grid.random() * count;\n    const pick = Math.floor(roll);\n    const isFree = grid.isBusy[pick] === 0;\n    if (isFree) {\n      beginFlicker(grid, pick, now);\n    }\n  }\n}\n\n/** Moves one square along its flicker and draws it. It answers whether the flicker has ended. */\nfunction advanceSquare(\n  pen: CanvasRenderingContext2D,\n  grid: Grid,\n  index: number,\n  now: number\n) {\n  const age = now - grid.startsAt[index];\n  if (age < 0) {\n    return false;\n  }\n  const progress = Math.min(1, age / FLICKER_MS);\n  const eased = smoothstep(0, 1, progress);\n  grid.level[index] = towards(grid.from[index], grid.to[index], eased);\n  paintSquare(pen, grid, index);\n  return progress === 1;\n}\n\n/** Only the squares in the middle of a flicker are drawn. One that has ended leaves the list. */\nfunction advanceFlickers(\n  pen: CanvasRenderingContext2D,\n  grid: Grid,\n  now: number\n) {\n  let slot = 0;\n  while (slot < grid.busyCount) {\n    const index = grid.busy[slot];\n    const hasEnded = advanceSquare(pen, grid, index, now);\n    if (hasEnded) {\n      const last = grid.busyCount - 1;\n      grid.isBusy[index] = 0;\n      grid.busy[slot] = grid.busy[last];\n      grid.busyCount = last;\n    }\n    if (!hasEnded) {\n      slot += 1;\n    }\n  }\n}\n\nfunction stepGrid(grid: Grid, surface: Surface, seconds: number, now: number) {\n  if (grid.isStill) {\n    return AT_REST;\n  }\n  surface.pen.fillStyle = grid.inks.hue;\n  startFlickers(grid, seconds, now);\n  advanceFlickers(surface.pen, grid, now);\n  return NEXT_FRAME;\n}\n\ntype FlickerScene = Scene & {\n  setWord: (word: string) => void;\n};\n\nfunction createFlickerScene(options: GridOptions): FlickerScene {\n  const grid = gridOf(options);\n  return {\n    ink(inks) {\n      grid.inks = inks;\n    },\n    fit(surface, isStill) {\n      layGrid(grid, surface, isStill);\n    },\n    draw(surface) {\n      drawGrid(grid, surface);\n    },\n    step(surface, seconds, now) {\n      return stepGrid(grid, surface, seconds, now);\n    },\n    setWord(word) {\n      const isSameWord = word === grid.word;\n      if (isSameWord) {\n        return;\n      }\n      grid.word = word;\n      takeWord(grid, performance.now());\n    },\n  };\n}\n\nexport type FlickeringGridProps = {\n  className?: string;\n  /** Any colour token, such as `var(--primary)` or `var(--series-2)`. The squares wear it. */\n  hue?: string;\n  /** The side of a square, in pixels. */\n  size?: number;\n  /** The space between two squares, in pixels. */\n  gap?: number;\n  /** The darkest a square outside the word gets, from 0 to 1. */\n  maxOpacity?: number;\n  /** A word whose squares sit higher than the rest. It reads by opacity alone. */\n  word?: string;\n  /** Where the middle of the word sits down the grid, from 0 at the top to 1 at the bottom. */\n  wordAt?: number;\n};\n\n/**\n * A grid of small squares that flicker under a low ceiling, a few at a time, on one canvas. A word\n * can be set into it: its squares sit higher, and a new word surfaces square by square. Only the\n * squares in the middle of a flicker are drawn. It fills its parent, which must be positioned.\n * Under reduced motion the grid stands still, the word in it.\n */\nexport function FlickeringGrid({\n  className,\n  hue = DEFAULT_HUE,\n  size = DEFAULT_SQUARE,\n  gap = DEFAULT_GAP,\n  maxOpacity = DEFAULT_CEILING,\n  word = '',\n  wordAt = 0.5,\n}: FlickeringGridProps) {\n  const stage = useRef<StageHandle>(null);\n  const scene = useMemo(\n    () => createFlickerScene({ size, gap, maxOpacity, wordAt }),\n    [size, gap, maxOpacity, wordAt]\n  );\n\n  useEffect(() => {\n    scene.setWord(word);\n    stage.current?.refresh();\n  }, [scene, word]);\n\n  return (\n    <StageCanvas\n      handleRef={stage}\n      scene={scene}\n      hue={hue}\n      className={className}\n    />\n  );\n}\n\nconst WORDS = ['ndeko', 'quiet', 'fields'];\n\n/** The word sits above the middle of the band, clear of the headline at its foot. */\nconst WORD_AT = 0.38;\n\nconst WORD_HOLD_MS = 3600;\n\nexport default function Background05() {\n  const [round, setRound] = useState(0);\n  const { pressed, press } = usePress<'next'>();\n  const word = WORDS[round % WORDS.length];\n\n  function showNextWord() {\n    setRound((current) => current + 1);\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: WORD_HOLD_MS, run: () => press('next') },\n    { after: PRESS_LEAD_MS, run: showNextWord },\n  ];\n  const { ref } = useAutoplay<HTMLElement>(steps, { loopAfter: 0 });\n\n  return (\n    <DemoBand\n      ref={ref}\n      align='end'\n      title='A word surfaces from the grid'\n      background={<FlickeringGrid word={word} wordAt={WORD_AT} />}\n    >\n      <Button\n        onClick={showNextWord}\n        className={pressedSolidOf(pressed === 'next')}\n      >\n        Next word\n      </Button>\n    </DemoBand>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/background/background-05.tsx"
    },
    {
      "path": "registry/ndeko/components/background/_parts/demo-band.tsx",
      "content": "import { useId, type ReactNode, type Ref } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\ntype BandAlign = 'center' | 'end';\n\nconst ALIGNMENTS: Record<BandAlign, string> = {\n  center: 'justify-center',\n  end: 'justify-end pb-10',\n};\n\ntype DemoBandProps = {\n  ref?: Ref<HTMLElement>;\n  title: string;\n  /** The background under test. It fills the band, behind the headline and the actions. */\n  background: ReactNode;\n  /** `end` sets the headline at the foot of the band and leaves its middle to the background. */\n  align?: BandAlign;\n  children: ReactNode;\n};\n\n/**\n * The band every background is shown in: the page colour, a headline in the foreground colour and\n * the actions laid straight over the background, to prove that text stays readable above it.\n */\nexport function DemoBand({\n  ref,\n  title,\n  background,\n  align = 'center',\n  children,\n}: DemoBandProps) {\n  const titleId = useId();\n\n  return (\n    <section\n      ref={ref}\n      aria-labelledby={titleId}\n      className={cn(\n        'bg-background @container relative isolate flex h-90 w-full flex-col items-center overflow-hidden rounded-xl',\n        ALIGNMENTS[align]\n      )}\n    >\n      {background}\n      <div className='relative flex max-w-lg flex-col items-center gap-5 px-6 text-center'>\n        <h3\n          id={titleId}\n          className='text-2xl font-semibold text-balance @lg:text-3xl'\n        >\n          {title}\n        </h3>\n        <div className='flex flex-wrap items-center justify-center gap-2'>\n          {children}\n        </div>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/demo-band.tsx"
    },
    {
      "path": "registry/ndeko/components/background/_parts/frame-loop.ts",
      "content": "const FRAMES_PER_SECOND = 30;\n\nconst FRAME_MS = 1000 / FRAMES_PER_SECOND;\n\n/**\n * The timer between two frames ends this long before the next one is due, so the frame it asks for\n * lands on the screen refresh that is due and not on the one after.\n */\nconst REFRESH_LEAD_MS = 5;\n\nconst TIMER_MS = FRAME_MS - REFRESH_LEAD_MS;\n\n/** A frame that comes late, after a long task, moves the picture no further than this long would. */\nconst MAX_STEP_S = 0.05;\n\n/** What a frame answers while the picture still moves: the next one comes as soon as the cap allows. */\nexport const NEXT_FRAME = 0;\n\n/** What a frame answers once the picture has come to rest: nothing is asked for until `wake`. */\nexport const AT_REST = Number.POSITIVE_INFINITY;\n\n/** Draws one frame, `seconds` after the last one, and answers how many milliseconds it can wait for the next. */\nexport type FrameHandler = (seconds: number, now: number) => number;\n\nexport type FrameLoop = {\n  start: () => void;\n  stop: () => void;\n  wake: () => void;\n};\n\n/**\n * Frames at thirty a second at most. Between two frames there is one timer and no animation frame,\n * so a 120 Hz screen does not run four rounds of main-thread work for one frame drawn. Stopped or\n * at rest, the loop holds no timer and asks for no frame.\n */\nexport function createFrameLoop(onFrame: FrameHandler): FrameLoop {\n  let frame = 0;\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  let isStarted = false;\n  let lastFrameAt = 0;\n\n  function clearPending() {\n    cancelAnimationFrame(frame);\n    clearTimeout(timer);\n    frame = 0;\n    timer = undefined;\n  }\n\n  function askForFrame() {\n    timer = undefined;\n    frame = requestAnimationFrame(tick);\n  }\n\n  function schedule(wait: number) {\n    clearPending();\n    const now = performance.now();\n    const sinceFrame = now - lastFrameAt;\n    const untilCap = TIMER_MS - sinceFrame;\n    const delay = Math.max(wait, untilCap);\n    if (delay <= 0) {\n      askForFrame();\n      return;\n    }\n    timer = setTimeout(askForFrame, delay);\n  }\n\n  function tick(now: number) {\n    frame = 0;\n    const elapsedMs = now - lastFrameAt;\n    const elapsed = elapsedMs / 1000;\n    const forward = Math.max(0, elapsed);\n    const seconds = Math.min(forward, MAX_STEP_S);\n    lastFrameAt = now;\n    const wait = onFrame(seconds, now);\n    const isResting = wait === AT_REST;\n    if (isResting || !isStarted) {\n      return;\n    }\n    schedule(wait);\n  }\n\n  function start() {\n    if (isStarted) {\n      return;\n    }\n    const now = performance.now();\n    isStarted = true;\n    lastFrameAt = now - FRAME_MS;\n    schedule(NEXT_FRAME);\n  }\n\n  function stop() {\n    isStarted = false;\n    clearPending();\n  }\n\n  function wake() {\n    const isFrameComing = frame !== 0;\n    if (!isStarted || isFrameComing) {\n      return;\n    }\n    schedule(NEXT_FRAME);\n  }\n\n  return { start, stop, wake };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/frame-loop.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/hue.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\n/** A background wears one hue: the brand unless it is told otherwise. */\nexport const DEFAULT_HUE = 'var(--primary)';\n\n/** The brand first, then the series hues that differ from it. */\nconst DEMO_HUES = [\n  DEFAULT_HUE,\n  'var(--series-2)',\n  'var(--series-3)',\n  'var(--series-4)',\n  'var(--series-5)',\n];\n\n/** The hue of a demo, and the step to the next one, to show a background in each hue it accepts. */\nexport function useHueCycle() {\n  const [index, setIndex] = useState(0);\n  const hue = DEMO_HUES[index] ?? DEFAULT_HUE;\n\n  function nextHue() {\n    setIndex((current) => {\n      const next = current + 1;\n      return next % DEMO_HUES.length;\n    });\n  }\n\n  return { hue, nextHue };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/hue.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/math.ts",
      "content": "export type Point = {\n  x: number;\n  y: number;\n};\n\nexport function clamp(value: number, low: number, high: number) {\n  const raised = Math.max(low, value);\n  return Math.min(high, raised);\n}\n\n/** How much of the way left is covered in `seconds`: the same glide whatever the frame rate. */\nexport function shareOf(seconds: number, easeSeconds: number) {\n  const ratio = seconds / easeSeconds;\n  const decay = Math.exp(-ratio);\n  return 1 - decay;\n}\n\nexport function towards(from: number, to: number, share: number) {\n  const gap = to - from;\n  const step = gap * share;\n  return from + step;\n}\n\n/** From 0 at `low` to 1 at `high`, leaving and arriving without a corner. */\nexport function smoothstep(low: number, high: number, value: number) {\n  const span = high - low;\n  const offset = value - low;\n  const raw = offset / span;\n  const share = clamp(raw, 0, 1);\n  const doubled = 2 * share;\n  const curve = 3 - doubled;\n  const squared = share * share;\n  return squared * curve;\n}\n\n/** The damping that brings a spring of this stiffness to its target without passing it. */\nexport function dampingOf(stiffness: number) {\n  const root = Math.sqrt(stiffness);\n  return 2 * root;\n}\n\n/**\n * The speed of a spring one step later. The caller then moves the value by that speed over the\n * same step, so the value follows its target and settles on it.\n */\nexport function springSpeedOf(\n  gap: number,\n  speed: number,\n  stiffness: number,\n  damping: number,\n  seconds: number\n) {\n  const pull = gap * stiffness;\n  const drag = speed * damping;\n  const push = pull - drag;\n  const gain = push * seconds;\n  return speed + gain;\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/math.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/pointer.ts",
      "content": "import type { Point } from './math';\n\n/**\n * Where a point of the window falls inside `host`, in the pixels of its own box, or null when it\n * falls outside. A host that an ancestor scales still answers in its own pixels.\n */\nexport function placeIn(\n  host: HTMLElement,\n  clientX: number,\n  clientY: number\n): Point | null {\n  const box = host.getBoundingClientRect();\n  const isEmpty = box.width === 0 || box.height === 0;\n  if (isEmpty) {\n    return null;\n  }\n  const isInsideX = clientX >= box.left && clientX <= box.right;\n  const isInsideY = clientY >= box.top && clientY <= box.bottom;\n  if (!isInsideX || !isInsideY) {\n    return null;\n  }\n  const scaleX = host.offsetWidth / box.width;\n  const scaleY = host.offsetHeight / box.height;\n  const offsetX = clientX - box.left;\n  const offsetY = clientY - box.top;\n  const x = offsetX * scaleX;\n  const y = offsetY * scaleY;\n  return { x, y };\n}\n\n/** Where the centre of `element` falls inside `host`, or null when it falls outside. */\nexport function centreIn(host: HTMLElement, element: Element) {\n  const box = element.getBoundingClientRect();\n  const halfWidth = box.width / 2;\n  const halfHeight = box.height / 2;\n  const centreX = box.left + halfWidth;\n  const centreY = box.top + halfHeight;\n  return placeIn(host, centreX, centreY);\n}\n\n/**\n * Follows a pointer that can hover, from the window: content laid over a background takes the\n * pointer events of its own box, so a listener on the background would go blind under a headline.\n * The place is read once a frame at most, and only on a frame where the pointer moved. `onMove`\n * gets the place inside `host`; `onLeave` is called once when the pointer goes out of it. The\n * function returned ends the watch, and lets go of a pointer that was still over the host.\n */\nexport function watchPointer(\n  host: HTMLElement,\n  onMove: (x: number, y: number) => void,\n  onLeave: () => void\n) {\n  let clientX = 0;\n  let clientY = 0;\n  let frame = 0;\n  let isOver = false;\n\n  function leave() {\n    if (!isOver) {\n      return;\n    }\n    isOver = false;\n    onLeave();\n  }\n\n  function read() {\n    frame = 0;\n    const place = placeIn(host, clientX, clientY);\n    if (!place) {\n      leave();\n      return;\n    }\n    isOver = true;\n    onMove(place.x, place.y);\n  }\n\n  function onPointerMove(event: PointerEvent) {\n    const isTouch = event.pointerType === 'touch';\n    if (isTouch) {\n      return;\n    }\n    clientX = event.clientX;\n    clientY = event.clientY;\n    const isReadComing = frame !== 0;\n    if (isReadComing) {\n      return;\n    }\n    frame = requestAnimationFrame(read);\n  }\n\n  function onPointerGone() {\n    cancelAnimationFrame(frame);\n    frame = 0;\n    leave();\n  }\n\n  const root = document.documentElement;\n  window.addEventListener('pointermove', onPointerMove, { passive: true });\n  root.addEventListener('pointerleave', onPointerGone, { passive: true });\n\n  return () => {\n    window.removeEventListener('pointermove', onPointerMove);\n    root.removeEventListener('pointerleave', onPointerGone);\n    onPointerGone();\n  };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/pointer.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/seeded.ts",
      "content": "const STREAM_STEP = 0x6d2b79f5;\n\nconst UINT32_RANGE = 4294967296;\n\nconst FIRST_PRIME = 73856093;\n\nconst SECOND_PRIME = 19349663;\n\n/**\n * A stream of numbers from 0 to 1, the same for the same seed on the server and in the browser, so\n * a generated picture never changes between two renders.\n */\nexport function randomOf(seed: number) {\n  let state = seed >>> 0;\n\n  function next() {\n    const stepped = state + STREAM_STEP;\n    state = stepped >>> 0;\n    const shifted = state >>> 15;\n    const folded = state ^ shifted;\n    const odd = state | 1;\n    const first = Math.imul(folded, odd);\n    const reshifted = first >>> 7;\n    const refolded = first ^ reshifted;\n    const salted = first | 61;\n    const second = Math.imul(refolded, salted);\n    const summed = first + second;\n    const mixed = first ^ summed;\n    const lastShift = mixed >>> 14;\n    const settled = mixed ^ lastShift;\n    const positive = settled >>> 0;\n    return positive / UINT32_RANGE;\n  }\n\n  return next;\n}\n\n/** One seed out of two numbers, so each part of a picture draws from a stream of its own. */\nexport function seedOf(first: number, second: number) {\n  const firstHash = Math.imul(first, FIRST_PRIME);\n  const secondHash = Math.imul(second, SECOND_PRIME);\n  const mixed = firstHash ^ secondHash;\n  return mixed >>> 0;\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/seeded.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/showing.ts",
      "content": "/**\n * A background sits behind content for as long as the page is open, so everything it runs hangs on\n * this answer: its box touches the screen and the tab is the one looked at. `onChange` is called\n * each time the answer changes, starting from \"not showing\". The function returned ends the watch.\n */\nexport function watchShowing(\n  element: Element,\n  onChange: (isShowing: boolean) => void\n) {\n  let isOnScreen = false;\n  let wasShowing = false;\n\n  function report() {\n    const isTabShown = document.visibilityState === 'visible';\n    const isShowing = isOnScreen && isTabShown;\n    if (isShowing === wasShowing) {\n      return;\n    }\n    wasShowing = isShowing;\n    onChange(isShowing);\n  }\n\n  function onCrossing(entries: IntersectionObserverEntry[]) {\n    const latest = entries.at(-1);\n    if (!latest) {\n      return;\n    }\n    isOnScreen = latest.isIntersecting;\n    report();\n  }\n\n  const observer = new IntersectionObserver(onCrossing);\n  observer.observe(element);\n  document.addEventListener('visibilitychange', report);\n\n  return () => {\n    observer.disconnect();\n    document.removeEventListener('visibilitychange', report);\n  };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/showing.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/stage-canvas.tsx",
      "content": "'use client';\n\nimport { useEffect, useImperativeHandle, useRef, type Ref } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport type { Point } from './math';\nimport { mountStage, type Scene, type Stage } from './stage';\n\nexport type StageHandle = {\n  /** Something outside the loop changed the scene: it is drawn again, and its loop is woken. */\n  refresh: () => void;\n  /** Where the centre of an element sits on the canvas, or null when it is outside. */\n  centreOf: (element: Element) => Point | null;\n};\n\ntype StageCanvasProps = {\n  scene: Scene;\n  hue: string;\n  isInteractive?: boolean;\n  className?: string;\n  handleRef?: Ref<StageHandle>;\n};\n\n/**\n * The one canvas of a background. It fills its parent, lets every pointer event through and is\n * hidden from assistive technology, since it is decoration. A canvas cannot take a colour from a\n * class: the hue rides on its `color` and the neutral of lines on `decoration-foreground`, and the\n * stage reads both from the computed style. No transition may sit on those two, or the stage\n * would read a colour halfway through it.\n */\nexport function StageCanvas({\n  scene,\n  hue,\n  isInteractive = false,\n  className,\n  handleRef,\n}: StageCanvasProps) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const stage = useRef<Stage | null>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) {\n      return;\n    }\n    const mounted = mountStage(canvas, scene, {\n      isStill: shouldReduceMotion,\n      isInteractive,\n    });\n    stage.current = mounted;\n    return () => {\n      mounted?.dispose();\n      stage.current = null;\n    };\n  }, [scene, isInteractive, shouldReduceMotion]);\n\n  useEffect(() => {\n    stage.current?.reink();\n  }, [hue]);\n\n  useImperativeHandle(\n    handleRef,\n    () => ({\n      refresh: () => stage.current?.refresh(),\n      centreOf: (element) => stage.current?.centreOf(element) ?? null,\n    }),\n    []\n  );\n\n  return (\n    <canvas\n      ref={canvasRef}\n      aria-hidden='true'\n      style={{ color: hue }}\n      className={cn(\n        'decoration-foreground pointer-events-none absolute inset-0 size-full',\n        className\n      )}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/stage-canvas.tsx"
    },
    {
      "path": "registry/ndeko/components/background/_parts/stage.ts",
      "content": "import { createFrameLoop } from './frame-loop';\nimport type { Point } from './math';\nimport { centreIn, watchPointer } from './pointer';\nimport { watchShowing } from './showing';\nimport {\n  createSurface,\n  fitSurface,\n  hasSameInks,\n  inksOf,\n  isFitted,\n  watchSurface,\n  type Inks,\n  type Surface,\n} from './surface';\n\n/** What a background draws on its canvas. The stage decides when; the scene only knows how. */\nexport type Scene = {\n  /** The colours changed: the theme, or the hue. */\n  ink: (inks: Inks) => void;\n  /**\n   * The box changed, and the canvas was wiped: what depends on its size is built again. `isStill`\n   * is the reduced motion setting: the scene then holds its most telling picture and never moves.\n   */\n  fit: (surface: Surface, isStill: boolean) => void;\n  /** The whole picture as it stands. */\n  draw: (surface: Surface) => void;\n  /**\n   * Moves the picture on by `seconds` and draws what changed. It answers how long it can wait for\n   * its next frame: `NEXT_FRAME`, `AT_REST`, or a number of milliseconds.\n   */\n  step: (surface: Surface, seconds: number, now: number) => number;\n  pointerMoved?: (x: number, y: number) => void;\n  pointerLeft?: () => void;\n};\n\nexport type Stage = {\n  /** Something outside the loop changed the scene: it is drawn again, and its loop is woken. */\n  refresh: () => void;\n  /** Reads the colours again, and draws again when they changed. */\n  reink: () => void;\n  /** Where the centre of an element sits on the canvas, or null when it is outside. */\n  centreOf: (element: Element) => Point | null;\n  dispose: () => void;\n};\n\nexport type StageOptions = {\n  /** Reduced motion: no pointer is followed and nothing moves by itself. */\n  isStill: boolean;\n  isInteractive: boolean;\n};\n\nfunction idle() {}\n\nfunction stageOf(\n  surface: Surface,\n  scene: Scene,\n  { isStill, isInteractive }: StageOptions\n): Stage {\n  const { canvas } = surface;\n  const followsPointer = isInteractive && !isStill;\n  let isShowing = false;\n  let stopPointer = idle;\n  let inks = inksOf(canvas);\n\n  const loop = createFrameLoop((seconds, now) =>\n    scene.step(surface, seconds, now)\n  );\n\n  function wake() {\n    if (isShowing) {\n      loop.wake();\n    }\n  }\n\n  function lay() {\n    fitSurface(surface);\n    scene.fit(surface, isStill);\n    scene.draw(surface);\n  }\n\n  function onPointerMove(x: number, y: number) {\n    scene.pointerMoved?.(x, y);\n    wake();\n  }\n\n  function onPointerLeave() {\n    scene.pointerLeft?.();\n    wake();\n  }\n\n  function show() {\n    isShowing = true;\n    if (followsPointer) {\n      stopPointer = watchPointer(canvas, onPointerMove, onPointerLeave);\n    }\n    loop.start();\n  }\n\n  function hide() {\n    isShowing = false;\n    stopPointer();\n    stopPointer = idle;\n    loop.stop();\n  }\n\n  function onShowing(isNowShowing: boolean) {\n    if (isNowShowing) {\n      show();\n      return;\n    }\n    hide();\n  }\n\n  function onResize() {\n    if (isFitted(surface)) {\n      return;\n    }\n    lay();\n    wake();\n  }\n\n  function reink() {\n    const latest = inksOf(canvas);\n    if (hasSameInks(inks, latest)) {\n      return;\n    }\n    inks = latest;\n    scene.ink(inks);\n    scene.draw(surface);\n    wake();\n  }\n\n  /** In the loop, the next frame draws the change. Out of it, nothing would, so it is drawn here. */\n  function refresh() {\n    const isOutOfLoop = isStill || !isShowing;\n    if (isOutOfLoop) {\n      scene.draw(surface);\n    }\n    wake();\n  }\n\n  scene.ink(inks);\n  lay();\n  const stopSurface = watchSurface(canvas, onResize, reink);\n  const stopShowing = watchShowing(canvas, onShowing);\n\n  return {\n    refresh,\n    reink,\n    centreOf: (element) => centreIn(canvas, element),\n    dispose() {\n      stopShowing();\n      stopSurface();\n      hide();\n    },\n  };\n}\n\n/**\n * Puts a scene on a canvas. The stage sizes the canvas for the screen, reads its colours, and runs\n * the loop of the scene only while the canvas is on screen in a visible tab. It draws one frame\n * when it is set up, so the picture is there before anything moves.\n */\nexport function mountStage(\n  canvas: HTMLCanvasElement,\n  scene: Scene,\n  options: StageOptions\n) {\n  const surface = createSurface(canvas);\n  if (!surface) {\n    return null;\n  }\n  return stageOf(surface, scene, options);\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/stage.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/surface.ts",
      "content": "/** A backing store above two device pixels a point costs four times the fill for a picture nobody sees sharper. */\nconst MAX_PIXEL_RATIO = 2;\n\nconst THEME_WATCH = {\n  attributes: true,\n  attributeFilter: ['class', 'data-theme'],\n};\n\nconst DARK_SCHEME = '(prefers-color-scheme: dark)';\n\nexport type Surface = {\n  canvas: HTMLCanvasElement;\n  pen: CanvasRenderingContext2D;\n  /** The box of the canvas in CSS pixels: one unit drawn is one of them, whatever the screen. */\n  width: number;\n  height: number;\n  pixelRatio: number;\n};\n\nexport type Inks = {\n  /** The hue of the background, resolved by the browser for the current theme. */\n  hue: string;\n  /** The neutral of lines: the foreground of the theme. */\n  line: string;\n};\n\nexport function createSurface(canvas: HTMLCanvasElement): Surface | null {\n  const pen = canvas.getContext('2d');\n  if (!pen) {\n    return null;\n  }\n  return { canvas, pen, width: 0, height: 0, pixelRatio: 1 };\n}\n\nfunction pixelRatioOf() {\n  const devicePixelRatio = window.devicePixelRatio || 1;\n  return Math.min(devicePixelRatio, MAX_PIXEL_RATIO);\n}\n\n/** Sizes the backing store to the box of the canvas and to the screen. It also wipes the canvas. */\nexport function fitSurface(surface: Surface) {\n  const { canvas, pen } = surface;\n  const pixelRatio = pixelRatioOf();\n  const width = canvas.clientWidth;\n  const height = canvas.clientHeight;\n  const deviceWidth = width * pixelRatio;\n  const deviceHeight = height * pixelRatio;\n  surface.width = width;\n  surface.height = height;\n  surface.pixelRatio = pixelRatio;\n  canvas.width = Math.round(deviceWidth);\n  canvas.height = Math.round(deviceHeight);\n  pen.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n}\n\nexport function isFitted(surface: Surface) {\n  const { canvas } = surface;\n  const hasWidth = surface.width === canvas.clientWidth;\n  const hasHeight = surface.height === canvas.clientHeight;\n  const hasRatio = surface.pixelRatio === pixelRatioOf();\n  const hasSize = hasWidth && hasHeight;\n  return hasSize && hasRatio;\n}\n\nexport function wipeSurface(surface: Surface) {\n  surface.pen.globalAlpha = 1;\n  surface.pen.clearRect(0, 0, surface.width, surface.height);\n}\n\n/**\n * A canvas cannot take a colour from a class, so it reads its colours from its own computed style,\n * where the browser has already resolved the tokens for the current theme. The hue rides on\n * `color` and the neutral of lines on `text-decoration-color`, which paints nothing on a canvas.\n */\nexport function inksOf(canvas: HTMLCanvasElement): Inks {\n  const style = getComputedStyle(canvas);\n  return { hue: style.color, line: style.textDecorationColor };\n}\n\nexport function hasSameInks(first: Inks, second: Inks) {\n  const hasSameHue = first.hue === second.hue;\n  const hasSameLine = first.line === second.line;\n  return hasSameHue && hasSameLine;\n}\n\nfunction densityQueryOf() {\n  return `(resolution: ${window.devicePixelRatio}dppx)`;\n}\n\n/**\n * Calls `onResize` when the box of the canvas or the density of the screen changes, and `onTheme`\n * when the page may have changed theme: a class or an attribute on the root or the body, or the\n * system setting. The function returned ends the watch.\n */\nexport function watchSurface(\n  canvas: HTMLCanvasElement,\n  onResize: () => void,\n  onTheme: () => void\n) {\n  const sizeObserver = new ResizeObserver(() => onResize());\n  const themeObserver = new MutationObserver(() => onTheme());\n  const scheme = window.matchMedia(DARK_SCHEME);\n  let density = window.matchMedia(densityQueryOf());\n\n  function onScheme() {\n    onTheme();\n  }\n\n  /** The query names one density: once the screen has left it, a new query watches the next one. */\n  function onDensity() {\n    density.removeEventListener('change', onDensity);\n    density = window.matchMedia(densityQueryOf());\n    density.addEventListener('change', onDensity);\n    onResize();\n  }\n\n  sizeObserver.observe(canvas);\n  themeObserver.observe(document.documentElement, THEME_WATCH);\n  themeObserver.observe(document.body, THEME_WATCH);\n  scheme.addEventListener('change', onScheme);\n  density.addEventListener('change', onDensity);\n\n  return () => {\n    sizeObserver.disconnect();\n    themeObserver.disconnect();\n    scheme.removeEventListener('change', onScheme);\n    density.removeEventListener('change', onDensity);\n  };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/surface.ts"
    }
  ],
  "categories": [
    "components",
    "background"
  ],
  "type": "registry:component"
}