{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"liquid-image-reveal","type":"registry:component","title":"Liquid image reveal","description":"An organic reveal with SVG filters.","author":"DiMaac (HankTheTank) <https://dimaac.com>","dependencies":["gsap","@gsap/react"],"files":[{"path":"registry/dimaac/liquid-image-reveal/liquid-image-reveal.tsx","type":"registry:component","target":"components/dimaac/liquid-image-reveal.tsx","content":"\"use client\";\n\nimport { useCallback, useId, useRef, type CSSProperties } from \"react\";\nimport { gsap } from \"gsap\";\nimport { useGSAP } from \"@gsap/react\";\n\n// An image that opens like a drop of liquid. A circle grows from a point and the image shows\n// through it. The edge of the circle is pushed around by an SVG noise filter, so it wobbles like\n// a puddle instead of a clean circle. Click it and the puddle closes, then opens again from\n// wherever you clicked.\n\nexport type LiquidImageRevealProps = {\n  /** The image address. */\n  src: string;\n  /** What the image shows. It becomes the accessible name of the whole piece. */\n  alt: string;\n  /** Width of the box: a number in pixels or any CSS length. It fills its parent by default. */\n  width?: number | string;\n  /** Height of the box: a number in pixels or any CSS length. It fills its parent by default. */\n  height?: number | string;\n  /** How long the reveal takes, in seconds. */\n  duration?: number;\n  /** Seconds to wait before the reveal starts. */\n  delay?: number;\n  /** The GSAP ease of the reveal, e.g. \"power2.out\" or \"expo.out\". */\n  ease?: string;\n  /** When the first reveal plays: \"visible\" waits until the image is scrolled into view, \"mount\" plays straight away. */\n  trigger?: \"visible\" | \"mount\";\n  /** Clicking (or pressing Enter on) the image closes the puddle and opens it again from that spot. */\n  replayOnClick?: boolean;\n  /** Where the puddle starts, across the box: 0 is the left edge, 0.5 the middle, 1 the right edge. */\n  centerX?: number;\n  /** Where the puddle starts, down the box: 0 is the top edge, 0.5 the middle, 1 the bottom edge. */\n  centerY?: number;\n  /** How big the circle gets, in pixels. Leave empty to grow just enough to cover the whole image. */\n  maxRadius?: number;\n  /** How fine the wobble is. Small numbers give big slow waves, large numbers give small ripples. */\n  turbulenceFrequency?: number;\n  /** Layers of detail in the wobble. More looks richer but costs more on phones. 2 to 4 is plenty. */\n  turbulenceOctaves?: number;\n  /** How far the noise pushes the edge, in pixels. 0 is a clean circle. */\n  displacementScale?: number;\n  /** Called every time a reveal finishes. */\n  onComplete?: () => void;\n  /** Extra classes for the outer box, e.g. a radius. */\n  className?: string;\n};\n\nconst toCss = (value: number | string) => (typeof value === \"number\" ? `${value}px` : value);\n\nexport function LiquidImageReveal({\n  src,\n  alt,\n  width = \"100%\",\n  height = \"100%\",\n  duration = 2.2,\n  delay = 0,\n  ease = \"power2.out\",\n  trigger = \"visible\",\n  replayOnClick = true,\n  centerX = 0.5,\n  centerY = 0.5,\n  maxRadius,\n  turbulenceFrequency = 0.02,\n  turbulenceOctaves = 3,\n  displacementScale = 80,\n  onComplete,\n  className = \"\",\n}: LiquidImageRevealProps) {\n  const boxRef = useRef<HTMLElement | null>(null);\n  const setBox = useCallback((node: HTMLElement | null) => {\n    boxRef.current = node;\n  }, []);\n  const maskRef = useRef<SVGMaskElement>(null);\n  const filterRef = useRef<SVGFilterElement>(null);\n  const circleRef = useRef<SVGCircleElement>(null);\n\n  // SVG ids can't hold the colons React puts in useId, and two copies on a page need different ids\n  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, \"\");\n  const maskId = `liquid-mask-${uid}`;\n  const filterId = `liquid-filter-${uid}`;\n\n  // Values the animation reads while it runs. Only the callback is live; the look props restart the reveal\n  // (see the dependencies below), so a new wobble is always shown by playing it, never hidden behind a finished mask.\n  const live = useRef({ displacementScale, maxRadius, onComplete });\n  live.current = { displacementScale, maxRadius, onComplete };\n\n  useGSAP(\n    (_context, contextSafe) => {\n      const box = boxRef.current;\n      const mask = maskRef.current;\n      const filter = filterRef.current;\n      const circle = circleRef.current;\n      if (!box || !mask || !filter || !circle || !contextSafe) return;\n\n      // progress: 0 is closed, 1 is fully open. The radius is worked out from it on every draw,\n      // so a resize in the middle of a reveal still ends up covering the whole image.\n      const state = { progress: 0 };\n      const origin = { x: centerX, y: centerY };\n\n      const draw = () => {\n        const w = box.clientWidth;\n        const h = box.clientHeight;\n        const { displacementScale: scale, maxRadius: fixedRadius } = live.current;\n        // The noise pulls pixels in from outside the box, so the filter and mask regions are a\n        // little bigger than the box. Otherwise the edges would get transparent holes.\n        const pad = Math.ceil(scale) + 2;\n        for (const el of [mask, filter]) {\n          el.setAttribute(\"x\", String(-pad));\n          el.setAttribute(\"y\", String(-pad));\n          el.setAttribute(\"width\", String(w + pad * 2));\n          el.setAttribute(\"height\", String(h + pad * 2));\n        }\n        const cx = origin.x * w;\n        const cy = origin.y * h;\n        // The farthest corner, plus the most the noise can pull the edge back\n        const farthest = Math.hypot(Math.max(cx, w - cx), Math.max(cy, h - cy)) + scale * 0.6;\n        circle.setAttribute(\"cx\", String(cx));\n        circle.setAttribute(\"cy\", String(cy));\n        circle.setAttribute(\"r\", String(state.progress * (fixedRadius ?? farthest)));\n      };\n\n      draw();\n      const resizeObserver = new ResizeObserver(draw);\n      resizeObserver.observe(box);\n\n      // Reduced motion: no growing circle. The image is simply there.\n      const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n      if (reduced) {\n        state.progress = 1;\n        draw();\n        return () => resizeObserver.disconnect();\n      }\n\n      const open = (wait: number) => {\n        gsap.to(state, {\n          progress: 1,\n          duration,\n          delay: wait,\n          ease,\n          onUpdate: draw,\n          onComplete: () => live.current.onComplete?.(),\n        });\n      };\n\n      // Close quickly toward the old spot, then open again from the new one\n      const reopenFrom = (x: number, y: number) => {\n        gsap.killTweensOf(state);\n        gsap.to(state, {\n          progress: 0,\n          duration: Math.min(0.6, duration * 0.3),\n          ease: \"power2.in\",\n          onUpdate: draw,\n          onComplete: () => {\n            origin.x = x;\n            origin.y = y;\n            open(0.05);\n          },\n        });\n      };\n\n      const onClick = contextSafe((event: MouseEvent) => {\n        if (!replayOnClick) return;\n        const rect = box.getBoundingClientRect();\n        // A keyboard press has no position (detail is 0), so it reopens from the usual spot\n        const fromKeyboard = event.detail === 0;\n        const x = fromKeyboard ? centerX : (event.clientX - rect.left) / rect.width;\n        const y = fromKeyboard ? centerY : (event.clientY - rect.top) / rect.height;\n        reopenFrom(Math.min(1, Math.max(0, x)), Math.min(1, Math.max(0, y)));\n      });\n      box.addEventListener(\"click\", onClick);\n\n      // Wait until the image is on screen, so the reveal isn't spent while nobody is looking\n      let visibility: IntersectionObserver | null = null;\n      if (trigger === \"visible\" && typeof IntersectionObserver !== \"undefined\") {\n        visibility = new IntersectionObserver(\n          ([entry]) => {\n            if (!entry?.isIntersecting) return;\n            visibility?.disconnect();\n            open(delay);\n          },\n          { threshold: 0.35 },\n        );\n        visibility.observe(box);\n      } else {\n        open(delay);\n      }\n\n      return () => {\n        visibility?.disconnect();\n        resizeObserver.disconnect();\n        box.removeEventListener(\"click\", onClick);\n        gsap.killTweensOf(state);\n      };\n    },\n    { scope: boxRef, dependencies: [duration, delay, ease, trigger, replayOnClick, centerX, centerY, displacementScale, turbulenceFrequency, turbulenceOctaves, maxRadius], revertOnUpdate: true },\n  );\n\n  const boxStyle: CSSProperties = { width: toCss(width), height: toCss(height) };\n\n  const picture = (\n    <svg className=\"absolute inset-0 block h-full w-full\" xmlns=\"http://www.w3.org/2000/svg\" aria-hidden=\"true\" focusable=\"false\">\n      <defs>\n        {/* The liquid edge: noise that pushes the circle's pixels around. sRGB keeps the push\n            even in every direction. */}\n        <filter id={filterId} filterUnits=\"userSpaceOnUse\" colorInterpolationFilters=\"sRGB\" ref={filterRef}>\n          <feTurbulence type=\"fractalNoise\" baseFrequency={turbulenceFrequency} numOctaves={turbulenceOctaves} result=\"noise\" />\n          <feDisplacementMap in=\"SourceGraphic\" in2=\"noise\" scale={displacementScale} xChannelSelector=\"R\" yChannelSelector=\"G\" />\n        </filter>\n        {/* White shows the image, black hides it. The growing circle is the white part. */}\n        <mask id={maskId} maskUnits=\"userSpaceOnUse\" ref={maskRef}>\n          <circle ref={circleRef} r=\"0\" fill=\"white\" filter={`url(#${filterId})`} />\n        </mask>\n      </defs>\n      <image href={src} width=\"100%\" height=\"100%\" preserveAspectRatio=\"xMidYMid slice\" mask={`url(#${maskId})`} />\n    </svg>\n  );\n\n  const shared = `relative block overflow-hidden ${className}`;\n\n  if (replayOnClick) {\n    return (\n      <button\n        type=\"button\"\n        ref={setBox}\n        aria-label={`${alt}. Press to replay the reveal.`}\n        className={`${shared} cursor-pointer border-0 bg-transparent p-0 text-left focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current`}\n        style={boxStyle}\n      >\n        {picture}\n      </button>\n    );\n  }\n\n  return (\n    <div ref={setBox} role=\"img\" aria-label={alt} className={shared} style={boxStyle}>\n      {picture}\n    </div>\n  );\n}\n"}],"categories":["cursor","svg","gsap","image","reveal","mask","click"],"docs":"import { LiquidImageReveal } from \"@/components/dimaac/liquid-image-reveal\". Give its parent a size: it fills it. Docs, playground and props: https://ui.dimaac.com/components/liquid-image-reveal","meta":{"tier":"free","preview":"https://ui.dimaac.com/components/liquid-image-reveal","credits":[{"by":"West Kast","url":"https://www.lummi.ai/photo/fashion-portrait-with-orange-visor-damql","what":"Photo: orange visor","source":"Lummi","licence":"Lummi License"},{"by":"Amino","url":"https://www.lummi.ai/photo/vivid-portrait-on-pink-oxbow","what":"Photo: lime blazer","source":"Lummi","licence":"Lummi License"},{"by":"Shaun Duval","url":"https://www.lummi.ai/photo/portrait-with-neon-sunglasses-gindg","what":"Photo: neon profile","source":"Lummi","licence":"Lummi License"}]}}