{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"time-overlap","type":"registry:component","title":"Time overlap","description":"Find a meeting time across time zones: each person’s day in hairline marks, a band you drag across everyone, and it settles into the hours you all share.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/time-overlap.tsx","type":"registry:component","content":"// Hairline UI · time-overlap · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { TextMorph } from \"./text-morph\";\nimport { createSpring, projectInertia, releaseVelocity, samplePointer, type PointerSample, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * TIME OVERLAP: when can everyone make it?\n *\n *   days       each person is a strip of one day in your time,\n *              drawn in hairline marks: lit in their colour while\n *              they're at work, faint while they're not\n *   overlap    where everyone is at work at once, a line runs along\n *              the ruler above the strips\n *   drag       a glass band the length of the meeting crosses every\n *              strip; drag it and each person's local time ticks\n *              beside their row as it moves\n *   settle     let go near the overlap and the band glides into it\n *              and settles; anywhere else it lands on the nearest\n *              quarter hour\n *   status     the header says whether everyone is in hours, or who\n *              isn't; their time turns amber\n *\n * The band moves by transform while you drag; the times change once\n * per quarter hour and React re-renders only then. The day is drawn\n * once per set of people.\n * ───────────────────────────────────────────────────────── */\n\nexport interface OverlapPerson {\n  id: string;\n  name: string;\n  /** IANA time zone, e.g. \"Europe/Lisbon\". */\n  timeZone: string;\n  /** Working hours in their own time, [start, end) in hours. Defaults to 9–17. */\n  hours?: [number, number];\n  /** Any CSS colour. Defaults to your chart colours in turn. */\n  color?: string;\n}\n\nexport interface TimeOverlapProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\" | \"defaultValue\" | \"onChange\"> {\n  people: OverlapPerson[];\n  /** The meeting's start. Controlled or not. */\n  value?: Date | number;\n  defaultValue?: Date | number;\n  onValueChange?: (start: Date) => void;\n  /** Minutes. */\n  duration?: number;\n  /** The day shown, in your time zone. Defaults to today. */\n  day?: Date | number;\n  /** The time zone the day is laid out in. Defaults to the visitor's. */\n  timeZone?: string;\n  title?: string;\n  locales?: string | string[];\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst SLOT = 15 * 60_000;\nconst SLOTS = 96;\nconst SNAP_REACH = 6; // slots: let go within 90 minutes of the overlap and the band goes into it\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\";\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// Today, read once in the browser and never while rendering on the server (prerendering refuses a moving clock).\nlet firstNow: number | undefined;\nconst readNow = () => (firstNow ??= Date.now());\nconst useNow = () => React.useSyncExternalStore(subscribeNothing, readNow, () => null);\n\nconst formats = new Map<string, Intl.DateTimeFormat>();\nfunction fmt(key: string, make: () => Intl.DateTimeFormat) {\n  let f = formats.get(key);\n  if (!f) formats.set(key, (f = make()));\n  return f;\n}\n/** Minutes past midnight in a time zone, and that zone's offset from UTC in ms. */\nfunction clock(ms: number, timeZone: string) {\n  const parts = fmt(`p|${timeZone}`, () =>\n    new Intl.DateTimeFormat(\"en-US\", { timeZone, hourCycle: \"h23\", year: \"numeric\", month: \"numeric\", day: \"numeric\", hour: \"numeric\", minute: \"numeric\" }),\n  ).formatToParts(ms);\n  const get = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);\n  const asUtc = Date.UTC(get(\"year\"), get(\"month\") - 1, get(\"day\"), get(\"hour\") % 24, get(\"minute\"));\n  return { minutes: (get(\"hour\") % 24) * 60 + get(\"minute\"), offset: asUtc - Math.floor(ms / 60_000) * 60_000, y: get(\"year\"), m: get(\"month\"), d: get(\"day\") };\n}\n/** The instant the day starts in a time zone. */\nfunction dayStart(at: number, timeZone: string) {\n  const { y, m, d } = clock(at, timeZone);\n  const guess = Date.UTC(y, m - 1, d);\n  return guess - clock(guess, timeZone).offset;\n}\nconst inHours = (minutes: number, [a, b]: [number, number]) => (a <= b ? minutes >= a * 60 && minutes < b * 60 : minutes >= a * 60 || minutes < b * 60);\nconst clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));\n\nexport function TimeOverlap({\n  people,\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  duration = 60,\n  day,\n  timeZone: zoneProp,\n  title = \"Find a time\",\n  locales,\n  className = \"\",\n  ...props\n}: TimeOverlapProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  // Times depend on the visitor's zone and clock: lay the day out once mounted.\n  const zone = zoneProp ?? (hydrated ? Intl.DateTimeFormat().resolvedOptions().timeZone : \"UTC\");\n  const now = useNow();\n  const start = React.useMemo(() => dayStart(day === undefined ? (now ?? 0) : +day, zone), [day, now, zone]);\n  const span = clamp(Math.round(duration / 15), 1, SLOTS);\n\n  // Who is at work in each quarter hour, and where everyone is.\n  const grid = React.useMemo(\n    () => people.map((p) => Array.from({ length: SLOTS }, (_, i) => inHours(clock(start + i * SLOT, p.timeZone).minutes, p.hours ?? [9, 17]))),\n    [people, start],\n  );\n  const runs = React.useMemo(() => {\n    const out: [number, number][] = [];\n    let from = -1;\n    for (let i = 0; i <= SLOTS; i++) {\n      const all = i < SLOTS && grid.length > 0 && grid.every((g) => g[i]);\n      if (all && from < 0) from = i;\n      if (!all && from >= 0) {\n        out.push([from, i]);\n        from = -1;\n      }\n    }\n    return out;\n  }, [grid]);\n\n  const controlled = valueProp !== undefined;\n  const toSlot = React.useCallback((v: Date | number | undefined) => (v === undefined ? null : clamp(Math.round((+v - start) / SLOT), 0, SLOTS - span)), [start, span]);\n  const firstFit = runs.find(([a, b]) => b - a >= span)?.[0] ?? 36;\n  const [own, setOwn] = React.useState<number | null>(null);\n  const slot = (controlled ? toSlot(valueProp) : (own ?? toSlot(defaultValue))) ?? firstFit;\n  // While dragging, what the band is over (re-rendered once per quarter hour).\n  const [preview, setPreview] = React.useState<number | null>(null);\n  const shown = preview ?? slot;\n\n  const trackRef = React.useRef<HTMLDivElement>(null);\n  const bandRef = React.useRef<HTMLDivElement>(null);\n  const pitch = React.useRef(0);\n  const spring = React.useRef<Spring | null>(null);\n  const drag = React.useRef<{ id: number; x0: number; s0: number; samples: PointerSample[]; moved: boolean } | null>(null);\n\n  const paint = React.useCallback(() => {\n    const band = bandRef.current;\n    if (band && spring.current) band.style.transform = `translateX(${spring.current.get() * pitch.current}px)`;\n  }, []);\n\n  React.useLayoutEffect(() => {\n    spring.current = createSpring(slot, { stiffness: 300, damping: 30 }, paint, 0.002);\n    return () => spring.current?.stop();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [paint]);\n\n  React.useLayoutEffect(() => {\n    const track = trackRef.current;\n    if (!track) return;\n    const measure = () => {\n      pitch.current = track.clientWidth / SLOTS;\n      paint();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(track);\n    return () => observer.disconnect();\n  }, [paint]);\n\n  // The band follows the value when nothing is holding it.\n  React.useEffect(() => {\n    const s = spring.current;\n    if (!s || drag.current) return;\n    if (reduced) s.jump(slot);\n    else s.set(slot);\n  }, [slot, reduced]);\n\n  const commit = (next: number) => {\n    if (!controlled) setOwn(next);\n    if (next !== slot) onValueChange?.(new Date(start + next * SLOT));\n  };\n\n  /** Where a band let go near `at` should come to rest. */\n  const settle = (at: number) => {\n    const free = clamp(Math.round(at), 0, SLOTS - span);\n    let best: number | null = null;\n    for (const [a, b] of runs) {\n      if (b - a < span) continue;\n      const inside = clamp(at, a, b - span);\n      if (Math.abs(inside - at) <= SNAP_REACH && (best === null || Math.abs(inside - at) < Math.abs(best - at))) best = Math.round(inside);\n    }\n    return best ?? free;\n  };\n\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.button !== 0 || !pitch.current) return;\n    const s = spring.current!;\n    const r = trackRef.current!.getBoundingClientRect();\n    const scale = r.width / (trackRef.current!.clientWidth || 1);\n    const at = (e.clientX - r.left) / scale / pitch.current;\n    const onBand = at >= s.get() && at <= s.get() + span;\n    // Pressing the strips away from the band brings the band to the pointer.\n    const s0 = onBand ? s.get() : clamp(at - span / 2, 0, SLOTS - span);\n    if (!onBand) {\n      s.set(s0);\n      if (reduced) s.jump(s0);\n    }\n    e.currentTarget.setPointerCapture(e.pointerId);\n    drag.current = { id: e.pointerId, x0: e.clientX / scale, s0, samples: [], moved: !onBand };\n    samplePointer(drag.current.samples, e.clientX / scale, e.timeStamp);\n    setPreview(clamp(Math.round(s0), 0, SLOTS - span));\n  };\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || d.id !== e.pointerId) return;\n    const r = trackRef.current!.getBoundingClientRect();\n    const scale = r.width / (trackRef.current!.clientWidth || 1);\n    const x = e.clientX / scale;\n    if (Math.abs(x - d.x0) > 3) d.moved = true;\n    samplePointer(d.samples, x, e.timeStamp);\n    const raw = d.s0 + (x - d.x0) / pitch.current;\n    const max = SLOTS - span;\n    // Past either end of the day the band gives a little, then stops.\n    const soft = raw < 0 ? raw * 0.25 : raw > max ? max + (raw - max) * 0.25 : raw;\n    spring.current!.jump(soft);\n    const q = clamp(Math.round(raw), 0, max);\n    setPreview((p) => (p === q ? p : q));\n  };\n  const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || d.id !== e.pointerId) return;\n    drag.current = null;\n    const s = spring.current!;\n    const v = releaseVelocity(d.samples, e.timeStamp);\n    const projected = s.get() + projectInertia(0, v, 0.12) / pitch.current;\n    const target = settle(projected);\n    s.push((v * 1000) / pitch.current);\n    if (reduced) s.jump(target);\n    else s.set(target);\n    setPreview(null);\n    commit(target);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const max = SLOTS - span;\n    const keys: Record<string, number> = { ArrowLeft: slot - 1, ArrowRight: slot + 1, PageUp: slot + 4, PageDown: slot - 4, Home: 0, End: max };\n    if (!(e.key in keys)) return;\n    e.preventDefault();\n    commit(clamp(keys[e.key], 0, max));\n  };\n\n  // Readouts.\n  const time = (ms: number, tz: string) => fmt(`t|${tz}|${locale}`, () => new Intl.DateTimeFormat(locale, { timeZone: tz, hour: \"numeric\", minute: \"2-digit\" })).format(ms);\n  const at = start + shown * SLOT;\n  const out = people.filter((_, i) => !grid[i].slice(shown, shown + span).every(Boolean));\n  const status = !people.length ? \"\" : out.length === 0 ? `Everyone’s in hours` : out.length === 1 ? `${out[0].name} is outside hours` : `${out.length} people outside hours`;\n  const longest = runs.reduce((m, [a, b]) => Math.max(m, b - a), 0);\n  const hoursText = (slots: number) => (slots % 4 === 0 ? `${slots / 4} h` : `${Math.floor(slots / 4) ? `${Math.floor(slots / 4)} h ` : \"\"}${(slots % 4) * 15} min`);\n  const colorOf = (p: OverlapPerson, i: number) => p.color ?? `color-mix(in oklab, var(--chart-${(i % 5) + 1}, var(--primary)) 80%, var(--foreground))`;\n\n  return (\n    <div className={`w-full rounded-[20px] 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, 520px)\" }} />\n      <div className=\"@container w-full p-4 @md:p-5\">\n        <div className=\"flex flex-wrap items-start justify-between gap-x-3 gap-y-1\">\n          <div className=\"min-w-0\">\n            <p className=\"truncate text-[12.5px] text-muted-foreground\">{title}</p>\n            <p className=\"mt-1 whitespace-nowrap text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]\" suppressHydrationWarning>\n              {hydrated ? `${time(at, zone)} – ${time(at + span * SLOT, zone)}` : \" \"}\n            </p>\n          </div>\n          <p className=\"mt-0.5 inline-flex shrink-0 items-center gap-1.5 text-[12px] font-medium\">\n            <span className={`size-1.5 rounded-full transition-colors duration-300 ${out.length ? \"bg-amber-500\" : \"bg-emerald-500\"}`} />\n            <span className={out.length ? \"text-amber-600 dark:text-amber-400\" : \"text-emerald-700 dark:text-emerald-400\"}>\n              <TextMorph>{status}</TextMorph>\n            </span>\n          </p>\n        </div>\n\n        <div className=\"mt-4 grid grid-cols-[minmax(0,60px)_minmax(0,1fr)_auto] items-center gap-x-2.5 @md:grid-cols-[minmax(0,96px)_minmax(0,1fr)_auto] @md:gap-x-3\">\n          {/* The ruler: your day, and where everyone overlaps. */}\n          <span className=\"text-[11px] text-muted-foreground\">{longest ? hoursText(longest) : \"No\"} overlap</span>\n          <div className=\"relative h-5\" aria-hidden=\"true\">\n            {[0, 6, 12, 18].map((h) => (\n              <span key={h} className={`absolute top-0 -translate-x-1/2 whitespace-nowrap text-[10.5px] tabular-nums text-muted-foreground first:translate-x-0 ${h % 12 ? \"@max-[24rem]:hidden\" : \"\"}`} style={{ left: `${(h / 24) * 100}%` }} suppressHydrationWarning>\n                {hydrated ? fmt(`h|${zone}|${locale}`, () => new Intl.DateTimeFormat(locale, { timeZone: zone, hour: \"numeric\" })).format(start + h * 4 * SLOT) : \"\"}\n              </span>\n            ))}\n            {runs.map(([a, b]) => (\n              <span key={a} className=\"absolute bottom-0.5 h-[3px] rounded-full bg-emerald-500\" style={{ left: `${(a / SLOTS) * 100}%`, width: `${((b - a) / SLOTS) * 100}%` }} />\n            ))}\n          </div>\n          <span />\n\n          {people.map((p, i) => (\n            <Row key={p.id} row={i + 2} person={p} color={colorOf(p, i)} slots={grid[i]} local={hydrated ? time(at, p.timeZone) : \"\"} out={out.includes(p)} />\n          ))}\n\n          {/* The band: over the strips, the length of the meeting. */}\n          <div\n            ref={trackRef}\n            role=\"slider\"\n            tabIndex={0}\n            aria-label={`${title}, ${duration} minutes`}\n            aria-valuemin={0}\n            aria-valuemax={SLOTS - span}\n            aria-valuenow={slot}\n            aria-valuetext={hydrated ? `${time(start + slot * SLOT, zone)}. ${status}` : undefined}\n            onKeyDown={onKeyDown}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={onPointerUp}\n            className={`relative cursor-grab touch-pan-y self-stretch rounded-[10px] active:cursor-grabbing ${FOCUS}`}\n            style={{ gridColumn: 2, gridRow: `2 / span ${Math.max(1, people.length)}` }}\n          >\n            <div\n              ref={bandRef}\n              aria-hidden=\"true\"\n              className=\"absolute inset-y-0 left-0 rounded-[9px] transition-[box-shadow,background-color] duration-300\"\n              style={{\n                width: `${(span / SLOTS) * 100}%`,\n                background: \"color-mix(in oklab, var(--foreground) 6%, transparent)\",\n                boxShadow: out.length\n                  ? \"inset 0 0 0 1.5px color-mix(in oklab, var(--foreground) 30%, transparent)\"\n                  : \"inset 0 0 0 1.5px color-mix(in oklab, var(--color-emerald-500, #10b981) 85%, var(--foreground))\",\n                transitionTimingFunction: EASE,\n              }}\n            />\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst Row = React.memo(function Row({ row, person, color, slots, local, out }: { row: number; person: OverlapPerson; color: string; slots: boolean[]; local: string; out: boolean }) {\n  const city = person.timeZone.split(\"/\").pop()?.replace(/_/g, \" \") ?? person.timeZone;\n  return (\n    <>\n      <div className=\"flex h-9 min-w-0 flex-col justify-center\" style={{ gridRow: row, gridColumn: 1 }}>\n        <p className=\"truncate text-[12.5px] font-medium leading-tight text-foreground\">{person.name}</p>\n        <p className=\"truncate text-[11px] leading-tight text-muted-foreground\">{city}</p>\n      </div>\n      <Strip slots={slots} color={color} row={row} />\n      <p className={`h-9 min-w-[40px] whitespace-nowrap text-right text-[11.5px] leading-9 tabular-nums @md:min-w-[52px] @md:text-[12px] transition-colors duration-300 ${out ? \"text-amber-600 dark:text-amber-400\" : \"text-foreground\"}`} style={{ gridRow: row, gridColumn: 3 }} suppressHydrationWarning>\n        {local}\n      </p>\n    </>\n  );\n});\n\n/** One day in hairline marks, one every half hour: their colour at work, faint otherwise. */\nconst Strip = React.memo(function Strip({ slots, color, row }: { slots: boolean[]; color: string; row: number }) {\n  const marks = [];\n  for (let i = 0; i < SLOTS; i += 2) marks.push(slots[i]);\n  return (\n    <div aria-hidden=\"true\" className=\"flex h-9 items-center\" style={{ gridRow: row, gridColumn: 2 }}>\n      {marks.map((on, i) => (\n        <span key={i} className=\"flex h-5 flex-1 justify-center\">\n          <span className=\"w-[2px] rounded-full\" style={{ background: on ? color : \"color-mix(in oklab, var(--foreground) 11%, transparent)\", height: on ? \"100%\" : \"55%\", marginTop: on ? 0 : \"auto\" }} />\n        </span>\n      ))}\n    </div>\n  );\n});\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · time-overlap · 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/time-overlap. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}