{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "background-03",
  "title": "Dither light",
  "description": "A soft light drawn as crisp ordered dots behind a hero, that follows the pointer, rises as a horizon or flows as noise, dots lighting and going out as it passes.",
  "dependencies": [
    "not showing"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/segments.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-03.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 { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { DemoBand } from './_parts/demo-band';\nimport { AT_REST, NEXT_FRAME } from './_parts/frame-loop';\nimport { DEFAULT_HUE } from './_parts/hue';\nimport { clamp, shareOf, towards, type Point } from './_parts/math';\nimport type { Scene } from './_parts/stage';\nimport { StageCanvas, type StageHandle } from './_parts/stage-canvas';\nimport { wipeSurface, type Inks, type Surface } from './_parts/surface';\n\nexport type DitherMode = 'pointer' | 'horizon' | 'noise';\n\nconst DEFAULT_CELL = 6;\n\nconst MIN_CELL = 4;\n\n/** The 4 by 4 ordered dither: the rank at which each cell of a tile lights up as the light grows. */\nconst BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];\n\nconst BAYER_SIDE = 4;\n\nfunction thresholdOf(rank: number) {\n  const centred = rank + 0.5;\n  return centred / BAYER.length;\n}\n\nconst THRESHOLDS = BAYER.map(thresholdOf);\n\n/** A dot takes a third of its cell, and never less than two pixels. */\nconst DOT_SHARE = 3;\n\nconst MIN_DOT = 2;\n\n/** Dots are small and stay a tint: text sits above them and must stay easy to read. */\nconst DOT_ALPHA = 0.6;\n\n/** The light never fills every cell: a few dots stay dark even at its heart, so it keeps a grain. */\nconst PEAK = 0.92;\n\n/** Seconds for a cell to follow the light most of the way: a change of mode fades instead of cutting. */\nconst CELL_EASE_S = 0.2;\n\nconst SETTLED = 0.004;\n\nconst LIGHT_REACH_PX = 250;\n\nconst LIGHT_REACH_SQUARED = LIGHT_REACH_PX * LIGHT_REACH_PX;\n\nconst LIGHT_EASE_S = 0.3;\n\nconst LIGHT_HOME_PX = 0.5;\n\n/** Without a pointer the light walks a slow loop, so the piece shows what it does by itself. */\nconst WALK_ACROSS = 0.3;\n\nconst WALK_DOWN = 0.22;\n\nconst WALK_ACROSS_SPEED = 0.31;\n\nconst WALK_DOWN_SPEED = 0.47;\n\nconst WALK_DOWN_PHASE = 1.3;\n\n/** The share of the height the horizon light fills once it has risen. */\nconst HORIZON_SHARE = 0.52;\n\nconst HORIZON_RISE_S = 0.9;\n\nconst HORIZON_BREATH = 0.04;\n\nconst HORIZON_BREATH_SPEED = 0.5;\n\n/** The share of the height over which the light grows from nothing to its peak, below the horizon. */\nconst HORIZON_SPAN_SHARE = 0.44;\n\nconst SWELL_PX = 12;\n\nconst SWELL_WAVE = 0.014;\n\nconst SWELL_SPEED = 0.6;\n\ntype Wave = {\n  /** Radians a pixel: how tight the wave is. */\n  wave: number;\n  /** Radians a second: how fast it travels, and which way. */\n  speed: number;\n};\n\n/** Four travelling waves add up to the noise: across, down and along both diagonals. */\nconst NOISE_ACROSS: Wave = { wave: 0.021, speed: 0.42 };\n\nconst NOISE_DOWN: Wave = { wave: 0.029, speed: -0.33 };\n\nconst NOISE_FALLING: Wave = { wave: 0.013, speed: 0.27 };\n\nconst NOISE_RISING: Wave = { wave: 0.017, speed: -0.21 };\n\nconst NOISE_GAIN = 0.21;\n\n/** Where the light rests in the still picture, across and down the box. */\nconst STILL_AT: Point = { x: 0.5, y: 0.42 };\n\nconst STILL_CLOCK = 2.4;\n\nconst NO_INKS: Inks = { hue: 'transparent', line: 'transparent' };\n\ntype DitherField = {\n  cell: number;\n  dot: number;\n  inset: number;\n  mode: DitherMode;\n  isStill: boolean;\n  inks: Inks;\n  columns: number;\n  rows: number;\n  width: number;\n  height: number;\n  /** The light each cell should show, and the light it shows now on its way there. */\n  target: Float32Array;\n  shown: Float32Array;\n  /** What is on the canvas: 1 where a dot is drawn. */\n  lit: Uint8Array;\n  clock: number;\n  light: Point;\n  pointer: Point;\n  hasPointer: boolean;\n  horizonRise: number;\n  edge: Float32Array;\n  across: Float32Array;\n  down: Float32Array;\n  falling: Float32Array;\n  rising: Float32Array;\n};\n\nfunction fieldOf(size: number): DitherField {\n  const rounded = Math.round(size);\n  const cell = Math.max(MIN_CELL, rounded);\n  const third = Math.round(cell / DOT_SHARE);\n  const dot = Math.max(MIN_DOT, third);\n  const margin = cell - dot;\n  const inset = Math.floor(margin / 2);\n  return {\n    cell,\n    dot,\n    inset,\n    mode: 'pointer',\n    isStill: false,\n    inks: NO_INKS,\n    columns: 0,\n    rows: 0,\n    width: 0,\n    height: 0,\n    target: new Float32Array(0),\n    shown: new Float32Array(0),\n    lit: new Uint8Array(0),\n    clock: 0,\n    light: { x: 0, y: 0 },\n    pointer: { x: 0, y: 0 },\n    hasPointer: false,\n    horizonRise: 1,\n    edge: new Float32Array(0),\n    across: new Float32Array(0),\n    down: new Float32Array(0),\n    falling: new Float32Array(0),\n    rising: new Float32Array(0),\n  };\n}\n\n/** The middle of a cell, counted in cells from the edge of the box. */\nfunction centreOf(field: DitherField, cells: number) {\n  const start = cells * field.cell;\n  const half = field.cell / 2;\n  return start + half;\n}\n\n/** A share of the box that swings around its middle as the clock runs. */\nfunction swingOf(clock: number, speed: number, phase: number, reach: number) {\n  const turned = clock * speed;\n  const turn = turned + phase;\n  const swing = Math.sin(turn);\n  const offset = swing * reach;\n  return 0.5 + offset;\n}\n\nfunction walkOf(field: DitherField): Point {\n  const across = swingOf(field.clock, WALK_ACROSS_SPEED, 0, WALK_ACROSS);\n  const down = swingOf(\n    field.clock,\n    WALK_DOWN_SPEED,\n    WALK_DOWN_PHASE,\n    WALK_DOWN\n  );\n  const x = field.width * across;\n  const y = field.height * down;\n  return { x, y };\n}\n\nfunction goalOf(field: DitherField) {\n  if (field.hasPointer) {\n    return field.pointer;\n  }\n  return walkOf(field);\n}\n\nfunction restLight(field: DitherField) {\n  field.light.x = field.width * STILL_AT.x;\n  field.light.y = field.height * STILL_AT.y;\n}\n\nfunction glowOf(squared: number) {\n  if (squared >= LIGHT_REACH_SQUARED) {\n    return 0;\n  }\n  const distance = Math.sqrt(squared);\n  const farness = distance / LIGHT_REACH_PX;\n  const nearness = 1 - farness;\n  const soft = nearness * nearness;\n  return soft * PEAK;\n}\n\n/** A light around one point, falling off to nothing at its reach. */\nfunction aimPointer(field: DitherField) {\n  const { columns, rows, light, target } = field;\n  let index = 0;\n  for (let row = 0; row < rows; row += 1) {\n    const y = centreOf(field, row);\n    const offsetY = y - light.y;\n    const squaredY = offsetY * offsetY;\n    for (let column = 0; column < columns; column += 1) {\n      const x = centreOf(field, column);\n      const offsetX = x - light.x;\n      const squaredX = offsetX * offsetX;\n      const squared = squaredX + squaredY;\n      target[index] = glowOf(squared);\n      index += 1;\n    }\n  }\n}\n\n/** Where the horizon stands now, in pixels from the top: it rises once, then breathes. */\nfunction horizonOf(field: DitherField) {\n  const breathTurn = field.clock * HORIZON_BREATH_SPEED;\n  const swing = Math.sin(breathTurn);\n  const breath = swing * HORIZON_BREATH;\n  const risen = HORIZON_SHARE * field.horizonRise;\n  const filled = risen + breath;\n  const empty = 1 - filled;\n  return field.height * empty;\n}\n\n/** A light that rises from the bottom edge. Its upper edge swells along the width. */\nfunction aimHorizon(field: DitherField) {\n  const { columns, rows, edge, target } = field;\n  const level = horizonOf(field);\n  const span = field.height * HORIZON_SPAN_SHARE;\n  const drift = field.clock * SWELL_SPEED;\n  for (let column = 0; column < columns; column += 1) {\n    const x = centreOf(field, column);\n    const along = x * SWELL_WAVE;\n    const turn = along + drift;\n    const swell = Math.sin(turn) * SWELL_PX;\n    edge[column] = level + swell;\n  }\n  let index = 0;\n  for (let row = 0; row < rows; row += 1) {\n    const y = centreOf(field, row);\n    for (let column = 0; column < columns; column += 1) {\n      const depth = y - edge[column];\n      const reach = depth / span;\n      const share = clamp(reach, 0, 1);\n      target[index] = share * PEAK;\n      index += 1;\n    }\n  }\n}\n\n/** One wave, worked out once for every row, column or diagonal it crosses. */\nfunction fillBand(\n  band: Float32Array,\n  field: DitherField,\n  firstCell: number,\n  wave: Wave\n) {\n  const drift = field.clock * wave.speed;\n  const turnPerCell = field.cell * wave.wave;\n  for (let index = 0; index < band.length; index += 1) {\n    const cells = index + firstCell;\n    const along = cells * turnPerCell;\n    const turn = along + drift;\n    band[index] = Math.sin(turn);\n  }\n}\n\n/**\n * Four waves that travel across, down and along both diagonals. Each depends on one number a\n * cell, so a cell only adds four numbers that were worked out once a row, a column or a diagonal.\n */\nfunction aimNoise(field: DitherField) {\n  const { columns, rows, across, down, falling, rising, target } = field;\n  fillBand(across, field, 0, NOISE_ACROSS);\n  fillBand(down, field, 0, NOISE_DOWN);\n  fillBand(falling, field, 0, NOISE_FALLING);\n  fillBand(rising, field, -rows, NOISE_RISING);\n  let index = 0;\n  for (let row = 0; row < rows; row += 1) {\n    const firstRising = rows - row;\n    for (let column = 0; column < columns; column += 1) {\n      const fallingIndex = column + row;\n      const risingIndex = column + firstRising;\n      const straight = across[column] + down[row];\n      const diagonal = falling[fallingIndex] + rising[risingIndex];\n      const sum = straight + diagonal;\n      const swing = sum * NOISE_GAIN;\n      const centred = 0.5 + swing;\n      const level = clamp(centred, 0, 1);\n      target[index] = level * PEAK;\n      index += 1;\n    }\n  }\n}\n\nfunction aim(field: DitherField) {\n  if (field.mode === 'horizon') {\n    aimHorizon(field);\n    return;\n  }\n  if (field.mode === 'noise') {\n    aimNoise(field);\n    return;\n  }\n  aimPointer(field);\n}\n\nfunction dotOn(\n  pen: CanvasRenderingContext2D,\n  field: DitherField,\n  column: number,\n  row: number\n) {\n  const cellX = column * field.cell;\n  const cellY = row * field.cell;\n  const x = cellX + field.inset;\n  const y = cellY + field.inset;\n  pen.fillRect(x, y, field.dot, field.dot);\n}\n\n/** The whole cell is wiped, not the dot alone: on a screen of uneven density a dot leaves a rim. */\nfunction dotOff(\n  pen: CanvasRenderingContext2D,\n  field: DitherField,\n  column: number,\n  row: number\n) {\n  const x = column * field.cell;\n  const y = row * field.cell;\n  pen.clearRect(x, y, field.cell, field.cell);\n}\n\nfunction isLitAt(\n  field: DitherField,\n  index: number,\n  column: number,\n  row: number\n) {\n  const tileRow = row % BAYER_SIDE;\n  const tileColumn = column % BAYER_SIDE;\n  const firstOfRow = tileRow * BAYER_SIDE;\n  const rank = firstOfRow + tileColumn;\n  return field.shown[index] > THRESHOLDS[rank];\n}\n\n/**\n * Every cell eases towards its light, and only a dot that crosses its threshold is drawn or wiped.\n * It answers whether any cell is still on its way.\n */\nfunction easeCells(field: DitherField, surface: Surface, share: number) {\n  const { columns, rows, target, shown, lit } = field;\n  const { pen } = surface;\n  let isEasing = false;\n  let index = 0;\n  pen.fillStyle = field.inks.hue;\n  pen.globalAlpha = DOT_ALPHA;\n  for (let row = 0; row < rows; row += 1) {\n    for (let column = 0; column < columns; column += 1) {\n      const gap = target[index] - shown[index];\n      const step = gap * share;\n      const isOnItsWay = Math.abs(gap) > SETTLED;\n      shown[index] += step;\n      isEasing = isEasing || isOnItsWay;\n      const isLit = isLitAt(field, index, column, row);\n      const wasLit = lit[index] === 1;\n      if (isLit && !wasLit) {\n        dotOn(pen, field, column, row);\n        lit[index] = 1;\n      }\n      if (wasLit && !isLit) {\n        dotOff(pen, field, column, row);\n        lit[index] = 0;\n      }\n      index += 1;\n    }\n  }\n  return isEasing;\n}\n\nfunction drawDots(field: DitherField, surface: Surface) {\n  const { columns, rows, lit } = field;\n  const { pen } = surface;\n  let index = 0;\n  wipeSurface(surface);\n  pen.fillStyle = field.inks.hue;\n  pen.globalAlpha = DOT_ALPHA;\n  for (let row = 0; row < rows; row += 1) {\n    for (let column = 0; column < columns; column += 1) {\n      const isLit = isLitAt(field, index, column, row);\n      lit[index] = Number(isLit);\n      if (isLit) {\n        dotOn(pen, field, column, row);\n      }\n      index += 1;\n    }\n  }\n}\n\n/** The still picture of the current mode: the light at rest, every cell already where it is going. */\nfunction poseStill(field: DitherField) {\n  field.clock = STILL_CLOCK;\n  field.horizonRise = 1;\n  restLight(field);\n  aim(field);\n  field.shown.set(field.target);\n}\n\nfunction layCells(field: DitherField, surface: Surface, isStill: boolean) {\n  const columns = Math.ceil(surface.width / field.cell);\n  const rows = Math.ceil(surface.height / field.cell);\n  const count = columns * rows;\n  const diagonals = columns + rows;\n  field.columns = columns;\n  field.rows = rows;\n  field.width = surface.width;\n  field.height = surface.height;\n  field.isStill = isStill;\n  field.hasPointer = false;\n  field.target = new Float32Array(count);\n  field.shown = new Float32Array(count);\n  field.lit = new Uint8Array(count);\n  field.edge = new Float32Array(columns);\n  field.across = new Float32Array(columns);\n  field.down = new Float32Array(rows);\n  field.falling = new Float32Array(diagonals);\n  field.rising = new Float32Array(diagonals);\n  restLight(field);\n  aim(field);\n  field.shown.set(field.target);\n}\n\n/** The light eases after its goal. It answers whether it is still on its way. */\nfunction moveLight(field: DitherField, seconds: number) {\n  const goal = goalOf(field);\n  const share = shareOf(seconds, LIGHT_EASE_S);\n  field.light.x = towards(field.light.x, goal.x, share);\n  field.light.y = towards(field.light.y, goal.y, share);\n  const offsetX = goal.x - field.light.x;\n  const offsetY = goal.y - field.light.y;\n  const distance = Math.hypot(offsetX, offsetY);\n  return distance > LIGHT_HOME_PX;\n}\n\n/** The horizon and the noise never rest. The pointer light rests once it has reached a pointer that stays still. */\nfunction stepDots(field: DitherField, surface: Surface, seconds: number) {\n  if (field.isStill) {\n    return AT_REST;\n  }\n  field.clock += seconds;\n  const riseShare = shareOf(seconds, HORIZON_RISE_S);\n  field.horizonRise = towards(field.horizonRise, 1, riseShare);\n  const isTravelling = moveLight(field, seconds);\n  aim(field);\n  const cellShare = shareOf(seconds, CELL_EASE_S);\n  const isEasing = easeCells(field, surface, cellShare);\n  const isLed = field.mode === 'pointer' && field.hasPointer;\n  const isMoving = isTravelling || isEasing;\n  if (isLed && !isMoving) {\n    return AT_REST;\n  }\n  return NEXT_FRAME;\n}\n\ntype DitherScene = Scene & {\n  setMode: (mode: DitherMode) => void;\n};\n\nfunction createDitherScene(size: number): DitherScene {\n  const field = fieldOf(size);\n  return {\n    ink(inks) {\n      field.inks = inks;\n    },\n    fit(surface, isStill) {\n      layCells(field, surface, isStill);\n    },\n    draw(surface) {\n      if (field.isStill) {\n        poseStill(field);\n      }\n      drawDots(field, surface);\n    },\n    step(surface, seconds) {\n      return stepDots(field, surface, seconds);\n    },\n    pointerMoved(x, y) {\n      field.pointer.x = x;\n      field.pointer.y = y;\n      field.hasPointer = true;\n    },\n    pointerLeft() {\n      field.hasPointer = false;\n    },\n    setMode(mode) {\n      const isNewHorizon = mode === 'horizon' && field.mode !== 'horizon';\n      field.mode = mode;\n      if (isNewHorizon) {\n        field.horizonRise = 0;\n      }\n    },\n  };\n}\n\nexport type DitherLightProps = {\n  className?: string;\n  /** Any colour token, such as `var(--primary)` or `var(--series-2)`. The dots wear it. */\n  hue?: string;\n  /** A glow that follows the pointer, a light that rises from the bottom edge, or noise that flows. */\n  mode?: DitherMode;\n  /** The side of a dither cell, in pixels. */\n  size?: number;\n  /** In `pointer` mode the glow follows the pointer. Without it, the glow walks by itself. */\n  interactive?: boolean;\n};\n\n/**\n * A soft light drawn as crisp dots: a 4 by 4 ordered dither of a light field, on one canvas. Each\n * frame only draws or wipes the dots that cross their threshold. It fills its parent, which must\n * be positioned. Under reduced motion the light stands still.\n */\nexport function DitherLight({\n  className,\n  hue = DEFAULT_HUE,\n  mode = 'pointer',\n  size = DEFAULT_CELL,\n  interactive = true,\n}: DitherLightProps) {\n  const stage = useRef<StageHandle>(null);\n  const scene = useMemo(() => createDitherScene(size), [size]);\n\n  useEffect(() => {\n    scene.setMode(mode);\n    stage.current?.refresh();\n  }, [scene, mode]);\n\n  return (\n    <StageCanvas\n      handleRef={stage}\n      scene={scene}\n      hue={hue}\n      isInteractive={interactive}\n      className={className}\n    />\n  );\n}\n\nconst MODES: Segment<DitherMode>[] = [\n  { value: 'pointer', label: 'Pointer' },\n  { value: 'horizon', label: 'Horizon' },\n  { value: 'noise', label: 'Noise' },\n];\n\n/** Long enough to see a mode move before the demonstration shows the next one. */\nconst MODE_HOLD_MS = 5200;\n\nexport default function Background03() {\n  const [mode, setMode] = useState<DitherMode>('pointer');\n  const steps: AutoplayStep[] = [\n    { after: MODE_HOLD_MS, run: () => setMode('horizon') },\n    { after: MODE_HOLD_MS, run: () => setMode('noise') },\n    { after: MODE_HOLD_MS, run: () => setMode('pointer') },\n  ];\n  const { ref } = useAutoplay<HTMLElement>(steps, { loopAfter: 0 });\n\n  return (\n    <DemoBand\n      ref={ref}\n      title='One light, drawn in dots'\n      background={<DitherLight mode={mode} />}\n    >\n      <Segments\n        value={mode}\n        segments={MODES}\n        onValueChange={setMode}\n        label='How the light moves'\n        className='bg-card hairline-ring ring-border'\n      />\n    </DemoBand>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/background/background-03.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/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"
}