summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/timeline/use-initial-scroll-bottom.ts
blob: 50833f14128f5a8a7b73f5c7d98a64dbb40812a5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { type RefObject, useLayoutEffect, useRef } from "react";

interface UseInitialScrollBottomProps {
	tracksScrollRef: RefObject<HTMLDivElement | null>;
	trackLabelsScrollRef: RefObject<HTMLDivElement | null>;
	onAfterScroll?: () => void;
	/** Defers the scroll until there is at least one track to measure against. */
	isReady: boolean;
}

/**
 * Scrolls the timeline tracks viewport to the bottom once on mount.
 * useLayoutEffect runs synchronously after React commits the DOM but before
 * the browser paints, so the initial scroll position is never visible.
 */
export function useInitialScrollBottom({
	tracksScrollRef,
	trackLabelsScrollRef,
	onAfterScroll,
	isReady,
}: UseInitialScrollBottomProps): void {
	const hasScrolledRef = useRef(false);

	useLayoutEffect(() => {
		if (!isReady || hasScrolledRef.current) return;

		const viewport = tracksScrollRef.current;
		if (!viewport) return;

		const maxScrollTop = viewport.scrollHeight - viewport.clientHeight;
		if (maxScrollTop <= 0) return;

		viewport.scrollTop = maxScrollTop;

		if (trackLabelsScrollRef.current) {
			trackLabelsScrollRef.current.scrollTop = maxScrollTop;
		}

		onAfterScroll?.();
		hasScrolledRef.current = true;
	}, [isReady, tracksScrollRef, trackLabelsScrollRef, onAfterScroll]);
}