forked from Hackception/hc-tree-view
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhc-nested-list-behavior.html
277 lines (259 loc) · 9.37 KB
/
hc-nested-list-behavior.html
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
<link rel="import" href="../polymer/polymer.html">
<script>
/* global hc */
// Ensure our namespace exists
window.hc = window.hc || {};
/**
* Use `hc.NestedListBehavior` to implement a flat data structure of nested items into a list with
* children getting added/remove to emulate open/close functionality.
*
* @polymerBehavior hc.NestedListBehavior
*/
hc.NestedListBehavior = {
properties: {
/* Notifies if the element is in the process of loading, mainly used for lazy-loading. */
isLoading: {
type: Boolean,
value: false,
notify: true
},
/* The property name for the id on each item. */
itemIdName: {
type: String,
value: 'id'
},
/* The property name for the parentId on each item. */
itemParentIdName: {
type: String,
value: 'parentId'
},
/**
* The flat array of items to build the nested list structure from, requires an id and
* parentId as defined by the itemIdName and itemParentIdName properties.
*
* @type {Object[]}
*/
items: Array,
/**
* A nested representation of items, maintains list state; gets rebuilt when items changes,
* when lazy-loading data add a new key-value pair to this object containing the data. The
* key value is used for looking up parentId to fetch the list of child items. All item data
* is taken from the items array.
*/
parts: {
type: Object,
notify: true
},
/**
* The currently visible subset of items from the items property
*
* @protected
*/
_items: {
type: Array,
readOnly: true,
computed: '_computeItems(parts)'
}
},
observers: ['_computeParts(items, itemIdName, itemParentIdName)'],
listeners: {
'item-open-changed': 'itemOpenChanged'
},
/**
* Called when an item's open status is changed. Update parts with children if lazy-loading then call update
* with the updated parts object once complete, update will always need to be called even if no changes were
* made to the parts object. It's recommended to optimize your loader by checking to see if items already exist
* before attempting to fetch them.
*
* @param {Object} item
* @param {Object} parts
* @param {Function} update
*/
fetchChildren(item, parts, update) {
update(parts);
},
/**
* Takes an item and looks up it's parent then returns it.
*
* @param {Object} item
* @param {Object} [parts = this.parts]
* @param {String} [idName = this.itemIdName]
* @return {Object|null}
*/
getParent(item, parts = this.parts, idName = this.itemIdName) {
// Ensure it has a parentId
const parentId = this._getParentId(item);
if (parentId === 'root') return null;
// Fetch the parent by the id
const keys = Object.keys(parts);
let parent;
for (let i = 0; i < keys.length; i++) {
parent = (parts[keys[i]] || []).find((p) => {
return p[idName] === parentId;
});
if (parent) break;
}
if (!parent) return null;
// Fetch the item from parts if it exists (maintain state)
const parents = parts[this._getParentId(parent)];
return parents ? parents.find((i) => i[idName] === parentId) : null;
},
/**
* Handles changes to the open status of an item.
*
* @listens hc-nested-list-behavior#item-open-changed
* @param {CustomEvent} [event]
* @param {Object} detail
* @param {String} [idName=this.itemIdName]
* @param {Object} [parts = this.parts]
*/
itemOpenChanged(event, detail, idName = this.itemIdName, parts = this.parts) {
// Block interactions while loading items
if (this.isLoading) return;
this.isLoading = true;
const items = parts[this._getParentId(detail.item)];
const id = detail.item[idName];
let item;
for (let i = 0; i < items.length; i++) {
if (items[i][idName] === id) {
// Toggle our item open
items[i].open = detail.open;
// If the item was toggled closed, we don't care about the rest, break out.
if (!detail.open) break;
// If it was opened, store it for use later.
else item = items[i];
} else items[i].open = false; // If it's not the item we want, ensure it's closed
}
(new Promise((res) => {
if (item) {
// fetch children and update when done, when there's an item
const ids = Object.keys(parts);
this.fetchChildren(item, parts, (parts) => {
const newIds = Object.keys(parts).filter((id) => ids.indexOf(id) < 0);
for (let i = 0; i < newIds.length; i++) {
const id = newIds[i];
for (let j = 0; j < parts[id].length; j++) {
parts[id][j] = this.__setDefaultPart(parts[id][j], parts, id, item.state === 'on' ? 'on' : 'off');
}
}
res(parts);
});
} else res(parts);
})).then(() => {
this.set('parts', Object.assign({}, parts));
this.isLoading = false;
});
},
/**
* Takes a parts object and optionally a start point for an array then iterates over the
* object starting at the root if there isn't a location already set and finds all open nodes
* recursively calling itself to ensure order is preserved once flattened.
*
* @protected
* @param {Object} parts
* @param {Object[]} [items=parts.root]
* @param {String} [idName=this.itemIdName]
* @returns {Object[]}
*/
_computeItems(parts, items = parts.root, idName = this.itemIdName) {
// Can't calculate items without parts or the name of the id property.
if (!parts || !items) return [];
const newItems = [];
// Push all items into the new array, and if there is a child item then push all of the children.
items.forEach((item) => {
// Some properties need to be re-calculated every time we update the list to support lazy-loading
item.hasChildren = item.hasChildren || Boolean(parts[item[this.itemIdName]]);
item.depth = !(item.depth >= 0) ? this._getItemDepth(item, parts) : item.depth;
newItems.push(item);
if (item.open)
newItems.push(...this._computeItems(parts, parts[item[idName]] || []));
});
return newItems;
},
/**
* Takes the flat items structure and builds out a map of parent-child elements which gets
* stored and used for optimized rendering later.
*
* @protected
* @param {Object[]} items
* @param {String} itemIdName
* @param {String} itemParentIdName
*/
_computeParts(items, itemIdName, itemParentIdName) {
if (!itemIdName || !itemParentIdName || !items) return;
this.debounce('computeParts', () => {
const parts = {};
this.items.forEach((item) => {
// Fetch the parentId or set it to 'root' if there isn't one
const parentId = this._getParentId(item);
if (!parts[parentId]) parts[parentId] = [];
// Add the item, but first ensure we have the minimum requirements for the object
parts[parentId].push(this.__setDefaultPart(item, parts, parentId));
});
this.set('parts', parts);
});
},
/**
* Traces up the nested structure returning a depth for the items, if the item is a root item the depth
* will be 0, if it can't be traced up to a root then it returns undefined.
*
* @protected
* @param {Object} item
* @param {Object} parts
* @param {String} [parentId = this._getParentId(item)]
* @returns {Number|undefined}
*/
_getItemDepth(item, parts, parentId = this._getParentId(item)) {
const parent = this.getParent(item, parts);
let depth;
// You're a root node
if (!parent && parentId === 'root')
depth = 0;
// You've got a parent, as long as it has a depth you can increment it to get yours
else if (parent) {
const parentDepth = typeof parent.depth === 'number' ?
parent.depth :
this._getItemDepth(parent, parts);
depth = typeof parentDepth === 'number' ? parentDepth + 1 : undefined;
}
return depth;
},
/**
* Used to fetch the parentId if it's available or default back to 'root'.
*
* @protected
* @param {Object} item
* @param {String} [parentIdName=this.itemParentIdName]
* @returns {String|Number}
*/
_getParentId(item, parentIdName = this.itemParentIdName) {
return (item[parentIdName] || item[parentIdName] === 0) ?
item[parentIdName] :
'root';
},
/**
* Ensures a part has the require default values.
*
* @private
* @param {Object} item
* @param {Object} parts
* @param {String} parentId
* @param {String} [parentState="off"]
* @return {Object}
*/
__setDefaultPart(item, parts, parentId, parentState = 'off') {
return Object.assign({
open: false,
state: parentState,
depth: this._getItemDepth(item, parts, parentId)
}, item);
}
};
/**
* Event for changed the open flag on a hc-nested-list item
*
* @event hc-nested-list-behavior#item-open-changed
* @type {Object}
* @property {Object} item - the item data
*/
</script>