{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "masonry-ascii-settle",
  "title": "Masonry ASCII Settle",
  "description": "A masonry gallery whose tiles render as live ASCII halftone and resolve from a coarse print to a fine one as they drop into their packed column slot, re-packing and re-dropping every tile when a resize crosses a column-count breakpoint.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/masonry-ascii-settle/component.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\n// ---------------------------------------------------------------------------\n// MasonryAsciiSettle — a masonry gallery where every tile renders as live\n// ASCII halftone (a deterministic noise field mapped to a \" .:-=+*#%@\" glyph\n// ramp, redrawn on <canvas>) that RESOLVES from a coarse print to a fine one\n// exactly as the tile drops into its packed column slot: glyph pitch and drop\n// offset ease together on one rAF loop, so \"settling\" is a real resolution\n// change, not a decorative fade layered over a CSS `columns` snap. Column\n// packing is this component's own shortest-column-first math (own math, not\n// CSS `columns`, which flows top-to-bottom per column and can't be re-packed\n// on demand). A container resize that crosses a column-count breakpoint\n// re-packs every tile into its new column and replays the full coarse ->\n// fine drop for all of them, staggered by row order — the reflow IS the\n// interaction. This differs from gallery-coverflow-caustic (a 3D coverflow\n// carousel with frosted-glass caustics, one card focused at a time, no\n// masonry packing and no ASCII), testimonial-wall-reflow (FLIP-reflows real\n// text cards on an expand/collapse toggle, no image content and no\n// resolution mechanic), and logo-cloud-settle (drops static SVG marks once\n// per viewport entry with no live rendering and no re-pack on resize).\n// ---------------------------------------------------------------------------\n\nexport interface MasonryAsciiTile {\n  id: string;\n  title: string;\n  /** noise seed for the generated ASCII field */\n  seed: number;\n  /** height as a multiple of the column width */\n  aspect: number;\n}\n\nexport interface MasonryAsciiSettleProps {\n  /** the tiles, laid into the masonry grid and settling into place */\n  tiles: MasonryAsciiTile[];\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\nconst GAP = 14;\nconst COARSE_PITCH = 15;\nconst FINE_PITCH = 6;\nconst DROP_MS = 620;\nconst STAGGER_MS = 55;\nconst DROP_PX = 26;\nconst RAMP = \" .:-=+*#%@\";\n\nfunction columnsFor(width: number): number {\n  if (width < 520) return 1;\n  if (width < 860) return 2;\n  return 3;\n}\n\nfunction hash2(x: number, y: number) {\n  const n = Math.sin(x * 127.1 + y * 311.7) * 43758.5453123;\n  return n - Math.floor(n);\n}\nfunction vnoise(x: number, y: number) {\n  const xi = Math.floor(x);\n  const yi = Math.floor(y);\n  const xf = x - xi;\n  const yf = y - yi;\n  const u = xf * xf * (3 - 2 * xf);\n  const v = yf * yf * (3 - 2 * yf);\n  const a = hash2(xi, yi);\n  const b = hash2(xi + 1, yi);\n  const c = hash2(xi, yi + 1);\n  const d = hash2(xi + 1, yi + 1);\n  return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;\n}\nfunction noise2(x: number, y: number) {\n  return 0.6 * vnoise(x, y) + 0.4 * vnoise(x * 2.1 + 11.3, y * 2.1 + 4.7);\n}\n\nfunction easeOutCubic(t: number) {\n  const c = Math.min(1, Math.max(0, t));\n  return 1 - Math.pow(1 - c, 3);\n}\n\ninterface Tokens {\n  fg: string;\n  bg: 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 { fg: get(\"--foreground\", \"#ededed\"), bg: get(\"--surface\", \"#171717\") };\n}\n\ntype Pos = { x: number; y: number; w: number; h: number };\n\nfunction pack(order: string[], sizeOf: (id: string) => number, cols: number, colW: number) {\n  const colH = new Array(cols).fill(0);\n  const pos: Record<string, Pos> = {};\n  for (const id of order) {\n    let target = 0;\n    for (let c = 1; c < cols; c++) if (colH[c] < colH[target]) target = c;\n    const h = sizeOf(id);\n    pos[id] = { x: target * (colW + GAP), y: colH[target], w: colW, h };\n    colH[target] += h + GAP;\n  }\n  const maxH = Math.max(0, ...colH.map((h) => Math.max(0, h - GAP)));\n  return { pos, maxH };\n}\n\nexport function MasonryAsciiSettle({ tiles, className = \"\" }: MasonryAsciiSettleProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const canvasRefs = useRef<Record<string, HTMLCanvasElement | null>>({});\n  const wrapRefs = useRef<Record<string, HTMLDivElement | null>>({});\n  const prevColsRef = useRef<number | null>(null);\n  const dropStartRef = useRef<Record<string, number>>({});\n  const tokensRef = useRef<Tokens>(typeof document === \"undefined\" ? { fg: \"#ededed\", bg: \"#171717\" } : readTokens());\n  const reducedRef = useRef(false);\n  const rafRef = useRef(0);\n  const [containerHeight, setContainerHeight] = useState(0);\n  const [colW, setColW] = useState(0);\n  const [posMap, setPosMap] = useState<Record<string, Pos>>({});\n\n  const ids = useMemo(() => tiles.map((t) => t.id), [tiles]);\n  const byId = useMemo(() => {\n    const m = new Map<string, MasonryAsciiTile>();\n    tiles.forEach((t) => m.set(t.id, t));\n    return m;\n  }, [tiles]);\n\n  const layout = useCallback(\n    (replay: boolean) => {\n      const container = containerRef.current;\n      if (!container) return;\n      const width = container.getBoundingClientRect().width;\n      if (width < 4) return;\n      const cols = columnsFor(width);\n      const w = (width - GAP * (cols - 1)) / cols;\n      setColW(w);\n\n      const sizeOf = (id: string) => w * (byId.get(id)?.aspect ?? 1);\n      const { pos, maxH } = pack(ids, sizeOf, cols, w);\n      setPosMap(pos);\n      setContainerHeight(maxH);\n\n      const colsChanged = prevColsRef.current !== null && prevColsRef.current !== cols;\n      prevColsRef.current = cols;\n\n      if (replay && (colsChanged || dropStartRef.current[\"__first\"] === undefined)) {\n        dropStartRef.current[\"__first\"] = 1;\n        const now = performance.now();\n        // stagger by final row (y), then column (x), so the reflow reads top\n        // to bottom, left to right\n        const order = [...ids].sort((a, b) => {\n          const pa = pos[a];\n          const pb = pos[b];\n          if (!pa || !pb) return 0;\n          if (Math.abs(pa.y - pb.y) > 1) return pa.y - pb.y;\n          return pa.x - pb.x;\n        });\n        order.forEach((id, i) => {\n          dropStartRef.current[id] = now + i * STAGGER_MS;\n        });\n        wake();\n      }\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [ids, byId]\n  );\n\n  const wake = () => {\n    if (rafRef.current) return;\n    rafRef.current = requestAnimationFrame(loop);\n  };\n\n  const loop = () => {\n    rafRef.current = 0;\n    const now = performance.now();\n    let stillAnimating = false;\n\n    for (const id of ids) {\n      const canvas = canvasRefs.current[id];\n      const wrap = wrapRefs.current[id];\n      if (!canvas || !wrap) continue;\n      const start = dropStartRef.current[id];\n      const tile = byId.get(id);\n      if (!tile) continue;\n\n      let t = 1;\n      if (start !== undefined && !reducedRef.current) {\n        const elapsed = now - start;\n        if (elapsed < 0) {\n          t = 0;\n          stillAnimating = true;\n        } else {\n          t = Math.min(1, elapsed / DROP_MS);\n          if (t < 1) stillAnimating = true;\n        }\n      }\n      const eased = easeOutCubic(t);\n      wrap.style.transform = `translateY(${(1 - eased) * -DROP_PX}px)`;\n      wrap.style.opacity = String(0.15 + 0.85 * eased);\n\n      const pitch = COARSE_PITCH + (FINE_PITCH - COARSE_PITCH) * eased;\n      paintTile(canvas, tile.seed, pitch);\n    }\n\n    if (stillAnimating) rafRef.current = requestAnimationFrame(loop);\n  };\n\n  const paintTile = (canvas: HTMLCanvasElement, seed: number, pitch: number) => {\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n    const dpr = Math.min(window.devicePixelRatio || 1, 2);\n    const cssW = canvas.clientWidth || 1;\n    const cssH = canvas.clientHeight || 1;\n    const targetW = Math.ceil(cssW * dpr);\n    const targetH = Math.ceil(cssH * dpr);\n    if (canvas.width !== targetW || canvas.height !== targetH) {\n      canvas.width = targetW;\n      canvas.height = targetH;\n    }\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    const { fg, bg } = tokensRef.current;\n    ctx.fillStyle = bg;\n    ctx.fillRect(0, 0, cssW, cssH);\n\n    const cols = Math.max(1, Math.ceil(cssW / pitch));\n    const rows = Math.max(1, Math.ceil(cssH / pitch));\n    const cellW = cssW / cols;\n    const cellH = cssH / rows;\n    ctx.fillStyle = fg;\n    ctx.font = `${Math.max(6, Math.round(cellH * 0.95))}px \"GeistMono\", ui-monospace, monospace`;\n    ctx.textAlign = \"center\";\n    ctx.textBaseline = \"middle\";\n    for (let gy = 0; gy < rows; gy++) {\n      for (let gx = 0; gx < cols; gx++) {\n        const raw = Math.min(1, Math.max(0, noise2(gx * 0.3 + seed * 13.7, gy * 0.3 + seed * 5.1)));\n        // Raw value-noise clusters tightly around the middle of the ramp —\n        // every cell prints some mid-weight character and the tile reads as\n        // uniform static, no negative space, no filaments. Power-sharpening\n        // the same field (same seed, same mechanic) pushes most cells to\n        // blank and only real peaks to the top of the ramp, so a tile reads\n        // as sparse bright structure on paper rather than gray noise.\n        const v = Math.pow(raw, 2.4);\n        const idx = Math.min(RAMP.length - 1, Math.floor(v * RAMP.length));\n        const ch = RAMP[idx];\n        if (!ch || ch === \" \") continue;\n        ctx.fillText(ch, gx * cellW + cellW / 2, gy * cellH + cellH / 2);\n      }\n    }\n  };\n\n  useLayoutEffect(() => {\n    reducedRef.current = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    tokensRef.current = readTokens();\n    layout(true);\n    const container = containerRef.current;\n    if (!container) return;\n    const ro = new ResizeObserver(() => layout(true));\n    ro.observe(container);\n    const mo = new MutationObserver(() => {\n      tokensRef.current = readTokens();\n      wake();\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\"] });\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      cancelAnimationFrame(rafRef.current);\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  useEffect(() => {\n    layout(true);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [tiles]);\n\n  return (\n    <div\n      ref={containerRef}\n      className={`relative w-full ${className}`}\n      style={{ height: containerHeight || undefined }}\n    >\n      {tiles.map((tile) => {\n        const p = posMap[tile.id];\n        return (\n          <div\n            key={tile.id}\n            ref={(el) => {\n              wrapRefs.current[tile.id] = el;\n            }}\n            data-masonry-tile={tile.id}\n            className=\"absolute overflow-hidden rounded-md border border-border will-change-transform\"\n            style={{\n              left: p?.x ?? 0,\n              top: p?.y ?? 0,\n              width: p?.w ?? colW,\n              height: p?.h ?? colW,\n            }}\n          >\n            <canvas\n              ref={(el) => {\n                canvasRefs.current[tile.id] = el;\n              }}\n              aria-hidden\n              className=\"block h-full w-full\"\n            />\n            <span className=\"pointer-events-none absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-background/90 to-transparent px-3 py-2 font-mono text-[11px] text-foreground\">\n              {tile.title}\n            </span>\n          </div>\n        );\n      })}\n      <p className=\"sr-only\">\n        {tiles.length} images: {tiles.map((t) => t.title).join(\", \")}.\n      </p>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/masonry-ascii-settle.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-surface": "var(--surface)"
    },
    "light": {
      "surface": "#fafafa"
    },
    "dark": {
      "surface": "#171717"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "masonry",
      "gallery",
      "ascii",
      "canvas",
      "settle",
      "ink"
    ],
    "instruction": "Build <MasonryAsciiSettle tiles className?> where tiles is MasonryAsciiTile[] ({id, title, seed, aspect}), aspect being the tile's height as a multiple of its column width. PACKING: own shortest-column-first math (never CSS `columns`, which flows top-to-bottom per column and cannot be re-packed on demand) — columnsFor(width) breaks at 1 column below 520px, 2 below 860px, 3 above; column width is (containerWidth - gap*(cols-1))/cols and each tile's height is columnWidth*aspect, packed by always placing the next tile into the currently-shortest column. THE MECHANIC: each tile is a <canvas> rendering a deterministic 2-octave value-noise field (per-tile seed) as literal ASCII glyphs from a \" .:-=+*#%@\" luminance ramp, drawn via ctx.fillText at a glyph pitch that EASES from a coarse ~15px cell down to a fine ~6px cell over ~620ms (eased, one rAF loop redrawing every animating tile's canvas each frame) — this is a real resolution change, not a fade or blur filter over a fixed image. That same eased progress simultaneously drives the tile's drop: translateY from -26px to 0 and opacity from ~0.15 to 1, so the tile visibly resolves into focus at the exact moment it lands in its slot. Every tile's drop is staggered ~55ms apart in final top-to-bottom, left-to-right order. On mount, and again any time a ResizeObserver on the container detects the column COUNT itself has changed (not just column width), every tile's position is recomputed via the packing pass and the FULL coarse-to-fine drop replays for every tile, staggered by its NEW position — a resize that changes column count is a real re-pack with visible re-drops, not a CSS reflow that snaps. A resize that keeps the same column count only updates each tile's pixel position/size with no replay. Canvas ink is var(--foreground) on a var(--surface) tile background, both 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. This is a display-only gallery — no buttons, nothing to tab to — so an sr-only paragraph lists every tile's title as its accessible content. `prefers-reduced-motion` renders every tile already at its fine pitch and final position on the first paint, skipping the drop and the resolution ease entirely, though re-packing on a column-count-changing resize still recomputes positions instantly. Zero dependencies."
  },
  "type": "registry:ui"
}