{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"chapter-rail","type":"registry:component","title":"Chapter Rail","description":"A reading map that moves while you read.","dependencies":[],"categories":["navigation","scroll","editorial","progress","anchors"],"files":[{"path":"components/lab/chapter-rail/chapter-rail.tsx","target":"components/lab/chapter-rail/chapter-rail.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n} from \"react\";\nimport \"./chapter-rail.css\";\n\nexport type Chapter = {\n  /** The id of the section this chapter points at. */\n  id: string;\n  label: string;\n  /** Optional fuller title, used as the link's accessible name. */\n  title?: string;\n};\n\nexport type ChapterRailProps = {\n  chapters: Chapter[];\n  /** Accessible name for the navigation landmark. */\n  label?: string;\n  /** Show 01, 02… beside each label. */\n  numbered?: boolean;\n  /**\n   * The element that owns scrolling. Omit to let the rail find the\n   * nearest scrollable ancestor, then fall back to the window.\n   */\n  scrollContainer?: HTMLElement | null;\n  className?: string;\n};\n\nfunction isScrollable(element: HTMLElement) {\n  const style = window.getComputedStyle(element);\n  return (\n    /(auto|scroll|overlay)/.test(style.overflowY) &&\n    element.scrollHeight > element.clientHeight + 2\n  );\n}\n\nfunction findScroller(start: HTMLElement | null): HTMLElement | Window {\n  let node = start?.parentElement ?? null;\n  while (node && node !== document.body) {\n    if (isScrollable(node)) return node;\n    node = node.parentElement;\n  }\n  return window;\n}\n\n/**\n * CHAPTER RAIL\n *\n * A reading map that follows the section you are actually in. The\n * marker is interpolated from the section's own scroll progress, so it\n * keeps moving while you read instead of jumping at section boundaries.\n * Scrolling is entirely native: links are ordinary anchors, there is no\n * snap and no scroll listener that writes to scrollTop.\n */\nexport function ChapterRail({\n  chapters,\n  label = \"Chapters\",\n  numbered = true,\n  scrollContainer,\n  className,\n}: ChapterRailProps) {\n  const rootRef = useRef<HTMLElement>(null);\n  const trackRef = useRef<HTMLDivElement>(null);\n  const linkRefs = useRef(new Map<string, HTMLAnchorElement>());\n  const [active, setActive] = useState(0);\n  const [position, setPosition] = useState(0);\n  const [progress, setProgress] = useState(0);\n  const [horizontal, setHorizontal] = useState(false);\n  const frame = useRef<number | null>(null);\n  const scroller = useRef<HTMLElement | Window | null>(null);\n  const activeId = chapters[active]?.id;\n\n  const measure = useCallback(() => {\n    const root = rootRef.current;\n    if (!root || chapters.length === 0) return;\n    const owner = scroller.current;\n    const isWindow = owner === window;\n    const container = isWindow ? null : (owner as HTMLElement);\n    const doc = root.ownerDocument;\n\n    const containerTop = container\n      ? container.getBoundingClientRect().top\n      : 0;\n    const scrollTop = isWindow ? window.scrollY : container!.scrollTop;\n    const viewportHeight = isWindow\n      ? window.innerHeight\n      : container!.clientHeight;\n    const anchorLine = scrollTop + Math.min(viewportHeight * 0.34, 320);\n\n    const sections = chapters.map((chapter) =>\n      doc.getElementById(chapter.id),\n    );\n    let index = 0;\n    for (let i = 0; i < sections.length; i += 1) {\n      const section = sections[i];\n      if (!section) continue;\n      const top =\n        section.getBoundingClientRect().top - containerTop + scrollTop;\n      if (top <= anchorLine) index = i;\n    }\n\n    const current = sections[index];\n    const next = sections[index + 1];\n    const currentTop = current\n      ? current.getBoundingClientRect().top - containerTop + scrollTop\n      : 0;\n    const currentHeight = current?.offsetHeight ?? 1;\n    const local = Math.max(\n      0,\n      Math.min(1, (anchorLine - currentTop) / Math.max(currentHeight, 1)),\n    );\n\n    /* A last section has no successor: let it hold the end of the rail. */\n    const span = index + (next ? local : 1);\n    const ratio = chapters.length <= 1 ? 0 : span / (chapters.length - 1);\n\n    const track = trackRef.current;\n    const rails = chapters\n      .map((chapter) => linkRefs.current.get(chapter.id))\n      .filter((node): node is HTMLAnchorElement => Boolean(node));\n    if (track && rails.length) {\n      const trackRect = track.getBoundingClientRect();\n      const centers = rails.map((node) => {\n        const rect = node.getBoundingClientRect();\n        return horizontal\n          ? rect.left + rect.width / 2 - trackRect.left\n          : rect.top + rect.height / 2 - trackRect.top;\n      });\n      const first = centers[0];\n      const last = centers[centers.length - 1];\n      const safe = Math.max(0, Math.min(1, ratio));\n      setPosition(first + safe * (last - first));\n      setProgress(safe);\n    }\n    setActive(index);\n  }, [chapters, horizontal]);\n\n  const schedule = useCallback(() => {\n    if (frame.current !== null) return;\n    frame.current = window.requestAnimationFrame(() => {\n      frame.current = null;\n      measure();\n    });\n  }, [measure]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const owner = scrollContainer ?? findScroller(root);\n    scroller.current = owner;\n    const target = owner === window ? window : owner;\n\n    target.addEventListener(\"scroll\", schedule, { passive: true });\n    window.addEventListener(\"resize\", schedule);\n\n    const media = window.matchMedia(\"(max-width: 720px)\");\n    const syncOrientation = () => {\n      setHorizontal(media.matches);\n      window.requestAnimationFrame(measure);\n    };\n    syncOrientation();\n    media.addEventListener?.(\"change\", syncOrientation);\n\n    let observer: ResizeObserver | null = null;\n    if (typeof ResizeObserver === \"function\") {\n      observer = new ResizeObserver(schedule);\n      observer.observe(root);\n      const doc = root.ownerDocument;\n      for (const chapter of chapters) {\n        const section = doc.getElementById(chapter.id);\n        if (section) observer.observe(section);\n      }\n    }\n    window.requestAnimationFrame(measure);\n\n    return () => {\n      target.removeEventListener(\"scroll\", schedule);\n      window.removeEventListener(\"resize\", schedule);\n      media.removeEventListener?.(\"change\", syncOrientation);\n      observer?.disconnect();\n      if (frame.current !== null) {\n        window.cancelAnimationFrame(frame.current);\n        frame.current = null;\n      }\n    };\n  }, [chapters, measure, schedule, scrollContainer]);\n\n  const style = {\n    \"--cr-pos\": `${position}px`,\n    \"--cr-progress\": progress,\n  } as CSSProperties;\n\n  useEffect(() => {\n    if (!horizontal) return;\n    const link = linkRefs.current.get(activeId ?? \"\");\n    link?.scrollIntoView({ block: \"nearest\", inline: \"nearest\" });\n  }, [activeId, horizontal]);\n\n  return (\n    <nav\n      ref={rootRef}\n      className={`cr-root${className ? ` ${className}` : \"\"}`}\n      aria-label={label}\n      data-horizontal={horizontal ? \"true\" : \"false\"}\n      style={style}\n    >\n      <p className=\"cr-kicker\">Reading map</p>\n      <div ref={trackRef} className=\"cr-track\" aria-hidden=\"true\">\n        <span className=\"cr-line\" />\n        <span className=\"cr-line cr-line--progress\" />\n        <span className=\"cr-marker\" />\n      </div>\n      <ol className=\"cr-list\" onScroll={schedule}>\n        {chapters.map((chapter, index) => (\n          <li key={chapter.id}>\n            <a\n              ref={(node) => {\n                if (node) linkRefs.current.set(chapter.id, node);\n                else linkRefs.current.delete(chapter.id);\n              }}\n              href={`#${chapter.id}`}\n              aria-current={index === active ? \"location\" : undefined}\n              aria-label={chapter.title ?? chapter.label}\n            >\n              {numbered ? (\n                <span className=\"cr-number\" aria-hidden=\"true\">\n                  {String(index + 1).padStart(2, \"0\")}\n                </span>\n              ) : null}\n              <span className=\"cr-label\">{chapter.label}</span>\n            </a>\n          </li>\n        ))}\n      </ol>\n    </nav>\n  );\n}\n"},{"path":"components/lab/chapter-rail/chapter-rail.css","target":"components/lab/chapter-rail/chapter-rail.css","type":"registry:file","content":".cr-root {\n  --cr-ink: #232018;\n  --cr-muted: #7b7568;\n  --cr-line: rgba(35, 32, 24, 0.16);\n  --cr-accent: #8a2f27;\n  --cr-paper: #f4f0e6;\n  --cr-ease: cubic-bezier(0.22, 1, 0.36, 1);\n  position: relative;\n  display: grid;\n  grid-template-columns: 18px minmax(0, 1fr);\n  column-gap: 14px;\n  min-width: 0;\n  color: var(--cr-ink);\n  font: inherit;\n}\n\n.cr-kicker {\n  grid-column: 1 / -1;\n  margin: 0 0 18px;\n  font-family: ui-monospace, \"SF Mono\", \"Cascadia Mono\", Consolas, monospace;\n  font-size: 0.625rem;\n  letter-spacing: 0.14em;\n  text-transform: uppercase;\n  color: var(--cr-muted);\n}\n\n.cr-track {\n  position: relative;\n  grid-column: 1;\n  grid-row: 2;\n  width: 18px;\n}\n\n.cr-line {\n  position: absolute;\n  top: 12px;\n  bottom: 12px;\n  left: 8px;\n  width: 1px;\n  background: var(--cr-line);\n}\n\n.cr-line--progress {\n  bottom: auto;\n  height: calc((100% - 24px) * var(--cr-progress, 0));\n  background: var(--cr-accent);\n  transition: height 120ms linear;\n}\n\n.cr-marker {\n  position: absolute;\n  top: var(--cr-pos, 0px);\n  left: 3px;\n  width: 11px;\n  height: 11px;\n  margin-top: -5.5px;\n  border: 1px solid var(--cr-accent);\n  border-radius: 50%;\n  background: var(--cr-paper);\n  box-shadow: 0 0 0 4px color-mix(in srgb, var(--cr-accent) 12%, transparent);\n  transition: top 180ms var(--cr-ease);\n}\n\n.cr-list {\n  grid-column: 2;\n  grid-row: 2;\n  display: grid;\n  gap: 2px;\n  margin: 0;\n  padding: 0;\n  list-style: none;\n}\n\n.cr-list a {\n  display: flex;\n  align-items: baseline;\n  gap: 9px;\n  min-height: 34px;\n  padding: 7px 8px;\n  border-radius: 6px;\n  color: var(--cr-muted);\n  font-size: 0.8125rem;\n  line-height: 1.35;\n  text-decoration: none;\n  transition:\n    color 180ms var(--cr-ease),\n    background-color 180ms var(--cr-ease);\n}\n\n.cr-number {\n  flex: none;\n  font-family: ui-monospace, \"SF Mono\", \"Cascadia Mono\", Consolas, monospace;\n  font-size: 0.5625rem;\n  letter-spacing: 0.06em;\n  color: var(--cr-muted);\n  opacity: 0.72;\n  transition: color 180ms var(--cr-ease);\n}\n\n.cr-label {\n  min-width: 0;\n  overflow-wrap: anywhere;\n  transition:\n    transform 220ms var(--cr-ease),\n    font-weight 220ms var(--cr-ease);\n}\n\n.cr-list a:hover {\n  color: var(--cr-ink);\n  background: color-mix(in srgb, var(--cr-ink) 5%, transparent);\n}\n\n.cr-list a[aria-current=\"location\"] {\n  color: var(--cr-ink);\n  font-weight: 600;\n}\n\n.cr-list a[aria-current=\"location\"] .cr-label {\n  transform: translateX(2px);\n}\n\n.cr-list a[aria-current=\"location\"] .cr-number {\n  color: var(--cr-accent);\n  opacity: 1;\n}\n\n.cr-list a:focus-visible {\n  outline: 2px solid var(--cr-accent);\n  outline-offset: 2px;\n}\n\n@media (max-width: 720px) {\n  .cr-root {\n    display: block;\n    padding: 10px 12px 12px;\n    border: 1px solid var(--cr-line);\n    border-radius: 10px;\n    background: color-mix(in srgb, var(--cr-paper) 92%, transparent);\n    backdrop-filter: blur(6px);\n  }\n\n  .cr-kicker {\n    margin: 0 0 9px;\n    font-size: 0.5625rem;\n  }\n\n  .cr-track {\n    position: absolute;\n    right: 14px;\n    bottom: 8px;\n    left: 14px;\n    top: auto;\n    width: auto;\n    height: 1px;\n  }\n\n  .cr-line {\n    top: 0;\n    bottom: auto;\n    left: 0;\n    width: 100%;\n    height: 1px;\n  }\n\n  .cr-line--progress {\n    width: calc(100% * var(--cr-progress, 0));\n    height: 1px;\n    transition: width 120ms linear;\n  }\n\n  .cr-marker {\n    top: -5px;\n    left: var(--cr-pos, 0px);\n    margin-top: 0;\n    margin-left: -5.5px;\n    transition: left 180ms var(--cr-ease);\n  }\n\n  .cr-list {\n    display: flex;\n    gap: 2px;\n    margin: 0 0 8px;\n    overflow-x: auto;\n    scrollbar-width: none;\n  }\n\n  .cr-list::-webkit-scrollbar {\n    display: none;\n  }\n\n  .cr-list li {\n    flex: 0 0 auto;\n  }\n\n  .cr-list a {\n    min-height: 32px;\n    padding: 5px 8px;\n    font-size: 0.75rem;\n    font-weight: 500;\n    white-space: nowrap;\n  }\n\n  .cr-list a[aria-current=\"location\"] {\n    font-weight: 500;\n  }\n\n  .cr-list a[aria-current=\"location\"] .cr-label {\n    transform: none;\n  }\n\n  .cr-number {\n    font-size: 0.5rem;\n  }\n}\n\n@media (max-width: 480px) {\n  .cr-number {\n    display: none;\n  }\n\n  .cr-list a {\n    padding: 5px 6px;\n    font-size: 0.6875rem;\n  }\n}\n\n@media (max-width: 380px) {\n  .cr-root {\n    padding: 8px 9px 10px;\n  }\n\n  .cr-list a {\n    padding: 4px 4px;\n    font-size: 0.625rem;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .cr-marker,\n  .cr-line--progress,\n  .cr-list a,\n  .cr-label,\n  .cr-number {\n    transition-duration: 0.01ms;\n  }\n}\n"}]}