{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"rewind","title":"Rewind","description":"A textarea you can rewind. Hold undo and drag, and your writing runs back under your hand, with the words you deleted coming back in colour.","type":"registry:component","author":"Detent","dependencies":["motion"],"registryDependencies":["https://detentui.com/r/theme.json"],"files":[{"path":"components/detent/components/rewind/Rewind.tsx","target":"components/detent/components/rewind/Rewind.tsx","type":"registry:component","content":"'use client'\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from 'react'\nimport { useReducedMotion } from 'motion/react'\nimport { clamp, feedback, notched, useDetent } from '@/components/detent/lib/detent'\n\nexport type RewindStep = { text: string; caret: number; t: number }\nexport type RewindCell = { id: number; c: string; born: number; died: number }\nexport type RewindHistory = { steps: RewindStep[]; tape: RewindCell[] }\ntype Token = { space: boolean; cells: number[] }\n\nexport type RewindProps = {\n  value?: string\n  defaultValue?: string\n  onChange?: (value: string) => void\n  history?: RewindHistory\n  onHistory?: (history: RewindHistory) => void\n  pill?: boolean\n  lost?: string\n  ghost?: number\n  intro?: number\n  rows?: number\n  maxHeight?: number\n  placeholder?: string\n  label?: string\n  className?: string\n}\n\nexport const NEVER = Number.MAX_SAFE_INTEGER\nconst HOLD = 220\nconst PAUSE = 2.5\nconst GAIN = 0.75\nconst EDGE = 36\nconst GLIDE = 30\nconst LIMIT = 6000\n\nconst VERTEX = `attribute vec2 a;varying vec2 u;void main(){u=(a+1.)/2.;gl_Position=vec4(a,0.,1.);}`\nconst FRAGMENT = `precision highp float;\nvarying vec2 u;\nuniform sampler2D T;\nuniform vec3 ink,lost;\nuniform float cell,ghost;\nfloat hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}\nvoid main(){\n  vec4 t=texture2D(T,vec2(u.x,1.-u.y));\n  if(t.a<.004){gl_FragColor=vec4(0.);return;}\n  float L=t.r;\n  vec2 g=gl_FragCoord.xy/cell;\n  float h=hash(floor(g));\n  float d=length(fract(g)-.5)*2.;\n  float on=smoothstep(h-.08,h+.08,L*1.16-.08);\n  float dot_=mix(smoothstep(1.05,.55,d),1.,smoothstep(.62,.98,L));\n  float lit=L>.992?1.:on*dot_;\n  float a=t.a*mix(ghost,1.,lit);\n  vec3 c=t.g>.5?lost:ink;\n  gl_FragColor=vec4(c*a,a);\n}`\n\nconst rgb = (color: string) => {\n  const x = document.createElement('canvas').getContext('2d')!\n  x.fillStyle = '#000'\n  x.fillStyle = color\n  const v = x.fillStyle\n  if (v.startsWith('#')) return [1, 3, 5].map((i) => parseInt(v.slice(i, i + 2), 16) / 255)\n  return (v.match(/[\\d.]+/g) ?? ['0', '0', '0']).slice(0, 3).map((n) => Number(n) / 255)\n}\n\nconst living = (tape: RewindCell[]) => tape.filter((m) => m.died === NEVER)\nconst slot = (tape: RewindCell[], at: number) => {\n  while (at < tape.length && tape[at].died !== NEVER) at++\n  return at\n}\n\nfunction tokens(tape: RewindCell[]) {\n  const out: Token[] = []\n  tape.forEach((m, k) => {\n    const space = /\\s/.test(m.c)\n    const top = out[out.length - 1]\n    const dead = m.died !== NEVER\n    if (top && !top.space && !space && (tape[top.cells[0]].died !== NEVER) === dead) top.cells.push(k)\n    else out.push({ space, cells: [k] })\n  })\n  return out\n}\n\nconst fresh = (text: string): RewindHistory => {\n  return { steps: [{ text, caret: text.length, t: 0 }], tape: [...text].map((c, id) => ({ id, c, born: 0, died: NEVER })) }\n}\n\nconst ago = (s: number) => (s < 5 ? 'Just now' : s < 60 ? `${Math.round(s / 5) * 5} seconds ago` : s < 3600 ? `${Math.round(s / 60)} min ago` : `${Math.round(s / 3600)} hr ago`)\n\nexport function Rewind({ value, defaultValue = '', onChange, history: saved, onHistory, pill: showPill = true, lost = '#0a6cff', ghost = 0.13, intro, rows = 6, maxHeight, placeholder, label = 'Note', className = '' }: RewindProps) {\n  const reduce = !!useReducedMotion()\n  const seed = useMemo(() => saved ?? fresh(value ?? defaultValue), []) // eslint-disable-line react-hooks/exhaustive-deps\n  const steps = useRef(seed.steps)\n  const tape = useRef(seed.tape)\n  const nextId = useRef(seed.tape.reduce((a, m) => Math.max(a, m.id + 1), 0))\n  const [count, setCount] = useState(seed.steps.length)\n  const [version, setVersion] = useState(0)\n  const last = count - 1\n  const marks = useMemo(() => {\n    const h = steps.current\n    return h.flatMap((s, i) => (i === 0 || i === h.length - 1 || h[i + 1]?.t - s.t > PAUSE ? [i] : []))\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [count])\n\n  const box = useRef<HTMLTextAreaElement>(null)\n  const view = useRef<HTMLDivElement>(null)\n  const page = useRef<HTMLDivElement>(null)\n  const layer = useRef<HTMLDivElement>(null)\n  const bar = useRef<HTMLSpanElement>(null)\n  const glow = useRef<HTMLCanvasElement>(null)\n  const fill = useRef<HTMLSpanElement>(null)\n  const cells = useRef<(HTMLSpanElement | null)[]>([])\n  const wordEls = useRef<(HTMLSpanElement | null)[]>([])\n  const draft = useRef<HTMLCanvasElement | null>(null)\n  const gl = useRef<{ c: WebGLRenderingContext; u: (n: string) => WebGLUniformLocation | null } | null>(null)\n  const seats = useRef(new Map<number, { x: number; y: number }>())\n  const drift = useRef(new Map<number, { x: number; y: number }>())\n  const chase = useRef<number | null>(null)\n  const raf = useRef(0)\n  const then = useRef(0)\n  const [plain, setPlain] = useState(false)\n  const [at, setAt] = useState(seed.steps.length - 1)\n  const [live, setLive] = useState(false)\n  const shown = useRef(seed.steps.length - 1)\n  const exact = useRef(seed.steps.length - 1)\n  const playing = useRef(false)\n  const hand = useRef(0)\n  const home = useRef(0)\n  const mouse = useRef<number | null>(null)\n  const timer = useRef(0)\n  const held = useRef(false)\n  const composing = useRef(false)\n  const edge = reduce ? 1 : EDGE\n  const rest = at === last && !live\n  const words = useMemo(() => (rest ? [] : tokens(tape.current)), [version, rest]) // eslint-disable-line react-hooks/exhaustive-deps\n  const ready = useRef(false)\n  const quiet = useRef(false)\n\n  const draw = () => {\n    const i = shown.current\n    const soft = exact.current\n    const el = glow.current, core = gl.current, root = view.current, type = layer.current\n    if (!el || !core || !root || !type) return\n    const dpr = Math.min(2, devicePixelRatio || 1)\n    const W = Math.round(root.clientWidth * dpr), H = Math.round(root.clientHeight * dpr)\n    if (!W || !H) return\n    if (!draft.current) draft.current = document.createElement('canvas')\n    const off = draft.current\n    if (off.width !== W || off.height !== H) {\n      off.width = el.width = W\n      off.height = el.height = H\n      core.c.viewport(0, 0, W, H)\n    }\n    const x = off.getContext('2d')!\n    const end = steps.current.length - 1\n    const style = getComputedStyle(type)\n    x.setTransform(1, 0, 0, 1, 0, 0)\n    x.clearRect(0, 0, W, H)\n    x.setTransform(dpr, 0, 0, dpr, 0, 0)\n    x.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`\n    x.textBaseline = 'alphabetic'\n    const lift = x.measureText('x').fontBoundingBoxAscent\n    const size = parseFloat(style.fontSize)\n    const top = root.scrollTop\n    for (const w of words) {\n      if (w.space) continue\n      const shift = drift.current.get(w.cells[0])\n      for (const k of w.cells) {\n        const seat = seats.current.get(k)\n        if (!seat) continue\n        const y = seat.y - top + (shift?.y ?? 0)\n        if (y < -size * 2 || y > root.clientHeight + size) continue\n        const m = tape.current[k]\n        const on = m.born <= i && i < m.died\n        const L = i === end ? 1 : on ? clamp((soft - m.born + 1) / edge, 0, 1) : 0\n        x.fillStyle = `rgb(${Math.round(L * 255)},${on && m.died !== NEVER ? 255 : 0},0)`\n        x.fillText(m.c, seat.x + (shift?.x ?? 0), y + lift)\n      }\n    }\n    const c = core.c\n    c.texImage2D(c.TEXTURE_2D, 0, c.RGBA, c.RGBA, c.UNSIGNED_BYTE, off)\n    c.uniform3fv(core.u('ink'), rgb(getComputedStyle(root).color))\n    c.uniform1f(core.u('cell'), 1.25 * dpr)\n    c.clearColor(0, 0, 0, 0)\n    c.clear(c.COLOR_BUFFER_BIT)\n    c.drawArrays(c.TRIANGLES, 0, 3)\n  }\n\n  const settle = (now: number) => {\n    const dt = Math.min(0.05, (now - then.current) / 1000)\n    then.current = now\n    let busy = false\n    const e = Math.exp(-GLIDE * dt)\n    drift.current.forEach((v, k) => {\n      v.x *= e\n      v.y *= e\n      if (Math.abs(v.x) + Math.abs(v.y) < 0.15) drift.current.delete(k)\n      else busy = true\n    })\n    const root = view.current\n    if (root && chase.current !== null) {\n      const left = chase.current - root.scrollTop\n      if (Math.abs(left) < 1) chase.current = null\n      else {\n        root.scrollTop += left * (1 - Math.exp(-12 * dt))\n        busy = true\n      }\n    }\n    latest.current.draw()\n    raf.current = busy ? requestAnimationFrame(latest.current.settle) : 0\n  }\n  const wake = () => {\n    if (raf.current) return\n    then.current = performance.now()\n    raf.current = requestAnimationFrame(latest.current.settle)\n  }\n\n  const paint = (i: number) => {\n    const end = steps.current.length - 1\n    const root = page.current\n    if (fill.current) fill.current.style.transform = `translate3d(${(i / Math.max(1, end) - 1) * 100}%,0,0)`\n    if (!ready.current) return\n    tape.current.forEach((m, k) => {\n      const el = cells.current[k]\n      if (!el) return\n      const display = (m.born <= i && i < m.died) || m.died === NEVER ? '' : 'none'\n      if (el.style.display !== display) el.style.display = display\n    })\n    if (root) {\n      const r = root.getBoundingClientRect()\n      const scale = root.offsetWidth ? r.width / root.offsetWidth || 1 : 1\n      const size_ = parseFloat(getComputedStyle(root).fontSize)\n      words.forEach((w, n) => {\n        const el = wordEls.current[n]\n        if (!el) return\n        const seen = w.cells.some((k) => cells.current[k]?.style.display !== 'none')\n        el.style.display = seen ? '' : 'none'\n        const after = words[n + 1]\n        const ends = !after || tape.current[after.cells[0]].died === NEVER\n        if (!w.space) el.style.marginRight = seen && ends && tape.current[w.cells[0]].died !== NEVER ? '.26em' : ''\n      })\n      for (const w of words) {\n        if (w.space) continue\n        let first = true\n        for (const k of w.cells) {\n          const el = cells.current[k]\n          if (!el || el.style.display === 'none') {\n            seats.current.delete(k)\n            continue\n          }\n          const q = el.getBoundingClientRect()\n          const seat = { x: (q.left - r.left) / scale, y: (q.top - r.top) / scale }\n          const old = seats.current.get(k)\n          if (old && first && !reduce) {\n            const was = drift.current.get(w.cells[0]) ?? { x: 0, y: 0 }\n            const dx = old.x + was.x - seat.x, dy = old.y + was.y - seat.y\n            if (Math.abs(dy) > size_ / 2) drift.current.delete(w.cells[0])\n            else if (Math.abs(dx) > 0.5) drift.current.set(w.cells[0], { x: dx, y: 0 })\n          }\n          first = false\n          seats.current.set(k, seat)\n        }\n      }\n    }\n    const mark = bar.current, frame = view.current\n    if (mark && root && frame) {\n      let seen = 0\n      let prior: HTMLSpanElement | null = null\n      const want = steps.current[i].caret\n      for (let k = 0; k < tape.current.length && seen < want; k++) {\n        const m = tape.current[k]\n        if (m.born <= i && i < m.died) {\n          seen++\n          prior = cells.current[k]\n        }\n      }\n      const q = prior?.getBoundingClientRect(), r = root.getBoundingClientRect()\n      const scale = root.offsetWidth ? r.width / root.offsetWidth || 1 : 1\n      const y = q ? (q.top - r.top) / scale : 0\n      mark.style.opacity = i === end ? '0' : '1'\n      mark.style.height = q ? `${q.height / scale}px` : '1.3em'\n      mark.style.transform = `translate3d(${q ? (q.right - r.left) / scale : 0}px,${y}px,0)`\n      const pad = 48\n      if (i !== end && (y < frame.scrollTop + pad || y > frame.scrollTop + frame.clientHeight - pad)) chase.current = clamp(y - frame.clientHeight / 2, 0, frame.scrollHeight - frame.clientHeight)\n    }\n    draw()\n    if (drift.current.size || chase.current !== null) wake()\n  }\n\n  const show = (x: number) => {\n    if (quiet.current) return\n    exact.current = x\n    if (playing.current) {\n      const i = clamp(Math.round(x), 0, steps.current.length - 1)\n      if (i !== shown.current) {\n        shown.current = i\n        setAt(i)\n        paint(i)\n      } else draw()\n      return\n    }\n    const near = marks.reduce((a, m) => (Math.abs(m - x) < Math.abs(a - x) ? m : a), marks[0] ?? 0)\n    const i = clamp(Math.round(notched(x, [near], 5, 0.6)), 0, steps.current.length - 1)\n    if (i === shown.current) return draw()\n    if (marks.includes(i)) feedback.tick()\n    shown.current = i\n    setAt(i)\n    paint(i)\n  }\n  const latest = useRef({ show, draw, settle, glide: (_: number) => {} })\n  latest.current = { ...latest.current, show, draw, settle }\n  const goal = useRef(seed.steps.length - 1)\n  const soft = useRef(seed.steps.length - 1)\n  const trail = useRef(0)\n  const trailed = useRef(0)\n  const glide = (now: number) => {\n    const dt = Math.min(0.05, (now - trailed.current) / 1000)\n    trailed.current = now\n    soft.current += (goal.current - soft.current) * (1 - Math.exp(-24 * dt))\n    if (Math.abs(goal.current - soft.current) < 0.02) soft.current = goal.current\n    latest.current.show(soft.current)\n    trail.current = soft.current === goal.current ? 0 : requestAnimationFrame(latest.current.glide)\n  }\n  latest.current.glide = glide\n  const follow = (x: number) => {\n    goal.current = x\n    if (reduce || quiet.current) {\n      soft.current = x\n      return show(x)\n    }\n    if (trail.current) return\n    trailed.current = performance.now()\n    trail.current = requestAnimationFrame(latest.current.glide)\n  }\n  const d = useDetent({ value: last, min: 0, max: Math.max(1, last), reach: 18, spring: { w: 18, z: 1 }, onFrame: (x) => follow(x) })\n\n  useLayoutEffect(() => {\n    if (!gl.current && glow.current) {\n      const c = glow.current.getContext('webgl', { alpha: true, premultipliedAlpha: true, antialias: false, preserveDrawingBuffer: true })\n      if (!c) setPlain(true)\n      else {\n        const sh = (t: number, src: string) => {\n          const o = c.createShader(t)!\n          c.shaderSource(o, src)\n          c.compileShader(o)\n          return o\n        }\n        const prog = c.createProgram()!\n        c.attachShader(prog, sh(c.VERTEX_SHADER, VERTEX))\n        c.attachShader(prog, sh(c.FRAGMENT_SHADER, FRAGMENT))\n        c.linkProgram(prog)\n        c.useProgram(prog)\n        c.bindBuffer(c.ARRAY_BUFFER, c.createBuffer())\n        c.bufferData(c.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), c.STATIC_DRAW)\n        const a = c.getAttribLocation(prog, 'a')\n        c.enableVertexAttribArray(a)\n        c.vertexAttribPointer(a, 2, c.FLOAT, false, 0, 0)\n        c.bindTexture(c.TEXTURE_2D, c.createTexture())\n        c.texParameteri(c.TEXTURE_2D, c.TEXTURE_MIN_FILTER, c.NEAREST)\n        c.texParameteri(c.TEXTURE_2D, c.TEXTURE_MAG_FILTER, c.NEAREST)\n        c.texParameteri(c.TEXTURE_2D, c.TEXTURE_WRAP_S, c.CLAMP_TO_EDGE)\n        c.texParameteri(c.TEXTURE_2D, c.TEXTURE_WRAP_T, c.CLAMP_TO_EDGE)\n        const u = (n: string) => c.getUniformLocation(prog, n)\n        c.uniform3fv(u('lost'), rgb(lost))\n        c.uniform1f(u('ghost'), ghost)\n        gl.current = { c, u }\n      }\n    }\n    quiet.current = true\n    if (rest) d.set(shown.current)\n    quiet.current = false\n    ready.current = !rest\n    drift.current.clear()\n    seats.current.clear()\n    paint(shown.current)\n    if (rest) return\n    const again = () => {\n      seats.current.clear()\n      paint(shown.current)\n    }\n    void document.fonts?.ready.then(again)\n    const watch = new ResizeObserver(again)\n    if (view.current) watch.observe(view.current)\n    return () => watch.disconnect()\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [version, rest])\n\n  useEffect(() => {\n    const el = box.current!\n    el.value = steps.current[shown.current].text\n    return () => {\n      cancelAnimationFrame(raf.current)\n      cancelAnimationFrame(trail.current)\n    }\n  }, [])\n\n  const begin = () => {\n    feedback.wake(true)\n    home.current = shown.current\n    hand.current = shown.current\n    d.grab(hand.current)\n    setLive(true)\n  }\n  const move = (px: number) => {\n    hand.current += px * GAIN\n    d.drag(hand.current)\n  }\n  const place = (i: number) => {\n    const el = box.current\n    if (!el) return\n    const s = steps.current[i]\n    el.value = s.text\n    el.setSelectionRange(s.caret, s.caret)\n  }\n  const end = (keep: boolean) => {\n    held.current = false\n    mouse.current = null\n    setLive(false)\n    const i = keep ? shown.current : home.current\n    d.release({ flick: false, home: i })\n    place(i)\n    box.current?.focus()\n  }\n  const stepTo = (i: number) => {\n    feedback.wake()\n    d.to(i, { spring: { w: 40, z: 1 } })\n    place(i)\n  }\n  const prev = () => [...marks].reverse().find((m) => m < shown.current) ?? 0\n  const next = () => marks.find((m) => m > shown.current) ?? steps.current.length - 1\n\n  useEffect(() => {\n    if (!live) return\n    const over = (e: MouseEvent) => {\n      if (!held.current) return\n      if (mouse.current !== null) move(e.clientX - mouse.current)\n      mouse.current = e.clientX\n    }\n    const wheel = (e: WheelEvent) => {\n      e.preventDefault()\n      move((e.deltaX || e.deltaY) * -0.6)\n    }\n    const up = (e: KeyboardEvent) => {\n      if (held.current && (e.key === 'Meta' || e.key === 'Control' || e.key.toLowerCase() === 'z')) end(true)\n    }\n    addEventListener('mousemove', over)\n    addEventListener('wheel', wheel, { passive: false })\n    addEventListener('keyup', up)\n    return () => {\n      removeEventListener('mousemove', over)\n      removeEventListener('wheel', wheel)\n      removeEventListener('keyup', up)\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [live])\n\n  const keys = (e: ReactKeyboardEvent) => {\n    if (e.key === 'Escape' && live) return end(false)\n    if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== 'z') return\n    e.preventDefault()\n    if (e.repeat) return\n    if (e.shiftKey) return stepTo(next())\n    window.clearTimeout(timer.current)\n    const was = shown.current\n    timer.current = window.setTimeout(() => {\n      held.current = true\n      begin()\n    }, HOLD)\n    const lift = (u: globalThis.KeyboardEvent) => {\n      if (u.key !== 'Meta' && u.key !== 'Control' && u.key.toLowerCase() !== 'z') return\n      removeEventListener('keyup', lift)\n      window.clearTimeout(timer.current)\n      if (!held.current && shown.current === was) stepTo(prev())\n    }\n    addEventListener('keyup', lift)\n  }\n\n  const record = (text: string, caret: number) => {\n    const i = shown.current\n    const old = steps.current[i].text\n    if (text === old) return\n    const step = i + 1\n    tape.current = tape.current.filter((m) => m.born <= i)\n    tape.current.forEach((m) => {\n      if (m.died > i) m.died = NEVER\n    })\n    const keep = steps.current.slice(0, i + 1)\n    let head = 0\n    while (head < old.length && head < text.length && old[head] === text[head]) head++\n    let tail = 0\n    while (tail < old.length - head && tail < text.length - head && old[old.length - 1 - tail] === text[text.length - 1 - tail]) tail++\n    const alive = living(tape.current)\n    for (let k = head; k < old.length - tail; k++) alive[k].died = step\n    const after = slot(tape.current, head ? tape.current.indexOf(alive[head - 1]) + 1 : 0)\n    tape.current.splice(after, 0, ...[...text.slice(head, text.length - tail)].map((c) => ({ id: nextId.current++, c, born: step, died: NEVER })))\n    const now = Date.now() / 1000\n    if (!keep[0].t) keep[0] = { ...keep[0], t: now }\n    keep.push({ text, caret, t: now })\n    if (keep.length > LIMIT) {\n      const cut = keep.length - LIMIT\n      keep.splice(0, cut)\n      tape.current = tape.current.filter((m) => m.died > cut).map((m) => ({ ...m, born: Math.max(0, m.born - cut), died: m.died === NEVER ? NEVER : m.died - cut }))\n    }\n    steps.current = keep\n    shown.current = keep.length - 1\n    setCount(keep.length)\n    setAt(keep.length - 1)\n    setVersion((v) => v + 1)\n    quiet.current = true\n    d.set(keep.length - 1)\n    quiet.current = false\n    onHistory?.({ steps: keep, tape: tape.current })\n  }\n\n  const input = () => {\n    if (composing.current) return\n    const el = box.current!\n    record(el.value, el.selectionStart)\n    onChange?.(el.value)\n  }\n\n  useEffect(() => {\n    if (value !== undefined && value !== steps.current[shown.current].text) {\n      record(value, value.length)\n      if (box.current) box.current.value = value\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [value])\n\n  const press = (e: ReactPointerEvent) => {\n    e.currentTarget.setPointerCapture(e.pointerId)\n    begin()\n    mouse.current = e.clientX\n  }\n  const drag = (e: ReactPointerEvent) => {\n    if (mouse.current === null || held.current) return\n    move(e.clientX - mouse.current)\n    mouse.current = e.clientX\n  }\n  const show_ = useRef<number[]>([])\n  const stopIntro = () => {\n    show_.current.forEach((t) => window.clearTimeout(t))\n    show_.current = []\n    playing.current = false\n  }\n  useEffect(() => {\n    if (intro === undefined || reduce) return\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (!e.isIntersecting) return\n        io.disconnect()\n        playing.current = true\n        const end = steps.current.length - 1\n        show_.current = [\n          window.setTimeout(() => d.sweep(intro, 3400), 600),\n          window.setTimeout(() => d.sweep(end, 2200), 5200),\n          window.setTimeout(() => stopIntro(), 7600),\n        ]\n      },\n      { threshold: 0.6 },\n    )\n    if (view.current) io.observe(view.current)\n    return () => {\n      io.disconnect()\n      stopIntro()\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [intro, reduce])\n  const touched = (e: ReactPointerEvent) => {\n    if (!playing.current) return\n    stopIntro()\n    if (!(e.target as HTMLElement).closest('[role=slider]')) stepTo(steps.current.length - 1)\n  }\n\n  const pillKeys = (e: ReactKeyboardEvent) => {\n    const go = { ArrowLeft: prev, ArrowRight: next }[e.key]\n    if (go) {\n      e.preventDefault()\n      return stepTo(go())\n    }\n    keys(e)\n  }\n\n  const word = at === last ? 'Now' : ago(steps.current[last].t - steps.current[at].t)\n  return (\n    <div onPointerDownCapture={touched} onKeyDownCapture={stopIntro} className={`w-full ${className}`}>\n      <div className=\"relative\">\n        <div\n          ref={view}\n          onScroll={draw}\n          className=\"overflow-y-auto overscroll-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n          style={{ maxHeight }}\n        >\n          <div ref={page} className=\"relative\" style={{ minHeight: `${rows * 1.4}em` }}>\n            <div ref={layer} aria-hidden className={`pointer-events-none min-h-[1lh] whitespace-pre-wrap break-words ${plain && !rest ? '' : 'text-transparent'}`}>\n              {rest && steps.current[at].text}\n              {words.map((w, n) => (\n                <span\n                  key={tape.current[w.cells[0]].id}\n                  ref={(el) => {\n                    wordEls.current[n] = el\n                  }}\n                  className={w.space ? undefined : 'inline-block'}\n                >\n                  {w.cells.map((k) => (\n                    <span\n                      key={tape.current[k].id}\n                      ref={(el) => {\n                        cells.current[k] = el\n                      }}\n                    >\n                      {tape.current[k].c}\n                    </span>\n                  ))}\n                </span>\n              ))}\n              {'​'}\n            </div>\n            <span ref={bar} aria-hidden className=\"pointer-events-none absolute left-0 top-0 w-[2px] rounded-full bg-current opacity-0\" />\n            <textarea\n              ref={box}\n              aria-label={label}\n              placeholder={placeholder}\n              spellCheck={false}\n              readOnly={live}\n              onChange={input}\n              onCompositionStart={() => (composing.current = true)}\n              onCompositionEnd={() => {\n                composing.current = false\n                input()\n              }}\n              onKeyDown={keys}\n              className={`absolute inset-0 size-full resize-none overflow-hidden whitespace-pre-wrap break-words border-0 bg-transparent p-0 outline-none placeholder:text-current/40 [font:inherit] [letter-spacing:inherit] ${rest ? 'text-inherit' : 'text-transparent'}`}\n              style={{ caretColor: rest ? 'currentColor' : 'transparent' }}\n            />\n          </div>\n        </div>\n        <canvas ref={glow} aria-hidden className={`pointer-events-none absolute inset-0 size-full ${plain || rest ? 'invisible' : ''}`} />\n      </div>\n      {showPill && (\n        <div className=\"sticky bottom-6 mt-6 flex justify-center\">\n          <button\n            type=\"button\"\n            role=\"slider\"\n            aria-label=\"Rewind\"\n            aria-valuemin={0}\n            aria-valuemax={last}\n            aria-valuenow={at}\n            aria-valuetext={word}\n            onPointerDown={press}\n            onPointerMove={drag}\n            onPointerUp={() => mouse.current !== null && !held.current && end(true)}\n            onPointerCancel={() => mouse.current !== null && !held.current && end(false)}\n            onKeyDown={pillKeys}\n            className={`ring-focus relative h-9 w-[148px] max-w-full cursor-ew-resize touch-none select-none overflow-hidden rounded-full bg-surface text-[14px] font-medium not-italic leading-none tracking-[-.005em] shadow-[0_0_0_.5px_var(--line),0_1px_2px_rgb(0_0_0/.05)] transition-[scale,color] ease-detent duration-150 before:absolute before:-inset-y-1.5 before:inset-x-0 active:scale-[.98] ${rest ? 'text-ink-3' : 'text-ink'}`}\n          >\n            <span ref={fill} aria-hidden className=\"absolute inset-0 bg-ink/[.07]\" />\n            <span className=\"tnum relative\">{word}</span>\n          </button>\n        </div>\n      )}\n    </div>\n  )\n}\n"},{"path":"components/detent/lib/detent.ts","target":"components/detent/lib/detent.ts","type":"registry:component","content":"import { useLayoutEffect, useRef, useState } from 'react'\nimport type { KeyboardEvent, PointerEvent as ReactPointerEvent } from 'react'\nimport { useReducedMotion } from 'motion/react'\n\nexport const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n))\nexport const lerp = (a: number, b: number, t: number) => a + (b - a) * t\nexport const glide = (a: number, b: number, t: number) => (a > 0 && b > 0 ? a * Math.pow(b / a, t) : lerp(a, b, t))\n\nexport const notched = (x: number, centres: number[], reach: number, hold = 0.7) => {\n  for (const c of centres) {\n    const d = (x - c) / reach\n    if (Math.abs(d) < 1) return x - ((hold * reach) / Math.PI) * Math.sin(Math.PI * d) * ((1 + Math.cos(Math.PI * d)) / 2)\n  }\n  return x\n}\n\nexport const at = (list: number[], i: number, mix = lerp) => {\n  const a = clamp(Math.floor(i), 0, list.length - 1)\n  return mix(list[a], list[Math.min(list.length - 1, a + 1)], clamp(i - a, 0, 1))\n}\n\nexport type Spring = { w: number; z: number }\nexport type Body = { x: number; v: number }\n\nexport function springStep(b: Body, target: number, { w, z }: Spring, dt: number) {\n  const a = b.x - target\n  if (z >= 1) {\n    const e = Math.exp(-w * dt)\n    const k = b.v + w * a\n    b.x = target + (a + k * dt) * e\n    b.v = (b.v - k * w * dt) * e\n    return b\n  }\n  const wd = w * Math.sqrt(1 - z * z)\n  const e = Math.exp(-z * w * dt)\n  const c = Math.cos(wd * dt)\n  const s = Math.sin(wd * dt)\n  const B = (b.v + z * w * a) / wd\n  b.x = target + e * (a * c + B * s)\n  b.v = e * ((B * wd - z * w * a) * c - (a * wd + z * w * B) * s)\n  return b\n}\n\nconst still = (b: Body, target: number, eps: number) => Math.abs(b.x - target) < eps && Math.abs(b.v) < eps * 12\n\nconst rubber = (d: number, reach: number, s: number) => reach * (1 - 1 / (1 + (s * d) / reach))\n\nfunction tracker(window = 90) {\n  const samples: [number, number][] = []\n  return {\n    clear: () => (samples.length = 0),\n    add(t: number, x: number) {\n      samples.push([t, x])\n      while (samples.length > 2 && t - samples[0][0] > window) samples.shift()\n    },\n    read(now: number) {\n      const n = samples.length\n      if (n < 2 || now - samples[n - 1][0] > 60) return 0\n      const mt = samples.reduce((s, p) => s + p[0], 0) / n\n      const mx = samples.reduce((s, p) => s + p[1], 0) / n\n      const num = samples.reduce((s, p) => s + (p[0] - mt) * (p[1] - mx), 0)\n      const den = samples.reduce((s, p) => s + (p[0] - mt) ** 2, 0)\n      return den > 0 ? (num / den) * 1000 : 0\n    },\n  }\n}\n\nexport const feedback = (() => {\n  let audio: AudioContext | null = null\n  let last = 0\n  let asked = false\n  let on = true\n  let cancel: (() => void) | null = null\n  let holding = false\n  const open = () => {\n    cancel = null\n    audio ??= new AudioContext()\n    if (asked && audio.state === 'suspended') void audio.resume()\n  }\n  const warm = () => {\n    if (!on || audio || cancel || holding || typeof AudioContext === 'undefined') return\n    if (typeof requestIdleCallback === 'function') {\n      const id = requestIdleCallback(open, { timeout: 300 })\n      cancel = () => cancelIdleCallback(id)\n    } else {\n      const id = setTimeout(open, 60)\n      cancel = () => clearTimeout(id)\n    }\n  }\n  const letGo = () => {\n    holding = false\n    removeEventListener('pointerup', letGo)\n    removeEventListener('pointercancel', letGo)\n    warm()\n  }\n  const play = (heavy: boolean, loud: number) => {\n    if (!audio) return\n    const t = audio.currentTime\n    const tone = audio.createOscillator()\n    const gain = audio.createGain()\n    tone.frequency.setValueAtTime(heavy ? 900 : 1500, t)\n    tone.frequency.exponentialRampToValueAtTime(heavy ? 240 : 420, t + 0.014)\n    gain.gain.setValueAtTime((heavy ? 0.034 : 0.02) * loud, t)\n    gain.gain.exponentialRampToValueAtTime(0.0001, t + (heavy ? 0.03 : 0.016))\n    tone.connect(gain).connect(audio.destination)\n    tone.start(t)\n    tone.stop(t + 0.034)\n  }\n  return {\n    set(next: boolean) {\n      on = next\n      if (on) return\n      cancel?.()\n      cancel = null\n      void audio?.suspend()\n    },\n    warm,\n    wake(grab = false) {\n      if (!on) return\n      asked = true\n      if (audio) {\n        if (audio.state === 'suspended') void audio.resume()\n      } else if (!grab) warm()\n      else if (!holding && typeof AudioContext !== 'undefined') {\n        cancel?.()\n        cancel = null\n        holding = true\n        addEventListener('pointerup', letGo)\n        addEventListener('pointercancel', letGo)\n      }\n    },\n    tick(heavy = false, speed = 1) {\n      if (!on || !asked) return\n      const now = performance.now()\n      if (now - last < 34) return\n      last = now\n      if (typeof navigator !== 'undefined' && 'vibrate' in navigator) navigator.vibrate(heavy ? 10 : 4)\n      if (!audio) return\n      const loud = 0.45 + 0.55 * clamp(speed, 0, 1)\n      if (audio.state === 'running') play(heavy, loud)\n      else void audio.resume().then(() => on && play(heavy, loud))\n    },\n  }\n})()\n\nexport type FrameInfo = {\n  dt: number\n  mode: Mode\n  live: boolean\n}\nexport type Mode = 'rest' | 'held' | 'coast' | 'settle' | 'sweep'\n\nexport type DetentOptions = {\n  value: number\n  stops?: number[]\n  min?: number\n  max?: number\n  magnet?: number\n  reach?: number\n  throw?: number\n  spring?: Spring\n  catch?: Spring\n  muted?: boolean\n  reduce?: boolean\n  onFrame: (x: number, v: number, info: FrameInfo) => boolean | void\n  onStop?: (i: number) => void\n  onRest?: (x: number, i: number) => void\n}\n\nexport type Detent = ReturnType<typeof createDetent>\n\nconst SPRING: Spring = { w: 17, z: 0.92 }\nconst CATCH: Spring = { w: 24, z: 1 }\nconst MOMENTUM = 1\nconst SWIFT = 8\n\nexport function createDetent(read: () => DetentOptions) {\n  const init = read()\n  const body: Body = { x: init.value, v: 0 }\n  const residual: Body = { x: 0, v: 0 }\n  const track = tracker()\n  let mode: Mode = 'rest'\n  let hand = init.value\n  let target = init.value\n  let spring = SPRING\n  let friction = 4\n  let frame = 0\n  let then = 0\n  let feel = false\n  let stop = -1\n  let shown = init.value\n  let sweep = { from: 0, to: 0, t: 0, T: 1 }\n  let keyAt = 0\n\n  const span = () => {\n    const o = read()\n    const s = o.stops\n    return { o, s, lo: o.min ?? s?.[0] ?? -Infinity, hi: o.max ?? s?.[s.length - 1] ?? Infinity, m: o.reduce ? 0 : o.magnet ?? 0, reach: o.reach ?? ((s && s.length > 1 ? s[1] - s[0] : 1) * 0.5) }\n  }\n\n  const out = (u: number) => {\n    const { s, lo, hi, m, reach } = span()\n    if (u < lo) return lo - rubber(lo - u, reach, 1 - m)\n    if (u > hi) return hi + rubber(u - hi, reach, 1 - m)\n    if (!s || s.length < 2 || !m) return u\n    let i = 0\n    while (i < s.length - 2 && u > s[i + 1]) i++\n    const t = (u - s[i]) / (s[i + 1] - s[i])\n    return s[i] + (s[i + 1] - s[i]) * (t - (m * Math.sin(2 * Math.PI * t)) / (2 * Math.PI))\n  }\n  const slope = (u: number) => {\n    const e = 1e-4\n    return (out(u + e) - out(u - e)) / (2 * e)\n  }\n  const nearest = (x: number) => {\n    const { s, lo, hi } = span()\n    if (!s?.length) return { i: -1, value: clamp(x, lo, hi) }\n    let i = 0\n    for (let k = 1; k < s.length; k++) if (Math.abs(s[k] - x) < Math.abs(s[i] - x)) i = k\n    return { i, value: s[i] }\n  }\n\n  const start = () => {\n    if (frame || typeof requestAnimationFrame === 'undefined') return\n    then = performance.now()\n    frame = requestAnimationFrame(loop)\n  }\n\n  const land = () => {\n    mode = 'rest'\n    body.x = target\n    body.v = 0\n    feel = false\n  }\n\n  const emit = (dt: number) => {\n    const { o } = span()\n    const x = out(body.x)\n    const v = slope(body.x) * body.v\n    shown = x\n    const n = nearest(x).i\n    if (n !== stop) {\n      if (stop >= 0) {\n        o.onStop?.(n)\n        if (feel && !o.muted) feedback.tick(false, Math.abs(v) / (gap() * SWIFT))\n      }\n      stop = n\n    }\n    return o.onFrame(x, v, { dt, mode, live: mode === 'held' || mode === 'coast' })\n  }\n\n  function advance(dt: number, now: number) {\n    const { o } = span()\n    if (mode === 'held' || mode === 'sweep') {\n      if (mode === 'sweep') {\n        sweep.t = Math.min(sweep.T, sweep.t + dt)\n        const p = sweep.t / sweep.T\n        const next = lerp(sweep.from, sweep.to, p * p * p * (p * (6 * p - 15) + 10))\n        body.v = dt > 0 ? (next - hand) / dt + residual.v : body.v\n        hand = next\n      }\n      springStep(residual, 0, o.catch ?? CATCH, dt)\n      body.x = hand + residual.x\n      if (mode === 'held') body.v = track.read(now) + residual.v\n      if (mode === 'sweep' && sweep.t >= sweep.T && still(residual, 0, 1e-3)) {\n        target = sweep.to\n        land()\n        return true\n      }\n      return false\n    }\n    if (mode === 'coast') {\n      const e = Math.exp(-friction * dt)\n      body.x += (body.v / friction) * (1 - e)\n      body.v *= e\n      const left = Math.abs(target - body.x)\n      if (left < coastEnd() || Math.abs(body.v) < 0.5 * coastEnd() || Math.sign(target - body.x) !== Math.sign(body.v)) mode = 'settle'\n      return false\n    }\n    if (mode === 'settle') {\n      springStep(body, target, spring, dt)\n      if (still(body, target, settleEps())) {\n        land()\n        return true\n      }\n    }\n    return false\n  }\n  const gap = () => {\n    const { s } = span()\n    return s && s.length > 1 ? (s[s.length - 1] - s[0]) / (s.length - 1) : 1\n  }\n  const landing = (s: Spring, v: number): Spring => (Math.abs(v) > gap() * MOMENTUM ? s : { ...s, z: 1 })\n  const coastEnd = () => gap() * 0.7\n  const settleEps = () => gap() * 0.0015\n\n  function loop(now: number) {\n    frame = 0\n    const dt = clamp((now - then) / 1000, 1 / 240, 0.05)\n    then = now\n    const was = mode\n    const landed = was !== 'rest' && advance(dt, now)\n    const more = emit(dt)\n    if (landed) {\n      const { o } = span()\n      o.onRest?.(out(body.x), nearest(out(body.x)).i)\n    }\n    if (mode !== 'rest' || more) frame = requestAnimationFrame(loop)\n  }\n\n  const launch = () => {\n    const away = target - body.x\n    if (Math.abs(away) > gap() * 1.6 && Math.sign(away) === Math.sign(body.v)) {\n      friction = clamp(Math.abs(body.v / away), 2.5, 9)\n      mode = 'coast'\n    } else mode = 'settle'\n    start()\n  }\n\n  const to = (value: number, opts: { spring?: Spring; instant?: boolean; velocity?: number; feel?: boolean } = {}) => {\n    const { o, lo, hi } = span()\n    target = clamp(value, lo, hi)\n    if (opts.velocity !== undefined) body.v = opts.velocity\n    feel = !!opts.feel\n    if (opts.instant || o.reduce) {\n      land()\n      emit(0)\n      o.onRest?.(target, nearest(target).i)\n      return\n    }\n    if (mode === 'held') {\n      body.x = hand + residual.x\n      residual.x = residual.v = 0\n    }\n    spring = opts.spring ?? landing(o.spring ?? SPRING, opts.velocity ?? 0)\n    mode = 'settle'\n    start()\n  }\n\n  const api = {\n    get: () => shown,\n    place: () => body.x + (mode === 'rest' ? 0 : body.v / (span().o.catch ?? CATCH).w),\n    velocity: () => slope(body.x) * body.v,\n    mode: () => mode,\n    target: () => target,\n    nearest,\n\n    set(value: number) {\n      body.x = target = hand = value\n      body.v = residual.x = residual.v = 0\n      mode = 'rest'\n      feel = false\n      stop = -1\n      emit(0)\n      stop = nearest(shown).i\n    },\n    to,\n\n    grab(place: number, { feel: touching = true }: { feel?: boolean } = {}) {\n      const { o } = span()\n      residual.x = o.reduce ? 0 : body.x - place\n      residual.v = o.reduce ? 0 : body.v\n      hand = place\n      track.clear()\n      track.add(performance.now(), place)\n      feel = touching\n      mode = 'held'\n      start()\n    },\n    drag(place: number) {\n      if (mode !== 'held') return\n      hand = place\n      track.add(performance.now(), place)\n    },\n    release({ flick = true, home }: { flick?: boolean; home?: number } = {}) {\n      if (mode !== 'held') return\n      const { o, lo, hi } = span()\n      const flung = flick ? track.read(performance.now()) : 0\n      body.x = hand + residual.x\n      body.v = flung + residual.v\n      residual.x = residual.v = 0\n      const rest = home ?? nearest(clamp(body.x + flung * (o.throw ?? 0.16), lo, hi)).value\n      target = rest\n      spring = landing(o.spring ?? SPRING, body.v)\n      if (o.reduce) {\n        to(rest)\n        return\n      }\n      launch()\n    },\n    fling(velocity: number) {\n      const { o, lo, hi } = span()\n      const rest = nearest(clamp(body.x + velocity * (o.throw ?? 0.16), lo, hi)).value\n      if (o.reduce) return to(rest)\n      residual.x = residual.v = 0\n      body.v = velocity\n      feel = false\n      target = rest\n      spring = o.spring ?? SPRING\n      launch()\n    },\n    sweep(value: number, ms: number) {\n      const { o } = span()\n      if (o.reduce) return to(value)\n      residual.x = 0\n      residual.v = body.v\n      hand = body.x\n      sweep = { from: body.x, to: value, t: 0, T: Math.max(0.05, ms / 1000) }\n      feel = false\n      mode = 'sweep'\n      start()\n    },\n    step(by: number, repeat = false) {\n      const { o, s, lo, hi } = span()\n      const now = performance.now()\n      const quick = repeat || now - keyAt < 110\n      keyAt = now\n      if (!o.muted) feedback.wake()\n      const from = mode === 'rest' ? body.x : target\n      const next = s ? s[clamp(nearest(from).i + by, 0, s.length - 1)] : clamp(from + by, lo, hi)\n      to(next, { instant: quick, feel: !quick })\n      return next\n    },\n    wake: start,\n    dispose() {\n      cancelAnimationFrame(frame)\n      frame = 0\n    },\n  }\n  return api\n}\n\nexport function useDetent(options: Omit<DetentOptions, 'reduce'>) {\n  const reduce = !!useReducedMotion()\n  const latest = useRef<DetentOptions>({ ...options, reduce })\n  useLayoutEffect(() => {\n    latest.current = { ...options, reduce }\n  })\n  const [d] = useState(() => createDetent(() => latest.current))\n  useLayoutEffect(() => () => d.dispose(), [d])\n  return d\n}\n\nexport type DragConfig = {\n  axis?: 'x' | 'y'\n  box: () => HTMLElement | null\n  units: number\n  absolute?: (fraction: number) => number\n  hover?: boolean\n  follow?: boolean\n  onTap?: (fraction: number) => void\n  onLeave?: () => void\n  onGrab?: () => void\n  release?: () => { flick?: boolean; home?: number }\n  muted?: boolean\n}\n\nconst SLOP = { mouse: 5, touch: 10 }\n\nexport function dragProps(d: Detent, read: () => DragConfig) {\n  let press: { id: number; px: number; py: number; from: number; moved: boolean; held: boolean; caught: boolean } | null = null\n  const place = (e: ReactPointerEvent) => {\n    const c = read()\n    const r = c.box()?.getBoundingClientRect()\n    if (!r) return null\n    const horizontal = (c.axis ?? 'x') === 'x'\n    const size = (horizontal ? r.width : r.height) || 1\n    const px = horizontal ? e.clientX : e.clientY\n    return { fraction: (px - (horizontal ? r.left : r.top)) / size, px, unit: size / c.units, c }\n  }\n  const hand = (e: ReactPointerEvent) => {\n    const p = place(e)\n    if (!p || !press) return null\n    return p.c.absolute && !press.caught ? p.c.absolute(p.fraction) : press.from + (p.px - ((p.c.axis ?? 'x') === 'x' ? press.px : press.py)) / p.unit\n  }\n  const take = (e: ReactPointerEvent) => {\n    if (!press) return\n    const at = hand(e)\n    if (at === null) return\n    press.held = true\n    read().onGrab?.()\n    d.grab(at)\n  }\n  const inFlight = () => d.mode() !== 'rest' && d.mode() !== 'held' && d.mode() !== 'sweep'\n  return {\n    onPointerDown(e: ReactPointerEvent) {\n      if (e.button) return\n      const c = read()\n      if (!c.muted) feedback.wake(true)\n      e.currentTarget.setPointerCapture?.(e.pointerId)\n      press = { id: e.pointerId, px: e.clientX, py: e.clientY, from: d.place(), moved: false, held: false, caught: inFlight() && !c.follow }\n      if (e.pointerType !== 'touch' || press.caught || !c.absolute) take(e)\n    },\n    onPointerMove(e: ReactPointerEvent) {\n      const c = read()\n      if (!c.muted && e.pointerType === 'mouse') feedback.warm()\n      if (press) {\n        if (e.pointerId !== press.id) return\n        if (!press.moved && Math.hypot(e.clientX - press.px, e.clientY - press.py) > (e.pointerType === 'touch' ? SLOP.touch : SLOP.mouse)) press.moved = true\n        if (!press.held && press.moved) take(e)\n        const at = hand(e)\n        if (at !== null && press.held) d.drag(at)\n        return\n      }\n      if (!c.hover || e.pointerType !== 'mouse' || (inFlight() && !c.follow)) return\n      const p = place(e)\n      if (!p || !c.absolute) return\n      const at = c.absolute(p.fraction)\n      if (d.mode() === 'held') d.drag(at)\n      else {\n        c.onGrab?.()\n        d.grab(at, { feel: false })\n      }\n    },\n    onPointerUp(e: ReactPointerEvent) {\n      if (!press || e.pointerId !== press.id) return\n      const { moved, held } = press\n      const p = place(e)\n      const c = read()\n      press = null\n      if (!moved && c.onTap && p) {\n        if (held) d.release({ flick: false, home: d.get() })\n        c.onTap(p.fraction)\n      } else if (held) d.release(c.release?.())\n    },\n    onPointerCancel(e: ReactPointerEvent) {\n      if (!press || e.pointerId !== press.id) return\n      const { held } = press\n      press = null\n      if (held) d.release({ flick: false })\n      read().onLeave?.()\n    },\n    onPointerLeave(e: ReactPointerEvent) {\n      if (press || e.pointerType !== 'mouse') return\n      const c = read()\n      if (!c.hover) return\n      if (d.mode() === 'held') d.release({ flick: false, home: d.get() })\n      c.onLeave?.()\n    },\n  }\n}\n\nexport const stepKey = (d: Detent, e: KeyboardEvent, keys: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1 }) => {\n  const by = keys[e.key]\n  if (!by) return false\n  e.preventDefault()\n  d.step(by, e.repeat)\n  return true\n}\n\nconst COLUMN = 'display:inline-block;height:1.25em;overflow:hidden;vertical-align:top'\nconst STRIP = '0123456789'\n\nexport function createRoller(el: HTMLElement, format: (n: number) => string, pad = 0, built?: (columns: HTMLElement[]) => void) {\n  let shape = ''\n  let wheels: { strip: HTMLElement; col: HTMLElement }[] = []\n  let scale = 1\n\n  const build = (s: string, digits: number) => {\n    el.textContent = ''\n    wheels = []\n    const col = () => {\n      const c = document.createElement('span')\n      c.style.cssText = COLUMN\n      const strip = document.createElement('span')\n      strip.style.cssText = 'display:block;will-change:transform'\n      strip.innerHTML = [...STRIP, '0'].map((n) => `<span style=\"display:block;height:1.25em\">${n}</span>`).join('')\n      c.append(strip)\n      el.append(c)\n      wheels.push({ strip, col: c })\n    }\n    let padded = Math.max(0, pad - digits)\n    let leading = true\n    for (const ch of s) {\n      if (/\\d/.test(ch)) {\n        if (leading) for (; padded > 0; padded--) col()\n        leading = false\n        col()\n      } else {\n        const c = document.createElement('span')\n        c.textContent = ch\n        c.style.whiteSpace = 'pre'\n        el.append(c)\n      }\n    }\n    built?.([...el.children] as HTMLElement[])\n  }\n\n  return (value: number, speed = 0) => {\n    const s = format(value)\n    const digits = s.replace(/\\D/g, '')\n    const next = s.replace(/\\d/g, '0')\n    if (next !== shape) {\n      shape = next\n      build(s, digits.length)\n    }\n    const numeric = s.replace(/[^\\d.]/g, '').replace(/\\.$/, '')\n    const shownNumber = parseFloat(numeric)\n    const decimals = numeric.includes('.') ? numeric.length - numeric.indexOf('.') - 1 : 0\n    if (shownNumber > 0) scale = Math.abs(value) / shownNumber\n    const place = Math.pow(10, -decimals) * (scale || 1)\n    const q = Math.abs(value) / place\n    const free = clamp(Math.abs(speed) / (place * 6), 0, 1)\n    const count = wheels.length\n    const whole = digits.padStart(count, '0')\n    for (let k = 0; k < count; k++) {\n      const { strip, col } = wheels[count - 1 - k]\n      const unit = Math.pow(10, k)\n      const lower = q % unit\n      const carry = k === 0 ? q - Math.floor(q) : clamp(lower - (unit - 1), 0, 1)\n      const running = (Math.floor(q / unit) % 10) + carry\n      const digit = +whole[count - 1 - k]\n      const off = ((digit - running + 15) % 10) - 5\n      const pos = (running + off * (1 - free) + 10) % 10\n      strip.style.transform = `translateY(${(-pos * 100) / 11}%)`\n      if (pad) {\n        const higher = Math.floor(q / unit)\n        const fade = k === 0 ? 1 : higher > 0 ? 1 : clamp(lower - (unit - 1), 0, 1)\n        col.style.opacity = String(fade)\n      }\n    }\n  }\n}\n\nexport const write = (el: HTMLElement | null | undefined, text: string) => {\n  if (el && el.textContent !== text) el.textContent = text\n}\n"}]}