This repository has been archived by the owner on Aug 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
96 lines (82 loc) · 2.01 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
var ObservGrid = require('observ-grid')
var watchGridChanges = require('observ-grid/watch-changes')
var computed = require('observ/computed')
module.exports = function(shape){
var self = ObservGrid([], shape)
self.selectedIndexes = computed([self], function(selectionGrid){
return selectionGrid.data.reduce(function(result, value, i){
if (value){
result.push(i)
}
return result
}, [])
})
var release = null
var doneCallback = null
var down = []
self.start = function(input, done){
self.stop()
release = watchGridChanges(input, handleInput)
doneCallback = done
}
self.clear = function(){
self.data.set([])
down.length = 0
}
self.stop = function(){
if (release){
release()
release = null
if (typeof doneCallback == 'function') {
doneCallback()
done = null
}
}
}
return self
function handleInput(changes){
changes.forEach(function(change){
var key = change.slice(0,2).join('/')
if (change[2]){
if (down.length){
var startCoords = down[0].split('/').map(pint)
selectRange(startCoords, change)
} else {
toggleSelected(change[0], change[1])
}
down.push(key)
} else {
remove(down, key)
}
})
}
function selectRange(start, end){
var rowStart = Math.min(start[0], end[0])
var rowEnd = Math.max(start[0], end[0])
var colStart = Math.min(start[1], end[1])
var colEnd = Math.max(start[1], end[1])
self.transaction(function(raw){
for (var row=rowStart;row<=rowEnd;row++){
for (var col=colStart;col<=colEnd;col++){
raw.set(row, col, true)
}
}
})
}
function toggleSelected(row, col){
if (self.get(row, col)){
self.set(row, col, null)
} else {
self.set(row, col, true)
}
}
}
function pint(val){
return parseInt(val)
}
function remove(array, value){
var index = array.indexOf(value)
if (~index){
array.splice(index, 1)
}
}