{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"inpaint-brush","type":"registry:component","title":"Inpaint brush","description":"Paint over what to change: the pixels lift away as grains, Fill sends your API a real mask, and the result fills in through the hole.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/inpaint-brush.tsx","type":"registry:component","content":"// Hairline UI · inpaint-brush · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * INPAINT BRUSH: paint what to change, get it back filled\n *\n * Brush over the part of the picture you want changed: the\n * paint lifts those pixels away as grains of their own colour,\n * leaving a hole. Fill sends your API the image's mask (white\n * where you painted, at the image's own resolution) and waits;\n * the new image it returns fills in through the hole first,\n * then takes over. Undo takes back the last stroke; keyboard\n * users move the brush with the arrows and paint with Space.\n * ───────────────────────────────────────────────────────── */\n\nimport * as React from \"react\";\nimport { LoaderCircle, Undo2, Wand2, X } from \"lucide-react\";\n\nexport interface InpaintBrushProps {\n  src: string;\n  alt: string;\n  /** Receives the mask (a PNG, white where painted, black elsewhere, at the image's natural size) and returns the new image's URL. */\n  onInpaint: (mask: Blob, size: { width: number; height: number }) => Promise<string>;\n  /** Called with the new image's URL once it has filled in. */\n  onChange?: (src: string) => void;\n  /** Brush radii in CSS pixels for Small, Medium and Large. */\n  sizes?: [number, number, number];\n  crossOrigin?: \"anonymous\" | \"use-credentials\";\n  labels?: { fill?: string; filling?: string; undo?: string; clear?: string; hint?: string; failed?: string };\n  /** Size the frame here, e.g. \"aspect-square w-80\". */\n  className?: string;\n}\n\ntype Dab = { x: number; y: number; r: number };\ntype Grain = { x: number; y: number; vx: number; vy: number; c: string; a: number; s: number };\ntype Dust = { pixels: Uint8ClampedArray | null; w: number; h: number; dpr: number; grains: Grain[]; loop: number };\n\nconst SIZES: [number, number, number] = [10, 18, 30];\nconst SIZE_NAMES = [\"Small\", \"Medium\", \"Large\"];\nconst MAX_GRAINS = 700;\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\n/** The part of the image object-fit: cover shows in a w × h box. */\nfunction coverCrop(iw: number, ih: number, w: number, h: number) {\n  const s = Math.max(w / iw, h / ih);\n  const sw = w / s;\n  const sh = h / s;\n  return { sx: (iw - sw) / 2, sy: (ih - sh) / 2, sw, sh, s };\n}\n\nexport function InpaintBrush({ src, alt, onInpaint, onChange, sizes = SIZES, crossOrigin, labels, className = \"\" }: InpaintBrushProps) {\n  const reduced = useReducedMotion();\n  const frame = React.useRef<HTMLDivElement>(null);\n  const photo = React.useRef<HTMLCanvasElement>(null);\n  const dust = React.useRef<HTMLCanvasElement>(null);\n  const ring = React.useRef<HTMLDivElement>(null);\n  const state = React.useRef({\n    img: null as HTMLImageElement | null,\n    pixels: null as Uint8ClampedArray | null,\n    w: 0,\n    h: 0,\n    dpr: 1,\n    strokes: [] as Dab[][],\n    painting: false,\n    grains: [] as Grain[],\n    loop: 0,\n    cursor: { x: 0.5, y: 0.5 },\n  });\n  const [current, setCurrent] = React.useState(src);\n  const [size, setSize] = React.useState(1);\n  const [strokes, setStrokes] = React.useState(0);\n  const [busy, setBusy] = React.useState(false);\n  const [error, setError] = React.useState<string | null>(null);\n  const [ready, setReady] = React.useState(false);\n  const [seenSrc, setSeenSrc] = React.useState(src);\n  if (src !== seenSrc) {\n    setSeenSrc(src);\n    setCurrent(src);\n  }\n\n  /** Draws the picture and every stroke's hole, from scratch. */\n  const redraw = React.useCallback(() => {\n    const st = state.current;\n    const canvas = photo.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!canvas || !ctx || !st.img) return;\n    const { w, h, dpr, img } = st;\n    const c = coverCrop(img.naturalWidth, img.naturalHeight, w, h);\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    ctx.globalCompositeOperation = \"source-over\";\n    ctx.clearRect(0, 0, w, h);\n    ctx.drawImage(img, c.sx, c.sy, c.sw, c.sh, 0, 0, w, h);\n    ctx.globalCompositeOperation = \"destination-out\";\n    for (const stroke of st.strokes) for (const d of stroke) hole(ctx, d);\n    ctx.globalCompositeOperation = \"source-over\";\n  }, []);\n\n  // Load the image, size the canvases, and read its pixels for the grains (when CORS allows).\n  React.useEffect(() => {\n    const box = frame.current;\n    if (!box) return;\n    let live = true;\n    const img = new Image();\n    if (crossOrigin) img.crossOrigin = crossOrigin;\n    img.src = current;\n    img.decode().then(\n      () => {\n        if (!live) return;\n        const st = state.current;\n        st.img = img;\n        st.w = box.clientWidth;\n        st.h = box.clientHeight;\n        st.dpr = Math.min(window.devicePixelRatio || 1, 2);\n        for (const c of [photo.current, dust.current]) {\n          if (!c) continue;\n          c.width = Math.round(st.w * st.dpr);\n          c.height = Math.round(st.h * st.dpr);\n        }\n        st.strokes = [];\n        redraw();\n        try {\n          const ctx = photo.current?.getContext(\"2d\", { willReadFrequently: true });\n          st.pixels = ctx ? ctx.getImageData(0, 0, photo.current!.width, photo.current!.height).data : null;\n        } catch {\n          st.pixels = null;\n        }\n        setStrokes(0);\n        setReady(true);\n      },\n      () => live && setError(labels?.failed ?? \"The image couldn’t be loaded.\"),\n    );\n    return () => {\n      live = false;\n    };\n  }, [current, crossOrigin, redraw, labels?.failed]);\n\n  React.useEffect(() => () => cancelAnimationFrame(state.current.loop), []);\n\n  const dab = (x: number, y: number) => {\n    const st = state.current;\n    const canvas = photo.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!ctx || !st.img) return;\n    const d = { x, y, r: sizes[size] };\n    st.strokes[st.strokes.length - 1]?.push(d);\n    ctx.setTransform(st.dpr, 0, 0, st.dpr, 0, 0);\n    ctx.globalCompositeOperation = \"destination-out\";\n    hole(ctx, d);\n    ctx.globalCompositeOperation = \"source-over\";\n    if (!reduced && frame.current && dust.current) emitGrains(st, d, getComputedStyle(frame.current).color, dust.current);\n  };\n\n  const local = (event: React.PointerEvent) => {\n    const r = frame.current!.getBoundingClientRect();\n    return { x: event.clientX - r.left, y: event.clientY - r.top };\n  };\n  const showRing = (x: number, y: number, on: boolean) => {\n    const el = ring.current;\n    if (!el) return;\n    const r = sizes[size];\n    el.style.transform = `translate(${x - r}px, ${y - r}px)`;\n    el.style.width = el.style.height = `${r * 2}px`;\n    el.style.opacity = on ? \"1\" : \"0\";\n  };\n\n  const start = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (busy || !ready) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const st = state.current;\n    st.painting = true;\n    st.strokes.push([]);\n    const p = local(event);\n    dab(p.x, p.y);\n  };\n  const moveTo = (event: React.PointerEvent<HTMLDivElement>) => {\n    const p = local(event);\n    showRing(p.x, p.y, event.pointerType === \"mouse\" && !busy);\n    if (!state.current.painting) return;\n    dab(p.x, p.y);\n  };\n  const end = () => {\n    const st = state.current;\n    if (!st.painting) return;\n    st.painting = false;\n    if (st.strokes[st.strokes.length - 1]?.length === 0) st.strokes.pop();\n    setStrokes(st.strokes.length);\n  };\n\n  const undo = () => {\n    state.current.strokes.pop();\n    redraw();\n    setStrokes(state.current.strokes.length);\n  };\n  const clear = () => {\n    state.current.strokes = [];\n    redraw();\n    setStrokes(0);\n  };\n\n  // Keyboard: arrows move the brush, Space or Enter paints, Ctrl/Cmd+Z undoes.\n  const key = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const st = state.current;\n    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === \"z\") {\n      event.preventDefault();\n      undo();\n      return;\n    }\n    const step = event.shiftKey ? 0.08 : 0.025;\n    const delta = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[event.key];\n    if (delta) {\n      event.preventDefault();\n      st.cursor.x = Math.min(1, Math.max(0, st.cursor.x + delta[0]));\n      st.cursor.y = Math.min(1, Math.max(0, st.cursor.y + delta[1]));\n      showRing(st.cursor.x * st.w, st.cursor.y * st.h, true);\n      return;\n    }\n    if (event.key === \" \" || event.key === \"Enter\") {\n      event.preventDefault();\n      if (busy || !ready) return;\n      st.strokes.push([]);\n      dab(st.cursor.x * st.w, st.cursor.y * st.h);\n      showRing(st.cursor.x * st.w, st.cursor.y * st.h, true);\n      setStrokes(st.strokes.length);\n    }\n  };\n\n  /** The mask your API gets: white where painted, black elsewhere, at the image's natural size. */\n  const exportMask = async () => {\n    const st = state.current;\n    const img = st.img!;\n    const c = coverCrop(img.naturalWidth, img.naturalHeight, st.w, st.h);\n    const mask = document.createElement(\"canvas\");\n    mask.width = img.naturalWidth;\n    mask.height = img.naturalHeight;\n    const ctx = mask.getContext(\"2d\")!;\n    ctx.fillStyle = \"#000\";\n    ctx.fillRect(0, 0, mask.width, mask.height);\n    ctx.fillStyle = \"#fff\";\n    for (const stroke of st.strokes)\n      for (const d of stroke) {\n        ctx.beginPath();\n        ctx.arc(c.sx + d.x / c.s, c.sy + d.y / c.s, d.r / c.s, 0, Math.PI * 2);\n        ctx.fill();\n      }\n    const blob = await new Promise<Blob | null>((resolve) => mask.toBlob(resolve, \"image/png\"));\n    return { blob: blob!, size: { width: mask.width, height: mask.height } };\n  };\n\n  const fill = async () => {\n    if (busy || !strokes) return;\n    setBusy(true);\n    setError(null);\n    try {\n      const { blob, size: natural } = await exportMask();\n      const next = await onInpaint(blob, natural);\n      const img = new Image();\n      if (crossOrigin) img.crossOrigin = crossOrigin;\n      img.src = next;\n      await img.decode();\n      await fillIn(img);\n      setCurrent(next);\n      onChange?.(next);\n    } catch (e) {\n      setError(e instanceof Error && e.message ? e.message : labels?.failed ?? \"That didn’t work. Try again.\");\n    } finally {\n      setBusy(false);\n    }\n  };\n\n  /** The new image appears through the hole first, then over everything. */\n  const fillIn = (img: HTMLImageElement) =>\n    new Promise<void>((resolve) => {\n      const st = state.current;\n      const ctx = photo.current?.getContext(\"2d\");\n      if (!ctx || reduced) return resolve();\n      const { w, h, dpr } = st;\n      const c = coverCrop(img.naturalWidth, img.naturalHeight, w, h);\n      const holes = document.createElement(\"canvas\");\n      holes.width = Math.round(w * dpr);\n      holes.height = Math.round(h * dpr);\n      const hctx = holes.getContext(\"2d\")!;\n      hctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      for (const stroke of st.strokes) for (const d of stroke) hole(hctx, d, \"#000\");\n      hctx.globalCompositeOperation = \"source-in\";\n      hctx.drawImage(img, c.sx, c.sy, c.sw, c.sh, 0, 0, w, h);\n      const begin = performance.now();\n      const step = (now: number) => {\n        const p = Math.min(1, (now - begin) / 900);\n        redraw();\n        ctx.setTransform(1, 0, 0, 1, 0, 0);\n        ctx.globalAlpha = Math.min(1, p / 0.55);\n        ctx.drawImage(holes, 0, 0);\n        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n        if (p > 0.55) {\n          ctx.globalAlpha = (p - 0.55) / 0.45;\n          ctx.drawImage(img, c.sx, c.sy, c.sw, c.sh, 0, 0, w, h);\n        }\n        ctx.globalAlpha = 1;\n        if (p < 1) requestAnimationFrame(step);\n        else resolve();\n      };\n      requestAnimationFrame(step);\n    });\n\n  const action = \"inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium transition-[background-color,opacity,scale] duration-150 active:scale-[0.97] disabled:cursor-default disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\n  return (\n    <div className={`flex [:where(&)]:w-full flex-col gap-2.5 ${className}`}>\n      <div\n        ref={frame}\n        role=\"application\"\n        aria-label={`${alt}. ${labels?.hint ?? \"Paint over what to change. Arrow keys move the brush, Space paints, Ctrl+Z undoes.\"}`}\n        tabIndex={0}\n        onPointerDown={start}\n        onPointerMove={moveTo}\n        onPointerUp={end}\n        onPointerCancel={end}\n        onPointerLeave={() => showRing(0, 0, false)}\n        onKeyDown={key}\n        onBlur={() => showRing(0, 0, false)}\n        className=\"relative aspect-square w-full cursor-crosshair touch-none overflow-hidden rounded-[18px] bg-muted text-muted-foreground outline-none select-none focus-visible:ring-2 focus-visible:ring-ring/60\"\n        style={{ backgroundImage: \"radial-gradient(color-mix(in oklab, currentColor 26%, transparent) 1px, transparent 1px)\", backgroundSize: \"10px 10px\" }}\n      >\n        <canvas ref={photo} aria-hidden=\"true\" className=\"absolute inset-0 size-full\" />\n        <canvas ref={dust} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 size-full\" />\n        <div ref={ring} aria-hidden=\"true\" className=\"pointer-events-none absolute top-0 left-0 rounded-full opacity-0 ring-1 ring-background shadow-[0_0_0_2px_color-mix(in_oklab,var(--foreground)_45%,transparent)] transition-opacity duration-150\" />\n        {busy && (\n          <span className=\"pointer-events-none absolute bottom-3 left-3 inline-flex h-6 items-center gap-1.5 rounded-full bg-background/90 px-2.5 text-[11.5px] font-medium text-foreground ring-1 ring-border\">\n            <LoaderCircle className=\"size-3 animate-spin\" aria-hidden=\"true\" />\n            {labels?.filling ?? \"Filling\"}\n          </span>\n        )}\n      </div>\n      <div className=\"flex items-center justify-between gap-2\">\n        <div role=\"radiogroup\" aria-label=\"Brush size\" className=\"inline-flex h-8 items-center gap-0.5 rounded-full p-0.5 ring-1 ring-border\">\n          {sizes.map((r, i) => (\n            <button\n              key={SIZE_NAMES[i]}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={size === i}\n              aria-label={`${SIZE_NAMES[i]} brush`}\n              onClick={() => setSize(i)}\n              className={`grid h-7 w-8 cursor-pointer place-items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${size === i ? \"bg-accent text-foreground\" : \"text-muted-foreground hover:text-foreground\"}`}\n            >\n              <span className=\"rounded-full bg-current\" style={{ width: 4 + i * 3, height: 4 + i * 3 }} />\n            </button>\n          ))}\n        </div>\n        <div className=\"flex items-center gap-1\">\n          <button type=\"button\" onClick={undo} disabled={!strokes || busy} aria-label={labels?.undo ?? \"Undo stroke\"} className={`${action} w-8 justify-center px-0 text-muted-foreground hover:bg-accent hover:text-foreground`}>\n            <Undo2 className=\"size-3.5\" aria-hidden=\"true\" />\n          </button>\n          <button type=\"button\" onClick={clear} disabled={!strokes || busy} aria-label={labels?.clear ?? \"Clear mask\"} className={`${action} w-8 justify-center px-0 text-muted-foreground hover:bg-accent hover:text-foreground`}>\n            <X className=\"size-3.5\" aria-hidden=\"true\" />\n          </button>\n          <button type=\"button\" onClick={fill} disabled={!strokes || busy} className={`${action} bg-primary text-primary-foreground hover:bg-primary/90`}>\n            {busy ? <LoaderCircle className=\"size-3.5 animate-spin\" aria-hidden=\"true\" /> : <Wand2 className=\"size-3.5\" aria-hidden=\"true\" />}\n            {busy ? labels?.filling ?? \"Filling\" : labels?.fill ?? \"Fill\"}\n          </button>\n        </div>\n      </div>\n      <p className=\"min-h-4 px-0.5 text-[12px] text-muted-foreground\" aria-live=\"polite\">\n        {error ? <span className=\"text-red-600 dark:text-red-400\">{error}</span> : strokes ? `${strokes} ${strokes === 1 ? \"stroke\" : \"strokes\"} to fill` : labels?.hint ?? \"Paint over what to change\"}\n      </p>\n    </div>\n  );\n}\n\n/** Grains lift out of a dab in the colours that were there (or the text colour when the image can't be read). */\nfunction emitGrains(st: Dust, d: Dab, ink: string, canvas: HTMLCanvasElement) {\n  const room = MAX_GRAINS - st.grains.length;\n  const W = Math.round(st.w * st.dpr);\n  const H = Math.round(st.h * st.dpr);\n  for (let i = 0; i < Math.min(24, room); i++) {\n    const a = Math.random() * Math.PI * 2;\n    const r = Math.random() * d.r * 0.85;\n    const x = d.x + Math.cos(a) * r;\n    const y = d.y + Math.sin(a) * r;\n    let c = ink;\n    if (st.pixels) {\n      const px = Math.min(W - 1, Math.max(0, Math.round(x * st.dpr)));\n      const py = Math.min(H - 1, Math.max(0, Math.round(y * st.dpr)));\n      const k = (py * W + px) * 4;\n      c = `rgb(${st.pixels[k]},${st.pixels[k + 1]},${st.pixels[k + 2]})`;\n    }\n    st.grains.push({ x, y, vx: (Math.random() - 0.5) * 1.4 - 0.3, vy: -0.6 - Math.random() * 1.8, c, a: 0.95, s: 1.8 + Math.random() * 1.4 });\n  }\n  if (!st.loop) st.loop = requestAnimationFrame(() => drift(st, canvas));\n}\n\n/** One frame of the grains drifting up and fading; sleeps once they've all gone. */\nfunction drift(st: Dust, canvas: HTMLCanvasElement) {\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) {\n    st.loop = 0;\n    return;\n  }\n  ctx.setTransform(st.dpr, 0, 0, st.dpr, 0, 0);\n  ctx.clearRect(0, 0, st.w, st.h);\n  let keep = 0;\n  for (const g of st.grains) {\n    g.x += g.vx;\n    g.y += g.vy;\n    g.vy -= 0.045;\n    g.vx *= 0.985;\n    g.a -= 0.022;\n    if (g.a <= 0.02) continue;\n    ctx.globalAlpha = g.a;\n    ctx.fillStyle = g.c;\n    ctx.fillRect(g.x, g.y, g.s, g.s);\n    st.grains[keep++] = g;\n  }\n  ctx.globalAlpha = 1;\n  st.grains.length = keep;\n  st.loop = keep ? requestAnimationFrame(() => drift(st, canvas)) : 0;\n}\n\nfunction hole(ctx: CanvasRenderingContext2D, d: Dab, colour = \"#000\") {\n  const g = ctx.createRadialGradient(d.x, d.y, d.r * 0.2, d.x, d.y, d.r);\n  g.addColorStop(0, colour);\n  g.addColorStop(0.72, colour);\n  g.addColorStop(1, \"rgba(0,0,0,0)\");\n  ctx.fillStyle = g;\n  ctx.beginPath();\n  ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2);\n  ctx.fill();\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/inpaint-brush. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}