{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "canvas-effect-core",
  "title": "Canvas Effect Core",
  "description": "BoldKit Canvas Effect core — framework-agnostic canvas lifecycle shared by every CanvasEffect: DPR-aware sizing with a pixel-count cap, pausing when off-screen or in a background tab, and prefers-reduced-motion support.",
  "registryDependencies": [
    "@boldkit/motion-core"
  ],
  "files": [
    {
      "path": "registry/default/lib/canvas-effect-core.ts",
      "content": "/**\n * BoldKit Canvas Effect Core — framework-agnostic canvas lifecycle.\n *\n * Every CanvasEffect used to hand-roll the same four concerns: size the\n * backing store, start a rAF loop, observe resize, cancel on teardown. None\n * of them paused when scrolled out of view, none paused in a background tab,\n * none capped the pixel count on a 4K display, and none respected\n * `prefers-reduced-motion` — so 19 effects × 2 frameworks each burned a full\n * core rendering pixels nobody could see.\n *\n * This owns all of it once. An effect supplies a per-frame draw function and\n * reads `canvas.width` / `canvas.height`; everything else is handled here.\n *\n * Layering mirrors motion-core: this file is framework-agnostic, and the\n * React hook (`use-canvas-effect`) and Vue composable (`useCanvasEffect`) are\n * thin wrappers over it. Adding a framework means wrapping `mountCanvasEffect`.\n *\n * SSR-safe: `mountCanvasEffect` is only ever called from a mount effect.\n */\n\nimport { prefersReducedMotion, onReducedMotionChange } from './motion-core';\n\n/**\n * Backing-store pixel ceiling. Unlike a GPU shader, these effects run a\n * per-pixel loop in JS, so area is the dominant cost.\n *\n * 1920×1080×2 leaves a retina laptop (≈2.6M px) untouched and clamps a\n * full-bleed 4K canvas (≈8.3M px) by half. Raise it for small canvases where\n * you want maximum crispness; lower it if an effect is heavy per pixel.\n */\nexport const DEFAULT_MAX_PIXEL_COUNT = 1920 * 1080 * 2;\n\nexport interface CanvasEffectOptions {\n  /** Backing-store pixel ceiling. @default 4147200 (1920×1080×2) */\n  maxPixelCount?: number;\n  /**\n   * Floor for the render scale, independent of the display's DPR. Raise to 2\n   * to supersample on 1× screens for smoother edges — at 4× the pixel cost.\n   * @default 1\n   */\n  minPixelRatio?: number;\n  /**\n   * When the user has asked for reduced motion, render a single static frame\n   * instead of animating. Set `false` only for effects whose first frame is\n   * blank and which convey no meaning without motion.\n   * @default true\n   */\n  respectReducedMotion?: boolean;\n  /**\n   * Pause the loop while the canvas is outside the viewport.\n   * @default true\n   */\n  pauseOffscreen?: boolean;\n  /**\n   * Which coordinate space the frame function draws in.\n   *\n   * - `'device'` (default) — draw in backing-store pixels, reading\n   *   `canvas.width` / `canvas.height`.\n   * - `'css'` — a scale transform is applied after every resize so the frame\n   *   function can draw in CSS pixels (`canvas.offsetWidth` / `offsetHeight`)\n   *   and still fill the canvas.\n   *\n   * This has to live here rather than in the effect: assigning `canvas.width`\n   * resets the 2D context transform, so it must be re-applied on every resize.\n   *\n   * @default 'device'\n   */\n  coordinates?: 'device' | 'css';\n}\n\n/**\n * Per-frame callback.\n *\n * @param dt     Milliseconds since the previous frame, clamped to 100ms so a\n *               backgrounded tab can't produce one enormous step. `0` on the\n *               first frame and on any redraw forced by a resize.\n * @param frames The same delta expressed in 60fps frames (`dt / 16.667`).\n *               Multiply a per-frame step by this to advance at a rate that\n *               is independent of display refresh — without it an effect runs\n *               at double speed on a 120Hz display.\n */\nexport type CanvasEffectFrame = (dt: number, frames: number) => void;\n\n/** One frame at 60fps, in milliseconds. */\nconst FRAME_MS_60 = 1000 / 60;\n\n/**\n * Setup callback. Runs once, after the canvas has been sized for the first\n * time. Allocate buffers and seed state here, then return the per-frame\n * function. Return nothing to render a single frame and stop.\n *\n * @param signal Aborted on dispose. Pass it to any listener you register\n *               (`el.addEventListener('pointermove', fn, { signal })`) and it\n *               is removed for you — the setup callback has no other place to\n *               put teardown, since its return value is the frame function.\n */\nexport type CanvasEffectSetup = (\n  ctx: CanvasRenderingContext2D,\n  canvas: HTMLCanvasElement,\n  signal: AbortSignal\n) => CanvasEffectFrame | void;\n\nexport interface CanvasEffectHandle {\n  /** Tear down: cancels the frame loop and disconnects every observer. */\n  dispose(): void;\n}\n\n/** Longest dt we'll ever hand a frame callback, in ms (≈6 frames at 60fps). */\nconst MAX_FRAME_DELTA = 100;\n\nconst noop: CanvasEffectHandle = { dispose() {} };\n\n/**\n * Mount an animated 2D canvas effect with a managed lifecycle.\n *\n * @example\n * const handle = mountCanvasEffect(canvas, (ctx) => {\n *   let t = 0\n *   return (dt) => {\n *     t += dt * 0.001\n *     ctx.clearRect(0, 0, canvas.width, canvas.height)\n *     // ...draw using canvas.width / canvas.height\n *   }\n * })\n * // later\n * handle.dispose()\n */\nexport function mountCanvasEffect(\n  canvas: HTMLCanvasElement | null | undefined,\n  setup: CanvasEffectSetup,\n  options: CanvasEffectOptions = {}\n): CanvasEffectHandle {\n  if (!canvas) return noop;\n\n  const ctx = canvas.getContext('2d');\n  if (!ctx) return noop;\n\n  const {\n    maxPixelCount = DEFAULT_MAX_PIXEL_COUNT,\n    minPixelRatio = 1,\n    respectReducedMotion = true,\n    pauseOffscreen = true,\n    coordinates = 'device',\n  } = options;\n\n  let disposed = false;\n  let raf: number | null = null;\n  let lastTime = 0;\n\n  /** Aborted on dispose; handed to `setup` for listener cleanup. */\n  const abortController = new AbortController();\n\n  /** Set by `setup`. Null until setup has run, or if setup opted out. */\n  let frame: CanvasEffectFrame | null = null;\n  let hasSetUp = false;\n\n  let isVisible = !pauseOffscreen;\n  let isTabVisible = !document.hidden;\n  let isReduced = respectReducedMotion && prefersReducedMotion();\n\n  // ────────────────────────────────────────────────────────────────\n  // Sizing\n  // ────────────────────────────────────────────────────────────────\n\n  /** CSS-pixel size of the canvas, from the ResizeObserver. */\n  let cssWidth = 0;\n  let cssHeight = 0;\n  /** True physical pixels, when the browser reports devicePixelContentBoxSize. */\n  let devicePixelWidth = 0;\n  let devicePixelHeight = 0;\n  let devicePixelsSupported = false;\n\n  /**\n   * Resize the backing store to the element's physical pixel size, clamped so\n   * total area never exceeds `maxPixelCount`.\n   *\n   * Prefers `devicePixelContentBoxSize` — the browser's own count of physical\n   * pixels, which already accounts for zoom and fractional DPR. Falls back to\n   * borderBox × devicePixelRatio.\n   *\n   * @returns true if the backing store actually changed size.\n   */\n  const applySize = (): boolean => {\n    const dpr = Math.max(1, window.devicePixelRatio || 1);\n\n    let targetWidth: number;\n    let targetHeight: number;\n\n    if (devicePixelsSupported) {\n      // Physical pixels already; only scale up if minPixelRatio demands it.\n      const supersample = Math.max(1, minPixelRatio / dpr);\n      targetWidth = devicePixelWidth * supersample;\n      targetHeight = devicePixelHeight * supersample;\n    } else {\n      const scale = Math.max(dpr, minPixelRatio);\n      targetWidth = cssWidth * scale;\n      targetHeight = cssHeight * scale;\n    }\n\n    // A zero-size parent (display:none ancestor, collapsed flex child) would\n    // make the clamp below divide by zero. Bail and keep the last good size.\n    if (targetWidth <= 0 || targetHeight <= 0) return false;\n\n    // Clamp by area, preserving aspect ratio.\n    const headroom = Math.sqrt(maxPixelCount / (targetWidth * targetHeight));\n    const clamp = Math.min(1, headroom);\n\n    // Round to whole pixels — but floor once clamping is in play, since\n    // rounding each axis up independently can push the area back over the\n    // ceiling the clamp was there to enforce.\n    const round = clamp < 1 ? Math.floor : Math.round;\n    const width = Math.max(1, round(targetWidth * clamp));\n    const height = Math.max(1, round(targetHeight * clamp));\n\n    if (canvas.width === width && canvas.height === height) return false;\n\n    canvas.width = width;\n    canvas.height = height;\n\n    // Assigning width/height resets the 2D transform, so a CSS-pixel effect\n    // needs its scale re-applied here every time — not once at setup.\n    if (coordinates === 'css') {\n      const sx = canvas.offsetWidth ? width / canvas.offsetWidth : 1;\n      const sy = canvas.offsetHeight ? height / canvas.offsetHeight : 1;\n      ctx.setTransform(sx, 0, 0, sy, 0, 0);\n    }\n\n    return true;\n  };\n\n  // ────────────────────────────────────────────────────────────────\n  // Frame loop\n  // ────────────────────────────────────────────────────────────────\n\n  /** Draw exactly one frame with dt = 0. Used for static and post-resize renders. */\n  const renderStaticFrame = () => {\n    if (disposed || !frame) return;\n    lastTime = performance.now();\n    frame(0, 0);\n  };\n\n  const tick = (now: number) => {\n    if (disposed || !frame) {\n      raf = null;\n      return;\n    }\n    const dt = Math.min(MAX_FRAME_DELTA, now - lastTime);\n    lastTime = now;\n    frame(dt, dt / FRAME_MS_60);\n    raf = requestAnimationFrame(tick);\n  };\n\n  /** True when nothing is blocking animation. */\n  const shouldAnimate = () => !disposed && !isReduced && isVisible && isTabVisible;\n\n  /**\n   * Start or stop the loop to match current visibility. Stopping cancels the\n   * rAF entirely rather than looping with a no-op, so a paused effect costs\n   * literally nothing.\n   */\n  const syncLoop = () => {\n    if (shouldAnimate()) {\n      if (raf === null) {\n        lastTime = performance.now();\n        raf = requestAnimationFrame(tick);\n      }\n    } else if (raf !== null) {\n      cancelAnimationFrame(raf);\n      raf = null;\n    }\n  };\n\n  /** Run `setup` once the canvas has a real size, then begin. */\n  const ensureSetUp = () => {\n    if (hasSetUp || disposed) return;\n    if (canvas.width <= 1 && canvas.height <= 1) return;\n    hasSetUp = true;\n    frame = setup(ctx, canvas, abortController.signal) ?? null;\n    // Paint immediately so a paused or reduced-motion effect still shows\n    // something rather than an empty canvas.\n    renderStaticFrame();\n    syncLoop();\n  };\n\n  // ────────────────────────────────────────────────────────────────\n  // Observers\n  // ────────────────────────────────────────────────────────────────\n\n  const resizeObserver = new ResizeObserver(([entry]) => {\n    if (!entry) return;\n\n    const physical = entry.devicePixelContentBoxSize?.[0];\n    if (physical) {\n      devicePixelsSupported = true;\n      devicePixelWidth = physical.inlineSize;\n      devicePixelHeight = physical.blockSize;\n    }\n    const border = entry.borderBoxSize?.[0];\n    if (border) {\n      cssWidth = border.inlineSize;\n      cssHeight = border.blockSize;\n    } else {\n      cssWidth = canvas.offsetWidth;\n      cssHeight = canvas.offsetHeight;\n    }\n\n    const changed = applySize();\n    if (!hasSetUp) {\n      ensureSetUp();\n    } else if (changed && !shouldAnimate()) {\n      // Resizing clears the backing store. A running loop repaints on its own\n      // next frame; a paused one would otherwise be left blank.\n      renderStaticFrame();\n    }\n  });\n  resizeObserver.observe(canvas);\n\n  // Seed from layout in case the ResizeObserver's first callback is late.\n  cssWidth = canvas.offsetWidth;\n  cssHeight = canvas.offsetHeight;\n  applySize();\n  ensureSetUp();\n\n  let intersectionObserver: IntersectionObserver | null = null;\n  if (pauseOffscreen && typeof IntersectionObserver !== 'undefined') {\n    intersectionObserver = new IntersectionObserver(([entry]) => {\n      isVisible = entry?.isIntersecting ?? true;\n      syncLoop();\n    });\n    intersectionObserver.observe(canvas);\n  } else {\n    isVisible = true;\n  }\n\n  const handleTabVisibility = () => {\n    isTabVisible = !document.hidden;\n    syncLoop();\n  };\n  document.addEventListener('visibilitychange', handleTabVisibility);\n\n  // React to the user toggling reduced motion mid-session, so the a11y\n  // guarantee holds without a reload.\n  const stopReducedMotionWatch = respectReducedMotion\n    ? onReducedMotionChange((reduced) => {\n        isReduced = reduced;\n        if (reduced) renderStaticFrame();\n        syncLoop();\n      })\n    : undefined;\n\n  return {\n    dispose() {\n      if (disposed) return;\n      disposed = true;\n      if (raf !== null) {\n        cancelAnimationFrame(raf);\n        raf = null;\n      }\n      frame = null;\n      abortController.abort();\n      resizeObserver.disconnect();\n      intersectionObserver?.disconnect();\n      document.removeEventListener('visibilitychange', handleTabVisibility);\n      stopReducedMotionWatch?.();\n    },\n  };\n}\n",
      "type": "registry:lib",
      "target": "lib/canvas-effect-core.ts"
    }
  ],
  "type": "registry:lib"
}