{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"liquid-glass-switch","type":"registry:component","title":"Liquid Glass Switch","description":"A toggle whose knob swells into a clear glass lens while you hold or drag it, magnifying the track beneath, then springs home solid.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/liquid-glass-switch.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { PointerEvent as ReactPointerEvent, RefObject } from \"react\";\n\n/**\n * LiquidGlassSwitch — a toggle whose knob turns to glass while you hold it.\n *\n * At rest the knob is a solid white pill. Press or drag and it swells into a\n * clear lens: the white drains away, a rim and a sheen appear, and the track\n * underneath shows through MAGNIFIED, because the knob carries an aligned\n * copy of the track and the whole knob is scaled up around its own centre.\n * In Chromium a displacement map then bends that copy at the knob's rim, so\n * the edge of the colour fill curves as it passes under the glass. It runs as\n * a CSS filter on the copy, applied only where an image-driven displacement\n * filter on HTML is verified; Safari and Firefox keep the magnified copy with\n * a straight edge.\n *\n * Drag it across and the fill follows the knob; let go past the middle and it\n * commits, springing into place. A tap toggles. Space and Enter toggle too,\n * with the same brief glass flash. role=\"switch\" with aria-checked; the label\n * is part of the control.\n *\n * Controlled (checked + onCheckedChange) or uncontrolled (defaultChecked).\n * Needs Tailwind v4 (or v3.4+). No dependencies beyond React.\n */\n\ntype Size = \"md\" | \"lg\";\ntype Geom = { w: number; h: number; kw: number; kh: number; pad: number };\n\nconst SIZES: Record<Size, Geom> = {\n  md: { w: 64, h: 28, kw: 38, kh: 24, pad: 2 },\n  lg: { w: 80, h: 36, kw: 48, kh: 30, pad: 3 },\n};\n\nconst SPRING = \"460ms cubic-bezier(0.34,1.4,0.64,1)\";\n\n/** Only \"#rrggbb\" is accepted; anything else falls back. Never interpolated raw. */\nfunction safeHex(hex: string | undefined, fallback: string): string {\n  return /^#[0-9a-f]{6}$/i.test(hex || \"\") ? (hex as string) : fallback;\n}\n\n/**\n * The knob's lens as a displacement map: red carries the x offset and green\n * the y offset (128 = none), pointing inward and growing toward the rim.\n */\nfunction lensMap(w: number, h: number, r: number, bezel: number): string {\n  const c = document.createElement(\"canvas\");\n  c.width = w;\n  c.height = h;\n  const ctx = c.getContext(\"2d\");\n  if (!ctx) return \"\";\n  const img = ctx.createImageData(w, h);\n  const hw = w / 2;\n  const hh = h / 2;\n  const sd = (x: number, y: number) => {\n    const qx = Math.abs(x) - (hw - r);\n    const qy = Math.abs(y) - (hh - r);\n    return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;\n  };\n  for (let j = 0; j < h; j++) {\n    for (let i = 0; i < w; i++) {\n      const x = i + 0.5 - hw;\n      const y = j + 0.5 - hh;\n      const t = -sd(x, y);\n      let dx = 0;\n      let dy = 0;\n      if (t > 0 && t < bezel) {\n        const nx = sd(x + 0.5, y) - sd(x - 0.5, y);\n        const ny = sd(x, y + 0.5) - sd(x, y - 0.5);\n        const len = Math.hypot(nx, ny) || 1;\n        const m = Math.pow(1 - t / bezel, 2);\n        dx = (-nx / len) * m;\n        dy = (-ny / len) * m;\n      }\n      const k = (j * w + i) * 4;\n      img.data[k] = Math.round(128 + 127 * dx);\n      img.data[k + 1] = Math.round(128 + 127 * dy);\n      img.data[k + 2] = 128;\n      img.data[k + 3] = 255;\n    }\n  }\n  ctx.putImageData(img, 0, 0);\n  return c.toDataURL();\n}\n\ntype Fill = \"on\" | \"off\" | \"drag\";\n\n/** Fully open when on, closed when off, and running to the knob's centre while dragged. */\nfunction clipFor(g: Geom, x: number, fill: Fill): string {\n  if (fill === \"on\") return \"inset(0 0 0 0 round 999px)\";\n  if (fill === \"off\") return \"inset(0 100% 0 0 round 999px)\";\n  return \"inset(0 \" + (g.w - (x + g.kw / 2)) + \"px 0 0 round 999px)\";\n}\n\ntype Parts = {\n  knob: RefObject<HTMLSpanElement | null>;\n  clone: RefObject<HTMLSpanElement | null>;\n  fill: RefObject<HTMLSpanElement | null>;\n  cloneFill: RefObject<HTMLSpanElement | null>;\n};\n\n/** Move the knob, its magnified copy of the track, and both fills. DOM only. */\nfunction placeKnob(p: Parts, g: Geom, x: number, animate: boolean, fill: Fill) {\n  const knob = p.knob.current;\n  const clone = p.clone.current;\n  if (knob) {\n    knob.style.transition = (animate ? \"transform \" + SPRING : \"none\") + \", box-shadow 200ms ease\";\n    knob.style.transform = \"translateX(\" + x + \"px) scale(var(--lgs-scale))\";\n  }\n  if (clone) {\n    clone.style.transition = animate ? \"left \" + SPRING : \"none\";\n    clone.style.left = -x + \"px\";\n  }\n  for (const f of [p.fill.current, p.cloneFill.current]) {\n    if (!f) continue;\n    f.style.transition = animate ? \"clip-path \" + SPRING : \"none\";\n    f.style.clipPath = clipFor(g, x, fill);\n  }\n}\n\nexport function LiquidGlassSwitch({\n  checked,\n  defaultChecked = false,\n  onCheckedChange,\n  label,\n  tint = \"#34c759\",\n  size = \"md\",\n  disabled = false,\n  labelSide = \"end\",\n  className = \"\",\n}: {\n  checked?: boolean;\n  defaultChecked?: boolean;\n  onCheckedChange?: (checked: boolean) => void;\n  /** Visible label, clickable, and the switch's accessible name. */\n  label?: string;\n  /** \"On\" colour, \"#rrggbb\". */\n  tint?: string;\n  size?: Size;\n  disabled?: boolean;\n  /** Label after the switch (\"end\") or before it, settings-row style (\"start\"). */\n  labelSide?: \"start\" | \"end\";\n  className?: string;\n}) {\n  const [inner, setInner] = useState(defaultChecked);\n  const on = checked ?? inner;\n  const g = SIZES[size];\n  const fillColour = safeHex(tint, \"#34c759\");\n  const uid = useId().replace(/[^a-zA-Z0-9]/g, \"\");\n  const labelId = \"lgs\" + uid;\n  const lensId = \"lgsl\" + uid;\n  const mapRef = useRef<SVGFEImageElement>(null);\n\n  const rootRef = useRef<HTMLButtonElement>(null);\n  const knob = useRef<HTMLSpanElement>(null);\n  const clone = useRef<HTMLSpanElement>(null);\n  const fill = useRef<HTMLSpanElement>(null);\n  const cloneFill = useRef<HTMLSpanElement>(null);\n  const lensWrap = useRef<HTMLSpanElement>(null);\n  const drag = useRef({ active: false, moved: false, startX: 0, from: 0, x: 0, id: -1, k: 1 });\n  const flashTimer = useRef(0);\n\n  const minX = g.pad;\n  const maxX = g.w - g.kw - g.pad;\n  const restX = on ? maxX : minX;\n\n  // Keep the knob in the committed position whenever the value changes.\n  useEffect(() => {\n    if (!drag.current.active) {\n      placeKnob({ knob, clone, fill, cloneFill }, SIZES[size], on ? maxX : minX, true, on ? \"on\" : \"off\");\n    }\n  }, [on, size, maxX, minX]);\n\n  useEffect(() => () => window.clearTimeout(flashTimer.current), []);\n\n  // The knob's lens map, built once per size (it only depends on the knob),\n  // and switched on only in Chromium.\n  useEffect(() => {\n    const k = SIZES[size];\n    mapRef.current?.setAttribute(\"href\", lensMap(k.kw, k.kh, k.kh / 2, Math.min(k.kh * 0.34, 9)));\n    const ua = (navigator as Navigator & { userAgentData?: { brands?: { brand: string }[] } }).userAgentData;\n    if (lensWrap.current && ua && ua.brands && ua.brands.some((b) => /Chromium/.test(b.brand))) {\n      lensWrap.current.style.filter = \"url(#\" + lensId + \")\";\n    }\n  }, [size, lensId]);\n\n  function setHeld(held: boolean) {\n    rootRef.current?.setAttribute(\"data-held\", held ? \"true\" : \"false\");\n  }\n  function commit(next: boolean) {\n    if (checked === undefined) setInner(next);\n    onCheckedChange?.(next);\n  }\n  /** Tap, label click or keyboard: a brief glass flash while the knob travels. */\n  function toggleWithFlash() {\n    if (disabled) return;\n    setHeld(true);\n    window.clearTimeout(flashTimer.current);\n    flashTimer.current = window.setTimeout(() => setHeld(false), 280);\n    commit(!on);\n  }\n\n  function onPointerDown(e: ReactPointerEvent<HTMLButtonElement>) {\n    if (disabled || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n    const d = drag.current;\n    d.active = true;\n    d.moved = false;\n    d.startX = e.clientX;\n    d.from = restX;\n    d.x = restX;\n    d.id = e.pointerId;\n    // Screen pixels to layout pixels, so dragging tracks inside a scaled container.\n    const r = e.currentTarget.getBoundingClientRect();\n    d.k = e.currentTarget.offsetWidth / (r.width || 1);\n    e.currentTarget.setPointerCapture(e.pointerId);\n    setHeld(true);\n  }\n  function onPointerMove(e: ReactPointerEvent<HTMLButtonElement>) {\n    const d = drag.current;\n    if (!d.active || e.pointerId !== d.id) return;\n    const dx = (e.clientX - d.startX) * d.k;\n    if (Math.abs(dx) > 3) d.moved = true;\n    d.x = Math.max(minX, Math.min(maxX, d.from + dx));\n    placeKnob({ knob, clone, fill, cloneFill }, g, d.x, false, \"drag\");\n  }\n  function onPointerUp(e: ReactPointerEvent<HTMLButtonElement>) {\n    const d = drag.current;\n    if (!d.active || e.pointerId !== d.id) return;\n    d.active = false;\n    setHeld(false);\n    // A drag commits by position; a tap is left to onClick.\n    if (d.moved) {\n      const next = d.x > (minX + maxX) / 2;\n      placeKnob({ knob, clone, fill, cloneFill }, g, next ? maxX : minX, true, next ? \"on\" : \"off\");\n      if (next !== on) commit(next);\n    }\n  }\n  function onPointerCancel(e: ReactPointerEvent<HTMLButtonElement>) {\n    const d = drag.current;\n    if (!d.active || e.pointerId !== d.id) return;\n    d.active = false;\n    d.moved = false;\n    setHeld(false);\n    placeKnob({ knob, clone, fill, cloneFill }, g, restX, true, on ? \"on\" : \"off\");\n  }\n  function onClick() {\n    // The click that follows a drag has already been handled by position.\n    if (drag.current.moved) {\n      drag.current.moved = false;\n      return;\n    }\n    toggleWithFlash();\n  }\n\n  const offTrack = \"rgba(120,120,128,0.36)\";\n  const track = (ref: RefObject<HTMLSpanElement | null>) => (\n    <>\n      <span className=\"absolute inset-0 rounded-full\" style={{ background: offTrack }} />\n      <span\n        ref={ref}\n        className=\"absolute inset-0 rounded-full\"\n        style={{ background: fillColour, clipPath: clipFor(g, restX, on ? \"on\" : \"off\") }}\n      />\n    </>\n  );\n\n  return (\n    <span className={\"inline-flex items-center gap-3 \" + (labelSide === \"start\" ? \"flex-row-reverse \" : \"\") + className}>\n      <button\n        ref={rootRef}\n        type=\"button\"\n        role=\"switch\"\n        aria-checked={on}\n        aria-labelledby={label ? labelId : undefined}\n        disabled={disabled}\n        data-held=\"false\"\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={onPointerUp}\n        onPointerCancel={onPointerCancel}\n        onClick={onClick}\n        className={\n          \"group relative shrink-0 touch-none select-none rounded-full outline-none \" +\n          \"focus-visible:ring-2 focus-visible:ring-white/80 focus-visible:ring-offset-2 focus-visible:ring-offset-black/0 \" +\n          \"disabled:cursor-not-allowed disabled:opacity-40 \" +\n          \"[--lgs-scale:1] data-[held=true]:[--lgs-scale:1.32] motion-reduce:data-[held=true]:[--lgs-scale:1]\"\n        }\n        style={{ width: g.w, height: g.h }}\n      >\n        {track(fill)}\n        <span\n          ref={knob}\n          aria-hidden\n          className=\"absolute left-0 overflow-hidden rounded-full\"\n          style={{\n            top: (g.h - g.kh) / 2,\n            width: g.kw,\n            height: g.kh,\n            transform: \"translateX(\" + restX + \"px) scale(var(--lgs-scale))\",\n            boxShadow: \"0 2px 7px rgba(0,0,0,0.28), 0 0 0 0.5px rgba(0,0,0,0.06)\",\n          }}\n        >\n          {/* The track again, aligned under the knob: scaled with it, it reads as\n              magnified, and (in Chromium) the lens map bends it at the rim. */}\n          <span ref={lensWrap} className=\"absolute inset-0\">\n            <span\n              ref={clone}\n              className=\"absolute\"\n              style={{ left: -restX, top: -(g.h - g.kh) / 2, width: g.w, height: g.h }}\n            >\n              {track(cloneFill)}\n            </span>\n          </span>\n          {/* Glass: a faint body, a graduated rim and a sheen along the top. */}\n          <span\n            className=\"absolute inset-0 rounded-full\"\n            style={{\n              background:\n                \"linear-gradient(180deg, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0.04) 45%, rgba(255,255,255,0.1) 100%)\",\n              boxShadow:\n                \"inset 0 1px 0 rgba(255,255,255,0.85), inset 0 -1px 1px rgba(255,255,255,0.3), inset 0 0 6px rgba(255,255,255,0.3)\",\n            }}\n          />\n          {/* The solid white knob, which drains away while held. */}\n          <span className=\"absolute inset-0 rounded-full bg-white transition-opacity duration-200 group-data-[held=true]:opacity-0\" />\n        </span>\n        <svg aria-hidden width=\"0\" height=\"0\" style={{ position: \"absolute\" }}>\n          <filter id={lensId} x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" colorInterpolationFilters=\"sRGB\">\n            <feImage ref={mapRef} x=\"0\" y=\"0\" width={g.kw} height={g.kh} preserveAspectRatio=\"none\" result=\"map\" />\n            <feDisplacementMap in=\"SourceGraphic\" in2=\"map\" scale=\"12\" xChannelSelector=\"R\" yChannelSelector=\"G\" />\n          </filter>\n        </svg>\n      </button>\n      {label && (\n        <span\n          id={labelId}\n          onClick={toggleWithFlash}\n          className={\"select-none text-[15px] \" + (disabled ? \"opacity-40\" : \"cursor-pointer\")}\n        >\n          {label}\n        </span>\n      )}\n    </span>\n  );\n}\n","type":"registry:component","target":"components/viberdy/liquid-glass-switch.tsx"}],"meta":{"tier":"free","tags":["switch","toggle","glass","liquid glass","lens","drag"],"href":"https://viberdy.dev/library/liquid-glass-switch","aiPrompt":"Create a React + Tailwind client component, LiquidGlassSwitch: an iOS-26-style toggle whose knob turns into a clear glass lens while it is held or dragged, magnifying the track beneath it.\n\nProps: checked + onCheckedChange (controlled) or defaultChecked (uncontrolled), label (visible, clickable, and the accessible name via aria-labelledby with a sanitised useId), tint (\"#rrggbb\" for the on colour, validated with a regex, default #34c759), size (\"md\": track 64x28, knob 38x24, inset 2 | \"lg\": 80x36, knob 48x30, inset 3), disabled, labelSide (\"end\" default, \"start\" puts the label first for settings rows), className.\n\nStructure: a <button role=\"switch\" aria-checked> with touch-action none and a visible focus ring. The track is two layers: an off layer rgba(120,120,128,0.36) and an on layer in the tint, clipped with clip-path: fully open when on, inset(0 100% 0 0 round 999px) when off, and inset(0 Rpx 0 0 round 999px) while dragging so the fill runs to the knob's centre. The knob is an absolutely positioned pill with overflow hidden and a shadow 0 2px 7px black at 0.28. Inside it: (1) a second copy of the track, positioned at (−x, −topInset) so it lines up exactly with the real track; (2) a glass layer with a vertical white gradient (0.3 → 0.04 → 0.1) and inset rims (top white 0.85, bottom 0.3, 6px inner glow 0.3); (3) a solid white layer on top that fades out over 200ms while held.\n\nThe lens: the knob's transform is translateX(x) scale(var(--lgs-scale)). The button sets --lgs-scale to 1, and to 1.32 when data-held=\"true\" (not under prefers-reduced-motion). Because the aligned track copy scales with the knob around its centre, the track reads as magnified through clear glass. Wrap the copy in a knob-sized span with CSS filter: url(#lens), an SVG filter whose feImage is a displacement map generated on a canvas for the knob size (rounded-rect signed distance, radius kh/2, bezel min(0.34·kh, 9px), inward offset (1 − t/bezel)², red = 128 + 127·dx, green = 128 + 127·dy) feeding an feDisplacementMap at scale 12 with color-interpolation-filters sRGB, so the fill edge curves at the knob rim. Apply that filter from an effect in Chromium only (navigator.userAgentData brands contains \"Chromium\"): an image-driven displacement filter on HTML content is only verified there, so Safari and Firefox keep the magnified copy with a straight edge.\n\nBehaviour: pointerdown (primary button only) captures the pointer and sets data-held; pointermove drags the knob between the insets (converting screen pixels to layout pixels with offsetWidth / rect width, so it tracks inside a scaled container) and moves the knob, its track copy and both fill clips with no transition; pointerup after a drag of more than 3px commits by position (past the middle = on) and animates everything home with 460ms cubic-bezier(0.34, 1.4, 0.64, 1); pointercancel returns to the committed position. A tap, a label click, or Space/Enter toggles and flashes the glass state for 280ms. The click that follows a drag is ignored. Write the knob, copy and clip positions straight to the DOM through refs in a module-level placeKnob() helper; an effect re-places the knob whenever the value changes. Clear the flash timer on unmount.\n\nOutput one self-contained \"use client\" TSX file with no dependencies beyond React. Build strings with + rather than template literals.","license":"https://viberdy.dev/license"}}