1"use client";
2
3import {
4 Direction as DirectionPrimitive,
5 Slot as SlotPrimitive,
6} from "radix-ui";
7import * as React from "react";
8import { useComposedRefs } from "@/lib/compose-refs";
9import { cn } from "@/lib/utils";
10import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
11import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
12import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
13
14const ROOT_NAME = "ScrollSpy";
15const NAV_NAME = "ScrollSpyNav";
16const LINK_NAME = "ScrollSpyLink";
17const VIEWPORT_NAME = "ScrollSpyViewport";
18const SECTION_NAME = "ScrollSpySection";
19
20type Direction = "ltr" | "rtl";
21type Orientation = "horizontal" | "vertical";
22
23type LinkElement = React.ComponentRef<typeof ScrollSpyLink>;
24type SectionElement = React.ComponentRef<typeof ScrollSpySection>;
25
26function getDefaultScrollBehavior(): ScrollBehavior {
27 if (typeof window === "undefined") return "smooth";
28 return window.matchMedia("(prefers-reduced-motion: reduce)").matches
29 ? "auto"
30 : "smooth";
31}
32
33interface StoreState {
34 value: string;
35}
36
37interface Store {
38 subscribe: (callback: () => void) => () => void;
39 getState: () => StoreState;
40 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
41 notify: () => void;
42}
43
44const StoreContext = React.createContext<Store | null>(null);
45
46function useStore<T>(
47 selector: (state: StoreState) => T,
48 ogStore?: Store | null,
49): T {
50 const contextStore = React.useContext(StoreContext);
51
52 const store = ogStore ?? contextStore;
53
54 if (!store) {
55 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
56 }
57
58 const getSnapshot = React.useCallback(
59 () => selector(store.getState()),
60 [store, selector],
61 );
62
63 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
64}
65
66interface ScrollSpyContextValue {
67 offset: number;
68 scrollBehavior: ScrollBehavior;
69 dir: Direction;
70 orientation: Orientation;
71 scrollContainer: HTMLElement | null;
72 isScrollingRef: React.RefObject<boolean>;
73 onSectionRegister: (id: string, element: SectionElement) => void;
74 onSectionUnregister: (id: string) => void;
75 onScrollToSection: (sectionId: string) => void;
76}
77
78const ScrollSpyContext = React.createContext<ScrollSpyContextValue | null>(
79 null,
80);
81
82function useScrollSpyContext(consumerName: string) {
83 const context = React.useContext(ScrollSpyContext);
84 if (!context) {
85 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
86 }
87 return context;
88}
89
90interface ScrollSpyProps extends React.ComponentProps<"div"> {
91 value?: string;
92 defaultValue?: string;
93 onValueChange?: (value: string) => void;
94 rootMargin?: string;
95 threshold?: number | number[];
96 offset?: number;
97 scrollBehavior?: ScrollBehavior;
98 scrollContainer?: HTMLElement | null;
99 dir?: Direction;
100 orientation?: Orientation;
101 asChild?: boolean;
102}
103
104function ScrollSpy(props: ScrollSpyProps) {
105 const {
106 value,
107 defaultValue,
108 onValueChange,
109 rootMargin,
110 threshold = 0.1,
111 offset = 0,
112 scrollBehavior = getDefaultScrollBehavior(),
113 scrollContainer = null,
114 dir: dirProp,
115 orientation = "horizontal",
116 asChild,
117 className,
118 ...rootProps
119 } = props;
120
121 const dir = DirectionPrimitive.useDirection(dirProp);
122
123 const stateRef = useLazyRef<StoreState>(() => ({
124 value: value ?? defaultValue ?? "",
125 }));
126 const listenersRef = useLazyRef(() => new Set<() => void>());
127 const onValueChangeRef = useAsRef(onValueChange);
128
129 const store = React.useMemo<Store>(() => {
130 return {
131 subscribe: (cb) => {
132 listenersRef.current.add(cb);
133 return () => listenersRef.current.delete(cb);
134 },
135 getState: () => {
136 return stateRef.current;
137 },
138 setState: (key, value) => {
139 if (Object.is(stateRef.current[key], value)) return;
140
141 stateRef.current[key] = value;
142
143 if (key === "value" && value) {
144 onValueChangeRef.current?.(value);
145 }
146
147 store.notify();
148 },
149 notify: () => {
150 for (const cb of listenersRef.current) {
151 cb();
152 }
153 },
154 };
155 }, [listenersRef, stateRef, onValueChangeRef]);
156
157 const sectionMapRef = React.useRef(new Map<string, Element>());
158 const isScrollingRef = React.useRef(false);
159 const rafIdRef = React.useRef<number | null>(null);
160 const isMountedRef = React.useRef(false);
161 const scrollTimeoutRef = React.useRef<number | null>(null);
162
163 const onSectionRegister = React.useCallback(
164 (id: string, element: SectionElement) => {
165 sectionMapRef.current.set(id, element);
166 },
167 [],
168 );
169
170 const onSectionUnregister = React.useCallback((id: string) => {
171 sectionMapRef.current.delete(id);
172 }, []);
173
174 const onScrollToSection = React.useCallback(
175 (sectionId: string) => {
176 const section = scrollContainer
177 ? scrollContainer.querySelector(`#${sectionId}`)
178 : document.getElementById(sectionId);
179
180 if (!section) {
181 store.setState("value", sectionId);
182 return;
183 }
184
185 // Set flag to prevent observer from firing during programmatic scroll
186 isScrollingRef.current = true;
187 store.setState("value", sectionId);
188
189 if (scrollContainer) {
190 const containerRect = scrollContainer.getBoundingClientRect();
191 const sectionRect = section.getBoundingClientRect();
192 const scrollTop = scrollContainer.scrollTop;
193 const offsetPosition =
194 sectionRect.top - containerRect.top + scrollTop - offset;
195
196 scrollContainer.scrollTo({
197 top: offsetPosition,
198 behavior: scrollBehavior,
199 });
200 } else {
201 const sectionPosition = section.getBoundingClientRect().top;
202 const offsetPosition = sectionPosition + window.scrollY - offset;
203
204 window.scrollTo({
205 top: offsetPosition,
206 behavior: scrollBehavior,
207 });
208 }
209
210 if (scrollTimeoutRef.current !== null) {
211 clearTimeout(scrollTimeoutRef.current);
212 }
213
214 scrollTimeoutRef.current = window.setTimeout(() => {
215 isScrollingRef.current = false;
216 }, 500);
217 },
218 [scrollContainer, offset, scrollBehavior, store],
219 );
220
221 useIsomorphicLayoutEffect(() => {
222 const currentValue = value ?? defaultValue;
223 if (currentValue === undefined) return;
224
225 if (!isMountedRef.current) {
226 isMountedRef.current = true;
227 store.setState("value", currentValue);
228 return;
229 }
230
231 onScrollToSection(currentValue);
232 }, [value, onScrollToSection]);
233
234 useIsomorphicLayoutEffect(() => {
235 const sectionMap = sectionMapRef.current;
236 if (sectionMap.size === 0) return;
237
238 const observerRootMargin = rootMargin ?? `${-offset}px 0px -70% 0px`;
239
240 const observer = new IntersectionObserver(
241 (entries) => {
242 if (isScrollingRef.current) return;
243
244 if (rafIdRef.current !== null) {
245 cancelAnimationFrame(rafIdRef.current);
246 }
247
248 rafIdRef.current = requestAnimationFrame(() => {
249 const intersecting = entries.filter((entry) => entry.isIntersecting);
250
251 if (intersecting.length === 0) return;
252
253 const topmost = intersecting.reduce((prev, curr) => {
254 return curr.boundingClientRect.top < prev.boundingClientRect.top
255 ? curr
256 : prev;
257 });
258
259 const id = topmost.target.id;
260 if (id && sectionMap.has(id)) {
261 store.setState("value", id);
262 }
263 });
264 },
265 {
266 root: scrollContainer,
267 rootMargin: observerRootMargin,
268 threshold,
269 },
270 );
271
272 for (const element of sectionMap.values()) {
273 observer.observe(element);
274 }
275
276 return () => {
277 observer.disconnect();
278 if (rafIdRef.current !== null) {
279 cancelAnimationFrame(rafIdRef.current);
280 }
281 if (scrollTimeoutRef.current !== null) {
282 clearTimeout(scrollTimeoutRef.current);
283 }
284 };
285 }, [offset, rootMargin, threshold, scrollContainer]);
286
287 const contextValue = React.useMemo<ScrollSpyContextValue>(
288 () => ({
289 dir,
290 orientation,
291 offset,
292 scrollBehavior,
293 scrollContainer,
294 isScrollingRef,
295 onSectionRegister,
296 onSectionUnregister,
297 onScrollToSection,
298 }),
299 [
300 dir,
301 orientation,
302 offset,
303 scrollBehavior,
304 scrollContainer,
305 onSectionRegister,
306 onSectionUnregister,
307 onScrollToSection,
308 ],
309 );
310
311 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
312
313 return (
314 <StoreContext.Provider value={store}>
315 <ScrollSpyContext.Provider value={contextValue}>
316 <RootPrimitive
317 data-orientation={orientation}
318 data-slot="scroll-spy"
319 dir={dir}
320 {...rootProps}
321 className={cn(
322 "flex",
323 orientation === "horizontal" ? "flex-row" : "flex-col",
324 className,
325 )}
326 />
327 </ScrollSpyContext.Provider>
328 </StoreContext.Provider>
329 );
330}
331
332interface ScrollSpyNavProps extends React.ComponentProps<"nav"> {
333 asChild?: boolean;
334}
335
336function ScrollSpyNav(props: ScrollSpyNavProps) {
337 const { asChild, className, ...navProps } = props;
338
339 const { dir, orientation } = useScrollSpyContext(NAV_NAME);
340
341 const NavPrimitive = asChild ? SlotPrimitive.Slot : "nav";
342
343 return (
344 <NavPrimitive
345 data-orientation={orientation}
346 data-slot="scroll-spy-nav"
347 dir={dir}
348 {...navProps}
349 className={cn(
350 "flex gap-2",
351 orientation === "horizontal" ? "flex-col" : "flex-row",
352 className,
353 )}
354 />
355 );
356}
357
358interface ScrollSpyLinkProps extends React.ComponentProps<"a"> {
359 value: string;
360 asChild?: boolean;
361}
362
363function ScrollSpyLink(props: ScrollSpyLinkProps) {
364 const { value: linkValue, asChild, onClick, className, ...linkProps } = props;
365
366 const { orientation, onScrollToSection } = useScrollSpyContext(LINK_NAME);
367 const value = useStore((state) => state.value);
368 const isActive = value === linkValue;
369
370 const onLinkClick = React.useCallback(
371 (event: React.MouseEvent<LinkElement>) => {
372 event.preventDefault();
373 onClick?.(event);
374 onScrollToSection(linkValue);
375 },
376 [linkValue, onClick, onScrollToSection],
377 );
378
379 const LinkPrimitive = asChild ? SlotPrimitive.Slot : "a";
380
381 return (
382 <LinkPrimitive
383 data-orientation={orientation}
384 data-slot="scroll-spy-link"
385 data-state={isActive ? "active" : "inactive"}
386 {...linkProps}
387 href={asChild ? undefined : `#${linkValue}`}
388 className={cn(
389 "rounded px-3 py-1.5 font-medium text-muted-foreground text-sm transition-colors hover:bg-accent hover:text-accent-foreground data-[state=active]:bg-accent data-[state=active]:text-foreground",
390 className,
391 )}
392 onClick={onLinkClick}
393 />
394 );
395}
396
397interface ScrollSpyViewportProps extends React.ComponentProps<"div"> {
398 asChild?: boolean;
399}
400
401function ScrollSpyViewport(props: ScrollSpyViewportProps) {
402 const { asChild, className, ...viewportProps } = props;
403
404 const { dir, orientation } = useScrollSpyContext(VIEWPORT_NAME);
405
406 const ViewportPrimitive = asChild ? SlotPrimitive.Slot : "div";
407
408 return (
409 <ViewportPrimitive
410 data-orientation={orientation}
411 data-slot="scroll-spy-viewport"
412 dir={dir}
413 {...viewportProps}
414 className={cn("flex flex-1 flex-col gap-8", className)}
415 />
416 );
417}
418
419interface ScrollSpySectionProps extends React.ComponentProps<"div"> {
420 value: string;
421 asChild?: boolean;
422}
423
424function ScrollSpySection(props: ScrollSpySectionProps) {
425 const { asChild, ref, value, ...sectionProps } = props;
426
427 const { orientation, onSectionRegister, onSectionUnregister } =
428 useScrollSpyContext(SECTION_NAME);
429 const sectionRef = React.useRef<SectionElement>(null);
430 const composedRef = useComposedRefs(ref, sectionRef);
431
432 useIsomorphicLayoutEffect(() => {
433 const element = sectionRef.current;
434 if (!element || !value) return;
435
436 onSectionRegister(value, element);
437
438 return () => {
439 onSectionUnregister(value);
440 };
441 }, [value, onSectionRegister, onSectionUnregister]);
442
443 const SectionPrimitive = asChild ? SlotPrimitive.Slot : "div";
444
445 return (
446 <SectionPrimitive
447 data-orientation={orientation}
448 data-slot="scroll-spy-section"
449 {...sectionProps}
450 id={value}
451 ref={composedRef}
452 />
453 );
454}
455
456export {
457 ScrollSpy,
458 ScrollSpyLink,
459 ScrollSpyNav,
460 type ScrollSpyProps,
461 ScrollSpySection,
462 ScrollSpyViewport,
463};
464