{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "grid-field",
  "type": "registry:ui",
  "title": "Grid Field",
  "description": "Graph-paper lines (or a dot grid) behind a section, with a few cells that slowly light up and fade, like squares being filled in on a worksheet. It says \"careful, measured work\" without saying anything.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "decorative",
    "effect"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/effects/grid-field.tsx",
      "target": "components/ui/effects/grid-field.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/grid-field v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/grid-field\n// What changed since: https://ds.interlace.tools/c/grid-field#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — GridField\n *\n * Graph-paper lines (or a dot grid) behind a section, with a few cells that\n * slowly light up and fade, like squares being filled in on a worksheet. It\n * says \"careful, measured work\" without saying anything.\n *\n * ## Drawn the same everywhere\n *\n * The grid, lines or dots, is one SVG `<pattern>`, so a full-bleed field\n * costs one element, not hundreds. The lit cells come from a seeded\n * generator, so the server and the browser place them identically and\n * nothing jumps at hydration. Change `seed` for a different arrangement, or\n * pass `cells` to choose them yourself.\n *\n * ## Fading the edges\n *\n * `fade` masks the field so it dissolves toward the edges (`radial`), or\n * toward the top or bottom, which keeps the grid from competing with the\n * text laid over it.\n *\n * ## Following the pointer\n *\n * With `interactive`, the cell under the pointer lights up too. The field is\n * `pointer-events-none` so it never takes a click, which means it cannot hear\n * the pointer either; the listener goes on its parent, the surface it covers.\n * One highlight square moves from cell to cell, so a field of a thousand\n * cells is still one element plus one square.\n *\n * ## Out of the way\n *\n * The root is `aria-hidden` and `pointer-events-none`, and a caller cannot\n * turn either off. Lines default to `--border` and lit cells to `--primary`.\n *\n * ## Motion\n *\n * Each lit cell breathes on its own Web Animations API timeline, offset from\n * the others, and all of them pause off screen. Under\n * `prefers-reduced-motion: reduce` the cells hold at a soft, even glow, and\n * the pointer highlight moves without fading.\n *\n * | Rule | Concept                 | Where in this file                                   |\n * | ---- | ----------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el       | `div` props (minus aria-hidden)                       |\n * | R6   | data-slot per part      | grid-field / -cell                                    |\n * | R7   | cn + ...rest            | `cn(…, className)` + `{...props}`                     |\n * | R8   | Enums, not booleans     | `mark`, `fade`                                        |\n * | R19  | Tokens only             | `--border`, `--primary` defaults                      |\n * | R25  | Client component        | the breathing runs in the browser                     |\n * | R26  | A11y                    | hidden, inert to the pointer                          |\n */\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\n\nconst FADE = {\n  none: '',\n  radial: '[mask-image:radial-gradient(ellipse_at_center,black_30%,transparent_75%)]',\n  top: '[mask-image:linear-gradient(to_bottom,transparent,black_60%)]',\n  bottom: '[mask-image:linear-gradient(to_top,transparent,black_60%)]',\n} as const;\n\n/** Mulberry32: a small seeded generator, the same sequence on every runtime. */\nfunction seeded(seed: number) {\n  let a = seed >>> 0;\n  return () => {\n    a = (a + 0x6d2b79f5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n/** The board `GridField` lights cells on: columns and rows of `cell`-sized squares. */\nconst COLS = 32;\nconst ROWS = 16;\n\n/** Cell positions (column, row) for `count` lit cells, on `GridField`'s board unless you name another. */\nexport function gridFieldCells(count: number, seed: number, cols = COLS, rows = ROWS) {\n  const next = seeded(seed);\n  const taken = new Set<string>();\n  const cells: Array<[number, number]> = [];\n  const max = Math.min(count, cols * rows);\n  while (cells.length < max) {\n    const c = Math.floor(next() * cols);\n    const r = Math.floor(next() * rows);\n    const key = `${c}:${r}`;\n    if (taken.has(key)) continue;\n    taken.add(key);\n    cells.push([c, r]);\n  }\n  return cells;\n}\n\nexport interface GridFieldProps extends Omit<React.ComponentPropsWithoutRef<'div'>, 'aria-hidden' | 'children'> {\n  /** Draw the grid as lines or as dots at the crossings. @default 'lines' */\n  mark?: 'lines' | 'dots';\n  /** Size of one cell, in pixels. @default 40 */\n  cell?: number;\n  /** How many cells light up, placed by `seed`. Ignored when `cells` is set. @default 14 */\n  lit?: number;\n  /** The cells to light, as `[column, row]` pairs, instead of seeded ones. */\n  cells?: ReadonlyArray<readonly [number, number]>;\n  /** Changes which cells light up. @default 5 */\n  seed?: number;\n  /** Colour of the lines or dots. @default 'var(--border)' */\n  lineColor?: string;\n  /** Colour of the lit cells. @default 'var(--primary)' */\n  litColor?: string;\n  /** Strongest a lit cell gets, 0 to 1. @default 0.18 */\n  intensity?: number;\n  /** Where the field dissolves. @default 'radial' */\n  fade?: keyof typeof FADE;\n  /** Set false to hold the cells still even when motion is allowed. @default true */\n  animated?: boolean;\n  /** Light the cell under the pointer as well. @default false */\n  interactive?: boolean;\n}\n\nexport function GridField({\n  mark = 'lines',\n  cell = 40,\n  lit = 14,\n  cells: chosenCells,\n  seed = 5,\n  lineColor = 'var(--border)',\n  litColor = 'var(--primary)',\n  intensity = 0.18,\n  fade = 'radial',\n  animated = true,\n  interactive = false,\n  className,\n  ...props\n}: GridFieldProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const hoverRef = React.useRef<SVGRectElement>(null);\n  const id = React.useId().replace(/:/g, '');\n  const svgRef = React.useRef<SVGSVGElement>(null);\n  const reduced = useReducedMotion();\n  const moving = animated && !reduced;\n  const seededCells = React.useMemo(() => gridFieldCells(lit, seed), [lit, seed]);\n  const cells = chosenCells ?? seededCells;\n  // Keyed by value, so an inline `cells={[[0, 0]]}` does not restart the breathing each render.\n  const cellsKey = cells.map(([c, r]) => `${c}:${r}`).join(' ');\n  const peak = Math.min(Math.max(intensity, 0), 1);\n\n  React.useEffect(() => {\n    const svg = svgRef.current;\n    if (!svg || !moving) return;\n    const rects = Array.from(svg.querySelectorAll<SVGRectElement>('[data-slot=grid-field-cell]'));\n    if (!rects.length || typeof rects[0]!.animate !== 'function') return;\n    const next = seeded(seed + 1);\n    const animations = rects.map((rect) =>\n      rect.animate([{ opacity: 0 }, { opacity: peak }, { opacity: 0 }], {\n        duration: 4000 + next() * 4000,\n        delay: -next() * 8000,\n        iterations: Infinity,\n        easing: 'ease-in-out',\n      }),\n    );\n    const io =\n      typeof IntersectionObserver === 'undefined'\n        ? null\n        : new IntersectionObserver(([entry]) => {\n            for (const a of animations) {\n              if (entry?.isIntersecting) a.play();\n              else a.pause();\n            }\n          });\n    io?.observe(svg);\n    return () => {\n      io?.disconnect();\n      for (const a of animations) a.cancel();\n    };\n  }, [moving, cellsKey, seed, peak]);\n\n  React.useEffect(() => {\n    const root = rootRef.current;\n    const hover = hoverRef.current;\n    const surface = root?.parentElement;\n    if (!interactive || !root || !hover || !surface) return;\n    const onMove = (event: PointerEvent) => {\n      const box = root.getBoundingClientRect();\n      const c = Math.floor((event.clientX - box.left) / cell);\n      const r = Math.floor((event.clientY - box.top) / cell);\n      hover.setAttribute('x', String(c * cell + 1));\n      hover.setAttribute('y', String(r * cell + 1));\n      hover.style.opacity = String(peak);\n    };\n    const onLeave = () => {\n      hover.style.opacity = '0';\n    };\n    surface.addEventListener('pointermove', onMove, { passive: true });\n    surface.addEventListener('pointerleave', onLeave);\n    return () => {\n      surface.removeEventListener('pointermove', onMove);\n      surface.removeEventListener('pointerleave', onLeave);\n    };\n  }, [interactive, cell, peak]);\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"grid-field\"\n      className={cn('pointer-events-none absolute inset-0 -z-10 overflow-hidden', FADE[fade], className)}\n      {...props}\n      aria-hidden\n    >\n      <svg ref={svgRef} className=\"absolute inset-0 size-full\">\n        <defs>\n          <pattern id={`${id}-grid`} width={cell} height={cell} patternUnits=\"userSpaceOnUse\">\n            {mark === 'dots' ? (\n              <circle cx={0.5} cy={0.5} r={1.25} fill={lineColor} />\n            ) : (\n              <path d={`M ${cell} 0 L 0 0 0 ${cell}`} fill=\"none\" stroke={lineColor} strokeWidth={1} />\n            )}\n          </pattern>\n        </defs>\n        <rect width=\"100%\" height=\"100%\" fill={`url(#${id}-grid)`} />\n        {cells.map(([c, r]) => (\n          <rect\n            key={`${c}:${r}`}\n            data-slot=\"grid-field-cell\"\n            x={c * cell + 1}\n            y={r * cell + 1}\n            width={cell - 1}\n            height={cell - 1}\n            fill={litColor}\n            opacity={moving ? 0 : peak * 0.6}\n          />\n        ))}\n        {interactive ? (\n          <rect\n            ref={hoverRef}\n            data-slot=\"grid-field-hover\"\n            width={cell - 1}\n            height={cell - 1}\n            fill={litColor}\n            style={{ opacity: 0 }}\n            className={reduced ? undefined : 'transition-opacity duration-300 ease-out'}\n          />\n        ) : null}\n      </svg>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "tier": "effect",
    "client": true,
    "minViewport": null,
    "loading": false,
    "version": "1.0.0",
    "since": null
  },
  "docs": "## @interlace/grid-field\n\nInstalled to `components/ui/effects/grid-field.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/effects/grid-field';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/grid-field\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
