-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (83 loc) · 2.32 KB
/
index.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// NOTE(ibash)
// For keyboards:
// 1. up / down is treated like a click on the elment in that direction
// 2. shift+up / shift+down is treated like shift click in that direction
export default class Multiselect {
constructor() {
this.anchor = 0
this.focus = 0
this.selection = new Set()
}
reset() {
this.anchor = 0
this.focus = 0
this.selection = new Set()
}
isSelected(index) {
return this.selection.has(index)
}
click(index) {
// anchor and focus collapse to the element
this.anchor = index
this.focus = index
// only the clicked element is selected
this.selection.clear()
this.selection.add(index)
}
// NOTE(ibash) in finder command takes precedence over shift. That is if you
// command+shift+click an element, it acts like a command click.
commandClick(index) {
if (this.selection.has(index)) {
// anchor/focus move to the next selected element with a larger index, if
// there isn't one then it moves to the next selected with a smaller
// index. Finally, if that doesn't exist they reset to 0.
let isFound
// search forwards
const values = Array.from(this.selection.values())
const max = Math.max(...values)
for (var i = index + 1; i < max; i++) {
if (this.selection.has(i)) {
this.anchor = i
this.focus = i
isFound = true
break
}
}
// search backwards
if (!isFound) {
for (i = index - 1; i > -1; i--) {
if (this.selection.has(i)) {
this.anchor = i
this.focus = i
isFound = true
break
}
}
}
// nothing selected
if (!isFound) {
this.anchor = 0
this.focus = 0
}
this.selection.delete(index)
} else {
this.anchor = index
this.focus = index
this.selection.add(index)
}
}
shiftClick(index) {
let start = Math.min(this.anchor, this.focus)
let end = Math.max(this.anchor, this.focus)
// remove between anchor and focus
for (var i = start; i <= end; i++) {
this.selection.delete(i)
}
this.focus = index
start = Math.min(this.anchor, this.focus)
end = Math.max(this.anchor, this.focus)
for (i = start; i <= end; i++) {
this.selection.add(i)
}
}
}