summaryrefslogtreecommitdiff
path: root/apps/web/src/lib/selection/hooks/use-selection-scope.ts
blob: 7ed6381553c33fef47207e76c21921ec39f5dca3 (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
import { useEffect, useRef } from "react";
import { useSelectionContext } from "@/lib/selection/context";
import { activateScope, type ScopeEntry } from "@/lib/selection/scope";

export function useSelectionScope() {
	const { selectedIds, clearSelection } = useSelectionContext();
	const hasSelectionRef = useRef(selectedIds.length > 0);
	const clearSelectionRef = useRef(clearSelection);
	const hasSelection = selectedIds.length > 0;

	hasSelectionRef.current = hasSelection;
	clearSelectionRef.current = clearSelection;

	const entryRef = useRef<ScopeEntry>({
		hasSelection: () => hasSelectionRef.current,
		clear: () => {
			clearSelectionRef.current();
		},
	});

	useEffect(() => {
		if (!hasSelection) {
			return;
		}

		return activateScope({ entry: entryRef.current });
	}, [hasSelection]);
}