{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"timeline","type":"registry:block","title":"Timeline","description":"Tasks over days joined by what they wait for: drag one and the tasks behind it are pushed along on springs, their lines stretching like rubber bands.","author":"Hairline UI","dependencies":["lucide-react"],"files":[{"path":"registry/timeline.tsx","type":"registry:component","content":"// Hairline UI · timeline · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Lock } from \"lucide-react\";\nimport { createSpring, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * TIMELINE: tasks over days, joined by what they wait for\n *\n *   drag      drag a task along the days and it follows your\n *             pointer; the tasks waiting on it are pushed along on\n *             springs, each a beat behind the one before, so the\n *             dependency lines stretch like rubber bands and the\n *             knock-on effect travels down the plan\n *   locked    a task pinned to its date doesn't move: its line pulls\n *             taut and turns red, so you see the clash as you make it\n *   resize    drag a task's right edge to change how long it takes;\n *             the same knock-on follows\n *   release   everything snaps to whole days and settles; the\n *             critical path (the chain that sets the end date) is\n *             lit in your colour\n *\n * Keyboard: ← → move a focused task a day, Shift with them changes\n * its length. Dates in and out are plain YYYY-MM-DD strings.\n * ───────────────────────────────────────────────────────── */\n\nexport interface TimelineTask {\n  id: string;\n  title: string;\n  /** First day, YYYY-MM-DD. */\n  start: string;\n  /** How many days it takes. */\n  days: number;\n  /** Ids of the tasks it waits for. */\n  after?: string[];\n  /** Pinned to its date: never pushed. */\n  locked?: boolean;\n  /** Tasks in a group share a colour. */\n  group?: string;\n}\n\nexport interface TimelineProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\"> {\n  tasks: TimelineTask[];\n  /** Called with the whole plan after a move settles. */\n  onTasksChange?: (tasks: TimelineTask[]) => void;\n  title?: string;\n  /** The first day shown, YYYY-MM-DD. Defaults to two days before the earliest task. */\n  from?: string;\n  /** How many days to show. Defaults to the plan plus a week. */\n  span?: number;\n  /** Draws a Today line, YYYY-MM-DD. */\n  today?: string;\n  /** For day and month names. */\n  locale?: string;\n}\n\nconst DAY = 34;\nconst ROW = 40;\nconst BAR = 26;\nconst AXIS = 40;\nconst MS = 86_400_000;\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-1 focus-visible:ring-offset-background\";\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);\n\nconst mix = (color: string, amount: number, into = \"transparent\") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;\nconst dayOf = (iso: string) => {\n  const [y, m, d] = iso.split(\"-\").map(Number);\n  return Math.round(Date.UTC(y, (m || 1) - 1, d || 1) / MS);\n};\nconst isoOf = (day: number) => new Date(day * MS).toISOString().slice(0, 10);\n\n/** Where every task would sit, pushed (never pulled) by what it waits for. */\nfunction settle(tasks: TimelineTask[], base: Map<string, number>, fixed: Map<string, number>) {\n  const out = new Map<string, number>();\n  const byId = new Map(tasks.map((t) => [t.id, t]));\n  const visiting = new Set<string>();\n  const place = (id: string): number => {\n    if (out.has(id)) return out.get(id)!;\n    const t = byId.get(id);\n    if (!t) return 0;\n    if (fixed.has(id)) {\n      out.set(id, fixed.get(id)!);\n      return out.get(id)!;\n    }\n    let at = base.get(id) ?? 0;\n    if (!t.locked && !visiting.has(id)) {\n      visiting.add(id);\n      for (const p of t.after ?? []) {\n        const pt = byId.get(p);\n        if (pt) at = Math.max(at, place(p) + pt.days);\n      }\n      visiting.delete(id);\n    }\n    out.set(id, at);\n    return at;\n  };\n  tasks.forEach((t) => place(t.id));\n  return out;\n}\n\n/** How far down the chain of waiting each task is, so the far ends trail further behind. */\nfunction depths(tasks: TimelineTask[], root: string) {\n  const out = new Map<string, number>([[root, 0]]);\n  let frontier = [root];\n  for (let d = 1; frontier.length && d < 12; d++) {\n    const next: string[] = [];\n    for (const t of tasks) if (!out.has(t.id) && (t.after ?? []).some((a) => frontier.includes(a))) {\n      out.set(t.id, d);\n      next.push(t.id);\n    }\n    frontier = next;\n  }\n  return out;\n}\n\nexport function Timeline({ tasks: tasksProp, onTasksChange, title = \"Plan\", from, span, today, locale = \"en-US\", className = \"\", ...props }: TimelineProps) {\n  const reduced = useReducedMotion();\n  const [tasks, setTasks] = React.useState(tasksProp);\n  const [seenProp, setSeenProp] = React.useState(tasksProp);\n  if (seenProp !== tasksProp) {\n    setSeenProp(tasksProp);\n    setTasks(tasksProp);\n  }\n  const [dragging, setDragging] = React.useState<string | null>(null);\n  const [said, setSaid] = React.useState(\"\");\n\n  const first = React.useMemo(() => Math.min(...tasks.map((t) => dayOf(t.start))), [tasks]);\n  const lastEnd = Math.max(...tasks.map((t) => dayOf(t.start) + t.days));\n  const origin = from ? dayOf(from) : first - 2;\n  const days = span ?? Math.max(21, lastEnd - origin + 7);\n  const width = days * DAY;\n  const groups = React.useMemo(() => [...new Set(tasks.map((t) => t.group ?? \"\"))], [tasks]);\n  const colorOf = (t: TimelineTask) => `var(--chart-${(groups.indexOf(t.group ?? \"\") % 5) + 1}, var(--primary))`;\n\n  // The committed plan in day numbers relative to the first column.\n  const starts = React.useMemo(() => new Map(tasks.map((t) => [t.id, dayOf(t.start) - origin])), [tasks, origin]);\n\n  // The critical path: the chain that ends on the last day.\n  const critical = React.useMemo(() => {\n    const end = Math.max(...tasks.map((t) => starts.get(t.id)! + t.days));\n    const lit = new Set(tasks.filter((t) => starts.get(t.id)! + t.days === end).map((t) => t.id));\n    let grew = true;\n    while (grew) {\n      grew = false;\n      for (const t of tasks)\n        if (lit.has(t.id))\n          for (const p of t.after ?? []) {\n            const pt = tasks.find((x) => x.id === p);\n            if (pt && !lit.has(p) && starts.get(p)! + pt.days === starts.get(t.id)) {\n              lit.add(p);\n              grew = true;\n            }\n          }\n    }\n    return lit;\n  }, [tasks, starts]);\n\n  const barRefs = React.useRef(new Map<string, HTMLElement>());\n  const lineRefs = React.useRef(new Map<string, SVGPathElement>());\n  const springs = React.useRef(new Map<string, Spring>());\n  const lengths = React.useRef(new Map<string, number>());\n  const live = React.useRef({ tasks, starts, critical, frame: 0 });\n  const drag = React.useRef<{ id: string; mode: \"move\" | \"resize\"; x0: number; at0: number; len0: number; base: Map<string, number>; moved: boolean } | null>(null);\n\n  React.useLayoutEffect(() => {\n    live.current.tasks = tasks;\n    live.current.starts = starts;\n    live.current.critical = critical;\n  });\n\n  // One frame: bars where their springs are, and every line drawn between them.\n  const paint = React.useCallback(() => {\n    const L = live.current;\n    L.frame = 0;\n    const byId = new Map(L.tasks.map((t) => [t.id, t]));\n    const index = new Map(L.tasks.map((t, i) => [t.id, i]));\n    const x = (id: string) => (springs.current.get(id)?.get() ?? L.starts.get(id) ?? 0) * DAY;\n    const len = (id: string) => (lengths.current.get(id) ?? byId.get(id)?.days ?? 1) * DAY;\n    L.tasks.forEach((t) => {\n      const bar = barRefs.current.get(t.id);\n      if (!bar) return;\n      bar.style.transform = `translate3d(${x(t.id) + 2}px,0,0)`;\n      bar.style.width = `${Math.max(DAY - 4, len(t.id) - 4)}px`;\n    });\n    L.tasks.forEach((t) =>\n      (t.after ?? []).forEach((p) => {\n        const path = lineRefs.current.get(`${p}>${t.id}`);\n        if (!path || !byId.has(p)) return;\n        const x1 = x(p) + len(p) - 2;\n        const y1 = (index.get(p) ?? 0) * ROW + ROW / 2;\n        const x2 = x(t.id) + 2;\n        const y2 = (index.get(t.id) ?? 0) * ROW + ROW / 2;\n        // Behind its task the line is stretched: it pulls straight. Only a pinned task that can't follow is a clash.\n        const taut = x2 < x1 + 2;\n        const clash = taut && !!t.locked;\n        const reach = taut ? 0 : Math.max(14, Math.min(40, Math.abs(x2 - x1) * 0.5 + 10));\n        path.setAttribute(\"d\", taut ? `M ${x1} ${y1} L ${x2} ${y2}` : `M ${x1} ${y1} C ${x1 + reach} ${y1} ${x2 - reach} ${y2} ${x2} ${y2}`);\n        path.dataset.state = clash ? \"clash\" : L.critical.has(p) && L.critical.has(t.id) && Math.abs(x2 - x1 - 4) < 1 ? \"critical\" : \"rest\";\n      }),\n    );\n  }, []);\n  const request = React.useCallback(() => {\n    const L = live.current;\n    if (!L.frame) L.frame = requestAnimationFrame(paint);\n  }, [paint]);\n\n  // A spring per task; created once per id and aimed at the committed plan.\n  React.useLayoutEffect(() => {\n    const map = springs.current;\n    tasks.forEach((t) => {\n      if (!map.has(t.id)) map.set(t.id, createSpring(starts.get(t.id) ?? 0, { stiffness: 260, damping: 26 }, request, 0.002));\n    });\n    [...map.keys()].forEach((id) => {\n      if (!tasks.some((t) => t.id === id)) {\n        map.get(id)?.stop();\n        map.delete(id);\n      }\n    });\n    tasks.forEach((t) => {\n      const s = map.get(t.id)!;\n      if (drag.current) return;\n      if (reduced) s.jump(starts.get(t.id) ?? 0);\n      else s.set(starts.get(t.id) ?? 0);\n      lengths.current.set(t.id, t.days);\n    });\n    paint();\n  }, [tasks, starts, reduced, request, paint]);\n\n  React.useEffect(() => {\n    const map = springs.current;\n    const L = live.current;\n    return () => {\n      map.forEach((s) => s.stop());\n      if (L.frame) cancelAnimationFrame(L.frame);\n      L.frame = 0;\n    };\n  }, []);\n\n  /** Aim every spring at where the plan would sit with this one task here. */\n  const aim = (id: string, at: number, len: number, final: boolean) => {\n    const L = live.current;\n    const plan = L.tasks.map((t) => (t.id === id ? { ...t, days: len } : t));\n    const placed = settle(plan, drag.current?.base ?? L.starts, new Map([[id, at]]));\n    const depth = depths(plan, id);\n    lengths.current.set(id, len);\n    plan.forEach((t) => {\n      const s = springs.current.get(t.id);\n      if (!s) return;\n      const target = final ? Math.round(placed.get(t.id)!) : placed.get(t.id)!;\n      if (t.id === id) {\n        if (final && !reduced) s.set(target);\n        else s.jump(target);\n        return;\n      }\n      // Further down the chain, softer: the push arrives a beat later at each step.\n      const d = depth.get(t.id) ?? 0;\n      const k = 260 / (1 + d * 0.9);\n      s.configure({ stiffness: k, damping: 2 * Math.sqrt(k) * 0.72 });\n      if (reduced) s.jump(target);\n      else s.set(target);\n    });\n    request();\n    return { plan, placed };\n  };\n\n  const commit = (id: string, at: number, len: number) => {\n    const { plan, placed } = aim(id, Math.round(at), Math.max(1, Math.round(len)), true);\n    const next = plan.map((t) => ({ ...t, start: isoOf(origin + Math.round(placed.get(t.id)!)), days: t.id === id ? Math.max(1, Math.round(len)) : t.days }));\n    const moved = next.filter((t, i) => t.start !== live.current.tasks[i].start || t.days !== live.current.tasks[i].days);\n    setTasks(next);\n    onTasksChange?.(next);\n    const t = next.find((x) => x.id === id);\n    if (t) setSaid(`${t.title}: ${fmtDay(dayOf(t.start))}, ${t.days} ${t.days === 1 ? \"day\" : \"days\"}.${moved.length > 1 ? ` ${moved.length - 1} more moved.` : \"\"}`);\n    window.setTimeout(() => springs.current.forEach((s) => s.configure({ stiffness: 260, damping: 26 })), 900);\n  };\n\n  const fmtDay = (day: number) => new Date(day * MS).toLocaleDateString(locale, { month: \"short\", day: \"numeric\", timeZone: \"UTC\" });\n\n  const down = (t: TimelineTask, mode: \"move\" | \"resize\") => (e: React.PointerEvent) => {\n    if (e.button !== 0 || (t.locked && mode === \"move\")) return;\n    e.stopPropagation();\n    (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n    drag.current = { id: t.id, mode, x0: e.clientX, at0: starts.get(t.id) ?? 0, len0: t.days, base: new Map(starts), moved: false };\n  };\n  const move = (e: React.PointerEvent) => {\n    const d = drag.current;\n    if (!d) return;\n    const dx = e.clientX - d.x0;\n    if (!d.moved && Math.abs(dx) < 4) return;\n    if (!d.moved) {\n      d.moved = true;\n      d.x0 = e.clientX;\n      setDragging(d.id);\n      return;\n    }\n    if (d.mode === \"move\") aim(d.id, Math.max(0, d.at0 + dx / DAY), d.len0, false);\n    else aim(d.id, d.at0, Math.max(1, d.len0 + dx / DAY), false);\n  };\n  const up = (e: React.PointerEvent) => {\n    const d = drag.current;\n    drag.current = null;\n    setDragging(null);\n    if (!d || !d.moved) return;\n    const dx = e.clientX - d.x0;\n    if (d.mode === \"move\") commit(d.id, Math.max(0, d.at0 + dx / DAY), d.len0);\n    else commit(d.id, d.at0, Math.max(1, d.len0 + dx / DAY));\n  };\n\n  const key = (t: TimelineTask) => (e: React.KeyboardEvent) => {\n    if (e.key !== \"ArrowLeft\" && e.key !== \"ArrowRight\") return;\n    e.preventDefault();\n    const step = e.key === \"ArrowRight\" ? 1 : -1;\n    const at = starts.get(t.id) ?? 0;\n    if (e.shiftKey) commit(t.id, at, Math.max(1, t.days + step));\n    else if (!t.locked) {\n      drag.current = null;\n      live.current.starts = starts;\n      commit(t.id, Math.max(0, at + step), t.days);\n    }\n  };\n\n  const columns = Array.from({ length: days }, (_, i) => origin + i);\n  const todayAt = today ? dayOf(today) - origin : null;\n  const end = Math.max(...tasks.map((t) => (starts.get(t.id) ?? 0) + t.days));\n\n  return (\n    // One minmax(0, 1fr) column: the days scroll inside, and never set the card's minimum width.\n    <div className={`grid w-full grid-cols-[minmax(0,1fr)] rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 720px)\" }} />\n      <div className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 px-4 pb-3 pt-4\">\n        <div className=\"min-w-0\">\n          <p className=\"truncate text-[15px] font-medium tracking-[-0.01em] text-foreground\">{title}</p>\n          <p className=\"mt-0.5 text-[12px] text-muted-foreground tabular-nums\">\n            {fmtDay(origin + Math.min(...tasks.map((t) => starts.get(t.id) ?? 0)))} – {fmtDay(origin + end - 1)} · {end - Math.min(...tasks.map((t) => starts.get(t.id) ?? 0))} days\n          </p>\n        </div>\n        <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-muted-foreground\">\n          {groups.filter(Boolean).map((g, i) => (\n            <span key={g} className=\"inline-flex items-center gap-1.5\">\n              <span className=\"size-2 rounded-[2px]\" style={{ background: `var(--chart-${(i % 5) + 1}, var(--primary))` }} />\n              {g}\n            </span>\n          ))}\n          <span className=\"inline-flex items-center gap-1.5\">\n            <span className=\"h-[2px] w-3 rounded-full bg-primary\" />\n            Critical path\n          </span>\n        </div>\n      </div>\n\n      <div className=\"overflow-x-auto overscroll-x-contain border-t border-border [scrollbar-width:thin]\">\n        <div className=\"relative\" style={{ width, height: AXIS + tasks.length * ROW + 10 }} onPointerMove={move} onPointerUp={up} onPointerCancel={up}>\n          {/* The days: a column each, weekends shaded, month names where a month starts. */}\n          {columns.map((day, i) => {\n            const date = new Date(day * MS);\n            const weekend = date.getUTCDay() === 0 || date.getUTCDay() === 6;\n            const monthStart = date.getUTCDate() === 1 || i === 0;\n            return (\n              <div key={day} aria-hidden=\"true\" className=\"absolute top-0 h-full\" style={{ left: i * DAY, width: DAY, background: weekend ? mix(\"var(--foreground)\", 3) : undefined }}>\n                {monthStart && (\n                  <span className=\"absolute left-1.5 top-1.5 whitespace-nowrap text-[10.5px] font-medium text-foreground\">\n                    {date.toLocaleDateString(locale, { month: \"short\", timeZone: \"UTC\" })}\n                  </span>\n                )}\n                <span className=\"absolute inset-x-0 top-[18px] text-center text-[10.5px] tabular-nums text-muted-foreground\">\n                  {date.getUTCDate()}\n                </span>\n                <span className=\"absolute bottom-0 left-0 w-px\" style={{ top: AXIS, background: date.getUTCDay() === 1 ? mix(\"var(--foreground)\", 8) : \"transparent\" }} />\n              </div>\n            );\n          })}\n          <div aria-hidden=\"true\" className=\"absolute inset-x-0 border-b border-border\" style={{ top: AXIS - 1 }} />\n          {todayAt !== null && todayAt >= 0 && todayAt < days && (\n            <div aria-hidden=\"true\" className=\"absolute bottom-0 w-px bg-primary\" style={{ left: todayAt * DAY + DAY / 2, top: AXIS - 6 }}>\n              <span className=\"absolute -left-[3px] -top-[3px] size-[7px] rounded-full bg-primary\" />\n            </div>\n          )}\n\n          <div className=\"absolute inset-x-0\" style={{ top: AXIS }}>\n            <svg aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-0 overflow-visible\" width={width} height={tasks.length * ROW}>\n              <defs>\n                <marker id=\"timeline-tip\" viewBox=\"0 0 6 6\" refX=\"5\" refY=\"3\" markerWidth=\"6\" markerHeight=\"6\" orient=\"auto-start-reverse\">\n                  <path d=\"M0 0 L6 3 L0 6 z\" fill=\"context-stroke\" />\n                </marker>\n              </defs>\n              {tasks.flatMap((t) =>\n                (t.after ?? []).map((p) => (\n                  <path\n                    key={`${p}>${t.id}`}\n                    ref={(el) => {\n                      if (el) lineRefs.current.set(`${p}>${t.id}`, el);\n                      else lineRefs.current.delete(`${p}>${t.id}`);\n                    }}\n                    fill=\"none\"\n                    strokeWidth={1.4}\n                    strokeLinecap=\"round\"\n                    markerEnd=\"url(#timeline-tip)\"\n                    className=\"stroke-[color-mix(in_oklab,var(--foreground)_28%,transparent)] transition-[stroke] duration-300 data-[state=clash]:stroke-red-500 data-[state=critical]:stroke-primary dark:data-[state=clash]:stroke-red-400\"\n                  />\n                )),\n              )}\n            </svg>\n\n            <ul aria-label={title}>\n              {tasks.map((t, i) => {\n                const color = colorOf(t);\n                const lit = critical.has(t.id);\n                const short = t.days <= 2;\n                return (\n                  <li key={t.id} className=\"absolute left-0\" style={{ top: i * ROW + (ROW - BAR) / 2, height: BAR }}>\n                    <div\n                      ref={(el) => {\n                        if (el) barRefs.current.set(t.id, el);\n                        else barRefs.current.delete(t.id);\n                      }}\n                      role=\"button\"\n                      tabIndex={0}\n                      aria-roledescription=\"task bar\"\n                      aria-label={`${t.title}, ${fmtDay(origin + (starts.get(t.id) ?? 0))}, ${t.days} ${t.days === 1 ? \"day\" : \"days\"}${t.locked ? \", locked\" : \"\"}${lit ? \", on the critical path\" : \"\"}`}\n                      aria-keyshortcuts=\"ArrowLeft ArrowRight Shift+ArrowLeft Shift+ArrowRight\"\n                      onPointerDown={down(t, \"move\")}\n                      onKeyDown={key(t)}\n                      className={`group absolute left-0 top-0 flex h-full touch-none select-none items-center rounded-[8px] ${t.locked ? \"cursor-default\" : dragging === t.id ? \"cursor-grabbing\" : \"cursor-grab\"} ${FOCUS}`}\n                      style={{\n                        background: `linear-gradient(90deg, ${mix(color, 26, \"var(--background)\")}, ${mix(color, 14, \"var(--background)\")})`,\n                        boxShadow: `inset 0 0 0 1px ${lit ? color : mix(color, 40, \"transparent\")}`,\n                        willChange: \"transform\",\n                      }}\n                    >\n                      <span className=\"absolute inset-y-[5px] left-[5px] w-[3px] rounded-full\" style={{ background: color }} />\n                      <span\n                        className={`pointer-events-none flex items-center gap-1 whitespace-nowrap pl-3.5 pr-2 text-[12px] font-medium text-foreground ${short ? \"absolute left-full ml-1.5 pl-0\" : \"min-w-0 truncate\"}`}\n                      >\n                        {t.locked && <Lock aria-hidden=\"true\" className=\"size-3 shrink-0 text-muted-foreground\" />}\n                        <span className=\"truncate\">{t.title}</span>\n                      </span>\n                      {!t.locked && (\n                        <span\n                          aria-hidden=\"true\"\n                          onPointerDown={down(t, \"resize\")}\n                          className=\"absolute inset-y-0 -right-1 w-3 cursor-ew-resize touch-none\"\n                        >\n                          <span className=\"absolute inset-y-[7px] right-[5px] w-[2px] rounded-full opacity-0 transition-opacity duration-200 group-hover:opacity-100\" style={{ background: color }} />\n                        </span>\n                      )}\n                    </div>\n                  </li>\n                );\n              })}\n            </ul>\n          </div>\n        </div>\n      </div>\n      <p className=\"px-4 py-2.5 text-[11.5px] text-muted-foreground\">\n        Drag a task to move it, its edge to change its length. Tasks that wait on it follow.\n      </p>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {said}\n      </p>\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · timeline · 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/timeline. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}