{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dither-drop-input","type":"registry:component","title":"Dither Drop Input","description":"Drop an image and see it dithered right there, with CSS alone: choose the cell size and the ink, set the exposure, and the request URL for that output builds as you go; submitting copies it.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/dither-drop-input.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { ChangeEvent, CSSProperties, DragEvent as ReactDragEvent, FormEvent, KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from \"react\";\n\n/**\n * DitherDropInput — drop an image, see it dithered here, and get the request for it.\n *\n * A real file input (click, keyboard or drag). The image never leaves the\n * browser: it prints in through the kit's CSS dither. Choose the cell size\n * and ink, set the exposure; the request URL updates as you go, and\n * submitting copies it or hands everything to `onSubmit`. Images only, up to\n * `maxBytes`; object URLs are released.\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 * Needs Tailwind v4 (on v3.4, add the @tailwindcss/container-queries plugin).\n */\n\nconst SANS = 'var(--font-sans, \"Geist\", \"Inter\", ui-sans-serif, system-ui, sans-serif)';\n\nconst MONO = 'var(--font-mono, \"Geist Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace)';\n\nconst EASE = \"cubic-bezier(0.22, 1, 0.36, 1)\";\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 daTileCache = new Map<number, string>();\n\n/**\n * The 8x8 Bayer thresholds as a tile of greys, inverted, for dithering any\n * element with CSS alone (see DitherLayer). Each threshold t is stored as\n * t^(1/gamma): at 2.2 the comparison is in linear light (the share of lit\n * cells matches the light exactly, which thins every midtone); at 1 it is\n * straight sRGB; 1.5 keeps photographs full without crushing the shadows.\n */\nfunction daBayerTile(gamma: number): string {\n  const k = Math.round(clamp(gamma, 0.5, 3) * 10) / 10;\n  const hit = daTileCache.get(k);\n  if (hit) return hit;\n  let rects = \"\";\n  for (let y = 0; y < 8; y++) {\n    for (let x = 0; x < 8; x++) {\n      const t = Math.pow((bayer8(x, y) + 0.5) / 64, 1 / k);\n      const g = Math.round((1 - t) * 255);\n      rects += `<rect x='${x}' y='${y}' width='1' height='1' fill='rgb(${g},${g},${g})'/>`;\n    }\n  }\n  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' shape-rendering='crispEdges'>${rects}</svg>`;\n  const url = `url(\"data:image/svg+xml,${encodeURIComponent(svg)}\")`;\n  daTileCache.set(k, url);\n  return url;\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/** Image sources: http(s), same-site paths, blob: and data:image/ (for dropped files); nothing else. */\nfunction safeSrc(raw: string): string {\n  const v = raw.replace(/[\\t\\n\\r]/g, \"\").trim();\n  if (!v || v.includes(\"\\\\\")) return \"\";\n  if (/^(https?:|blob:)/i.test(v) || /^data:image\\/(png|jpe?g|gif|webp|avif);/i.test(v)) return v;\n  if (/^[/.]/.test(v) && !/^\\/\\//.test(v)) return v;\n  return \"\";\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\n/**\n * DitherLayer: ordered-dithers whatever is inside it (an image, a gradient,\n * text, video) with CSS alone. The content is made grey, a tile of Bayer\n * thresholds is laid over it at half opacity, and a very high contrast on\n * the group turns every pixel into on or off by which of the two is lighter.\n * The result is then inked: lit cells in `ink`, the rest in `ground`.\n * `level` scales the light (0 prints nothing, 1 the full picture) and\n * transitions, so a change prints in or out cell by cell. With `light`, a\n * soft light follows the pointer and is dithered with the picture.\n */\nfunction DitherLayer({\n  children,\n  cell = 2,\n  ink = SHEET.paper,\n  ground = SHEET.ground,\n  level = 1,\n  light = false,\n  lightSize = 240,\n  duration = 900,\n  gamma = 1.5,\n  className = \"\",\n  style,\n}: {\n  children: ReactNode;\n  /** CSS pixels a cell, snapped to whole device pixels. */\n  cell?: number;\n  ink?: string;\n  ground?: string;\n  /** How much of the light prints: 0 nothing, 1 all of it; above 1 brightens. */\n  level?: number;\n  /** A light that follows the pointer, dithered with the picture. */\n  light?: boolean;\n  lightSize?: number;\n  /** How long a change of level takes to print, in ms. */\n  duration?: number;\n  /** Tone curve of the thresholds: 2.2 is strict linear light, 1 straight sRGB. */\n  gamma?: number;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const ref = useRef<HTMLDivElement>(null);\n  const lightRef = useRef<HTMLDivElement>(null);\n  const px = useSnappedCell(ref, cell);\n  const reduced = useReducedMotion();\n\n  useEffect(() => {\n    const el = ref.current;\n    const lamp = lightRef.current;\n    if (!light || !el || !lamp) return;\n    const move = (e: PointerEvent) => {\n      const r = el.getBoundingClientRect();\n      const k = el.offsetWidth ? r.width / el.offsetWidth : 1;\n      lamp.style.setProperty(\"--da-lx\", `${(e.clientX - r.left) / k}px`);\n      lamp.style.setProperty(\"--da-ly\", `${(e.clientY - r.top) / k}px`);\n      lamp.style.opacity = \"1\";\n    };\n    const leave = () => {\n      lamp.style.opacity = \"0\";\n    };\n    el.addEventListener(\"pointermove\", move);\n    el.addEventListener(\"pointerleave\", leave);\n    return () => {\n      el.removeEventListener(\"pointermove\", move);\n      el.removeEventListener(\"pointerleave\", leave);\n    };\n  }, [light]);\n\n  return (\n    <div ref={ref} className={\"relative isolate overflow-hidden \" + className} style={{ background: ground, ...style }}>\n      <div className=\"absolute inset-0\" style={{ filter: \"contrast(255)\", background: \"#000\" }}>\n        <div\n          className=\"absolute inset-0\"\n          style={{ filter: `grayscale(1) brightness(${level})`, transition: reduced ? \"none\" : `filter ${duration}ms ${EASE}` }}\n        >\n          {children}\n        </div>\n        {light ? (\n          <div\n            ref={lightRef}\n            aria-hidden\n            className=\"pointer-events-none absolute inset-0\"\n            style={{\n              opacity: 0,\n              background: `radial-gradient(${lightSize}px circle at var(--da-lx, 50%) var(--da-ly, 50%), rgba(255,255,255,0.62), rgba(255,255,255,0.18) 40%, transparent 72%)`,\n              mixBlendMode: \"screen\",\n              transition: reduced ? \"none\" : `opacity 420ms ${EASE}`,\n            }}\n          />\n        ) : null}\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0\"\n          style={{ opacity: 0.5, backgroundImage: daBayerTile(gamma), backgroundSize: `${px * 8}px ${px * 8}px`, imageRendering: \"pixelated\" }}\n        />\n      </div>\n      <div aria-hidden className=\"pointer-events-none absolute inset-0\" style={{ background: ink, mixBlendMode: \"multiply\" }} />\n      <div aria-hidden className=\"pointer-events-none absolute inset-0\" style={{ background: ground, mixBlendMode: \"screen\" }} />\n    </div>\n  );\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\n/** Code-drawn stills for the cards (greys only: the dither inks them). */\nexport type DaArt = \"sphere\" | \"rings\" | \"stack\";\n\nfunction DaStill({ kind }: { kind: DaArt }) {\n  // Gradient ids are per instance, so several stills on one page never share one.\n  const id = \"da\" + useId().replace(/[^a-zA-Z0-9]/g, \"\");\n  if (kind === \"rings\") {\n    return (\n      <svg aria-hidden viewBox=\"0 0 320 200\" preserveAspectRatio=\"xMidYMid slice\" className=\"absolute inset-0 h-full w-full\">\n        <defs>\n          <radialGradient id={`${id}-rg-ring`} cx=\"0.38\" cy=\"0.3\" r=\"0.9\">\n            <stop offset=\"0\" stopColor=\"#fff\" />\n            <stop offset=\"0.55\" stopColor=\"#a6a6a6\" />\n            <stop offset=\"1\" stopColor=\"#2a2a2a\" />\n          </radialGradient>\n          <linearGradient id={`${id}-lg-floor`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n            <stop offset=\"0\" stopColor=\"#262626\" />\n            <stop offset=\"1\" stopColor=\"#7a7a7a\" />\n          </linearGradient>\n        </defs>\n        <rect width=\"320\" height=\"200\" fill=\"#050505\" />\n        <rect y=\"132\" width=\"320\" height=\"68\" fill={`url(#${id}-lg-floor)`} />\n        <ellipse cx=\"170\" cy=\"160\" rx=\"92\" ry=\"10\" fill=\"#000\" opacity=\"0.8\" />\n        {[0, 1, 2, 3].map((i) => (\n          <ellipse key={i} cx={160 + i * 8} cy={98 - i * 4} rx={72 - i * 13} ry={58 - i * 11} fill=\"none\" stroke={`url(#${id}-rg-ring)`} strokeWidth={17 - i * 2.5} />\n        ))}\n      </svg>\n    );\n  }\n  if (kind === \"stack\") {\n    return (\n      <svg aria-hidden viewBox=\"0 0 320 200\" preserveAspectRatio=\"xMidYMid slice\" className=\"absolute inset-0 h-full w-full\">\n        <defs>\n          <linearGradient id={`${id}-lg-top`} x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n            <stop offset=\"0\" stopColor=\"#fff\" />\n            <stop offset=\"1\" stopColor=\"#a8a8a8\" />\n          </linearGradient>\n          <linearGradient id={`${id}-lg-side`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n            <stop offset=\"0\" stopColor=\"#6a6a6a\" />\n            <stop offset=\"1\" stopColor=\"#1c1c1c\" />\n          </linearGradient>\n        </defs>\n        <rect width=\"320\" height=\"200\" fill=\"#060606\" />\n        {[0, 1, 2, 3, 4].map((i) => {\n          const y = 150 - i * 22;\n          return (\n            <g key={i} opacity={1 - i * 0.12}>\n              <path d={`M160 ${y - 26} L236 ${y} L160 ${y + 26} L84 ${y} Z`} fill={`url(#${id}-lg-top)`} />\n              <path d={`M84 ${y} L160 ${y + 26} L160 ${y + 34} L84 ${y + 8} Z`} fill={`url(#${id}-lg-side)`} />\n              <path d={`M236 ${y} L160 ${y + 26} L160 ${y + 34} L236 ${y + 8} Z`} fill=\"#3e3e3e\" />\n            </g>\n          );\n        })}\n      </svg>\n    );\n  }\n  return (\n    <svg aria-hidden viewBox=\"0 0 320 200\" preserveAspectRatio=\"xMidYMid slice\" className=\"absolute inset-0 h-full w-full\">\n      <defs>\n        <radialGradient id={`${id}-rg-ball`} cx=\"0.36\" cy=\"0.32\" r=\"0.72\">\n          <stop offset=\"0\" stopColor=\"#fff\" />\n          <stop offset=\"0.45\" stopColor=\"#c4c4c4\" />\n          <stop offset=\"0.85\" stopColor=\"#404040\" />\n          <stop offset=\"1\" stopColor=\"#181818\" />\n        </radialGradient>\n        <radialGradient id={`${id}-rg-shadow`} cx=\"0.5\" cy=\"0.5\" r=\"0.5\">\n          <stop offset=\"0\" stopColor=\"#000\" />\n          <stop offset=\"1\" stopColor=\"#000\" stopOpacity=\"0\" />\n        </radialGradient>\n        <linearGradient id={`${id}-lg-plane`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor=\"#141414\" />\n          <stop offset=\"0.45\" stopColor=\"#8e8e8e\" />\n          <stop offset=\"1\" stopColor=\"#3c3c3c\" />\n        </linearGradient>\n      </defs>\n      <rect width=\"320\" height=\"200\" fill=\"#050505\" />\n      <rect y=\"112\" width=\"320\" height=\"88\" fill={`url(#${id}-lg-plane)`} />\n      <ellipse cx=\"198\" cy=\"160\" rx=\"96\" ry=\"17\" fill={`url(#${id}-rg-shadow)`} />\n      <circle cx=\"160\" cy=\"100\" r=\"64\" fill={`url(#${id}-rg-ball)`} />\n    </svg>\n  );\n}\n\nexport type DaDropValue = { file: File | null; cell: number; ink: \"paper\" | \"signal\"; exposure: number; url: string };\n\n/** A file name made safe for a URL path: lower case, a-z 0-9 and dashes, 48 characters at most. */\nfunction daSlug(name: string): string {\n  return (\n    name\n      .toLowerCase()\n      .replace(/\\.[a-z0-9]+$/, \"\")\n      .replace(/[^a-z0-9]+/g, \"-\")\n      .replace(/^-+|-+$/g, \"\")\n      .slice(0, 48) || \"image\"\n  );\n}\n\n/**\n * DitherDropInput — drop an image, see it dithered here, and get the\n * request that would deliver it.\n *\n * The drop zone is a real file input (click, keyboard or drag). The image\n * never leaves the browser: it is shown through the kit's CSS dither and\n * prints in cell by cell. Choose the cell size and the ink, and set the\n * exposure; the request URL updates as you go, and submitting copies it\n * (or hands everything to `onSubmit`). Only images, up to `maxBytes`; the\n * object URL is released when it's replaced.\n */\nexport function DitherDropInput({\n  label = \"Drop an image\",\n  hint = \"PNG, JPG, WebP or AVIF. It stays in your browser.\",\n  endpoint = \"/v1/i/\",\n  maxBytes = 20 * 1024 * 1024,\n  onSubmit,\n  className = \"\",\n  style,\n}: {\n  label?: string;\n  hint?: string;\n  /** Shown before the file name in the request; never fetched. */\n  endpoint?: string;\n  maxBytes?: number;\n  /** Receives the file and settings; without it, submitting copies the URL. */\n  onSubmit?: (value: DaDropValue) => void;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const inputId = useId();\n  const hintId = useId();\n  const groupId = useId();\n  const expId = useId();\n  const fileRef = useRef<File | null>(null);\n  const [pic, setPic] = useState<{ url: string; name: string } | null>(null);\n  const [cell, setCell] = useState(2);\n  const [ink, setInk] = useState<\"paper\" | \"signal\">(\"paper\");\n  const [exposure, setExposure] = useState(1);\n  const [level, setLevel] = useState(1);\n  const [over, setOver] = useState(false);\n  const [err, setErr] = useState(\"\");\n  const [done, setDone] = useState(\"\");\n\n  // Release each object URL once it is replaced or the input goes away.\n  useEffect(() => {\n    const url = pic?.url;\n    return () => {\n      if (url) URL.revokeObjectURL(url);\n    };\n  }, [pic]);\n\n  // A guard for the preview, not a security check: File.type comes from the name. If onSubmit uploads\n  // the file, validate it again on the server (type by its bytes, size, dimensions).\n  const take = (f: File | undefined | null) => {\n    if (!f) return;\n    if (!/^image\\//.test(f.type)) {\n      setErr(\"That file isn't an image.\");\n      return;\n    }\n    if (f.size > maxBytes) {\n      setErr(`That image is over ${Math.round(maxBytes / 1024 / 1024)} MB.`);\n      return;\n    }\n    setErr(\"\");\n    setDone(\"\");\n    fileRef.current = f;\n    setPic({ url: URL.createObjectURL(f), name: f.name });\n    setLevel(0);\n    requestAnimationFrame(() => requestAnimationFrame(() => setLevel(1)));\n  };\n\n  const url = `${endpoint}${pic ? daSlug(pic.name) : \"your-image\"}.png?t=bayer8&cell=${cell}&ink=${ink}&exp=${exposure.toFixed(2)}`;\n\n  const submit = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    const value: DaDropValue = { file: fileRef.current, cell, ink, exposure, url };\n    if (onSubmit) {\n      onSubmit(value);\n      setDone(\"Sent.\");\n      return;\n    }\n    navigator.clipboard?.writeText(url).then(\n      () => setDone(\"Copied the request.\"),\n      () => setDone(\"Couldn't copy: select the line above.\"),\n    );\n  };\n\n  const choice = (name: string, value: string, checked: boolean, onChange: () => void, text: string) => (\n    <label key={value} className=\"relative cursor-pointer\">\n      <input type=\"radio\" name={name} value={value} checked={checked} onChange={onChange} className=\"peer sr-only\" />\n      <span\n        className=\"block rounded-[10px] px-3 py-1.5 text-[12px] transition-colors duration-200 peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2\"\n        style={{\n          fontFamily: MONO,\n          border: `1px solid ${checked ? SHEET.paper : SHEET.line2}`,\n          background: checked ? SHEET.paper : \"transparent\",\n          color: checked ? SHEET.ground : SHEET.ink2,\n          outlineColor: SHEET.signal,\n        }}\n      >\n        {text}\n      </span>\n    </label>\n  );\n\n  return (\n    <form onSubmit={submit} className={\"da-scope w-full @container \" + className} style={{ fontFamily: SANS, color: SHEET.ink, ...style }}>\n      <style>{FOCUS_CSS + \".da-range{appearance:none;-webkit-appearance:none;background:transparent;height:28px}.da-range::-webkit-slider-runnable-track{height:2px;background:var(--da-track)}.da-range::-moz-range-track{height:2px;background:var(--da-track)}.da-range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:18px;height:18px;margin-top:-8px;border-radius:0;background:#f3f0e6;border:0}.da-range::-moz-range-thumb{width:18px;height:18px;border-radius:0;background:#f3f0e6;border:0}\"}</style>\n      <div className=\"grid gap-5 @3xl:grid-cols-[1.3fr_1fr]\">\n        <label\n          htmlFor={inputId}\n          onDragOver={(e: ReactDragEvent<HTMLLabelElement>) => {\n            e.preventDefault();\n            setOver(true);\n          }}\n          onDragLeave={() => setOver(false)}\n          onDrop={(e: ReactDragEvent<HTMLLabelElement>) => {\n            e.preventDefault();\n            setOver(false);\n            take(e.dataTransfer.files?.[0]);\n          }}\n          className=\"group relative block cursor-pointer overflow-hidden rounded-[18px] focus-within:outline focus-within:outline-2 focus-within:outline-offset-2\"\n          style={{ border: `1px ${over ? \"solid\" : \"dashed\"} ${over ? SHEET.signal : SHEET.line2}`, outlineColor: SHEET.signal }}\n        >\n          <input\n            id={inputId}\n            type=\"file\"\n            accept=\"image/png,image/jpeg,image/webp,image/avif,image/gif\"\n            aria-describedby={hintId}\n            className=\"sr-only\"\n            onChange={(e: ChangeEvent<HTMLInputElement>) => {\n              take(e.target.files?.[0]);\n              e.target.value = \"\";\n            }}\n          />\n          <DitherLayer className=\"aspect-[16/10] w-full\" cell={cell} ink={ink === \"signal\" ? SHEET.signal : SHEET.paper} level={level * exposure} duration={1100}>\n            {pic ? (\n              // eslint-disable-next-line @next/next/no-img-element -- pasted into any project: a plain img needs no next/image config\n              <img src={safeSrc(pic.url)} alt=\"\" className=\"absolute inset-0 h-full w-full object-cover\" draggable={false} />\n            ) : (\n              <DaStill kind=\"sphere\" />\n            )}\n          </DitherLayer>\n          <span\n            className=\"absolute inset-x-3 bottom-3 flex items-center justify-between gap-3 px-3 py-2 text-[12px]\"\n            style={{ background: \"rgba(11,11,13,0.86)\", border: `1px solid ${SHEET.line2}`, color: SHEET.ink }}\n          >\n            <span className=\"truncate\">{pic ? pic.name : label}</span>\n            <span className=\"shrink-0 text-[10.5px] uppercase\" style={{ fontFamily: MONO, letterSpacing: \"0.12em\", color: SHEET.signal }}>\n              {pic ? \"Replace\" : \"Choose\"}\n            </span>\n          </span>\n        </label>\n        <div className=\"flex flex-col gap-5\">\n          <p id={hintId} className=\"m-0 text-[13px] leading-[1.55]\" style={{ color: SHEET.ink2 }}>\n            {hint}\n          </p>\n          <fieldset className=\"m-0 flex min-w-0 flex-col gap-2 border-0 p-0\">\n            <legend className=\"mb-2 p-0 text-[11px] uppercase\" style={{ fontFamily: MONO, letterSpacing: \"0.14em\", color: SHEET.ink3 }}>\n              Cell\n            </legend>\n            <div className=\"flex flex-wrap gap-2\">{[1, 2, 3].map((c) => choice(groupId + \"-cell\", String(c), cell === c, () => setCell(c), `${c}px`))}</div>\n          </fieldset>\n          <fieldset className=\"m-0 flex min-w-0 flex-col gap-2 border-0 p-0\">\n            <legend className=\"mb-2 p-0 text-[11px] uppercase\" style={{ fontFamily: MONO, letterSpacing: \"0.14em\", color: SHEET.ink3 }}>\n              Ink\n            </legend>\n            <div className=\"flex flex-wrap gap-2\">\n              {choice(groupId + \"-ink\", \"paper\", ink === \"paper\", () => setInk(\"paper\"), \"Paper\")}\n              {choice(groupId + \"-ink\", \"signal\", ink === \"signal\", () => setInk(\"signal\"), \"Signal\")}\n            </div>\n          </fieldset>\n          <div className=\"flex flex-col gap-1\">\n            <label htmlFor={expId} className=\"flex items-baseline justify-between text-[11px] uppercase\" style={{ fontFamily: MONO, letterSpacing: \"0.14em\", color: SHEET.ink3 }}>\n              Exposure <span style={{ color: SHEET.ink2 }}>{exposure.toFixed(2)}</span>\n            </label>\n            <input\n              id={expId}\n              type=\"range\"\n              min={50}\n              max={160}\n              value={Math.round(exposure * 100)}\n              onChange={(e: ChangeEvent<HTMLInputElement>) => setExposure(Number(e.target.value) / 100)}\n              className=\"da-range w-full\"\n              style={{ [\"--da-track\" as string]: SHEET.line2 } as CSSProperties}\n            />\n          </div>\n          <output className=\"block break-all rounded-[10px] px-3 py-2.5 text-[11.5px] leading-[1.5]\" style={{ fontFamily: MONO, background: SHEET.panel, border: `1px solid ${SHEET.line}`, color: SHEET.ink2 }}>\n            <span style={{ color: SHEET.signal }}>GET </span>\n            {url}\n          </output>\n          <div className=\"flex flex-wrap items-center gap-3\">\n            <BayerFillButton type=\"submit\" variant=\"signal\" size=\"md\">\n              Copy the request\n            </BayerFillButton>\n            <span role=\"status\" className=\"text-[12px]\" style={{ color: SHEET.ink2 }}>\n              {done}\n            </span>\n          </div>\n          {err ? (\n            <p role=\"alert\" className=\"m-0 text-[12.5px]\" style={{ color: SHEET.signal }}>\n              {err}\n            </p>\n          ) : null}\n        </div>\n      </div>\n    </form>\n  );\n}\n","type":"registry:component","target":"components/viberdy/dither-drop-input.tsx"}],"meta":{"tier":"free","tags":["form","file upload","dropzone","dither","image","url builder","css"],"href":"https://viberdy.dev/library/dither-drop-input","aiPrompt":"Build a React + Tailwind form, `DitherDropInput({ label, hint, endpoint, maxBytes, onSubmit, className, style })`.\n\nA label wraps a visually hidden file input (accept PNG, JPEG, WebP, AVIF, GIF) and the preview, and takes dragover, dragleave and drop. On a file: reject anything not image/* or over maxBytes (an alert line), otherwise create an object URL (revoke the previous one on change and unmount), show it through the kit's CSS dither (a DitherLayer: grayscale + brightness(level x exposure), a 50% Bayer tile of thresholds on a 1.5 tone curve, contrast(255), then the ink in multiply and the ground in screen) and print it in by dropping level to 0 and back to 1 over 1.1s. Radios for cell (1, 2, 3 px) and ink (paper, signal), a range input for exposure (0.5-1.6), and an output element with GET endpoint + slug(name).png?t=bayer8&cell=&ink=&exp=, the slug lower case a-z 0-9 and dashes, 48 characters at most. Submit copies the URL to the clipboard, or calls onSubmit({ file, cell, ink, exposure, url }), and reports it in a status line.\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"}}