{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"page-outline","type":"registry:component","title":"Page outline","description":"A spring-guided hairline table of contents and collapsible reading progress pill whose active indicator glides smoothly along a continuous stepped SVG path.","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/page-outline.tsx","type":"registry:component","content":"// Hairline UI · page-outline · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { ChevronDown } from \"lucide-react\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  MATERIAL_LIFT,\n  createSpring,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * PAGE OUTLINE: spring-guided stepped hairline TOC & scroll pill\n *\n *   path     measures each heading row and builds one continuous\n *            stepped SVG hairline track (indenting smoothly along\n *            a crisp 45° elbow for nested H3 sections). Coupled\n *            createSpring springs drive stroke-dasharray and\n *            stroke-dashoffset directly on the SVG path so the\n *            active indicator literally glides around corners.\n *\n *   variants \"rail\" for sticky desktop docs sidebars; \"pill\" for\n *            a compact floating reading pill with a circular\n *            progress ring that unfolds into the full stepped\n *            outline on tap and folds cleanly back on jump.\n *\n *   spy      tracks either window scroll or any scrollable\n *            containerRef, locking cleanly to the last section at\n *            the bottom and respecting prefers-reduced-motion.\n * ───────────────────────────────────────────────────────── */\n\nexport interface OutlineItem {\n  /** Matching DOM element id on the page or inside containerRef. */\n  id: string;\n  /** Heading label shown in the outline and collapsed pill. */\n  title: string;\n  /** Heading depth: 2 for top-level sections, 3 (or higher) for indented sub-sections. */\n  level?: number;\n}\n\nexport interface PageOutlineProps extends Omit<React.HTMLAttributes<HTMLElement>, \"onSelect\"> {\n  /** Ordered list of document headings to track. */\n  items: OutlineItem[];\n  /** \"rail\" renders a sidebar outline; \"pill\" renders a compact expanding reading pill (default \"rail\"). */\n  variant?: \"rail\" | \"pill\";\n  /** Optional scroll container to spy on; defaults to the browser window. */\n  containerRef?: React.RefObject<HTMLElement | null>;\n  /** Controlled active heading id (bypasses automatic scroll-spy when supplied). */\n  activeId?: string;\n  /** Controlled reading progress 0..1 (bypasses automatic scroll-spy when supplied). */\n  progress?: number;\n  /** Called whenever the user clicks a section or scroll-spy updates the active heading. */\n  onActiveChange?: (id: string) => void;\n  /** Reading line offset from top of viewport or container in px (default 84). */\n  topOffset?: number;\n  /** Heading above the rail outline (default \"On this page\"). */\n  title?: string;\n  /** Show circular scroll ring and reading percentage (default true). */\n  showProgress?: boolean;\n  /** Highlight already-read portion of the stepped rail (default true). */\n  showTrail?: boolean;\n  /** Direction the pill outline panel opens: \"down\" (default) or \"up\". */\n  popoverSide?: \"down\" | \"up\";\n  /** Opt-in quiet Web Audio tick on section jump (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\ninterface PathSegment {\n  id: string;\n  startLen: number;\n  endLen: number;\n}\n\ninterface RailGeometry {\n  width: number;\n  height: number;\n  d: string;\n  totalLen: number;\n  segments: PathSegment[];\n}\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);\n\nfunction ProgressRing({ progress, size = 16 }: { progress: number; size?: number }) {\n  const stroke = 1.75;\n  const r = (size - stroke) * 0.5;\n  const c = 2 * Math.PI * r;\n  const offset = c * (1 - clamp01(progress));\n  return (\n    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden=\"true\" className=\"-rotate-90 shrink-0\">\n      <circle cx={size / 2} cy={size / 2} r={r} fill=\"none\" stroke=\"currentColor\" strokeOpacity={0.2} strokeWidth={stroke} />\n      <circle\n        cx={size / 2}\n        cy={size / 2}\n        r={r}\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={stroke}\n        strokeLinecap=\"round\"\n        strokeDasharray={c}\n        strokeDashoffset={offset}\n      />\n    </svg>\n  );\n}\n\ninterface SteppedListProps {\n  items: OutlineItem[];\n  activeId: string;\n  showTrail: boolean;\n  reduced: boolean;\n  onJump: (id: string) => void;\n}\n\nfunction SteppedRailList({ items, activeId, showTrail, reduced, onJump }: SteppedListProps) {\n  const listRef = React.useRef<HTMLUListElement>(null);\n  const activePathRef = React.useRef<SVGPathElement>(null);\n  const trailPathRef = React.useRef<SVGPathElement>(null);\n  const geomRef = React.useRef<RailGeometry | null>(null);\n  const [geom, setGeom] = React.useState<RailGeometry | null>(null);\n\n  const springsRef = React.useRef<{ start: Spring; end: Spring } | null>(null);\n\n  // Measure real row positions and synthesize one continuous stepped SVG hairline path\n  const measureRail = React.useCallback(() => {\n    const list = listRef.current;\n    if (!list || items.length === 0) return;\n\n    const rowEls = list.querySelectorAll<HTMLElement>(\"[data-outline-row]\");\n    if (rowEls.length !== items.length) return;\n\n    const X_ROOT = 2;\n    const X_NEST = 12;\n    const cmds: string[] = [];\n    const segments: PathSegment[] = [];\n\n    let curX = 0;\n    let curY = 0;\n    let totalLen = 0;\n\n    for (let i = 0; i < items.length; i++) {\n      const row = rowEls[i];\n      const depth = (items[i].level ?? 2) > 2 ? 1 : 0;\n      const x = depth > 0 ? X_NEST : X_ROOT;\n      const top = row.offsetTop + 5;\n      const bottom = row.offsetTop + Math.max(14, row.offsetHeight - 5);\n\n      if (i === 0) {\n        cmds.push(`M ${x} ${top}`);\n        curX = x;\n        curY = top;\n      } else if (x !== curX) {\n        // Crisp 45° architectural step connector between H2 and H3 depths\n        const stepH = Math.min(Math.abs(x - curX), Math.max(4, top - curY));\n        const midY = top - stepH;\n        if (midY > curY) {\n          cmds.push(`L ${curX} ${midY}`);\n          totalLen += midY - curY;\n          curY = midY;\n        }\n        cmds.push(`L ${x} ${top}`);\n        totalLen += Math.hypot(x - curX, top - curY);\n        curX = x;\n        curY = top;\n      } else if (top > curY) {\n        cmds.push(`L ${x} ${top}`);\n        totalLen += top - curY;\n        curY = top;\n      }\n\n      const segStart = totalLen;\n      cmds.push(`L ${x} ${bottom}`);\n      totalLen += Math.max(0, bottom - curY);\n      const segEnd = totalLen;\n      curY = bottom;\n\n      segments.push({ id: items[i].id, startLen: segStart, endLen: segEnd });\n    }\n\n    const nextGeom: RailGeometry = {\n      width: 16,\n      height: Math.max(1, list.offsetHeight),\n      d: cmds.join(\" \"),\n      totalLen: Math.max(1, totalLen),\n      segments,\n    };\n\n    geomRef.current = nextGeom;\n    setGeom(nextGeom);\n  }, [items]);\n\n  React.useEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n    const ro = new ResizeObserver(() => measureRail());\n    ro.observe(list);\n    return () => ro.disconnect();\n  }, [measureRail]);\n\n  // Paint active spring-gliding path stroke + read trail directly on the SVG <path> elements\n  const paintStroke = React.useCallback(() => {\n    const sp = springsRef.current;\n    const g = geomRef.current;\n    const activeEl = activePathRef.current;\n    if (!sp || !g || !activeEl) return;\n\n    const s = clamp(sp.start.get(), 0, g.totalLen);\n    const e = clamp(sp.end.get(), s + 2, g.totalLen);\n    const len = Math.max(2, e - s);\n\n    activeEl.style.strokeDasharray = `${len.toFixed(2)} ${(g.totalLen + 10).toFixed(2)}`;\n    activeEl.style.strokeDashoffset = `${(-s).toFixed(2)}`;\n\n    if (trailPathRef.current) {\n      trailPathRef.current.style.strokeDasharray = `${s.toFixed(2)} ${(g.totalLen + 10).toFixed(2)}`;\n      trailPathRef.current.style.strokeDashoffset = \"0\";\n    }\n  }, []);\n\n  React.useEffect(() => {\n    const start = createSpring(0, { stiffness: 250, damping: 25 }, paintStroke, 0.15);\n    const end = createSpring(18, { stiffness: 280, damping: 26 }, paintStroke, 0.15);\n    springsRef.current = { start, end };\n    return () => {\n      start.stop();\n      end.stop();\n      springsRef.current = null;\n    };\n  }, [paintStroke]);\n\n  // Aim coupled springs at the active heading's exact arc-length segment along the stepped path!\n  const seededRef = React.useRef(false);\n  React.useEffect(() => {\n    const sp = springsRef.current;\n    if (!sp || !geom) return;\n    const seg = geom.segments.find((s) => s.id === activeId) ?? geom.segments[0];\n    if (!seg) return;\n\n    if (!seededRef.current || reduced) {\n      sp.start.jump(seg.startLen);\n      sp.end.jump(seg.endLen);\n      seededRef.current = true;\n    } else {\n      sp.start.set(seg.startLen);\n      sp.end.set(seg.endLen);\n    }\n    paintStroke();\n  }, [activeId, geom, reduced, paintStroke]);\n\n  return (\n    <div className=\"relative\">\n      {geom && (\n        <svg\n          width={geom.width}\n          height={geom.height}\n          viewBox={`0 0 ${geom.width} ${geom.height}`}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute left-0 top-0 overflow-visible\"\n        >\n          {/* Base stepped hairline track */}\n          <path d={geom.d} fill=\"none\" stroke=\"var(--border)\" strokeWidth={1.25} strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n\n          {/* Subtle already-read trail along the stepped path */}\n          {showTrail && (\n            <path\n              ref={trailPathRef}\n              d={geom.d}\n              fill=\"none\"\n              stroke=\"var(--foreground)\"\n              strokeOpacity={0.28}\n              strokeWidth={1.5}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n            />\n          )}\n\n          {/* Active spring-gliding indicator curving cleanly around every 45° elbow */}\n          <path\n            ref={activePathRef}\n            d={geom.d}\n            fill=\"none\"\n            stroke=\"var(--foreground)\"\n            strokeWidth={2}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n          />\n        </svg>\n      )}\n\n      <ul ref={listRef} className=\"flex flex-col\">\n        {items.map((item) => {\n          const isNested = (item.level ?? 2) > 2;\n          const isActive = item.id === activeId;\n          return (\n            <li key={item.id} data-outline-row={item.id}>\n              <button\n                type=\"button\"\n                aria-current={isActive ? \"location\" : undefined}\n                onClick={() => onJump(item.id)}\n                className={`block w-full cursor-pointer rounded-[8px] py-1.5 pr-2 text-left text-[13px] leading-5 transition-colors duration-150 ${\n                  isNested ? \"pl-6\" : \"pl-4\"\n                } ${\n                  isActive\n                    ? \"font-medium text-foreground\"\n                    : \"text-muted-foreground hover:text-foreground\"\n                } ${INTERACTION_FOCUS}`}\n              >\n                <span className=\"block truncate\">{item.title}</span>\n              </button>\n            </li>\n          );\n        })}\n      </ul>\n    </div>\n  );\n}\n\nexport function PageOutline({\n  items,\n  variant = \"rail\",\n  containerRef,\n  activeId: controlledActiveId,\n  progress: controlledProgress,\n  onActiveChange,\n  topOffset = 84,\n  title = \"On this page\",\n  showProgress = true,\n  showTrail = true,\n  popoverSide = \"down\",\n  sound = false,\n  className = \"\",\n  ...props\n}: PageOutlineProps) {\n  const reduced = useInteractionReducedMotion();\n  const [ownActiveId, setOwnActiveId] = React.useState<string>(() => items[0]?.id ?? \"\");\n  const [ownProgress, setOwnProgress] = React.useState(0);\n  const [pillOpen, setPillOpen] = React.useState(false);\n\n  const navRef = React.useRef<HTMLElement>(null);\n  const scrollLockRef = React.useRef<{ id: string; until: number } | null>(null);\n\n  const activeId = controlledActiveId ?? (items.some((i) => i.id === ownActiveId) ? ownActiveId : items[0]?.id ?? \"\");\n  const progress = controlledProgress !== undefined ? clamp01(controlledProgress) : ownProgress;\n\n  // Real-time scroll-spy tracking either a scrollable containerRef or full window scroll\n  React.useEffect(() => {\n    if (controlledActiveId !== undefined && controlledProgress !== undefined) return;\n    if (items.length === 0) return;\n\n    let raf = 0;\n\n    const compute = () => {\n      raf = 0;\n      const container = containerRef?.current ?? null;\n      const scrollTop = container ? container.scrollTop : window.scrollY;\n      const scrollHeight = container ? container.scrollHeight : document.documentElement.scrollHeight;\n      const clientHeight = container ? container.clientHeight : window.innerHeight;\n      const maxScroll = Math.max(1, scrollHeight - clientHeight);\n      const nextProgress = clamp01(scrollTop / maxScroll);\n\n      if (controlledProgress === undefined) setOwnProgress(nextProgress);\n\n      // Avoid flicker while smooth-scrolling to a clicked target\n      if (scrollLockRef.current && Date.now() < scrollLockRef.current.until) return;\n\n      if (controlledActiveId === undefined) {\n        let nextActive = items[0].id;\n        // Lock cleanly to the final section when scrolled to the bottom\n        if (scrollTop >= maxScroll - 8) {\n          nextActive = items[items.length - 1].id;\n        } else {\n          const baseTop = container ? container.getBoundingClientRect().top : 0;\n          for (const item of items) {\n            const targetEl = container\n              ? container.querySelector<HTMLElement>(`#${CSS.escape(item.id)}`)\n              : document.getElementById(item.id);\n            if (!targetEl) continue;\n            const relTop = targetEl.getBoundingClientRect().top - baseTop;\n            if (relTop <= topOffset) nextActive = item.id;\n            else break;\n          }\n        }\n        setOwnActiveId((prev) => {\n          if (prev !== nextActive) onActiveChange?.(nextActive);\n          return nextActive;\n        });\n      }\n    };\n\n    const onScroll = () => {\n      if (!raf) raf = requestAnimationFrame(compute);\n    };\n\n    onScroll();\n    const target: EventTarget = containerRef?.current ?? window;\n    target.addEventListener(\"scroll\", onScroll, { passive: true });\n    window.addEventListener(\"resize\", onScroll, { passive: true });\n    return () => {\n      cancelAnimationFrame(raf);\n      target.removeEventListener(\"scroll\", onScroll);\n      window.removeEventListener(\"resize\", onScroll);\n    };\n  }, [items, containerRef, controlledActiveId, controlledProgress, topOffset, onActiveChange]);\n\n  // Close pill popover on click-outside or Escape\n  React.useEffect(() => {\n    if (!pillOpen) return;\n    const onPointerDown = (e: PointerEvent) => {\n      if (navRef.current && !navRef.current.contains(e.target as Node)) setPillOpen(false);\n    };\n    const onKeyDown = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") setPillOpen(false);\n    };\n    window.addEventListener(\"pointerdown\", onPointerDown, true);\n    window.addEventListener(\"keydown\", onKeyDown);\n    return () => {\n      window.removeEventListener(\"pointerdown\", onPointerDown, true);\n      window.removeEventListener(\"keydown\", onKeyDown);\n    };\n  }, [pillOpen]);\n\n  const handleJump = React.useCallback(\n    (id: string) => {\n      const container = containerRef?.current ?? null;\n      const targetEl = container\n        ? container.querySelector<HTMLElement>(`#${CSS.escape(id)}`)\n        : document.getElementById(id);\n\n      scrollLockRef.current = { id, until: Date.now() + 550 };\n      if (controlledActiveId === undefined) setOwnActiveId(id);\n      onActiveChange?.(id);\n      if (sound) playSound(\"tick\", 0.3);\n\n      if (targetEl) {\n        if (container) {\n          const cRect = container.getBoundingClientRect();\n          const tRect = targetEl.getBoundingClientRect();\n          const dest = container.scrollTop + (tRect.top - cRect.top) - Math.max(16, topOffset - 56);\n          container.scrollTo({ top: Math.max(0, dest), behavior: reduced ? \"auto\" : \"smooth\" });\n        } else {\n          const dest = window.scrollY + targetEl.getBoundingClientRect().top - Math.max(16, topOffset - 24);\n          window.scrollTo({ top: Math.max(0, dest), behavior: reduced ? \"auto\" : \"smooth\" });\n        }\n      }\n\n      if (variant === \"pill\") setPillOpen(false);\n    },\n    [containerRef, controlledActiveId, onActiveChange, sound, topOffset, reduced, variant],\n  );\n\n  const activeItem = items.find((i) => i.id === activeId) ?? items[0];\n  const pct = Math.round(progress * 100);\n\n  if (variant === \"pill\") {\n    return (\n      <nav ref={navRef} aria-label={title} className={`relative inline-flex flex-col items-start ${className}`} {...props}>\n        <button\n          type=\"button\"\n          aria-expanded={pillOpen}\n          onClick={() => setPillOpen((v) => !v)}\n          className={`inline-flex h-10 max-w-[280px] cursor-pointer items-center gap-2.5 rounded-full border border-border bg-card px-3.5 text-[13px] text-card-foreground hover:bg-[color-mix(in_oklab,var(--card)_92%,var(--foreground)_8%)] ${MATERIAL_LIFT} ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n        >\n          {showProgress && (\n            <span className=\"text-foreground\">\n              <ProgressRing progress={progress} size={16} />\n            </span>\n          )}\n          <span className=\"min-w-0 truncate font-medium text-foreground\">\n            <TextMorph>{activeItem?.title ?? title}</TextMorph>\n          </span>\n          {showProgress && (\n            <span className=\"shrink-0 font-mono text-[11.5px] tabular-nums text-muted-foreground\">\n              <NumberRoll value={pct} suffix=\"%\" duration={420} />\n            </span>\n          )}\n          <ChevronDown\n            className={`size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 ${pillOpen ? \"rotate-180\" : \"\"}`}\n            strokeWidth={2}\n            aria-hidden=\"true\"\n          />\n        </button>\n\n        {/* Unfolding stepped-path outline card */}\n        <div\n          aria-hidden={!pillOpen || undefined}\n          className={`absolute left-0 z-30 w-[256px] overflow-hidden rounded-[15px] border border-border bg-card p-3 text-card-foreground ${MATERIAL_LIFT} ${\n            popoverSide === \"up\" ? \"bottom-[calc(100%_+_8px)] origin-bottom-left\" : \"top-[calc(100%_+_8px)] origin-top-left\"\n          } ${pillOpen ? \"pointer-events-auto opacity-100 scale-100\" : \"pointer-events-none opacity-0 scale-[0.96]\"}`}\n          style={{ transition: reduced ? \"none\" : `opacity 180ms ${EASE_OUT}, transform 220ms ${EASE_OUT}` }}\n        >\n          <div className=\"mb-2 flex items-center justify-between px-1 text-[11.5px] font-medium text-muted-foreground\">\n            <span>{title}</span>\n            {showProgress && (\n              <span className=\"font-mono tabular-nums\">\n                <NumberRoll value={pct} suffix=\"%\" duration={420} />\n              </span>\n            )}\n          </div>\n          <SteppedRailList items={items} activeId={activeId} showTrail={showTrail} reduced={reduced} onJump={handleJump} />\n        </div>\n      </nav>\n    );\n  }\n\n  return (\n    <nav ref={navRef} aria-label={title} className={`flex w-full flex-col gap-2.5 ${className}`} {...props}>\n      <div className=\"flex items-center justify-between gap-2 text-[12px] text-muted-foreground\">\n        <span className=\"font-medium text-foreground/85\">{title}</span>\n        {showProgress && (\n          <span className=\"inline-flex items-center gap-1.5 font-mono text-[11.5px] tabular-nums\">\n            <ProgressRing progress={progress} size={14} />\n            <NumberRoll value={pct} suffix=\"%\" duration={420} />\n          </span>\n        )}\n      </div>\n\n      <SteppedRailList items={items} activeId={activeId} showTrail={showTrail} reduced={reduced} onJump={handleJump} />\n    </nav>\n  );\n}\n\nexport default PageOutline;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · page-outline · 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 · page-outline · 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/page-outline. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}