{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "feature-grid-ascii-rule",
  "title": "Feature Grid ASCII Rule",
  "description": "A feature grid where hovering or focusing a cell draws real box-drawing connectors to its related features, routed orthogonally through the grid's gutters and retracted glyph by glyph on leave.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/feature-grid-ascii-rule/component.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\n\n// ---------------------------------------------------------------------------\n// FeatureGridAsciiRule — a feature grid where hovering or focusing a cell\n// draws real box-drawing connectors between it and its related features,\n// routed orthogonally through the grid's own gutters (never straight through\n// a neighbouring cell). Every related pair always meets at the ONE shared\n// horizontal gutter between the two rows: the connector drops from the\n// source cell's gutter-facing edge, runs across at the gutter's mid-line,\n// then rises into the target cell's gutter-facing edge — a uniform 3-segment\n// Manhattan route regardless of which rows the two cells sit in, rasterized\n// into individual ─ │ ┌ ┐ └ ┘ glyphs at a fixed pitch and revealed glyph by\n// glyph (source -> target) on entry, retracted glyph by glyph in the\n// opposite order (target -> source) on leave. This is a distinct mechanic\n// from grid-bento-ascii (one static seam that structurally disappears when a\n// single tile re-spans the whole grid — no relationships, no routing, no\n// second cell involved once expanded), grid-bento-dense (FLIP reflow of tile\n// footprints, no connectors at all) and grid-magnetic-lattice (a continuous\n// cursor-warped field sampled by every line at once, not discrete per-pair\n// routes tied to a data relationship).\n// ---------------------------------------------------------------------------\n\nexport interface FeatureGridAsciiRuleItem {\n  id: string;\n  title: string;\n  description: string;\n  /** ids of other items in this same array this feature relates to */\n  relatedIds: string[];\n}\n\nexport interface FeatureGridAsciiRuleProps {\n  /** the feature cards */\n  items: FeatureGridAsciiRuleItem[];\n  /** number of grid columns */\n  cols?: number;\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\ninterface Tokens {\n  fg: string;\n  border: string;\n  accent: string;\n}\n\nfunction readTokens(): Tokens {\n  const cs = getComputedStyle(document.documentElement);\n  const get = (name: string, fallback: string) => cs.getPropertyValue(name).trim() || fallback;\n  return {\n    fg: get(\"--foreground\", \"#ededed\"),\n    border: get(\"--border\", \"#2e2e2e\"),\n    accent: get(\"--ns-accent\", \"#006bff\"),\n  };\n}\n\nconst PITCH = 11; // px per glyph, both axes\nconst STAGGER = 26; // ms per glyph step\nconst FADE = 140; // ms per glyph's own fade\n\ntype GlyphKind = \"h\" | \"v\" | \"corner\";\n\ninterface Glyph {\n  x: number;\n  y: number;\n  ch: string;\n  kind: GlyphKind;\n  dist: number; // step index from source (0-based)\n}\n\nfunction corner(vert: \"up\" | \"down\", horiz: \"left\" | \"right\"): string {\n  if (vert === \"up\" && horiz === \"right\") return \"└\"; // └\n  if (vert === \"up\" && horiz === \"left\") return \"┘\"; // ┘\n  if (vert === \"down\" && horiz === \"right\") return \"┌\"; // ┌\n  return \"┐\"; // ┐\n}\n\n/** Builds the glyph list for one source -> target connector, routed through\n *  the single shared horizontal gutter between the two grid rows. */\nfunction routeGlyphs(\n  a: DOMRect,\n  b: DOMRect,\n  aIsTopRow: boolean,\n  bIsTopRow: boolean,\n  containerRect: DOMRect,\n  gutterY: number\n): Glyph[] {\n  const ax = a.left + a.width / 2 - containerRect.left;\n  const bx = b.left + b.width / 2 - containerRect.left;\n  const aEdgeY = (aIsTopRow ? a.bottom : a.top) - containerRect.top;\n  const bEdgeY = (bIsTopRow ? b.bottom : b.top) - containerRect.top;\n\n  const glyphs: Glyph[] = [];\n  let step = 0;\n\n  // Anchor dot right on the source cell's own edge — without an explicit\n  // mark here the connector's first glyph was drawn centered ON the\n  // boundary line (half hidden behind the card), so the wire read as\n  // fading into nothing rather than visibly plugging into the cell.\n  glyphs.push({ x: ax, y: aEdgeY, ch: \"●\", kind: \"corner\", dist: step++ });\n\n  // vertical run from the source cell's gutter-facing edge to the gutter line\n  const v1Steps = Math.max(1, Math.round(Math.abs(gutterY - aEdgeY) / PITCH));\n  for (let i = 1; i <= v1Steps; i++) {\n    const y = aEdgeY + ((gutterY - aEdgeY) * i) / v1Steps;\n    glyphs.push({ x: ax, y, ch: \"│\", kind: \"v\", dist: step++ });\n  }\n\n  // bend 1: connects back toward the source (vert) and across toward bend 2 (horiz)\n  const vert1: \"up\" | \"down\" = aIsTopRow ? \"up\" : \"down\";\n  const horiz1: \"left\" | \"right\" = bx >= ax ? \"right\" : \"left\";\n  if (Math.abs(bx - ax) > 1) {\n    glyphs.push({ x: ax, y: gutterY, ch: corner(vert1, horiz1), kind: \"corner\", dist: step++ });\n\n    // horizontal run across the gutter\n    const hSteps = Math.max(1, Math.round(Math.abs(bx - ax) / PITCH));\n    for (let i = 1; i < hSteps; i++) {\n      const x = ax + ((bx - ax) * i) / hSteps;\n      glyphs.push({ x, y: gutterY, ch: \"─\", kind: \"h\", dist: step++ });\n    }\n\n    // bend 2: connects back toward bend 1 (horiz) and up/down toward the target (vert)\n    const vert2: \"up\" | \"down\" = bIsTopRow ? \"up\" : \"down\";\n    const horiz2: \"left\" | \"right\" = horiz1 === \"right\" ? \"left\" : \"right\";\n    glyphs.push({ x: bx, y: gutterY, ch: corner(vert2, horiz2), kind: \"corner\", dist: step++ });\n  } else {\n    // same column: no bend needed, straight vertical line the whole way\n  }\n\n  // vertical run from the gutter to the target cell's gutter-facing edge\n  const v2Steps = Math.max(1, Math.round(Math.abs(bEdgeY - gutterY) / PITCH));\n  for (let i = 1; i <= v2Steps; i++) {\n    const y = gutterY + ((bEdgeY - gutterY) * i) / v2Steps;\n    glyphs.push({ x: bx, y, ch: \"│\", kind: \"v\", dist: step++ });\n  }\n\n  // Anchor dot on the target cell's edge, same reasoning as the source\n  // anchor — this is the glyph that reads \"arrived\", so it's also the\n  // first thing to fade on leave (retraction runs target -> source).\n  glyphs.push({ x: bx, y: bEdgeY, ch: \"●\", kind: \"corner\", dist: step++ });\n\n  return glyphs;\n}\n\nfunction easeOutCubic(t: number): number {\n  const c = Math.min(1, Math.max(0, t));\n  return 1 - Math.pow(1 - c, 3);\n}\n\nexport function FeatureGridAsciiRule({ items, cols = 3, className = \"\" }: FeatureGridAsciiRuleProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const cellRefs = useRef<Record<string, HTMLButtonElement | null>>({});\n  const [tokens, setTokens] = useState<Tokens>(() =>\n    typeof document === \"undefined\" ? { fg: \"#ededed\", border: \"#2e2e2e\", accent: \"#006bff\" } : readTokens()\n  );\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const reducedRef = useRef(false);\n\n  const byId = useMemo(() => {\n    const m = new Map<string, FeatureGridAsciiRuleItem>();\n    items.forEach((it) => m.set(it.id, it));\n    return m;\n  }, [items]);\n\n  const rows = Math.ceil(items.length / cols);\n\n  useEffect(() => {\n    const sync = () => setTokens(readTokens());\n    sync();\n    const mo = new MutationObserver(sync);\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\"] });\n    return () => mo.disconnect();\n  }, []);\n\n  useEffect(() => {\n    reducedRef.current = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n  }, []);\n\n  // active/last-active tracked with a transition timestamp so leaving\n  // animates a real retraction rather than an instant clear\n  const stateRef = useRef<{ id: string | null; since: number; leavingId: string | null }>({\n    id: null,\n    since: 0,\n    leavingId: null,\n  });\n\n  useEffect(() => {\n    const now = performance.now();\n    if (activeId) {\n      stateRef.current = { id: activeId, since: now, leavingId: null };\n    } else if (stateRef.current.id) {\n      stateRef.current = { id: null, since: now, leavingId: stateRef.current.id };\n    }\n  }, [activeId]);\n\n  useEffect(() => {\n    const container = containerRef.current;\n    const canvas = canvasRef.current;\n    if (!container || !canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    let raf = 0;\n\n    const sizeCanvas = () => {\n      const rect = container.getBoundingClientRect();\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      canvas.width = Math.ceil(rect.width * dpr);\n      canvas.height = Math.ceil(rect.height * dpr);\n      canvas.style.width = `${rect.width}px`;\n      canvas.style.height = `${rect.height}px`;\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    };\n    sizeCanvas();\n    const ro = new ResizeObserver(sizeCanvas);\n    ro.observe(container);\n\n    const draw = () => {\n      const rect = container.getBoundingClientRect();\n      ctx.clearRect(0, 0, rect.width, rect.height);\n\n      const st = stateRef.current;\n      const showId = st.id ?? st.leavingId;\n      if (showId) {\n        const source = byId.get(showId);\n        const sourceEl = cellRefs.current[showId];\n        if (source && sourceEl) {\n          const aRect = sourceEl.getBoundingClientRect();\n          const aRow = Object.keys(cellRefs.current).indexOf(showId); // fallback, unused\n          const aIndex = items.findIndex((it) => it.id === showId);\n          const aTopRow = Math.floor(aIndex / cols) === 0;\n          const rowGutterTop = Math.min(...items.map((_, i) => (Math.floor(i / cols) === 0 ? 1 : 0)));\n          void aRow;\n          void rowGutterTop;\n\n          // gutter mid-line: between row 0's bottom and row 1's top, using the\n          // first cell of each row actually present\n          const row0El = cellRefs.current[items[0]?.id ?? \"\"];\n          const row1Idx = items.findIndex((_, i) => Math.floor(i / cols) === 1);\n          const row1El = row1Idx >= 0 ? cellRefs.current[items[row1Idx]!.id] : null;\n          const gutterY =\n            row0El && row1El\n              ? (row0El.getBoundingClientRect().bottom + row1El.getBoundingClientRect().top) / 2 -\n                rect.top\n              : aRect.bottom - rect.top;\n\n          const now = performance.now();\n          const elapsed = now - st.since;\n          const advancing = st.id === showId;\n\n          ctx.font = `${PITCH}px \"GeistMono\", ui-monospace, monospace`;\n          ctx.textAlign = \"center\";\n          ctx.textBaseline = \"middle\";\n\n          for (const relId of source.relatedIds) {\n            const targetEl = cellRefs.current[relId];\n            const bIndex = items.findIndex((it) => it.id === relId);\n            if (!targetEl || bIndex < 0) continue;\n            const bRect = targetEl.getBoundingClientRect();\n            const bTopRow = Math.floor(bIndex / cols) === 0;\n            const glyphs = routeGlyphs(aRect, bRect, aTopRow, bTopRow, rect, gutterY);\n            const n = Math.max(1, glyphs.length);\n\n            for (const g of glyphs) {\n              let opacity: number;\n              if (reducedRef.current) {\n                opacity = advancing ? 1 : 0;\n              } else if (advancing) {\n                const t = (elapsed - g.dist * STAGGER) / FADE;\n                opacity = easeOutCubic(t);\n              } else {\n                // retract target-first: glyphs nearer the target (higher dist)\n                // fade out earlier than glyphs nearer the source\n                const revIndex = n - 1 - g.dist;\n                const t = (elapsed - revIndex * STAGGER) / FADE;\n                opacity = 1 - easeOutCubic(t);\n              }\n              if (opacity <= 0.01) continue;\n              // Anchor dots draw in --ns-accent so both ends read as a clear\n              // \"plugged in\" terminal against the fg-colored border glyphs;\n              // the run between them stays --foreground so the accent reads\n              // as an endpoint marker, not a wash over the whole wire.\n              ctx.fillStyle = g.ch === \"●\" ? tokens.accent : tokens.fg;\n              ctx.globalAlpha = Math.min(1, Math.max(0, opacity)) * (g.ch === \"●\" ? 1 : 0.9);\n              ctx.fillText(g.ch, g.x, g.y);\n            }\n          }\n          ctx.globalAlpha = 1;\n        }\n      }\n\n      const st2 = stateRef.current;\n      const stillLeaving = st2.leavingId && performance.now() - st2.since < STAGGER * 20 + FADE + 40;\n      if (!stillLeaving && st2.leavingId) {\n        stateRef.current = { id: st2.id, since: st2.since, leavingId: null };\n      }\n      const active = st2.id !== null || (st2.leavingId !== null && stillLeaving);\n      if (active || !reducedRef.current) {\n        raf = requestAnimationFrame(draw);\n      }\n    };\n    raf = requestAnimationFrame(draw);\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n    };\n  }, [byId, items, cols, tokens]);\n\n  return (\n    <div ref={containerRef} className={`relative w-full ${className}`}>\n      <canvas ref={canvasRef} aria-hidden className=\"ns-fgar-canvas pointer-events-none absolute inset-0 z-10\" />\n      <div\n        className=\"relative grid gap-x-10 gap-y-8\"\n        style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}\n      >\n        {items.map((item) => {\n          const isActive = activeId === item.id;\n          const isRelated = activeId != null && byId.get(activeId)?.relatedIds.includes(item.id);\n          return (\n            <button\n              key={item.id}\n              type=\"button\"\n              ref={(el) => {\n                cellRefs.current[item.id] = el;\n              }}\n              data-feature-cell={item.id}\n              aria-label={`${item.title}: ${item.description}`}\n              onPointerEnter={() => setActiveId(item.id)}\n              onPointerLeave={() => setActiveId((c) => (c === item.id ? null : c))}\n              onFocus={() => setActiveId(item.id)}\n              onBlur={() => setActiveId((c) => (c === item.id ? null : c))}\n              className={`group relative flex flex-col items-start gap-1.5 rounded-md border p-4 text-left transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ns-accent ${\n                isActive\n                  ? \"border-foreground/40 bg-surface\"\n                  : isRelated\n                    ? \"border-foreground/25 bg-surface/60\"\n                    : \"border-border bg-surface hover:border-foreground/20\"\n              }`}\n            >\n              <span className=\"font-mono text-[10px] uppercase tracking-widest text-ns-muted\">\n                {String(items.indexOf(item) + 1).padStart(2, \"0\")}\n              </span>\n              <span className=\"text-sm font-semibold text-foreground\">{item.title}</span>\n              <span className=\"text-xs text-ns-muted\">{item.description}</span>\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/feature-grid-ascii-rule.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)",
      "color-ns-accent": "var(--ns-accent)",
      "color-surface": "var(--surface)"
    },
    "light": {
      "ns-muted": "#4d4d4d",
      "ns-accent": "#006bff",
      "surface": "#fafafa"
    },
    "dark": {
      "ns-muted": "#8f8f8f",
      "surface": "#171717"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "grid",
      "feature",
      "ascii",
      "mono",
      "box-drawing",
      "canvas"
    ],
    "instruction": "Build <FeatureGridAsciiRule items cols? className?> where items is FeatureGridAsciiRuleItem[] ({id, title, description, relatedIds: string[]}) laid out in a CSS grid (default 3 columns, 2 rows for 6 items). Each cell is a real <button data-feature-cell={id} aria-label=\"{title}: {description}\"> so hover, focus and click all reach it natively. A single <canvas aria-hidden> absolutely covers the grid. THE MECHANIC: on pointer-enter or focus of a cell, for every id in that cell's relatedIds, a connector is routed from the source cell to the target cell through the ONE shared horizontal gutter between the grid's two rows — never straight through an intervening cell. The route is always 3 orthogonal segments measured live via getBoundingClientRect: a vertical run from the source cell's gutter-facing edge (bottom edge if it's in the top row, top edge if bottom row) down/up to the gutter's mid-line, a horizontal run across the gutter to the target's x, and a vertical run into the target's gutter-facing edge — collapsing to a single straight vertical run when both cells share the same column. This whole path is rasterized into individual box-drawing glyphs (─ for horizontal steps, │ for vertical steps, one of ┌ ┐ └ ┘ at each bend, chosen by which two of up/down/left/right that bend actually connects) at a fixed ~11px pitch, each drawn via ctx.fillText in a monospace face. Glyphs reveal one at a time, source to target, on a per-glyph stagger (~26ms step, ~140ms own fade, eased) while the pointer/focus is on the source cell; on pointer-leave or blur they retract in the OPPOSITE order — the glyphs nearest the target fade first, working back toward the source — driven by one rAF loop keyed off an activation timestamp, never a CSS transition per glyph (there is no DOM node per glyph). Only one cell's connectors are visible at a time. Colors are token-only: canvas ink is var(--foreground) read via getComputedStyle at mount and re-read through a MutationObserver on the root's class/style attributes, so both themes stay correct with no remount; cell borders and backgrounds are Tailwind token utilities. Reduced motion skips the stagger/fade entirely: connectors snap fully in on activation and fully out on deactivation in one paint. Zero dependencies."
  },
  "type": "registry:ui"
}