Implementation:0xranx OpenContext useScrollSpy
| Knowledge Sources | |
|---|---|
| Domains | Scroll_Spy, React |
| Last Updated | 2026-10-24 00:00 GMT |
Overview
React hook for tracking the active heading during scroll, syncing TOC heading IDs to DOM elements, and providing smooth scroll navigation.
Description
The useScrollSpy.js hook in src/ui/src/hooks/ tracks which heading is currently active based on scroll position. It syncs TOC heading IDs to DOM data-heading-id attributes (avoiding text-based matching), handles IME composition events to avoid interfering with input, uses requestAnimationFrame for scroll throttling, and returns the active heading ID plus a scrollToId function for smooth scrolling. Also exports a pure pickActiveHeadingId helper for testing.
Usage
Import this hook in the document viewer/editor component to drive the table of contents highlight.
Code Reference
Source Location
- Repository: 0xranx_OpenContext
- File: src/ui/src/hooks/useScrollSpy.js
- Lines: 1-177
Signature
export function useScrollSpy({ containerRef, toc, offset = 120 })
// Returns: { activeId, scrollToId }
export function pickActiveHeadingId(headings, scrollTop, offset = 120)
Import
import { useScrollSpy } from './hooks/useScrollSpy';
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| containerRef | Ref | Yes | Scroll container ref |
| toc | Array | Yes | [{id, ...}] table of contents entries |
| offset | number | No | Activation offset (default 120) |
Outputs
| Name | Type | Description |
|---|---|---|
| activeId | string | Currently active heading ID |
| scrollToId | Function | Smooth scroll to a heading by ID |
Usage Examples
Tracking Active Heading
import { useRef } from 'react';
import { useScrollSpy } from './hooks/useScrollSpy';
function DocViewer({ toc }) {
const containerRef = useRef(null);
const { activeId, scrollToId } = useScrollSpy({ containerRef, toc });
return (
<div ref={containerRef} className="overflow-y-auto">
<Toc toc={toc} activeId={activeId} onItemClick={scrollToId} />
<DocContent />
</div>
);
}