Line data Source code
1 : export type SelectionModifiers = Partial<
2 : Pick<MouseEvent, 'shiftKey' | 'ctrlKey' | 'metaKey' | 'altKey'>
3 : >
4 :
5 : export type ClickSelectionIntent =
6 : | 'replace'
7 : | 'add'
8 : | 'remove'
9 : | 'clear'
10 : | 'none'
11 :
12 : export type MarqueeSelectionIntent = 'replace' | 'add' | 'subtract'
13 :
14 : export interface ClickSelectionContext {
15 : hasItem: boolean
16 : isSelected: boolean
17 : modifiers: SelectionModifiers | undefined
18 : multiSelect: boolean
19 : selectOnly: boolean
20 : sticky: boolean
21 : }
22 :
23 1328 : function hasToggleModifier(modifiers: SelectionModifiers | undefined): boolean {
24 1328 : return Boolean(
25 : modifiers?.shiftKey || modifiers?.ctrlKey || modifiers?.metaKey
26 : )
27 : }
28 :
29 1328 : export function resolveClickSelection({
30 : hasItem,
31 : isSelected,
32 : modifiers,
33 : multiSelect,
34 : selectOnly,
35 : sticky
36 : }: ClickSelectionContext): ClickSelectionIntent {
37 1328 : const toggling = hasToggleModifier(modifiers)
38 1328 : if (!hasItem) {
39 234 : if (selectOnly) return 'none'
40 234 : return !toggling || multiSelect ? 'clear' : 'none'
41 : }
42 1328 : const modifying = toggling || multiSelect || selectOnly
43 1328 : if (!isSelected) return modifying ? 'add' : 'replace'
44 529 : if (sticky) return 'none'
45 1328 : return modifying ? 'remove' : 'replace'
46 : }
47 :
48 267 : export function resolveMarqueeSelection(
49 : modifiers: SelectionModifiers
50 : ): MarqueeSelectionIntent {
51 267 : if (modifiers.shiftKey) return 'add'
52 246 : if (modifiers.altKey) return 'subtract'
53 246 : return 'replace'
54 : }
55 :
56 267 : export function applyMarqueeSelection<T>(
57 : intent: MarqueeSelectionIntent,
58 : current: Iterable<T>,
59 : enclosed: ReadonlySet<T>
60 : ): Set<T> {
61 267 : switch (intent) {
62 : case 'add':
63 21 : return new Set([...current, ...enclosed])
64 : case 'subtract':
65 0 : return new Set([...current].filter((item) => !enclosed.has(item)))
66 : case 'replace':
67 246 : return new Set(enclosed)
68 : }
69 : }
|