-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexm-tbody.html
542 lines (523 loc) · 17.8 KB
/
exm-tbody.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">
<!--
`exm-tbody` has some extra functionality that can be extended in the tbody table element which
will visualise the table as a material design data table. It also facilitates rows selection
and templating fucntionality.
### Template model
List item templates should bind to template models of the following structure:
```js
{
index: 0, // index in the visual item array
selected: false, // true if the current item is selected
item: {} // user data corresponding to items[index]
}
```
Alternatively, you can change the property name used as data index by changing the
`indexAs` property. The `as` property defines the name of the variable to add to the binding
scope for the array.
For example, given the following `data` array:
##### data.json
```js
[
{"name": "Bob", "email": "bob@test.com"},
{"name": "Tim", "email": "tim@test.com"},
{"name": "Mike", "email": "mike@test.com"}
]
```
The following code would render the table:
```html
<template is="dom-bind">
<iron-ajax url="data.json" last-response="{{items}}" auto></iron-ajax>
<table is="exm-datatable">
<tbody is="exm-tbody" items='[[items]]'>
<template>
<tr>
<td><paper-checkbox checked$="[[selected]]"></paper-checkbox></td>
<td>[[item.name]]</td>
<td>[[item.email]]</td>
</tr>
</template>
</tbody>
</table>
</template>
```
### Styling
The following custom properties and mixins are also available for styling:
Custom property | Description | Default
----------------|-------------|----------
`--exm-tbody-background-hover` | Background hover color for the table row | `#EEEEEE`
`--exm-tbody-row-bottom-border-color` | Color of table row bottom border | `#DBDBDB`
`--exm-tbody-td` | Mixin applied to all TD's' | `{}`
`--exm-tbody-td-not-expandable` | Mixin applied to TD that are not expandable | `{}`
`--exm-tbody-td-checkbox` | Mixin applied to the checkbox TD | `{}`
@element exm-tbody
@demo demo/index.html
-->
<dom-module id="exm-tbody">
<template>
<style>
:host ::content tr:not(.expandable):hover {
background: var(--exm-tbody-background-hover, #EEEEEE);
cursor: pointer;
}
:host ::content tr > td {
border: 0px;
border-bottom: 1px;
border-style: solid;
border-color: var(--exm-tbody-row-bottom-border-color, #dbdbdb);
box-sizing: border-box;
padding: 12px 24px;
@apply(--exm-tbody-td);
}
:host ::content tr:not(.expandable) > td {
height: 48px;
line-height: 36px;
vertical-align: middle;
white-space: nowrap;
text-overflow: ellipsis;
padding: 6px 6px 6px 24px;
overflow:hidden;
font-weight: normal;
@apply(--exm-tbody-td-not-expandable);
}
:host ::content tr:last-of-type td{
border-bottom:none;
}
:host[checkbox-used] ::content tr:not(.expandable) td:first-of-type,
:host[checkbox-used] ::content tr:not(.expandable) th:first-of-type{
padding-left: 24px;
padding-right: 0px;
width: 56px;
@apply(--exm-tbody-td-checkbox);
}
</style>
<content></content>
<!-- Array helper -->
<array-selector id="selector" items="{{items}}" selected="{{selectedItems}}" selected-item="{{selectedItem}}"></array-selector>
</template>
<script>
(function() {
var DEFAULT_PHYSICAL_COUNT = 10;
var SECRET_TABINDEX = -100;
Polymer({
is: 'exm-tbody',
extends: 'tbody',
properties: {
/**
* An array containing items determining how many instances of the template
* to stamp and that that each template instance should bind to.
*/
items: {
type: Array
},
/**
* The name of the variable to add to the binding scope for the array
* element associated with a given template instance.
*/
as: {
type: String,
value: 'item'
},
/**
* The name of the variable to add to the binding scope to indicate
* if the row is selected.
*/
selectedAs: {
type: String,
value: 'selected'
},
/**
* The name of the variable to add to the binding scope with the index
* for the row.
*/
indexAs: {
type: String,
value: 'index'
},
/**
* When true, tapping a row will select the item, placing its data model
* in the set of selected items retrievable via the selection property.
*
* Note that tapping focusable elements within the list item will not
* result in selection, since they are presumed to have their * own action.
*/
selectionEnabled: {
type: Boolean,
value: false
},
/**
* When `multiSelection` is false, this is the currently selected item, or `null`
* if no item is selected.
*/
selectedItem: {
type: Object,
notify: true
},
/**
* When `multiSelection` is true, this is an array that contains the selected items.
*/
selectedItems: {
type: Object,
notify: true
},
/**
* When `true`, multiple items may be selected at once (in this case,
* `selected` is an array of currently selected items). When `false`,
* only one item may be selected at a time.
*/
multiSelection: {
type: Boolean,
value: false
},
/**
* When `true`, extra style information is set on the first column for correct display.
*/
checkboxUsed: {
type: Boolean,
value: false
}
},
observers: [
'_itemsChanged(items.*)',
'_selectionEnabledChanged(selectionEnabled)',
'_multiSelectionChanged(multiSelection)'
],
behaviors: [
Polymer.Templatizer
],
attached: function() {
if (this._physicalCount === 0) {
this._debounceTemplate(this._render);
}
},
_multiSelectionChanged: function(multiSelection) {
this.clearSelection();
this.$.selector.multi = multiSelection;
},
/**
* Add an event listener to `tap` if `selectionEnabled` is true,
* it will remove the listener otherwise.
*/
_selectionEnabledChanged: function(selectionEnabled) {
var handler = selectionEnabled ? this.listen : this.unlisten;
handler.call(this, this, 'tap', '_selectionHandler');
},
/**
* Select an item from an event object.
*/
_selectionHandler: function(e) {
var model = this.modelForElement(e.target);
if (!model) {
return;
}
var modelTabIndex, activeElTabIndex;
var target = Polymer.dom(e).path[0];
var activeEl = Polymer.dom(this.domHost ? this.domHost.root : document).activeElement;
var physicalItem = this._physicalItems[model[this.indexAs]];
// Safari does not focus certain form controls via mouse
// https://bugs.webkit.org/show_bug.cgi?id=118043
if (target.localName === 'input' ||
target.localName === 'button' ||
target.localName === 'select') {
return;
}
// Set a temporary tabindex
modelTabIndex = model.tabIndex;
model.tabIndex = SECRET_TABINDEX;
activeElTabIndex = activeEl ? activeEl.tabIndex : -1;
model.tabIndex = modelTabIndex;
// Only select the item if the tap wasn't on a focusable child
// or the element bound to `tabIndex`
if (activeEl && physicalItem !== activeEl && physicalItem.contains(activeEl) && activeElTabIndex !== SECRET_TABINDEX) {
return;
}
this.toggleSelectionForItem(model[this.as]);
},
/**
* Implements extension point from Templatizer
* Called as a side effect of a template instance path change, responsible
* for notifying items.<key-for-instance>.<path> change up to host.
*/
_forwardInstancePath: function(inst, path, value) {
if (path.indexOf(this.as + '.') === 0) {
this.notifyPath('items.' + inst.__key__ + '.' +
path.slice(this.as.length + 1), value);
}
},
/**
* Implements extension point from Templatizer mixin
* Called as side-effect of a host property change, responsible for
* notifying parent path change on each row.
*/
_forwardParentProp: function(prop, value) {
if (this._physicalItems) {
this._physicalItems.forEach(function(item) {
item._templateInstance[prop] = value;
}, this);
}
},
/**
* Implements extension point from Templatizer
* Called as side-effect of a host path change, responsible for
* notifying parent.<path> path change on each row.
*/
_forwardParentPath: function(path, value) {
if (this._physicalItems) {
this._physicalItems.forEach(function(item) {
item._templateInstance.notifyPath(path, value, true);
}, this);
}
},
/**
* Creates a pool of DOM elements and attaches them to the local dom.
*
* @param {number} size Size of the pool
*/
_createPool: function(size) {
var physicalItems = new Array(size);
this._ensureTemplatized();
for (var i = 0; i < size; i++) {
var inst = this.stamp(null);
// First element child is item; Safari doesn't support children[0]
// on a doc fragment.
physicalItems[i] = inst.root.querySelector('*');
Polymer.dom(this.root).appendChild(inst.root);
}
return physicalItems;
},
/**
* Increases the pool size.
*/
_increasePool: function(poolSize) {
var ts = window.performance.now();
// Concat arrays in place.
[].push.apply(this._physicalItems, this._createPool(poolSize));
this._physicalCount = this._physicalItems.length;
this._update();
this._templateCost = (window.performance.now() - ts);
},
/**
* Templetizes the user template.
*/
_ensureTemplatized: function() {
// Check if already templatized
if (!this.ctor) {
// Template instance props that should be excluded from forwarding
var props = {};
props.__key__ = true;
props[this.as] = true;
props[this.indexAs] = true;
props[this.selectedAs] = true;
props.tabIndex = true;
this._instanceProps = props;
this._userTemplate = Polymer.dom(this).querySelector('template#tbody');
if (this._userTemplate) {
this.templatize(this._userTemplate);
} else {
console.warn('exm-tbody requires a template to be provided in light-dom');
}
}
},
/**
* Called when the items have changed. That is, ressignments
* to `items`, splices or updates to a single item.
*/
_itemsChanged: function(change) {
if (change.path === 'items') {
this.items = this.items || [];
this._collection = this.items ? Polymer.Collection.get(this.items) : null;
this._physicalCount = this._physicalCount || 0;
this._physicalItems = this._physicalItems || [];
this._debounceTemplate(this._render);
} else if (change.path === 'items.splices') {
change.value.indexSplices.forEach(function(splice) {
// deselect removed items
splice.removed.forEach(this._removeItem, this);
}, this);
this._debounceTemplate(this._render);
} else {
this._forwardItemPath(change.path.split('.').slice(1).join('.'), change.value);
}
},
_removeItem: function(item) {
this.$.selector.deselect(item);
},
/**
* Renders the a new list.
*/
_render: function() {
if (this.isAttached) {
if (this._physicalCount === 0) {
this._increasePool(this.items.length);
} else {
if(this.items.length > this._physicalCount) {
this._increasePool(this.items.length - this._physicalCount);
} else {
this._update();
}
}
}
},
/**
* Update the list of items.
* @param {!Array<number>=} itemSet
*/
_update: function(itemSet) {
if (itemSet && itemSet.length === 0) {
return;
}
this._assignModels(itemSet);
},
/**
* Assigns the data models to a given set of items.
* @param {!Array<number>=} itemSet
*/
_assignModels: function(itemSet) {
var count = 0;
this._physicalItems.forEach(function(el) {
var inst = el._templateInstance;
var item = this.items[count];
if (item != null) {
inst[this.as] = item;
inst.__key__ = this._collection.getKey(item);
inst[this.selectedAs] = /** @type {!ArraySelectorElement} */ (this.$.selector).isSelected(item);
inst[this.indexAs] = count;
inst.tabIndex = -1;
el.removeAttribute('hidden');
} else {
inst.__key__ = null;
el.setAttribute('hidden', '');
}
count++;
}.bind(this));
},
_getModelFromItem: function(item) {
var key = this._collection.getKey(item);
if (key != null) {
return this._physicalItems[key.substring(1)]._templateInstance;
}
return null;
},
_forwardItemPath: function(path, value) {
var dot = path.indexOf('.');
var key = path.substring(0, dot < 0 ? path.length : dot);
var idx = key.substring(1);
var el = this._physicalItems[idx];
if (!el || el._templateInstance.__key__ !== key) {
return;
}
if (dot >= 0) {
path = this.as + '.' + path.substring(dot+1);
el._templateInstance.notifyPath(path, value, true);
} else {
// Update selection if needed
var currentItem = el._templateInstance[this.as];
if (Array.isArray(this.selectedItems)) {
for (var i = 0; i < this.selectedItems.length; i++) {
if (this.selectedItems[i] === currentItem) {
this.set('selectedItems.' + i, value);
break;
}
}
} else if (this.selectedItem === currentItem) {
this.set('selectedItem', value);
}
el._templateInstance[this.as] = value;
}
},
/**
* Select the list item at the given index.
*
* @method selectItem
* @param {(Object|number)} item The item object or its index
*/
selectItem: function(item) {
item = this._getNormalizedItem(item);
var model = this._getModelFromItem(item);
if (!this.multiSelection && this.selectedItem) {
this.deselectItem(this.selectedItem);
}
if (model) {
model[this.selectedAs] = true;
}
this.$.selector.select(item);
},
/**
* Deselects the given item list if it is already selected.
*
* @method deselect
* @param {(Object|number)} item The item object or its index
*/
deselectItem: function(item) {
item = this._getNormalizedItem(item);
var model = this._getModelFromItem(item);
if (model) {
model[this.selectedAs] = false;
}
this.$.selector.deselect(item);
},
/**
* Select or deselect a given item depending on whether the item
* has already been selected.
*
* @method toggleSelectionForItem
* @param {(Object|number)} item The item object or its index
*/
toggleSelectionForItem: function(item) {
item = this._getNormalizedItem(item);
if (/** @type {!ArraySelectorElement} */ (this.$.selector).isSelected(item)) {
this.deselectItem(item);
} else {
this.selectItem(item);
}
},
/**
* Gets a valid item instance from its index or the object value.
*
* @param {(Object|number)} item The item object or its index
*/
_getNormalizedItem: function(item) {
if (this._collection.getKey(item) === undefined) {
if (typeof item === 'number') {
item = this.items[item];
if (!item) {
throw new RangeError('<item> not found');
}
return item;
}
throw new TypeError('<item> should be a valid item');
}
return item;
},
/**
* Clears the current selection state of the list.
*
* @method clearSelection
*/
clearSelection: function() {
function unselect(item) {
var model = this._getModelFromItem(item);
if (model) {
model[this.selectedAs] = false;
}
}
if (Array.isArray(this.selectedItems)) {
this.selectedItems.forEach(unselect, this);
} else if (this.selectedItem) {
unselect.call(this, this.selectedItem);
}
/** @type {!ArraySelectorElement} */ (this.$.selector).clearSelection();
},
});
})();
</script>
</dom-module>