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

export function useSelectionScope() {
	const { selectedIds, clearSelection } = useSelectionContext();
	const hasSelection = selectedIds.length > 0;
	const hasSelectionRef = useCommittedRef(hasSelection);
	const clearSelectionRef = useCommittedRef(clearSelection);
	const [entry] = useState<ScopeEntry>(() => ({
		hasSelection: () => hasSelectionRef.current,
		clear: () => {
			clearSelectionRef.current();
		},
	}));

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

		return activateScope({ entry });
	}, [entry, hasSelection]);
}