-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectable-group-behavior.html
More file actions
115 lines (89 loc) · 2.26 KB
/
selectable-group-behavior.html
File metadata and controls
115 lines (89 loc) · 2.26 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<link rel="import" href="../polymer/polymer-element.html">
<script>
window.SelectableGroupBehavior = subclass => class extends Polymer.Element {
static get properties() {
return {
/**
* The list of selectable-item
*/
items: {
type: Array,
readOnly: true,
notify: true,
value: function() {
return [];
}
},
selection: {
type: Array,
notify: true,
value: _ => []
}
};
}
static get observers() {
return [
'_selectionChanged(selection.*)'
];
}
get getSelection() {
return this.items.filter(item => item.selected);
}
constructor() {
super();
this._observer = null;
this._onItemSelectedChange = this._onItemSelectedChange.bind(this);
this._onKeydown = this._onKeydown.bind(this);
}
connectedCallback() {
super.connectedCallback();
requestAnimationFrame(_ => {
this._updateItems();
this._observer = this._observeItems(this);
this._toggleListeners({enable: true});
});
}
disconnectedCallback() {
super.disconnectedCallback();
this._toggleListeners({enable: false});
this._observer.disconnect();
this._observer = null;
}
_onItemSelectedChange() {
this._updateSelection();
}
_updateSelection() {
this.selection = this.items.filter(item => item.selected);
}
_selectionChanged() {
const activeSelection = !!this.selection.length;
this.items.forEach(item => {
item.selectOnDown = activeSelection;
});
}
_onKeydown(event) {
const escKey = 27;
if (event.keyCode === escKey) {
this.selection.forEach(item => {
item.selected = false;
});
}
}
_toggleListeners({enable}) {
const m = enable ? 'addEventListener' : 'removeEventListener';
this[m]('item-selected-change', this._onItemSelectedChange);
document.body[m]('keydown', this._onKeydown);
}
_observeItems(node) {
const observer = new MutationObserver(mutations => {
this._updateItems();
})
observer.observe(this, {subtree: true, childList: true});
return observer;
}
_updateItems() {
const nodes = Array.from(this.querySelectorAll('selectable-item'));
this._setItems(nodes);
}
}
</script>