{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"liquid-log","type":"registry:component","title":"Liquid log","description":"The card is the vessel you log into: tap + and a drop falls into a live surface, the ripple runs to the walls, then the level rises.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/liquid-log.tsx","type":"registry:component","content":"// Hairline UI · liquid-log · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Plus, Undo2 } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { createSpring, MATERIAL_LIFT, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * LIQUID LOG: the card is the vessel you log into\n *\n *   body      the card fills with liquid from the bottom: a live\n *             surface, a pale meniscus, and the liquid itself drawn\n *             in fine engraved lines, deepening toward the bottom\n *   log       tap + and the amount leaves it as a drop, arcs up and\n *             falls into the surface: a splash kicks up, the ripple\n *             runs out to the walls and back, a few bubbles rise,\n *             and only then does the level rise and the total roll\n *   read      wherever the liquid covers the words they turn light,\n *             cut exactly along the moving waterline, so the total\n *             is never lost\n *   pour      hold + and drops keep coming, faster and faster; the\n *             whole hold is one log to undo\n *   over      past the goal the card is full and a deeper liquid\n *             rises from the bottom for the second lap\n *   undo      a drop lifts out of the surface and falls back into\n *             the button while the level drops\n *   touch     a pointer moving along the waterline leaves a small\n *             wake\n *\n * One canvas and one frame loop that sleeps when the surface is\n * still. The total is yours: pass value and add in onLog, or leave\n * it uncontrolled.\n * ───────────────────────────────────────────────────────── */\n\nexport interface LiquidLogProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\" | \"defaultValue\" | \"onChange\"> {\n  value?: number;\n  defaultValue?: number;\n  goal: number;\n  /** What one tap logs. Defaults to an eighth of the goal. */\n  step?: number;\n  unit?: string;\n  title?: string;\n  icon?: React.ReactNode;\n  /** The liquid's colour: any CSS colour. Defaults to --chart-1. */\n  color?: string;\n  /** Called for every tap (and every drop of a hold) with the amount. Throw or reject to refuse it. */\n  onLog?: (amount: number) => Promise<unknown> | void;\n  /** Called with the last log's amount. Without it a controlled card hides Undo. */\n  onUndo?: (amount: number) => Promise<unknown> | void;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background\";\nconst COLS = 40; // surface columns\nconst STEP_S = 1 / 120;\nconst FLIGHT = 520;\nconst BUTTON = 52;\nconst INSET = 16;\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 = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nconst inOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);\n\ninterface Drop {\n  amount: number;\n  start: number;\n  up: boolean; // undo: from the surface back into the button\n  fromX: number;\n  toX: number;\n  x: number;\n  y: number;\n}\ninterface Particle {\n  x: number;\n  y: number;\n  vx: number;\n  vy: number;\n  r: number;\n  bubble: boolean;\n  born: number;\n}\n\ninterface Engine {\n  w: number;\n  h: number;\n  u: Float32Array; // surface displacement, px\n  v: Float32Array;\n  level: Spring | null;\n  drops: Drop[];\n  bits: Particle[];\n  frame: number;\n  last: number;\n  spare: number;\n  colors: { liquid: string; card: string; ink: string };\n  land: (amount: number) => void;\n  clips: { above: HTMLElement | null; below: HTMLElement | null };\n  pointer: { x: number; y: number } | null;\n  /** On screen and motion allowed: the surface sways gently. */\n  idle: boolean;\n  t: number;\n}\n\n/** A slow swell on the still surface, so the liquid never reads as a flat block of colour. */\nconst sway = (e: Engine, x: number) => (e.idle ? 1.7 * Math.sin(x * 0.034 + e.t * 1.25) + 1.1 * Math.sin(x * 0.069 - e.t * 0.85) : 0);\n\nconst surfaceAt = (e: Engine, x: number, base: number) => {\n  const f = (x / Math.max(1, e.w)) * (COLS - 1);\n  const i = Math.max(0, Math.min(COLS - 2, Math.floor(f)));\n  const t = f - i;\n  return base + e.u[i] * (1 - t) + e.u[i + 1] * t + sway(e, x);\n};\n\nconst levelY = (e: Engine, f: number) => e.h * (1 - Math.max(0, Math.min(1, f)));\n\nfunction kickSurface(e: Engine, x: number, speed: number, spread = 2.2) {\n  const c = (x / Math.max(1, e.w)) * (COLS - 1);\n  for (let i = 0; i < COLS; i++) e.v[i] += speed * Math.exp(-(((i - c) / spread) ** 2));\n}\n\n/** Step the surface: each column springs back to rest and pulls on its neighbours; the walls reflect. */\nfunction stepSurface(e: Engine, dt: number) {\n  e.spare += Math.min(dt, 0.05);\n  while (e.spare >= STEP_S) {\n    e.spare -= STEP_S;\n    for (let i = 0; i < COLS; i++) {\n      const l = e.u[i > 0 ? i - 1 : 0];\n      const r = e.u[i < COLS - 1 ? i + 1 : COLS - 1];\n      e.v[i] += ((l + r - 2 * e.u[i]) * 2200 - e.u[i] * 26) * STEP_S;\n      e.v[i] *= 0.991;\n    }\n    for (let i = 0; i < COLS; i++) e.u[i] += e.v[i] * STEP_S;\n  }\n}\n\nfunction draw(e: Engine, canvas: HTMLCanvasElement | null, now: number) {\n  if (!canvas || !e.w || !e.level) return false;\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) return false;\n  const dpr = Math.min(window.devicePixelRatio || 1, 2);\n  if (canvas.width !== Math.round(e.w * dpr) || canvas.height !== Math.round(e.h * dpr)) {\n    canvas.width = Math.round(e.w * dpr);\n    canvas.height = Math.round(e.h * dpr);\n  }\n  const dt = e.last ? (now - e.last) / 1000 : 0;\n  e.last = now;\n  e.t = now / 1000;\n  stepSurface(e, dt);\n\n  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n  ctx.clearRect(0, 0, e.w, e.h);\n  const { liquid, card } = e.colors;\n  const f = Math.max(0, e.level.get());\n  const y1 = levelY(e, f);\n  const y2 = f > 1 ? levelY(e, f - 1) : e.h + 4;\n  const calm = Math.min(1, Math.max(0, y1 / 18)); // the surface flattens as it meets the top edge\n\n  const surface = (base: number, damp: number) => {\n    ctx.beginPath();\n    ctx.moveTo(0, e.h);\n    const pts: [number, number][] = [];\n    for (let i = 0; i < COLS; i++) {\n      const x = (i / (COLS - 1)) * e.w;\n      pts.push([x, base + (e.u[i] + sway(e, x)) * damp]);\n    }\n    ctx.lineTo(pts[0][0], pts[0][1]);\n    for (let i = 1; i < COLS; i++) {\n      const [px, py] = pts[i - 1];\n      const [x, y] = pts[i];\n      ctx.quadraticCurveTo(px, py, (px + x) / 2, (py + y) / 2);\n    }\n    ctx.lineTo(e.w, pts[COLS - 1][1]);\n    ctx.lineTo(e.w, e.h);\n    ctx.closePath();\n    return pts;\n  };\n\n  const body = (base: number, damp: number, deep: number) => {\n    if (base >= e.h + 2) return;\n    ctx.save();\n    surface(base, damp);\n    ctx.clip();\n    ctx.globalAlpha = 1;\n    ctx.fillStyle = liquid;\n    ctx.fillRect(0, 0, e.w, e.h);\n    // Light near the surface, depth toward the bottom.\n    const top = Math.max(0, base - 6);\n    const shade = ctx.createLinearGradient(0, top, 0, e.h);\n    shade.addColorStop(0, \"rgba(255,255,255,0.26)\");\n    shade.addColorStop(Math.min(1, 70 / Math.max(1, e.h - top)), \"rgba(255,255,255,0)\");\n    shade.addColorStop(1, `rgba(0,0,0,${0.16 + deep})`);\n    ctx.fillStyle = shade;\n    ctx.fillRect(0, top, e.w, e.h - top);\n    if (deep) {\n      ctx.fillStyle = `rgba(0,0,0,${deep})`;\n      ctx.fillRect(0, top, e.w, e.h - top);\n    }\n    // The house mark: the liquid is drawn in fine engraved lines.\n    ctx.fillStyle = card;\n    ctx.globalAlpha = 0.11;\n    for (let y = Math.floor(top / 4) * 4 + 3; y < e.h; y += 4) ctx.fillRect(0, y, e.w, 1);\n    ctx.restore();\n    // The meniscus.\n    ctx.save();\n    ctx.beginPath();\n    for (let i = 0; i < COLS; i++) {\n      const x = (i / (COLS - 1)) * e.w;\n      const y = base + (e.u[i] + sway(e, x)) * damp;\n      if (i === 0) ctx.moveTo(x, y);\n      else {\n        const px = ((i - 1) / (COLS - 1)) * e.w;\n        const py = base + (e.u[i - 1] + sway(e, px)) * damp;\n        ctx.quadraticCurveTo(px, py, (px + x) / 2, (py + y) / 2);\n      }\n    }\n    ctx.strokeStyle = card;\n    ctx.globalAlpha = 0.6;\n    ctx.lineWidth = 1.5;\n    ctx.stroke();\n    ctx.restore();\n  };\n\n  body(y1, calm, 0);\n  body(y2, 1, 0.22);\n\n  // Splash and bubbles.\n  e.bits = e.bits.filter((p) => {\n    const age = (now - p.born) / 1000;\n    if (p.bubble) {\n      p.y -= 38 * dt;\n      p.x += Math.sin(age * 9 + p.r) * 6 * dt;\n      const s = surfaceAt(e, p.x, y1);\n      if (p.y < s + 2 || age > 2.4) return false;\n      ctx.globalAlpha = 0.55 * Math.min(1, age * 4);\n      ctx.strokeStyle = card;\n      ctx.lineWidth = 1;\n      ctx.beginPath();\n      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);\n      ctx.stroke();\n      return true;\n    }\n    p.vy += 900 * dt;\n    p.x += p.vx * dt;\n    p.y += p.vy * dt;\n    if (p.vy > 0 && p.y > surfaceAt(e, p.x, y1)) return false;\n    ctx.globalAlpha = 1;\n    ctx.fillStyle = liquid;\n    ctx.beginPath();\n    ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);\n    ctx.fill();\n    return true;\n  });\n\n  // Drops in the air, stretched along their path by their speed.\n  const bx = e.w - INSET - BUTTON / 2;\n  const by = e.h - INSET - BUTTON / 2;\n  e.drops = e.drops.filter((d) => {\n    if (d.start < 0) d.start = now;\n    const t = Math.min(1, (now - d.start) / FLIGHT);\n    let x: number;\n    let y: number;\n    if (!d.up) {\n      // Tossed up from the button, falling into the surface.\n      const sx = bx;\n      const sy = by - BUTTON / 2;\n      const ty = surfaceAt(e, d.toX, y1);\n      const apex = Math.min(sy, ty) - Math.max(36, e.h * 0.16);\n      const k = inOut(t * 0.92);\n      x = sx + (d.toX - sx) * k;\n      const a = Math.min(1, t * 1.1);\n      y = (1 - a) ** 2 * sy + 2 * (1 - a) * a * apex + a * a * ty;\n    } else {\n      const sy = surfaceAt(e, d.fromX, y1);\n      const k = inOut(t);\n      x = d.fromX + (bx - d.fromX) * k;\n      const apex = Math.min(sy, by) - Math.max(30, e.h * 0.12);\n      y = (1 - k) ** 2 * sy + 2 * (1 - k) * k * apex + k * k * by;\n    }\n    const vx = x - d.x;\n    const vy = y - d.y;\n    d.x = x;\n    d.y = y;\n    const speed = Math.min(1, Math.hypot(vx, vy) / 10);\n    const size = d.up ? 7 * (1 - t * 0.6) : 3 + 4.5 * Math.min(1, t * 3);\n    ctx.globalAlpha = d.up ? 1 - t ** 3 : Math.min(1, t * 8);\n    ctx.fillStyle = liquid;\n    ctx.save();\n    ctx.translate(x, y);\n    ctx.rotate(Math.atan2(vy, vx));\n    ctx.beginPath();\n    ctx.ellipse(0, 0, size * (1 + speed * 0.8), size / (1 + speed * 0.4), 0, 0, Math.PI * 2);\n    ctx.restore();\n    ctx.fill();\n    // A thin light rim so a drop reads against the liquid it falls into.\n    ctx.globalAlpha *= 0.7;\n    ctx.strokeStyle = card;\n    ctx.lineWidth = 1;\n    ctx.stroke();\n    if (t < 1) return true;\n    if (!d.up) {\n      kickSurface(e, d.toX, 210 + Math.min(120, d.amount));\n      for (let i = 0; i < 3; i++)\n        e.bits.push({ x: d.toX, y: surfaceAt(e, d.toX, y1), vx: (i - 1) * 70 + (Math.random() - 0.5) * 40, vy: -170 - Math.random() * 90, r: 1.6 + Math.random() * 1.2, bubble: false, born: now });\n      for (let i = 0; i < 3; i++)\n        e.bits.push({ x: d.toX + (Math.random() - 0.5) * 16, y: surfaceAt(e, d.toX, y1) + 14 + i * 9, vx: 0, vy: 0, r: 1.4 + Math.random() * 1.6, bubble: true, born: now + i * 60 });\n      e.land(d.amount);\n    }\n    return false;\n  });\n  ctx.globalAlpha = 1;\n\n  // The words: dark above the waterline, light below it, cut along the same curve.\n  const clipPts: string[] = [];\n  for (let i = 0; i <= 24; i++) {\n    const x = (i / 24) * e.w;\n    clipPts.push(`${x.toFixed(1)}px ${surfaceAt(e, x, y1).toFixed(1)}px`);\n  }\n  if (e.clips.below) e.clips.below.style.clipPath = f >= 1 ? \"none\" : `polygon(${clipPts.join(\",\")}, ${e.w}px ${e.h}px, 0px ${e.h}px)`;\n  if (e.clips.above) e.clips.above.style.clipPath = f >= 1 ? \"inset(0 0 100% 0)\" : `polygon(0px 0px, ${e.w}px 0px, ${[...clipPts].reverse().join(\",\")})`;\n\n  let energy = 0;\n  for (let i = 0; i < COLS; i++) energy += Math.abs(e.u[i]) + Math.abs(e.v[i]) * 0.02;\n  return e.idle || energy > 0.05 * COLS * 0.1 || e.drops.length > 0 || e.bits.length > 0;\n}\n\nexport function LiquidLog({\n  value: valueProp,\n  defaultValue = 0,\n  goal,\n  step: stepProp,\n  unit,\n  title = \"Today\",\n  icon,\n  color = \"var(--chart-1, var(--primary))\",\n  onLog,\n  onUndo,\n  format,\n  locales,\n  className = \"\",\n  style,\n  ...props\n}: LiquidLogProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const step = stepProp ?? goal / 8;\n  const [own, setOwn] = React.useState(defaultValue);\n  const controlled = valueProp !== undefined;\n  const value = controlled ? valueProp : own;\n\n  // While drops are in the air the card shows what has landed; once they're in, it shows your value.\n  const [display, setDisplay] = React.useState(value);\n  const [flying, setFlying] = React.useState(0);\n  const shown = flying > 0 ? display : value;\n\n  const [history, setHistory] = React.useState<number[]>([]);\n  const [visible, setVisible] = React.useState(false);\n  const [said, setSaid] = React.useState(\"\");\n  const [shake, setShake] = React.useState(0);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const aboveRef = React.useRef<HTMLDivElement>(null);\n  const belowRef = React.useRef<HTMLDivElement>(null);\n  const buttonRef = React.useRef<HTMLButtonElement>(null);\n  const probes = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const live = React.useRef({ value, flying, holding: false, joined: false });\n  const hold = React.useRef({ timer: 0, gap: 0 });\n  const engine = React.useRef<Engine>({\n    w: 0,\n    h: 0,\n    u: new Float32Array(COLS),\n    v: new Float32Array(COLS),\n    level: null,\n    drops: [],\n    bits: [],\n    frame: 0,\n    last: 0,\n    spare: 0,\n    colors: { liquid: \"#305dde\", card: \"#fff\", ink: \"#454545\" },\n    land: () => {},\n    clips: { above: null, below: null },\n    pointer: null,\n    idle: false,\n    t: 0,\n  });\n\n  React.useLayoutEffect(() => {\n    live.current.value = value;\n    live.current.flying = flying;\n  });\n\n  // One frame loop: it runs while the surface moves, drops fly or the level travels, then sleeps.\n  const kick = React.useCallback(() => {\n    const e = engine.current;\n    if (e.frame) return;\n    const loop = (now: number) => {\n      e.frame = 0;\n      const busy = draw(e, canvasRef.current, now);\n      const moving = !!e.level && (e.level.getVelocity() !== 0 || e.level.get() !== e.level.getTarget());\n      if (busy || moving) e.frame = requestAnimationFrame(loop);\n      else e.last = 0;\n    };\n    e.frame = requestAnimationFrame(loop);\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const e = engine.current;\n    e.clips = { above: aboveRef.current, below: belowRef.current };\n    e.level = createSpring(0, { stiffness: 60, damping: 15 }, kick, 0.0004);\n    e.land = (amount: number) => {\n      setDisplay((d) => d + amount);\n      setFlying((n) => Math.max(0, n - 1));\n    };\n    return () => {\n      e.level?.stop();\n      e.level = null;\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n      e.drops = [];\n      e.bits = [];\n    };\n  }, [kick]);\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const measure = () => {\n      const e = engine.current;\n      e.w = root.offsetWidth;\n      e.h = root.offsetHeight;\n      kick();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(root);\n    return () => observer.disconnect();\n  }, [kick]);\n\n  // The theme's colours, read again whenever the theme changes.\n  React.useEffect(() => {\n    const read = () => {\n      const [liquid, card, ink] = probes.current.map((p) => (p ? getComputedStyle(p).color : \"\"));\n      engine.current.colors = { liquid: liquid || \"#305dde\", card: card || \"#fff\", ink: ink || \"#454545\" };\n      kick();\n    };\n    read();\n    const observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n    const media = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", read);\n    return () => {\n      observer.disconnect();\n      media.removeEventListener(\"change\", read);\n    };\n  }, [color, kick]);\n\n  React.useEffect(() => {\n    const e = engine.current;\n    if (!e.level) return;\n    const target = visible && goal > 0 ? Math.max(0, shown) / goal : 0;\n    if (reduced) e.level.jump(Math.min(2, target));\n    else e.level.set(Math.min(2, target));\n  }, [shown, goal, visible, reduced]);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting) {\n          setVisible(true);\n          observer.disconnect();\n        }\n      },\n      { rootMargin: \"0px 0px -10% 0px\" },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  // The surface sways only while the card is on screen, and never with reduced motion.\n  React.useEffect(() => {\n    const el = rootRef.current;\n    const e = engine.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => {\n      e.idle = entry.isIntersecting && !reduced;\n      kick();\n    });\n    observer.observe(el);\n    return () => {\n      observer.disconnect();\n      e.idle = false;\n    };\n  }, [reduced, kick]);\n\n  React.useEffect(\n    () => () => {\n      window.clearTimeout(hold.current.timer);\n    },\n    [],\n  );\n\n  const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\n  const unitText = unit ? ` ${unit}` : \"\";\n\n  const launch = (drop: Omit<Drop, \"start\" | \"x\" | \"y\">) => {\n    const e = engine.current;\n    if (e.drops.length >= 12 || !e.w) return false;\n    e.drops.push({ ...drop, start: -1, x: e.w - INSET - BUTTON / 2, y: e.h - INSET - BUTTON });\n    kick();\n    return true;\n  };\n  // Where a drop lands: a little to the left of the middle, never twice in the same place.\n  const spot = React.useRef(0);\n  const target = () => {\n    spot.current = (spot.current + 0.38) % 1;\n    return engine.current.w * (0.28 + spot.current * 0.3);\n  };\n\n  const refuse = () => setShake((n) => n + 1);\n\n  const log = (amount: number) => {\n    const L = live.current;\n    if (!reduced && visible) {\n      if (L.flying === 0) setDisplay(L.value);\n      if (launch({ amount, up: false, fromX: 0, toX: target() })) {\n        L.flying += 1;\n        setFlying((n) => n + 1);\n      }\n    }\n    if (!controlled) setOwn((v) => v + amount);\n    // A hold is one log to undo. Read the flag now: the updater runs later, after it has moved on.\n    const join = L.joined;\n    setHistory((h) => (join && h.length ? [...h.slice(0, -1), h[h.length - 1] + amount] : [...h, amount]));\n    L.joined = L.holding;\n    let result: Promise<unknown> | void;\n    try {\n      result = onLog?.(amount);\n    } catch {\n      refuse();\n      if (!controlled) setOwn((v) => v - amount);\n      return;\n    }\n    if (result && typeof (result as Promise<unknown>).then === \"function\") {\n      (result as Promise<unknown>).then(undefined, () => {\n        refuse();\n        if (!controlled) setOwn((v) => v - amount);\n      });\n    }\n  };\n\n  const stopHold = () => {\n    window.clearTimeout(hold.current.timer);\n    if (!live.current.holding) return;\n    live.current.holding = false;\n    live.current.joined = false;\n    setSaid(`Logged. ${fmt(live.current.value)}${unitText} of ${fmt(goal)}${unitText}.`);\n  };\n\n  const pour = () => {\n    log(step);\n    hold.current.gap = Math.max(140, hold.current.gap * 0.86);\n    hold.current.timer = window.setTimeout(pour, hold.current.gap);\n  };\n\n  const canUndo = history.length > 0 && (!controlled || !!onUndo);\n  const undo = () => {\n    const amount = history[history.length - 1];\n    if (amount === undefined) return;\n    setHistory((h) => h.slice(0, -1));\n    if (!reduced) {\n      const x = target();\n      kickSurface(engine.current, x, -160);\n      launch({ amount, up: true, fromX: x, toX: 0 });\n    }\n    if (!controlled) setOwn((v) => v - amount);\n    const result = onUndo?.(amount);\n    if (result && typeof (result as Promise<unknown>).then === \"function\") (result as Promise<unknown>).then(undefined, refuse);\n    setSaid(`Removed ${fmt(amount)}${unitText}.`);\n  };\n\n  React.useEffect(() => {\n    if (!shake || reduced) return;\n    buttonRef.current?.animate(\n      [{ translate: \"0 0\" }, { translate: \"-4px 0\" }, { translate: \"4px 0\" }, { translate: \"-2px 0\" }, { translate: \"0 0\" }],\n      { duration: 380, easing: \"ease-out\" },\n    );\n  }, [shake, reduced]);\n\n  // A pointer moving along the waterline leaves a small wake.\n  const wake = (e: React.PointerEvent) => {\n    if (reduced || e.pointerType !== \"mouse\") return;\n    const en = engine.current;\n    const root = rootRef.current;\n    if (!root || !en.level) return;\n    const r = root.getBoundingClientRect();\n    const x = e.clientX - r.left;\n    const y = e.clientY - r.top;\n    const last = en.pointer;\n    en.pointer = { x, y };\n    if (!last) return;\n    const surface = levelY(en, Math.max(0, en.level.get()));\n    if (Math.abs(y - surface) > 22 || en.level.get() >= 1) return;\n    const dx = x - last.x;\n    if (Math.abs(dx) < 1) return;\n    kickSurface(en, x, Math.max(-60, Math.min(60, Math.abs(dx) * 5)) * (y < surface ? 1 : -1), 1.6);\n    kick();\n  };\n\n  const pct = goal > 0 ? Math.round((Math.max(0, shown) / goal) * 100) : 0;\n  const last = history[history.length - 1];\n  const onLiquid = `oklch(from ${color} clamp(0.22, (0.72 - l) * 100, 0.99) calc(c * 0.3) h)`;\n\n  // The words, drawn twice: once in ink above the waterline, once light below it.\n  const words = (light: boolean) => (\n    <div className=\"flex h-full flex-col p-4 @[17rem]:p-5\">\n      <p className=\"flex h-7 min-w-0 items-center gap-1.5 pr-28 text-[12.5px]\" style={{ color: light ? onLiquid : \"var(--muted-foreground)\" }}>\n        {icon && (\n          <span className=\"flex size-3.5 shrink-0 items-center justify-center [&>svg]:size-3.5\" style={{ color: light ? onLiquid : color }}>\n            {icon}\n          </span>\n        )}\n        <span className=\"truncate\">{title}</span>\n      </p>\n      <p className=\"mt-2 text-[40px] font-medium leading-none tracking-[-0.045em] tabular-nums @[17rem]:text-[46px]\" style={{ color: light ? onLiquid : \"var(--foreground)\" }}>\n        <NumberRoll value={visible ? shown : 0} format={format} locales={locale} duration={900} />\n        {unit && (\n          <span className=\"ml-1 text-[15px] font-normal tracking-normal\" style={{ opacity: 0.7 }}>\n            {unit}\n          </span>\n        )}\n      </p>\n      <p className=\"mt-2 text-[12.5px] tabular-nums\" style={{ color: light ? onLiquid : \"var(--muted-foreground)\" }}>\n        <span className=\"font-medium\" style={{ color: light ? onLiquid : color }}>\n          <NumberRoll value={visible ? pct : 0} duration={900} suffix=\"%\" />\n        </span>{\" \"}\n        of {fmt(goal)}\n        {unitText}\n      </p>\n      <p className=\"mt-auto text-[11.5px] font-medium tabular-nums\" style={{ color: light ? onLiquid : \"var(--muted-foreground)\", opacity: 0.85 }}>\n        +{fmt(step)}\n        {unitText} a tap\n      </p>\n    </div>\n  );\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"group\"\n      aria-label={title}\n      onPointerMove={wake}\n      onPointerLeave={() => void (engine.current.pointer = null)}\n      className={`relative isolate aspect-[1/1.02] w-full overflow-clip rounded-[24px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`}\n      style={style}\n      {...props}\n    >\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 300px)\" }} />\n      <canvas ref={canvasRef} aria-hidden=\"true\" className=\"absolute inset-0 size-full\" />\n      <div className=\"@container absolute inset-0\">\n        <div\n          ref={aboveRef}\n          role=\"meter\"\n          aria-label={title}\n          aria-valuemin={0}\n          aria-valuemax={goal}\n          aria-valuenow={Math.max(0, shown)}\n          aria-valuetext={`${fmt(shown)}${unitText} of ${fmt(goal)}${unitText}, ${pct}%`}\n          className=\"absolute inset-0\"\n        >\n          {words(false)}\n        </div>\n        <div ref={belowRef} aria-hidden=\"true\" inert className=\"pointer-events-none absolute inset-0\" style={{ clipPath: \"inset(100% 0 0 0)\" }}>\n          {words(true)}\n        </div>\n\n        <div\n          className=\"absolute right-4 top-4 grid transition-[grid-template-columns,opacity] duration-[420ms] @[17rem]:right-5 @[17rem]:top-5\"\n          style={{ gridTemplateColumns: canUndo ? \"1fr\" : \"0fr\", opacity: canUndo ? 1 : 0, transitionTimingFunction: EASE }}\n        >\n          <div className=\"flex min-w-0 justify-end overflow-clip\">\n            <button\n              type=\"button\"\n              tabIndex={canUndo ? 0 : -1}\n              aria-hidden={!canUndo}\n              onClick={undo}\n              className={`inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full bg-background pl-2.5 pr-3 text-[12px] text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] transition-[color,scale] duration-200 hover:text-foreground active:scale-[0.97] ${FOCUS}`}\n              style={{ transitionTimingFunction: EASE }}\n            >\n              <Undo2 aria-hidden=\"true\" className=\"size-3.5\" />\n              <TextMorph>{`Undo ${fmt(last ?? step)}${unitText}`}</TextMorph>\n            </button>\n          </div>\n        </div>\n\n        <button\n          ref={buttonRef}\n          type=\"button\"\n          aria-label={`Log ${fmt(step)}${unitText}`}\n          onPointerDown={(e) => {\n            if (e.button !== 0) return;\n            live.current.holding = true;\n            live.current.joined = false;\n            log(step);\n            hold.current.gap = 320;\n            window.clearTimeout(hold.current.timer);\n            hold.current.timer = window.setTimeout(pour, 460);\n          }}\n          onPointerUp={stopHold}\n          onPointerLeave={stopHold}\n          onPointerCancel={stopHold}\n          onClick={(e) => {\n            // Pointer presses log on the way down; this is the keyboard.\n            if (e.detail !== 0) return;\n            log(step);\n            setSaid(`Logged ${fmt(step)}${unitText}.`);\n          }}\n          onContextMenu={(e) => e.preventDefault()}\n          className={`absolute bottom-4 right-4 flex cursor-pointer touch-manipulation select-none items-center justify-center rounded-full bg-background shadow-[inset_0_0_0_1px_var(--border)] transition-[scale] duration-200 active:scale-[0.9] ${MATERIAL_LIFT} ${FOCUS}`}\n          style={{ width: BUTTON, height: BUTTON, color, transitionTimingFunction: EASE, WebkitTouchCallout: \"none\" }}\n        >\n          <Plus aria-hidden=\"true\" className=\"size-6\" strokeWidth={2.4} />\n        </button>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {said}\n      </p>\n      {/* Colour probes for the canvas. */}\n      <span ref={(el) => void (probes.current[0] = el)} aria-hidden=\"true\" className=\"hidden\" style={{ color }} />\n      <span ref={(el) => void (probes.current[1] = el)} aria-hidden=\"true\" className=\"hidden text-background\" />\n      <span ref={(el) => void (probes.current[2] = el)} aria-hidden=\"true\" className=\"hidden text-foreground\" />\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · liquid-log · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/liquid-log. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}