{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bayer-fill-button","type":"registry:component","title":"Bayer Fill Button","description":"A button whose fill prints in cell by cell through the 8x8 Bayer order on hover and focus, with its label inverting exactly where each cell lands; press it and the screen halves to a finer grid.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/bayer-fill-button.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from \"react\";\n\n/**\n * BayerFillButton — a button whose fill prints in, cell by cell.\n *\n * Hover or focus it and the fill develops through the 8x8 Bayer order to\n * solid in about 260ms (and back out in 360ms); the label inverts exactly\n * where each cell lands, because the inverted label lives inside the masked\n * fill. Press it and the screen halves to a finer grid. Signal, paper and\n * ghost inks; `lit` holds it filled for a chosen option. CSS masks and a\n * small animation loop, no canvas.\n *\n * Part of the Dither & ASCII kit: one ink, paper #f3f0e6, on a warm black\n * ground #0b0b0d, with vermillion #ff4f2b as a second ink inside the\n * pictures and for a live state. Cells snap to whole device pixels;\n * scenes dither in linear light, photographs on a gentler curve. Funnel Display through\n * var(--font-funnel) for display over Geist; Geist Mono for every glyph.\n * Respects prefers-reduced-motion. No dependencies beyond React.\n * Paste it as its own file: it repeats the kit's small helpers, which would\n * clash in one module. Load Funnel Display with next/font (variable:\n * \"--font-funnel\") on a parent, or from Google Fonts or @fontsource.\n */\n\nconst SANS = 'var(--font-sans, \"Geist\", \"Inter\", ui-sans-serif, system-ui, sans-serif)';\n\n/** One ink on a warm black ground, and one signal colour. */\nconst SHEET = {\n  ground: \"#0b0b0d\",\n  panel: \"#121214\",\n  raised: \"#19191c\",\n  paper: \"#f3f0e6\",\n  ink: \"rgba(243,240,230,0.92)\",\n  ink2: \"rgba(243,240,230,0.6)\",\n  ink3: \"rgba(243,240,230,0.38)\",\n  line: \"rgba(243,240,230,0.08)\",\n  line2: \"rgba(243,240,230,0.16)\",\n  signal: \"#ff4f2b\",\n} as const;\n\nfunction clamp(v: number, lo: number, hi: number): number {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\n/** Links: strip tabs and newlines, refuse backslashes, allow http(s), mailto, tel and same-site paths. */\nfunction safeHref(raw: string): string {\n  const v = raw.replace(/[\\t\\n\\r]/g, \"\").trim();\n  if (!v || v.includes(\"\\\\\")) return \"#\";\n  if (/^(https?:|mailto:|tel:)/i.test(v)) return v;\n  if (/^[/#?]/.test(v) && !/^\\/\\//.test(v)) return v;\n  return \"#\";\n}\n\nfunction subscribeMotion(cb: () => void) {\n  const m = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  m.addEventListener(\"change\", cb);\n  return () => m.removeEventListener(\"change\", cb);\n}\n\n/** True when the visitor asked for reduced motion. False on the server. */\nfunction useReducedMotion(): boolean {\n  return useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n// Each part carries only the CSS it needs, so any one of them works on its own.\n// Nothing is interpolated into these sheets; colours arrive as CSS variables.\n// revert-layer keeps an element's own rounded corners when a host page's focus rule flattens them.\nconst FOCUS_CSS = \".da-scope :focus-visible,.da-scope:focus-visible{outline:2px solid var(--da-ring,#ff4f2b)!important;outline-offset:3px;border-radius:revert-layer}\";\n\n/** The 8x8 Bayer index of a cell (0-63). Recursive, so every 2x2 and 4x4 block is itself in order. */\nfunction bayer8(x: number, y: number): number {\n  let v = 0;\n  for (let bit = 0; bit < 3; bit++) {\n    const xb = (x >> bit) & 1;\n    const yb = (y >> bit) & 1;\n    v |= (((xb ^ yb) << 1) | yb) << (2 * (2 - bit));\n  }\n  return v;\n}\n\nconst daMaskCache = new Map<number, string>();\n\n/** A mask tile with the first `level` of the 64 Bayer cells opaque: 0 shows nothing, 64 shows everything. */\nfunction daBayerMask(level: number): string {\n  const k = clamp(Math.round(level), 0, 64);\n  const hit = daMaskCache.get(k);\n  if (hit) return hit;\n  let d = \"\";\n  for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) if (bayer8(x, y) < k) d += `M${x} ${y}h1v1h-1z`;\n  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' shape-rendering='crispEdges'><path d='${d}'/></svg>`;\n  const url = `url(\"data:image/svg+xml,${encodeURIComponent(svg)}\")`;\n  daMaskCache.set(k, url);\n  return url;\n}\n\n/** The style that masks an element to a Bayer level, tiled at `px` CSS pixels a cell. */\nfunction daMaskStyle(level: number, px: number): CSSProperties {\n  const m = daBayerMask(level);\n  const s = `${px * 8}px ${px * 8}px`;\n  return { maskImage: m, WebkitMaskImage: m, maskSize: s, WebkitMaskSize: s, maskRepeat: \"repeat\", WebkitMaskRepeat: \"repeat\" };\n}\n\n/**\n * A cell size in CSS pixels snapped to whole device pixels for this element\n * (the screen's pixel ratio times any CSS scale on the way), so every dither\n * cell lands on the pixel grid and never blurs into grey.\n */\nfunction useSnappedCell(ref: RefObject<HTMLElement | null>, cell: number): number {\n  const [px, setPx] = useState(cell);\n  useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    let raf = 0;\n    const measure = () => {\n      const k = el.offsetWidth ? el.getBoundingClientRect().width / el.offsetWidth : 1;\n      const dev = (window.devicePixelRatio || 1) * (k || 1);\n      setPx(Math.max(1, Math.round(cell * dev)) / dev);\n    };\n    const ro = new ResizeObserver(() => {\n      measure();\n      cancelAnimationFrame(raf);\n      raf = requestAnimationFrame(measure);\n    });\n    ro.observe(el);\n    return () => {\n      ro.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, cell]);\n  return px;\n}\n\nconst DA_BUTTON_INK = {\n  signal: { fill: SHEET.signal, text: SHEET.ground, border: SHEET.signal, label: SHEET.paper, rest: 5 },\n  paper: { fill: SHEET.paper, text: SHEET.ground, border: \"rgba(243,240,230,0.5)\", label: SHEET.paper, rest: 5 },\n  ghost: { fill: SHEET.paper, text: SHEET.ground, border: SHEET.line2, label: SHEET.ink, rest: 0 },\n} as const;\n\nexport type DaButtonVariant = keyof typeof DA_BUTTON_INK;\n\n/**\n * BayerFillButton — a button whose fill prints in, cell by cell.\n *\n * At rest a few cells of its ink sit in the face. Hover or focus it and the\n * fill develops through the 8x8 Bayer order to solid in about 260ms (and\n * back out in 360ms), while the label inverts exactly where each cell\n * lands, because the inverted label lives inside the masked fill. Press it\n * and the grid halves to a finer screen and the face drops a pixel. Signal,\n * paper and ghost inks; `lit` holds it filled (a chosen option). CSS masks\n * and a few lines of animation, no canvas.\n */\nexport function BayerFillButton({\n  children,\n  href,\n  onClick,\n  type = \"button\",\n  variant = \"paper\",\n  size = \"lg\",\n  lit = false,\n  disabled = false,\n  ariaLabel,\n  ariaPressed,\n  className = \"\",\n}: {\n  children: ReactNode;\n  href?: string;\n  onClick?: () => void;\n  type?: \"button\" | \"submit\";\n  variant?: DaButtonVariant;\n  size?: \"lg\" | \"md\" | \"sm\";\n  /** Hold it filled, for a chosen option. */\n  lit?: boolean;\n  disabled?: boolean;\n  ariaLabel?: string;\n  ariaPressed?: boolean;\n  className?: string;\n}) {\n  const ink = DA_BUTTON_INK[variant] ?? DA_BUTTON_INK.signal;\n  const rootRef = useRef<HTMLElement | null>(null);\n  const fillRef = useRef<HTMLSpanElement>(null);\n  const reduced = useReducedMotion();\n  const px = useSnappedCell(rootRef, 2);\n  const state = useRef({ level: lit ? 64 : ink.rest, hover: false, focus: false, down: false, raf: 0, last: 0 });\n  const [down, setDown] = useState(false);\n  const litRef = useRef(lit);\n  // The mask React renders never changes after the first render: the loop below owns it from then on.\n  const [firstMask] = useState(() => daMaskStyle(lit ? 64 : ink.rest, 2));\n\n  // One small loop: the level walks toward its target (in 260ms, out 360ms) and the mask follows.\n  const run = () => {\n    const s = state.current;\n    if (s.raf) return;\n    s.last = 0;\n    const tick = (now: number) => {\n      s.raf = 0;\n      const el = fillRef.current;\n      if (!el) return;\n      const dt = s.last ? Math.min(0.05, (now - s.last) / 1000) : 1 / 60;\n      s.last = now;\n      const want = litRef.current || s.hover || s.focus || s.down ? 64 : ink.rest;\n      const rate = want > s.level ? 64 / 0.26 : 64 / 0.36;\n      s.level = reduced ? want : want > s.level ? Math.min(want, s.level + rate * dt) : Math.max(want, s.level - rate * dt);\n      Object.assign(el.style, daMaskStyle(s.level, s.down ? px / 2 : px));\n      if (s.level !== want) s.raf = requestAnimationFrame(tick);\n    };\n    s.raf = requestAnimationFrame(tick);\n  };\n  useEffect(() => {\n    litRef.current = lit;\n    run();\n  });\n  // Cancel on unmount and clear the handle, or a remount (StrictMode does one) would never start the loop again.\n  useEffect(() => {\n    const s = state.current;\n    return () => {\n      cancelAnimationFrame(s.raf);\n      s.raf = 0;\n    };\n  }, []);\n\n  const set = (patch: Partial<{ hover: boolean; focus: boolean; down: boolean }>) => {\n    Object.assign(state.current, patch);\n    if (patch.down !== undefined) setDown(patch.down);\n    run();\n  };\n  const pad = size === \"sm\" ? \"h-8 px-3 text-[12px]\" : size === \"md\" ? \"h-10 px-4 text-[13px]\" : \"h-12 px-6 text-[14px]\";\n  const common = {\n    className:\n      \"da-scope relative isolate inline-flex select-none items-center justify-center overflow-hidden rounded-[10px] font-medium no-underline outline-none transition-transform duration-150 \" +\n      pad +\n      (disabled ? \" pointer-events-none opacity-40 \" : \" \") +\n      className,\n    style: {\n      border: `1px solid ${ink.border}`,\n      color: ink.label,\n      background: SHEET.ground,\n      fontFamily: SANS,\n      letterSpacing: \"0.005em\",\n      transform: down ? \"translateY(1px)\" : undefined,\n    } as CSSProperties,\n    \"aria-label\": ariaLabel,\n    onPointerEnter: () => set({ hover: true }),\n    onPointerLeave: () => set({ hover: false, down: false }),\n    onPointerDown: () => set({ down: true }),\n    onPointerUp: () => set({ down: false }),\n    onPointerCancel: () => set({ down: false }),\n    onFocus: () => set({ focus: true }),\n    onBlur: () => set({ focus: false, down: false }),\n    // Enter activates both; Space activates only a button (a link scrolls on Space), so only then does it press.\n    onKeyDown: (e: ReactKeyboardEvent) => {\n      if (e.key === \"Enter\" || (e.key === \" \" && !href)) set({ down: true });\n    },\n    onKeyUp: () => set({ down: false }),\n  };\n  const face = (\n    <>\n      <span className=\"relative whitespace-nowrap\">{children}</span>\n      <span\n        ref={fillRef}\n        aria-hidden\n        className={\"pointer-events-none absolute inset-0 flex items-center justify-center whitespace-nowrap \" + pad}\n        style={{ background: ink.fill, color: ink.text, ...firstMask }}\n      >\n        {children}\n      </span>\n    </>\n  );\n  if (href) {\n    return (\n      <>\n        <style>{FOCUS_CSS}</style>\n        <a ref={(el) => void (rootRef.current = el)} href={safeHref(href)} onClick={onClick} {...common}>\n          {face}\n        </a>\n      </>\n    );\n  }\n  return (\n    <>\n      <style>{FOCUS_CSS}</style>\n      <button ref={(el) => void (rootRef.current = el)} type={type} onClick={onClick} disabled={disabled} aria-pressed={ariaPressed} {...common}>\n        {face}\n      </button>\n    </>\n  );\n}\n","type":"registry:component","target":"components/viberdy/bayer-fill-button.tsx"}],"meta":{"tier":"free","tags":["button","dither","bayer","hover","mask","css"],"href":"https://viberdy.dev/library/bayer-fill-button","aiPrompt":"Build a React + Tailwind button, `BayerFillButton({ children, href, onClick, type, variant, size, lit, disabled, ariaLabel, ariaPressed, className })`.\n\nBuild 65 mask tiles once: an 8x8 SVG (shape-rendering crispEdges) with the cells whose Bayer index is below the level filled, as data URIs. The face: a 1px border in the ink, the label in paper on the ground. Over it, an absolutely positioned fill in the ink holding a second copy of the label in the ground colour (aria-hidden), masked by the tile for the current level at 2 CSS px a cell, snapped to whole device pixels. A small requestAnimationFrame loop walks the level toward 64 when hovered, focused, pressed or lit (64 levels in 260ms) and back to rest (5 cells, or 0 for the ghost) in 360ms, writing mask-image straight to the element (React renders the first mask only). Pressed: the tile halves (1px cells) and the face translates 1px. Inks: paper (the default, for primary actions), signal (#ff4f2b, for a momentary action), ghost (a 16% hairline).\n\nDither & ASCII grammar: a warm black ground #0b0b0d (panels #121214, raised #19191c), one ink, paper #f3f0e6 (text at 92/60/38%, hairlines at 8% and 16%), and one signal colour, vermillion #ff4f2b, used as a second ink inside the pictures (the sun, a glint, a ball, a newly lit dot, a wordmark) and for a live state confined to a small mark (a square that lights, a peak character), never as a panel fill; a primary control's ink is paper, with signal kept for a momentary action. Every picture is computed and printed on purpose: rendered scenes dither in linear light and photographs on a gentler 1.5 curve so their midtones stay full, cells snap to whole device pixels (never blurred into grey), the 8x8 Bayer matrix for anything CSS, 64x64 void-and-cluster blue noise for the signature pictures, true error diffusion only on the CPU. Type stays crisp and undithered: Funnel Display through var(--font-funnel, \"Funnel Display\", ...) at 600-700 with -0.035em tracking for display, Geist for reading, Geist Mono uppercase with +0.14em tracking for labels and for every glyph an ASCII transform draws. Radii 10px controls, 14px cards, 18px panels. Motion: a transform change dissolves through blue noise in ~450ms, a fill prints in Bayer order in ~260ms and out in ~360ms, pictures print in on first view over ~900ms, ambient scenes loop over 30s or more. Respect prefers-reduced-motion (the picture still, changes instant). No dependencies beyond React.","license":"https://viberdy.dev/license"}}