{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"weekly-hours","type":"registry:component","title":"Weekly hours","description":"A recurring Mon to Sun operating and availability hours editor with split shifts, aligned 24-hour coverage bars, overlap guards and Copy to Mon-Fri.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency","https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/weekly-hours.tsx","type":"registry:component","content":"// Hairline UI · weekly-hours · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport {\n  AlertCircle,\n  Check,\n  Clock,\n  Copy,\n  Globe,\n  Plus,\n  Trash2,\n} from \"lucide-react\";\nimport {\n  EASE_OUT,\n  EASE_THROW,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  interactionIcon,\n  useInteractionReducedMotion,\n} from \"./ui-interaction-motion\";\nimport { NumberRoll } from \"./number-roll\";\nimport { PillSelect, type PillOption } from \"./pill-select\";\nimport { TextMorph } from \"./text-morph\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * WEEKLY HOURS: recurring availability & operating schedule\n *\n *   presets   gliding segmented pill (Mon–Fri 9–5 / 24/7) throws\n *             its active highlight across while weekly hours roll\n *             with NumberRoll and every day's 24-hour track eases\n *\n *   bars      every day renders a proportional 00:00–24:00\n *             hairline coverage ribbon aligned across Mon–Sun;\n *             intervals ease smoothly, split shifts part the bar,\n *             and overlapping ranges highlight their collision in\n *             crimson with a height-folded alert\n *\n *   ergonomic portaled PillSelect time pickers (zero native\n *             selects), smooth day toggle transitions, \"+\" smart\n *             next-slot split shifts and one-click Copy to Mon–Fri\n * ───────────────────────────────────────────────────────── */\n\nexport type WeekdayKey = \"mon\" | \"tue\" | \"wed\" | \"thu\" | \"fri\" | \"sat\" | \"sun\";\n\nexport interface TimeSlot {\n  /** 24-hour start time in \"HH:MM\" format (e.g. \"09:00\"). */\n  start: string;\n  /** 24-hour end time in \"HH:MM\" format (e.g. \"17:00\", or \"24:00\" for midnight end). */\n  end: string;\n}\n\nexport type WeeklySchedule = Record<WeekdayKey, TimeSlot[]>;\n\nexport interface WeeklyHoursProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"defaultValue\" | \"onChange\"> {\n  /** Controlled Mon–Sun weekly schedule. */\n  value?: WeeklySchedule;\n  /** Initial uncontrolled weekly schedule (defaults to Mon–Fri 09:00–17:00). */\n  defaultValue?: WeeklySchedule;\n  /** Called whenever any day or interval changes. */\n  onChange?: (next: WeeklySchedule) => void;\n  /** Minute increment for time selectors (default 30). */\n  stepMinutes?: 15 | 30 | 60;\n  /** Format displayed times in 12-hour AM/PM clock (default false -> crisp 24-hour). */\n  hour12?: boolean;\n  /** Optional IANA timezone label shown in the card header (e.g. \"Europe/London\"). */\n  timezone?: string;\n  /** Show the aligned 24-hour proportional coverage hairline column (default true). */\n  showTimeline?: boolean;\n  /** Show header quick presets (Mon–Fri 9–5, 24/7) (default true). */\n  showPresets?: boolean;\n  /** Start week on Sunday instead of Monday (default false). */\n  weekStartsOnSunday?: boolean;\n  /** Card header title (default \"Working hours\"). */\n  title?: string;\n  /** Opt-in Web Audio ticks (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\ninterface DayMeta {\n  key: WeekdayKey;\n  short: string;\n  full: string;\n  weekday: boolean;\n}\n\nconst DAYS_MON_FIRST: DayMeta[] = [\n  { key: \"mon\", short: \"Mon\", full: \"Monday\", weekday: true },\n  { key: \"tue\", short: \"Tue\", full: \"Tuesday\", weekday: true },\n  { key: \"wed\", short: \"Wed\", full: \"Wednesday\", weekday: true },\n  { key: \"thu\", short: \"Thu\", full: \"Thursday\", weekday: true },\n  { key: \"fri\", short: \"Fri\", full: \"Friday\", weekday: true },\n  { key: \"sat\", short: \"Sat\", full: \"Saturday\", weekday: false },\n  { key: \"sun\", short: \"Sun\", full: \"Sunday\", weekday: false },\n];\n\nexport const DEFAULT_WEEKLY_SCHEDULE: WeeklySchedule = {\n  mon: [{ start: \"09:00\", end: \"17:00\" }],\n  tue: [{ start: \"09:00\", end: \"17:00\" }],\n  wed: [{ start: \"09:00\", end: \"17:00\" }],\n  thu: [{ start: \"09:00\", end: \"17:00\" }],\n  fri: [{ start: \"09:00\", end: \"17:00\" }],\n  sat: [],\n  sun: [],\n};\n\nexport function timeToMinutes(hhmm: string): number {\n  const [hStr, mStr] = hhmm.split(\":\");\n  const h = Number.parseInt(hStr ?? \"0\", 10);\n  const m = Number.parseInt(mStr ?? \"0\", 10);\n  if (!Number.isFinite(h) || !Number.isFinite(m)) return 0;\n  return Math.max(0, Math.min(1440, h * 60 + m));\n}\n\nexport function minutesToTime(total: number): string {\n  const clamped = Math.max(0, Math.min(1440, Math.round(total)));\n  const h = Math.floor(clamped / 60);\n  const m = clamped % 60;\n  return `${String(h).padStart(2, \"0\")}:${String(m).padStart(2, \"0\")}`;\n}\n\nexport function formatTimeDisplay(hhmm: string, hour12: boolean): string {\n  if (!hour12) return hhmm;\n  const mins = timeToMinutes(hhmm);\n  if (mins === 1440) return \"12:00 AM\";\n  const h24 = Math.floor(mins / 60);\n  const m = mins % 60;\n  const suffix = h24 >= 12 ? \"PM\" : \"AM\";\n  const h12 = h24 % 12 === 0 ? 12 : h24 % 12;\n  return `${h12}:${String(m).padStart(2, \"0\")} ${suffix}`;\n}\n\nexport interface SlotValidation {\n  errors: Array<string | null>;\n  hasOverlap: boolean;\n  hasInvalid: boolean;\n  validMinutes: number;\n}\n\n/** Validate all intervals for a single day (invalid order and overlaps). */\nexport function validateDaySlots(slots: TimeSlot[]): SlotValidation {\n  const errors: Array<string | null> = slots.map(() => null);\n  let hasInvalid = false;\n  let hasOverlap = false;\n  let validMinutes = 0;\n\n  const ranges = slots.map((s, idx) => ({\n    idx,\n    start: timeToMinutes(s.start),\n    end: timeToMinutes(s.end),\n  }));\n\n  for (const r of ranges) {\n    if (r.end <= r.start) {\n      errors[r.idx] = \"End must be after start\";\n      hasInvalid = true;\n    } else {\n      validMinutes += r.end - r.start;\n    }\n  }\n\n  for (let i = 0; i < ranges.length; i++) {\n    const a = ranges[i];\n    if (a.end <= a.start) continue;\n    for (let j = i + 1; j < ranges.length; j++) {\n      const b = ranges[j];\n      if (b.end <= b.start) continue;\n      if (a.start < b.end && b.start < a.end) {\n        errors[a.idx] = errors[a.idx] ?? \"Overlaps another interval\";\n        errors[b.idx] = errors[b.idx] ?? \"Overlaps another interval\";\n        hasOverlap = true;\n      }\n    }\n  }\n\n  return { errors, hasOverlap, hasInvalid, validMinutes };\n}\n\n/** Calculate total valid open minutes across the entire Mon–Sun schedule. */\nexport function calculateWeeklyMinutes(schedule: WeeklySchedule): number {\n  let total = 0;\n  for (const day of DAYS_MON_FIRST) {\n    total += validateDaySlots(schedule[day.key] ?? []).validMinutes;\n  }\n  return total;\n}\n\nexport function formatWeeklyDuration(minutes: number): string {\n  const h = Math.floor(minutes / 60);\n  const m = minutes % 60;\n  if (m === 0) return `${h}h / wk`;\n  return `${h}h ${m}m / wk`;\n}\n\nfunction buildTimeOptions(stepMinutes: number, includeEndMidnight: boolean): string[] {\n  const out: string[] = [];\n  const limit = includeEndMidnight ? 1440 : 1440 - stepMinutes;\n  for (let m = 0; m <= limit; m += stepMinutes) {\n    out.push(minutesToTime(m));\n  }\n  return out;\n}\n\nfunction detectActivePreset(schedule: WeeklySchedule): \"weekdays\" | \"24x7\" | null {\n  const is9to5 = (slots: TimeSlot[]) => slots.length === 1 && slots[0].start === \"09:00\" && slots[0].end === \"17:00\";\n  const isFull = (slots: TimeSlot[]) => slots.length === 1 && slots[0].start === \"00:00\" && slots[0].end === \"24:00\";\n  if (\n    DAYS_MON_FIRST.every((d) => (d.weekday ? is9to5(schedule[d.key] ?? []) : (schedule[d.key] ?? []).length === 0))\n  ) {\n    return \"weekdays\";\n  }\n  if (DAYS_MON_FIRST.every((d) => isFull(schedule[d.key] ?? []))) {\n    return \"24x7\";\n  }\n  return null;\n}\n\n/** Hairline sliding segmented preset switcher. */\nfunction PresetPill({\n  active,\n  reduced,\n  onSelect,\n}: {\n  active: \"weekdays\" | \"24x7\" | null;\n  reduced: boolean;\n  onSelect: (kind: \"weekdays\" | \"24x7\") => void;\n}) {\n  const wrapRef = React.useRef<HTMLDivElement | null>(null);\n  const btnRefs = React.useRef<Record<string, HTMLButtonElement | null>>({});\n  const [pill, setPill] = React.useState<{ left: number; width: number; ready: boolean }>({\n    left: 0,\n    width: 0,\n    ready: false,\n  });\n\n  React.useLayoutEffect(() => {\n    const el = active ? btnRefs.current[active] : null;\n    if (!el) {\n      setPill((p) => (p.width === 0 ? p : { ...p, width: 0 }));\n      return;\n    }\n    const left = el.offsetLeft;\n    const width = el.offsetWidth;\n    setPill((p) => (p.left === left && p.width === width && p.ready ? p : { left, width, ready: true }));\n  }, [active]);\n\n  return (\n    <div\n      ref={wrapRef}\n      role=\"group\"\n      aria-label=\"Schedule presets\"\n      className=\"relative inline-flex items-center rounded-[9px] border border-border bg-muted/50 p-0.5\"\n    >\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0.5 left-0 rounded-[7px] bg-background shadow-[inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.07)]\"\n        style={{\n          width: pill.width,\n          transform: `translate3d(${pill.left}px, 0, 0)`,\n          opacity: active && pill.width > 0 ? 1 : 0,\n          transition:\n            reduced || !pill.ready\n              ? \"none\"\n              : `transform 360ms ${EASE_THROW}, width 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n        }}\n      />\n      {(\n        [\n          { id: \"weekdays\", label: \"Mon–Fri 9–5\" },\n          { id: \"24x7\", label: \"24/7\" },\n        ] as const\n      ).map((item) => {\n        const on = active === item.id;\n        return (\n          <button\n            key={item.id}\n            ref={(el) => {\n              btnRefs.current[item.id] = el;\n            }}\n            type=\"button\"\n            aria-pressed={on}\n            onClick={() => onSelect(item.id)}\n            className={`relative z-10 h-6 cursor-pointer rounded-[7px] px-2 text-[11px] font-medium transition-colors duration-150 ${\n              on ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\"\n            } ${INTERACTION_FOCUS}`}\n          >\n            {item.label}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\n/** Aligned 24-hour coverage bar with smooth interval transitions and crimson overlap highlight. */\nfunction DayCoverageBar({\n  slots,\n  hasError,\n  validMinutes,\n  reduced,\n}: {\n  slots: TimeSlot[];\n  hasError: boolean;\n  validMinutes: number;\n  reduced: boolean;\n}) {\n  const hours = Math.floor(validMinutes / 60);\n  const mins = validMinutes % 60;\n  const durLabel = validMinutes === 0 ? \"Off\" : mins === 0 ? `${hours}h` : `${hours}h ${mins}m`;\n\n  return (\n    <div className=\"hidden items-center gap-2 @[520px]:flex\">\n      <span className=\"w-10 text-right font-mono text-[10.5px] tabular-nums text-muted-foreground/80\">\n        <TextMorph>{durLabel}</TextMorph>\n      </span>\n      <div\n        aria-hidden=\"true\"\n        className=\"relative h-2 w-24 shrink-0 overflow-hidden rounded-full border border-border/70 bg-muted/40\"\n      >\n        <span className=\"absolute inset-y-0 left-1/4 w-px bg-border/60\" />\n        <span className=\"absolute inset-y-0 left-1/2 w-px bg-border/80\" />\n        <span className=\"absolute inset-y-0 left-3/4 w-px bg-border/60\" />\n\n        {slots.map((slot, idx) => {\n          const s = timeToMinutes(slot.start);\n          const e = timeToMinutes(slot.end);\n          if (e <= s) return null;\n          const left = (s / 1440) * 100;\n          const width = ((e - s) / 1440) * 100;\n          return (\n            <span\n              key={idx}\n              className={`absolute inset-y-0 rounded-full ${\n                hasError ? \"bg-red-500/85\" : \"bg-primary/85\"\n              }`}\n              style={{\n                left: `${left.toFixed(2)}%`,\n                width: `${Math.max(1.8, width).toFixed(2)}%`,\n                transition: reduced ? \"none\" : `left 320ms ${EASE_OUT}, width 320ms ${EASE_OUT}, background-color 200ms ${EASE_OUT}`,\n              }}\n            />\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\nexport function WeeklyHours({\n  value: controlledValue,\n  defaultValue = DEFAULT_WEEKLY_SCHEDULE,\n  onChange,\n  stepMinutes = 30,\n  hour12 = false,\n  timezone,\n  showTimeline = true,\n  showPresets = true,\n  weekStartsOnSunday = false,\n  title = \"Working hours\",\n  sound = false,\n  className = \"\",\n  ...props\n}: WeeklyHoursProps) {\n  const reduced = useInteractionReducedMotion();\n  const [ownSchedule, setOwnSchedule] = React.useState<WeeklySchedule>(defaultValue);\n  const schedule = controlledValue !== undefined ? controlledValue : ownSchedule;\n\n  const [copiedFromDay, setCopiedFromDay] = React.useState<WeekdayKey | null>(null);\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n  const copyTimerRef = React.useRef(0);\n\n  React.useEffect(\n    () => () => {\n      window.clearTimeout(copyTimerRef.current);\n    },\n    [],\n  );\n\n  const days = React.useMemo(() => {\n    if (!weekStartsOnSunday) return DAYS_MON_FIRST;\n    return [DAYS_MON_FIRST[6], ...DAYS_MON_FIRST.slice(0, 6)];\n  }, [weekStartsOnSunday]);\n\n  const startOptions = React.useMemo<PillOption[]>(\n    () => buildTimeOptions(stepMinutes, false).map((opt) => ({ value: opt, label: formatTimeDisplay(opt, hour12) })),\n    [stepMinutes, hour12],\n  );\n  const endOptions = React.useMemo<PillOption[]>(\n    () => buildTimeOptions(stepMinutes, true).map((opt) => ({ value: opt, label: formatTimeDisplay(opt, hour12) })),\n    [stepMinutes, hour12],\n  );\n\n  const commit = React.useCallback(\n    (next: WeeklySchedule) => {\n      if (controlledValue === undefined) setOwnSchedule(next);\n      onChange?.(next);\n    },\n    [controlledValue, onChange],\n  );\n\n  const toggleDay = (key: WeekdayKey) => {\n    const cur = schedule[key] ?? [];\n    const nextSlots = cur.length > 0 ? [] : [{ start: \"09:00\", end: \"17:00\" }];\n    commit({ ...schedule, [key]: nextSlots });\n    if (sound) playSound(nextSlots.length > 0 ? \"unfold\" : \"fold\", 0.25);\n  };\n\n  const updateSlot = (key: WeekdayKey, index: number, patch: Partial<TimeSlot>) => {\n    const cur = schedule[key] ?? [];\n    const next = cur.map((s, i) => (i === index ? { ...s, ...patch } : s));\n    commit({ ...schedule, [key]: next });\n  };\n\n  const addSlot = (key: WeekdayKey) => {\n    const cur = schedule[key] ?? [];\n    const last = cur[cur.length - 1];\n    let nextStart = 540;\n    let nextEnd = 1020;\n    if (last) {\n      const lastEnd = timeToMinutes(last.end);\n      nextStart = Math.min(1380, lastEnd + 60);\n      nextEnd = Math.min(1440, nextStart + 180);\n      if (nextEnd <= nextStart) {\n        nextStart = Math.min(1380, lastEnd);\n        nextEnd = Math.min(1440, nextStart + 60);\n      }\n    }\n    commit({\n      ...schedule,\n      [key]: [...cur, { start: minutesToTime(nextStart), end: minutesToTime(nextEnd) }],\n    });\n    if (sound) playSound(\"tick\", 0.28);\n  };\n\n  const removeSlot = (key: WeekdayKey, index: number) => {\n    const cur = schedule[key] ?? [];\n    commit({ ...schedule, [key]: cur.filter((_, i) => i !== index) });\n    if (sound) playSound(\"fold\", 0.24);\n  };\n\n  const copyToWeekdays = (sourceKey: WeekdayKey) => {\n    const sourceSlots = (schedule[sourceKey] ?? []).map((s) => ({ ...s }));\n    const next: WeeklySchedule = { ...schedule };\n    for (const d of DAYS_MON_FIRST) {\n      if (d.weekday) next[d.key] = sourceSlots.map((s) => ({ ...s }));\n    }\n    commit(next);\n    setCopiedFromDay(sourceKey);\n    setLiveStatus(\"Copied hours to Monday through Friday\");\n    if (sound) playSound(\"success\", 0.32);\n    window.clearTimeout(copyTimerRef.current);\n    copyTimerRef.current = window.setTimeout(() => setCopiedFromDay(null), 1800);\n  };\n\n  const applyPreset = (kind: \"weekdays\" | \"24x7\") => {\n    if (kind === \"weekdays\") {\n      commit({\n        mon: [{ start: \"09:00\", end: \"17:00\" }],\n        tue: [{ start: \"09:00\", end: \"17:00\" }],\n        wed: [{ start: \"09:00\", end: \"17:00\" }],\n        thu: [{ start: \"09:00\", end: \"17:00\" }],\n        fri: [{ start: \"09:00\", end: \"17:00\" }],\n        sat: [],\n        sun: [],\n      });\n      setLiveStatus(\"Applied Weekdays 9 to 5 preset\");\n    } else {\n      commit({\n        mon: [{ start: \"00:00\", end: \"24:00\" }],\n        tue: [{ start: \"00:00\", end: \"24:00\" }],\n        wed: [{ start: \"00:00\", end: \"24:00\" }],\n        thu: [{ start: \"00:00\", end: \"24:00\" }],\n        fri: [{ start: \"00:00\", end: \"24:00\" }],\n        sat: [{ start: \"00:00\", end: \"24:00\" }],\n        sun: [{ start: \"00:00\", end: \"24:00\" }],\n      });\n      setLiveStatus(\"Applied 24/7 open preset\");\n    }\n    if (sound) playSound(\"tick\", 0.28);\n  };\n\n  const totalMinutes = React.useMemo(() => calculateWeeklyMinutes(schedule), [schedule]);\n  const totalHours = Math.floor(totalMinutes / 60);\n  const remMinutes = totalMinutes % 60;\n  const openDaysCount = React.useMemo(\n    () => days.filter((d) => (schedule[d.key] ?? []).length > 0).length,\n    [days, schedule],\n  );\n  const anyConflict = React.useMemo(\n    () =>\n      days.some((d) => {\n        const v = validateDaySlots(schedule[d.key] ?? []);\n        return v.hasInvalid || v.hasOverlap;\n      }),\n    [days, schedule],\n  );\n  const activePreset = React.useMemo(() => detectActivePreset(schedule), [schedule]);\n\n  return (\n    <div\n      role=\"region\"\n      aria-label={title}\n      data-weekly-minutes={totalMinutes}\n      data-has-conflict={anyConflict ? \"true\" : \"false\"}\n      className={`@container flex w-full max-w-[620px] flex-col overflow-hidden rounded-[16px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${className}`}\n      {...props}\n    >\n      {/* Header */}\n      <div className=\"flex flex-wrap items-center justify-between gap-2 border-b border-border/80 bg-muted/20 px-4 py-3\">\n        <div className=\"flex flex-wrap items-center gap-2\">\n          <Clock className=\"size-4 text-muted-foreground\" strokeWidth={1.9} />\n          <span className=\"text-[13px] font-medium tracking-[-0.01em] text-foreground\">{title}</span>\n          <span className=\"inline-flex items-center gap-1 font-mono text-[11px] tabular-nums text-muted-foreground\">\n            <NumberRoll value={totalHours} suffix=\"h\" duration={500} />\n            {remMinutes > 0 && <NumberRoll value={remMinutes} suffix=\"m\" duration={450} />}\n            <span>/ wk ·</span>\n            <NumberRoll value={openDaysCount} suffix=\"d\" duration={450} />\n          </span>\n          {timezone && (\n            <span className=\"inline-flex items-center gap-1 rounded-[6px] border border-border/80 bg-background px-1.5 py-0.5 font-mono text-[10.5px] text-muted-foreground\">\n              <Globe className=\"size-2.5\" strokeWidth={2} />\n              {timezone}\n            </span>\n          )}\n          <span\n            aria-hidden={!copiedFromDay || undefined}\n            className=\"grid\"\n            style={{\n              gridTemplateColumns: copiedFromDay ? \"1fr\" : \"0fr\",\n              opacity: copiedFromDay ? 1 : 0,\n              transition: reduced ? \"none\" : `grid-template-columns 340ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,\n            }}\n          >\n            <span className=\"min-w-0 overflow-hidden\">\n              <span className=\"inline-flex w-max items-center gap-1 whitespace-nowrap rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 text-[10.5px] font-medium text-emerald-700 dark:text-emerald-300\">\n                <Check className=\"size-2.5\" strokeWidth={2.5} />\n                Copied to Mon–Fri\n              </span>\n            </span>\n          </span>\n        </div>\n\n        {showPresets && <PresetPill active={activePreset} reduced={reduced} onSelect={applyPreset} />}\n      </div>\n\n      {/* Mon–Sun structured hairline rows */}\n      <div className=\"divide-y divide-border/70\">\n        {days.map((day) => {\n          const slots = schedule[day.key] ?? [];\n          const enabled = slots.length > 0;\n          const validation = validateDaySlots(slots);\n          const hasDayError = validation.hasInvalid || validation.hasOverlap;\n          const justCopied = copiedFromDay === day.key;\n\n          return (\n            <div\n              key={day.key}\n              data-day-row={day.key}\n              data-enabled={enabled ? \"true\" : \"false\"}\n              className={`grid grid-cols-[1fr_auto] items-center gap-x-2 gap-y-2 px-4 py-2.5 transition-colors duration-200 @[460px]:flex @[460px]:items-start @[460px]:justify-between ${\n                enabled ? \"bg-card\" : \"bg-muted/[0.14]\"\n              }`}\n            >\n              {/* Left: switch + day label */}\n              <div className=\"order-1 flex h-8 w-24 shrink-0 items-center gap-2.5\">\n                <button\n                  type=\"button\"\n                  role=\"switch\"\n                  aria-checked={enabled}\n                  aria-label={`Enable ${day.full}`}\n                  onClick={() => toggleDay(day.key)}\n                  className={`relative inline-flex h-[18px] w-8 shrink-0 cursor-pointer items-center rounded-full border transition-colors duration-200 ${\n                    enabled\n                      ? \"border-primary bg-primary\"\n                      : \"border-border bg-muted/70\"\n                  } ${INTERACTION_FOCUS}`}\n                >\n                  <span\n                    className={`block size-3 rounded-full shadow-xs ${\n                      enabled\n                        ? \"bg-primary-foreground\"\n                        : \"bg-muted-foreground/75\"\n                    }`}\n                    style={{\n                      transform: enabled ? \"translateX(15px)\" : \"translateX(2px)\",\n                      transition: reduced ? \"none\" : `transform 280ms ${EASE_THROW}, background-color 180ms ${EASE_OUT}`,\n                    }}\n                  />\n                </button>\n                <span\n                  className={`text-[12.5px] font-medium transition-colors duration-150 ${\n                    enabled ? \"text-foreground\" : \"text-muted-foreground/70\"\n                  }`}\n                >\n                  {day.short}\n                </span>\n              </div>\n\n              {/* Centre: intervals OR Unavailable (on mobile <460px, enabled intervals wrap cleanly under Row 1; Unavailable stays inline on Row 1 right!) */}\n              <div\n                className={`flex min-w-0 flex-1 flex-col gap-1.5 ${\n                  enabled\n                    ? \"order-3 col-span-2 @[460px]:order-2 @[460px]:col-span-1\"\n                    : \"order-2 col-span-1 items-end @[460px]:order-2 @[460px]:items-start\"\n                }`}\n              >\n                {!enabled ? (\n                  <div className=\"flex h-8 items-center text-[12px] text-muted-foreground/65\">Unavailable</div>\n                ) : (\n                  slots.map((slot, idx) => {\n                    const slotErr = validation.errors[idx];\n                    const sList = startOptions.some((o) => o.value === slot.start)\n                      ? startOptions\n                      : [{ value: slot.start, label: formatTimeDisplay(slot.start, hour12) }, ...startOptions];\n                    const eList = endOptions.some((o) => o.value === slot.end)\n                      ? endOptions\n                      : [{ value: slot.end, label: formatTimeDisplay(slot.end, hour12) }, ...endOptions];\n                    const pillW = hour12 ? 114 : 90;\n\n                    return (\n                      <div key={idx} className=\"flex flex-col\">\n                        <div className=\"flex flex-wrap items-center gap-1.5\">\n                          <PillSelect\n                            options={sList}\n                            value={slot.start}\n                            onValueChange={(next) => updateSlot(day.key, idx, { start: next })}\n                            label={`${day.full} interval ${idx + 1} start`}\n                            mono\n                            size=\"sm\"\n                            width={pillW}\n                            className={slotErr ? \"ring-1 ring-red-500/60\" : \"\"}\n                          />\n\n                          <span className=\"text-[11px] text-muted-foreground\">–</span>\n\n                          <PillSelect\n                            options={eList}\n                            value={slot.end}\n                            onValueChange={(next) => updateSlot(day.key, idx, { end: next })}\n                            label={`${day.full} interval ${idx + 1} end`}\n                            mono\n                            size=\"sm\"\n                            width={pillW}\n                            className={slotErr ? \"ring-1 ring-red-500/60\" : \"\"}\n                          />\n\n                          {slots.length > 1 && (\n                            <button\n                              type=\"button\"\n                              aria-label={`Remove ${day.full} interval ${idx + 1}`}\n                              onClick={() => removeSlot(day.key, idx)}\n                              className={`inline-flex size-7 cursor-pointer items-center justify-center rounded-[7px] text-muted-foreground hover:bg-accent hover:text-red-600 dark:hover:text-red-400 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                            >\n                              <Trash2 className=\"size-3.5\" strokeWidth={1.9} />\n                            </button>\n                          )}\n                        </div>\n\n                        <div\n                          aria-hidden={!slotErr || undefined}\n                          className={`grid ${!slotErr ? \"pointer-events-none\" : \"\"}`}\n                          style={{\n                            gridTemplateRows: slotErr ? \"1fr\" : \"0fr\",\n                            opacity: slotErr ? 1 : 0,\n                            transition: reduced ? \"none\" : `grid-template-rows 260ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n                          }}\n                        >\n                          <div className=\"min-h-0 overflow-hidden\">\n                            <span role=\"alert\" className=\"inline-flex items-center gap-1 pt-1 text-[11px] text-red-600 dark:text-red-400\">\n                              <AlertCircle className=\"size-3 shrink-0\" strokeWidth={2} />\n                              {slotErr ?? \"\"}\n                            </span>\n                          </div>\n                        </div>\n                      </div>\n                    );\n                  })\n                )}\n              </div>\n\n              {/* Right: aligned 24h hairline bar + fixed-width action slot so all 7 bars align */}\n              <div\n                className={`order-2 h-8 shrink-0 items-center justify-end gap-2 @[460px]:order-3 ${\n                  enabled ? \"flex\" : \"hidden @[460px]:flex\"\n                }`}\n              >\n                {showTimeline && (\n                  <DayCoverageBar\n                    slots={slots}\n                    hasError={hasDayError}\n                    validMinutes={validation.validMinutes}\n                    reduced={reduced}\n                  />\n                )}\n\n                <div className=\"flex w-[60px] shrink-0 items-center justify-end gap-1\">\n                  {enabled && (\n                    <>\n                      <button\n                        type=\"button\"\n                        aria-label={`Add interval for ${day.full}`}\n                        title=\"Add split shift interval\"\n                        onClick={() => addSlot(day.key)}\n                        className={`inline-flex size-7 cursor-pointer items-center justify-center rounded-[7px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                      >\n                        <Plus className=\"size-3.5\" strokeWidth={2.1} />\n                      </button>\n\n                      <button\n                        type=\"button\"\n                        aria-label={`Copy ${day.full} hours to weekdays`}\n                        title=\"Copy to Mon–Fri\"\n                        onClick={() => copyToWeekdays(day.key)}\n                        className={`relative inline-flex size-7 cursor-pointer items-center justify-center rounded-[7px] hover:bg-accent ${\n                          justCopied\n                            ? \"text-emerald-600 dark:text-emerald-400\"\n                            : \"text-muted-foreground hover:text-foreground\"\n                        } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                      >\n                        <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!justCopied, reduced)}>\n                          <Copy className=\"size-3.5\" strokeWidth={1.9} />\n                        </span>\n                        <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(justCopied, reduced)}>\n                          <Check className=\"size-3.5\" strokeWidth={2.3} />\n                        </span>\n                      </button>\n                    </>\n                  )}\n                </div>\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      {/* Footer scale legend */}\n      {showTimeline && (\n        <div className=\"flex items-center justify-between border-t border-border/80 bg-muted/15 px-4 py-2 text-[11px] text-muted-foreground\">\n          <TextMorph animateWidth={false}>\n            {anyConflict ? \"Resolve highlighted interval conflicts before saving.\" : \"Click + to split a day around breaks.\"}\n          </TextMorph>\n          <div className=\"mr-[68px] hidden w-24 items-center justify-between font-mono text-[9.5px] tabular-nums opacity-75 @[520px]:flex\">\n            <span>00</span>\n            <span>12</span>\n            <span>24</span>\n          </div>\n        </div>\n      )}\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {liveStatus}\n      </span>\n    </div>\n  );\n}\n\nexport default WeeklyHours;\n"},{"path":"registry/pill-select.tsx","type":"registry:component","content":"// Hairline UI · weekly-hours · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * PILL SELECT: a select that's the same surface as its pill\n *\n *   open      the pill grows into its list (size and corners\n *             ease) from the edge it's lined up with, while its\n *             label fades into the options; it opens upward when\n *             there's no room below, and long lists scroll\n *   pick      the list folds back into the pill and the label\n *             morphs to the new choice; the current option\n *             carries a drawn check\n *   keys      arrows move a highlight that glides between rows,\n *             Home and End jump, typing a few letters finds an\n *             option, Enter picks, Escape folds it back\n *\n * The list lives in a portal on the page's body, placed over\n * the pill, so a clipping toolbar, fold or scroller never cuts\n * it off; it carries the theme's colours with it. Scrolling\n * the page closes it.\n *\n * Used wherever a component needs a choice from a list; never\n * the browser's own dropdown, which can't follow the theme.\n * ───────────────────────────────────────────────────────── */\n\nexport interface PillOption {\n  value: string;\n  label: string;\n  /** A second line in the list, e.g. a sample value. */\n  description?: string;\n}\n\nexport interface PillSelectProps {\n  options: PillOption[];\n  value: string | null | undefined;\n  onValueChange: (value: string) => void;\n  /** Accessible name, e.g. \"Column for Email\". */\n  label: string;\n  /** Shown while nothing is chosen. */\n  placeholder?: string;\n  /** What the pill shows for a choice; the option's label by default. */\n  display?: (option: PillOption | undefined) => string;\n  /** The pill's contents, when it needs more than text (an icon that turns). */\n  renderValue?: (option: PillOption | undefined, open: boolean) => React.ReactNode;\n  /** Monospace labels, for code-like values (event names, column headers). */\n  mono?: boolean;\n  /** Which edge of the pill the list lines up with. */\n  align?: \"start\" | \"end\";\n  /** The list's width; never narrower than the pill. */\n  width?: number;\n  /** Fill the width it's given. */\n  block?: boolean;\n  /** Dims the pill's text, e.g. for \"Don't import\". */\n  muted?: boolean;\n  disabled?: boolean;\n  /** \"sm\" is the 28px pill for toolbars; \"md\" is 36px, the height of the other form fields. */\n  size?: \"sm\" | \"md\";\n  className?: string;\n}\n\ntype Phase = \"closed\" | \"opening\" | \"open\" | \"closing\";\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst DURATION = 420;\nconst MAX_LIST = 280;\nconst PILL_SIZE = { sm: \"h-7 px-2.5 text-[12px]\", md: \"h-9 pl-4 pr-3.5 text-[13.5px]\" };\n// The theme travels with the list, so it matches the pill wherever the pill's colours were set.\nconst TOKENS = [\"--background\", \"--foreground\", \"--popover\", \"--popover-foreground\", \"--border\", \"--accent\", \"--accent-foreground\", \"--primary\", \"--primary-foreground\", \"--muted\", \"--muted-foreground\", \"--ring\"];\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\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\nfunction Chevron({ up, reduced }: { up: boolean; reduced: boolean }) {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"size-3 shrink-0 text-muted-foreground\" style={{ transform: up ? \"rotate(180deg)\" : \"none\", transition: reduced ? \"none\" : `transform 320ms ${EASE}` }}>\n      <path d=\"M4.5 6.25 8 9.75l3.5-3.5\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nexport function PillSelect({\n  options,\n  value,\n  onValueChange,\n  label,\n  placeholder = \"Choose\",\n  display,\n  renderValue,\n  mono = false,\n  align = \"start\",\n  width = 240,\n  block = false,\n  muted = false,\n  disabled = false,\n  size = \"sm\",\n  className = \"\",\n}: PillSelectProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const [phase, setPhase] = React.useState<Phase>(\"closed\");\n  const [active, setActive] = React.useState(0);\n  const [pill, setPill] = React.useState({ width: 0, height: 28 });\n  const [panelHeight, setPanelHeight] = React.useState(0);\n  const [fit, setFit] = React.useState({ up: false, width, shift: 0, x: 0, y: 0, theme: {} as Record<string, string> });\n  const [highlight, setHighlight] = React.useState({ top: 0, height: 0, ready: false });\n  const [quiet, setQuiet] = React.useState(false);\n  const wrapRef = React.useRef<HTMLDivElement>(null);\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const panelRef = React.useRef<HTMLDivElement>(null);\n  const surfaceRef = React.useRef<HTMLDivElement>(null);\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const rowRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const timer = React.useRef(0);\n  const typed = React.useRef({ text: \"\", at: 0 });\n  const selected = options.find((o) => o.value === value);\n  const expanded = phase === \"open\";\n  const mounted = phase !== \"closed\";\n  const [prevPhase, setPrevPhase] = React.useState(phase);\n  if (phase !== prevPhase) {\n    setPrevPhase(phase);\n    if (phase === \"closed\") {\n      setHighlight({ top: 0, height: 0, ready: false });\n    }\n  }\n  const text = display ? display(selected) : (selected?.label ?? placeholder);\n\n  const measureFit = () => {\n    const wrap = wrapRef.current;\n    if (!wrap) return;\n    const rect = wrap.getBoundingClientRect();\n    const vw = document.documentElement.clientWidth;\n    const w = Math.min(Math.max(width, rect.width), vw - 24);\n    // Lined up with the pill's edge, nudged back on screen.\n    const shift = align === \"start\" ? Math.min(0, vw - 12 - (rect.left + w)) : Math.max(0, 12 - (rect.right - w));\n    const estimate = Math.min(MAX_LIST, options.length * (options.some((o) => o.description) ? 46 : 32)) + 12;\n    const vh = window.innerHeight;\n    const below = vh - 8 - rect.top;\n    const above = rect.bottom - 8;\n    const up = below < estimate + 8 && above > below;\n    // Fixed coordinates of the pill's corner the list grows from.\n    const x = align === \"start\" ? rect.left : vw - rect.right;\n    const y = up ? vh - rect.bottom : rect.top;\n    const cs = getComputedStyle(wrap);\n    const theme: Record<string, string> = { colorScheme: cs.colorScheme, fontFamily: cs.fontFamily };\n    for (const t of TOKENS) {\n      const v = cs.getPropertyValue(t);\n      if (v) theme[t] = v;\n    }\n    setFit({ up, width: w, shift, x, y, theme });\n  };\n\n  const open = () => {\n    if (disabled || phase === \"open\" || phase === \"opening\") return;\n    window.clearTimeout(timer.current);\n    measureFit();\n    setActive(Math.max(0, options.findIndex((o) => o.value === value)));\n    setPhase(reduced ? \"open\" : \"opening\");\n  };\n\n  const close = React.useCallback(\n    (refocus = true) => {\n      window.clearTimeout(timer.current);\n      if (refocus) triggerRef.current?.focus({ preventScroll: true });\n      if (reduced) return setPhase(\"closed\");\n      setPhase(\"closing\");\n      timer.current = window.setTimeout(() => setPhase(\"closed\"), DURATION);\n    },\n    [reduced],\n  );\n\n  React.useEffect(() => {\n    if (phase !== \"opening\") return;\n    let inner = 0;\n    const outer = requestAnimationFrame(() => (inner = requestAnimationFrame(() => setPhase(\"open\"))));\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [phase]);\n  React.useEffect(() => () => window.clearTimeout(timer.current), []);\n\n  React.useLayoutEffect(() => {\n    const trigger = triggerRef.current;\n    if (!trigger) return;\n    const measure = () => setPill((p) => (p.width === trigger.offsetWidth && p.height === trigger.offsetHeight ? p : { width: trigger.offsetWidth, height: trigger.offsetHeight }));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(trigger);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const panel = panelRef.current;\n    if (panel) setPanelHeight(panel.offsetHeight);\n  }, [mounted, options]);\n\n  // The highlight glides to the active row, and the list scrolls to keep it in view.\n  React.useLayoutEffect(() => {\n    const row = rowRefs.current[active];\n    const list = listRef.current;\n    if (!row || !list) return;\n    setHighlight((h) => (h.top === row.offsetTop && h.height === row.offsetHeight && h.ready === (h.ready || expanded) ? h : { top: row.offsetTop, height: row.offsetHeight, ready: h.ready || expanded }));\n    const scroller = list.parentElement;\n    if (scroller && scroller.scrollHeight > scroller.clientHeight) {\n      if (row.offsetTop < scroller.scrollTop) scroller.scrollTop = row.offsetTop - 4;\n      else if (row.offsetTop + row.offsetHeight > scroller.scrollTop + scroller.clientHeight) scroller.scrollTop = row.offsetTop + row.offsetHeight - scroller.clientHeight + 4;\n    }\n  }, [active, expanded, mounted]);\n\n  React.useEffect(() => {\n    if (expanded) listRef.current?.focus({ preventScroll: true });\n  }, [expanded]);\n\n  React.useEffect(() => {\n    if (!expanded) return;\n    const inside = (n: Node) => Boolean(wrapRef.current?.contains(n) || surfaceRef.current?.contains(n));\n    const onDown = (e: PointerEvent) => {\n      if (!inside(e.target as Node)) close(false);\n    };\n    // The list sits where the pill was; if the page moves under it, it goes at once rather than fold in the wrong place.\n    const gone = () => {\n      window.clearTimeout(timer.current);\n      setPhase(\"closed\");\n    };\n    const onScroll = (e: Event) => {\n      if (!surfaceRef.current?.contains(e.target as Node)) gone();\n    };\n    const onResize = gone;\n    document.addEventListener(\"pointerdown\", onDown);\n    window.addEventListener(\"scroll\", onScroll, true);\n    window.addEventListener(\"resize\", onResize);\n    return () => {\n      document.removeEventListener(\"pointerdown\", onDown);\n      window.removeEventListener(\"scroll\", onScroll, true);\n      window.removeEventListener(\"resize\", onResize);\n    };\n  }, [expanded, close]);\n\n  const choose = (o: PillOption) => {\n    close();\n    if (o.value !== value) onValueChange(o.value);\n  };\n\n  const onListKey = (e: React.KeyboardEvent) => {\n    const last = options.length - 1;\n    const move = (to: number) => {\n      e.preventDefault();\n      setActive(Math.max(0, Math.min(last, to)));\n    };\n    if (e.key === \"ArrowDown\") move(active === last ? 0 : active + 1);\n    else if (e.key === \"ArrowUp\") move(active === 0 ? last : active - 1);\n    else if (e.key === \"Home\") move(0);\n    else if (e.key === \"End\") move(last);\n    else if (e.key === \"PageDown\") move(active + 6);\n    else if (e.key === \"PageUp\") move(active - 6);\n    else if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      if (options[active]) choose(options[active]);\n    } else if (e.key === \"Tab\") close(false);\n    else if (e.key.length === 1 && /\\S/.test(e.key)) {\n      // A few letters typed quickly find the option that starts with them.\n      const now = performance.now();\n      typed.current = { text: (now - typed.current.at < 700 ? typed.current.text : \"\") + e.key.toLowerCase(), at: now };\n      const hit = options.findIndex((o) => o.label.toLowerCase().startsWith(typed.current.text));\n      if (hit !== -1) setActive(hit);\n    }\n  };\n\n  const w = expanded ? fit.width : pill.width;\n  const h = expanded ? panelHeight : pill.height;\n  const listId = `${id}-list`;\n  const pillText = renderValue ? null : (\n    <>\n      <span className={`min-w-0 flex-1 truncate text-left ${mono ? \"font-mono text-[11.5px]\" : \"\"} ${muted || !selected ? \"text-muted-foreground\" : \"text-foreground\"}`}>\n        {block ? text : <TextMorph>{text}</TextMorph>}\n      </span>\n      <Chevron up={expanded} reduced={reduced} />\n    </>\n  );\n\n  return (\n    <div\n      ref={wrapRef}\n      className={`relative ${block ? \"flex w-full min-w-0\" : \"inline-flex\"} ${className}`}\n      onKeyDown={(e) => {\n        setQuiet(false);\n        if (e.key === \"Escape\" && expanded) {\n          e.preventDefault();\n          e.stopPropagation();\n          close();\n        }\n      }}\n      onBlur={(e) => {\n        const to = e.relatedTarget as Node | null;\n        if (expanded && document.hasFocus() && !(to && (wrapRef.current?.contains(to) || surfaceRef.current?.contains(to)))) close(false);\n      }}\n    >\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        aria-haspopup=\"listbox\"\n        aria-expanded={expanded}\n        aria-controls={mounted ? listId : undefined}\n        aria-label={`${label}: ${selected?.label ?? placeholder}`}\n        disabled={disabled}\n        onClick={() => (expanded ? close() : open())}\n        onKeyDown={(e) => {\n          if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n            e.preventDefault();\n            open();\n          }\n        }}\n        onPointerDown={() => setQuiet(true)}\n        className={`inline-flex ${PILL_SIZE[size]} min-w-0 cursor-pointer items-center gap-1.5 rounded-full font-medium whitespace-nowrap shadow-[inset_0_0_0_1px_var(--border)] transition-colors duration-150 hover:bg-accent disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent ${block ? \"w-full\" : \"\"} ${quiet ? \"outline-none\" : FOCUS}`}\n      >\n        {renderValue ? renderValue(selected, expanded) : pillText}\n      </button>\n\n      {mounted &&\n        createPortal(\n        <div\n          ref={surfaceRef}\n          onKeyDown={(e) => {\n            if (e.key === \"Escape\") {\n              e.preventDefault();\n              e.stopPropagation();\n              close();\n            }\n          }}\n          onPointerDown={(e) => {\n            if (!(e.target as HTMLElement).closest(\"[data-scroll]\")) e.preventDefault();\n            setQuiet(true);\n          }}\n          className=\"fixed z-[60] overflow-hidden bg-popover text-popover-foreground\"\n          style={{\n            ...fit.theme,\n            [fit.up ? \"bottom\" : \"top\"]: fit.y,\n            [align === \"start\" ? \"left\" : \"right\"]: fit.x + (expanded ? (align === \"start\" ? fit.shift : -fit.shift) : 0),\n            width: w,\n            height: h,\n            borderRadius: expanded ? 16 : pill.height / 2,\n            // The pill's own hairline, the whole way: it is the same surface.\n            boxShadow: \"inset 0 0 0 1px var(--border)\",\n            transition: reduced ? \"none\" : `width ${DURATION}ms ${EASE}, height ${DURATION}ms ${EASE}, left ${DURATION}ms ${EASE}, right ${DURATION}ms ${EASE}, border-radius ${DURATION}ms ${EASE}`,\n          }}\n        >\n          {/* The pill's label, fading out as the surface grows and back in as it folds. */}\n          <span\n            aria-hidden=\"true\"\n            className={`pointer-events-none absolute inline-flex ${PILL_SIZE[size]} items-center gap-1.5 font-medium whitespace-nowrap ${fit.up ? \"bottom-0\" : \"top-0\"} ${align === \"start\" ? \"left-0\" : \"right-0\"}`}\n            style={{ width: pill.width, opacity: expanded ? 0 : 1, transition: reduced ? \"none\" : `opacity ${expanded ? 120 : 260}ms ${EASE} ${expanded ? 0 : 120}ms` }}\n          >\n            {renderValue ? renderValue(selected, expanded) : pillText}\n          </span>\n          <div\n            ref={panelRef}\n            className={`absolute p-1 ${fit.up ? \"bottom-0\" : \"top-0\"} ${align === \"start\" ? \"left-0\" : \"right-0\"}`}\n            style={{ width: fit.width, opacity: expanded ? 1 : 0, transition: reduced ? \"none\" : `opacity ${expanded ? 260 : 120}ms ${EASE} ${expanded ? 90 : 0}ms` }}\n          >\n            <div data-scroll=\"\" className=\"overflow-y-auto overscroll-contain\" style={{ maxHeight: MAX_LIST }}>\n              <div\n                ref={listRef}\n                id={listId}\n                role=\"listbox\"\n                tabIndex={-1}\n                aria-label={label}\n                aria-activedescendant={`${id}-o${active}`}\n                onKeyDown={onListKey}\n                className=\"relative outline-none\"\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute inset-x-0 top-0 rounded-[12px] bg-accent\"\n                  style={{\n                    height: highlight.height,\n                    transform: `translateY(${highlight.top}px)`,\n                    opacity: highlight.ready ? 1 : 0,\n                    transition: highlight.ready && !reduced ? `transform 260ms ${EASE}, height 260ms ${EASE}, opacity 200ms` : \"none\",\n                  }}\n                />\n                {options.map((o, i) => {\n                  const on = o.value === value;\n                  return (\n                    <div\n                      key={o.value}\n                      ref={(el) => {\n                        rowRefs.current[i] = el;\n                      }}\n                      id={`${id}-o${i}`}\n                      role=\"option\"\n                      aria-selected={on}\n                      onPointerMove={() => setActive(i)}\n                      onClick={() => choose(o)}\n                      className=\"relative flex cursor-pointer items-start gap-2 rounded-[12px] px-2.5 py-1.5\"\n                    >\n                      <span className=\"min-w-0 flex-1\">\n                        <span className={`block truncate ${mono ? \"font-mono text-[12px]\" : \"text-[12.5px] font-medium\"}`}>{o.label}</span>\n                        {o.description && <span className=\"mt-0.5 block truncate text-[11.5px] text-muted-foreground\">{o.description}</span>}\n                      </span>\n                      <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"mt-0.5 size-3.5 shrink-0\">\n                        <path\n                          d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n                          stroke=\"currentColor\"\n                          strokeWidth=\"1.8\"\n                          strokeLinecap=\"round\"\n                          strokeLinejoin=\"round\"\n                          pathLength={1}\n                          strokeDasharray={1}\n                          style={{ strokeDashoffset: on && expanded ? 0 : 1, transition: reduced ? \"none\" : `stroke-dashoffset 380ms ${EASE} 160ms` }}\n                        />\n                      </svg>\n                    </div>\n                  );\n                })}\n              </div>\n            </div>\n          </div>\n        </div>,\n          document.body,\n        )}\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · weekly-hours · 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"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · weekly-hours · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/weekly-hours. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}