-
Notifications
You must be signed in to change notification settings - Fork 88
/
vaadin-combo-box-dropdown-wrapper.html
551 lines (468 loc) · 17.8 KB
/
vaadin-combo-box-dropdown-wrapper.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
543
544
545
546
547
548
549
550
551
<!--
@license
Copyright (c) 2017 Vaadin Ltd.
This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
-->
<link rel="import" href="../../polymer/polymer-element.html">
<link rel="import" href="../../iron-list/iron-list.html">
<link rel="import" href="vaadin-combo-box-item.html">
<link rel="import" href="vaadin-combo-box-dropdown.html">
<link rel="import" href="vaadin-combo-box-placeholder.html">
<dom-module id="vaadin-combo-box-dropdown-wrapper">
<template>
<vaadin-combo-box-dropdown id="dropdown"
hidden="[[_hidden(_items.*, loading)]]"
position-target="[[positionTarget]]"
on-template-changed="_templateChanged"
on-position-changed="_setOverlayHeight"
disable-upgrade
theme="[[theme]]">
<template>
<style>
#scroller {
overflow: auto;
/* Fixes item background from getting on top of scrollbars on Safari */
transform: translate3d(0, 0, 0);
/* Enable momentum scrolling on iOS (iron-list v1.2+ no longer does it for us) */
-webkit-overflow-scrolling: touch;
/* Fixes scrollbar disappearing when 'Show scroll bars: Always' enabled in Safari */
box-shadow: 0 0 0 white;
}
</style>
<div id="scroller" on-click="_stopPropagation">
<iron-list id="selector" role="listbox" items="[[_getItems(opened, _items)]]" scroll-target="[[_scroller]]">
<template>
<vaadin-combo-box-item
on-click="_onItemClick"
index="[[__requestItemByIndex(item, index, _resetScrolling)]]"
item="[[item]]"
label="[[getItemLabel(item, _itemLabelPath)]]"
selected="[[_isItemSelected(item, _selectedItem, _itemIdPath)]]"
renderer="[[renderer]]"
role$="[[_getAriaRole(index)]]"
aria-selected$="[[_getAriaSelected(_focusedIndex,index)]]"
focused="[[_isItemFocused(_focusedIndex,index)]]"
tabindex="-1"
theme$="[[theme]]">
</vaadin-combo-box-item>
</template>
</iron-list>
</div>
</template>
</vaadin-combo-box-dropdown>
</template>
</dom-module>
<script>
(function() {
'use strict';
const TOUCH_DEVICE = (() => {
try {
document.createEvent('TouchEvent');
return true;
} catch (e) {
return false;
}
})();
/**
* Element for internal use only.
*
* @memberof Vaadin
* @private
*/
class ComboBoxDropdownWrapperElement extends (class extends Polymer.Element {}) {
static get is() {
return 'vaadin-combo-box-dropdown-wrapper';
}
static get properties() {
return {
/**
* True if the device supports touch events.
*/
touchDevice: {
type: Boolean,
value: TOUCH_DEVICE
},
opened: Boolean,
/**
* The element to position/align the dropdown by.
*/
positionTarget: {
type: Object
},
/**
* Custom function for rendering the content of the `<vaadin-combo-box-item>` propagated from the combo box element.
*/
renderer: Function,
/**
* `true` when new items are being loaded.
*/
loading: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: '_setOverlayHeight'
},
/**
* Used to propagate the `theme` attribute from the host element.
*/
theme: String,
/**
* Used to recognize if the filter changed, so to skip the
* scrolling restore. If true, then scroll to 0 position. Restore
* the previous position otherwise.
*/
filterChanged: {
type: Boolean,
value: false
},
/**
* Used to recognize scroller reset after new items have been set
* to iron-list and to ignore unwanted pages load. If 'true', then
* skip loading of the pages until it becomes 'false'.
*/
_resetScrolling: {
type: Boolean,
value: false
},
_selectedItem: {
type: Object
},
_items: {
type: Object
},
_focusedIndex: {
type: Number,
value: -1,
observer: '_focusedIndexChanged'
},
_focusedItem: {
type: String,
computed: '_getFocusedItem(_focusedIndex)'
},
_itemLabelPath: {
type: String,
value: 'label'
},
_itemValuePath: {
type: String,
value: 'value'
},
_selector: Object,
_itemIdPath: String,
/**
* Stores the scroller position before updating the 'items', in
* order to restore it immediately after 'items' have been updated
*/
_oldScrollerPosition: {
type: Number,
value: 0
}
};
}
static get observers() {
return ['_selectorChanged(_selector)', '_loadingChanged(loading)',
'_openedChanged(opened, _items, loading)',
'_restoreScrollerPosition(_items)'];
}
_fireTouchAction(sourceEvent) {
this.dispatchEvent(new CustomEvent('vaadin-overlay-touch-action', {
detail: {sourceEvent: sourceEvent}
}));
}
_getItems(opened, items) {
if (opened) {
if (this._isNotEmpty(items) && this._selector && !this.filterChanged) {
// iron-list triggers the scroller's reset after items update, and
// this is not appropriate for undefined size lazy loading.
// see https://github.com/vaadin/vaadin-combo-box-flow/issues/386
// We store iron-list scrolling position in order to restore
// it later on after the items have been updated.
const currentScrollerPosition = this._selector.firstVisibleIndex;
if (currentScrollerPosition !== 0) {
this._oldScrollerPosition = currentScrollerPosition;
this._resetScrolling = true;
}
}
// Let the position to be restored in the future calls unless it's not
// caused by filtering
this.filterChanged = false;
return items;
}
return [];
}
_restoreScrollerPosition(items) {
if (this._isNotEmpty(items) && this._selector && this._oldScrollerPosition !== 0) {
// new items size might be less than old scrolling position
this._scrollIntoView(Math.min(items.length - 1, this._oldScrollerPosition));
this._resetScrolling = false;
// reset position to 0 again in order to properly handle the filter
// cases (scroll to 0 after typing the filter)
this._oldScrollerPosition = 0;
}
}
_isNotEmpty(items) {
return !this._isEmpty(items);
}
_isEmpty(items) {
return !items || !items.length;
}
_openedChanged(opened, items, loading) {
if (this.$.dropdown.hasAttribute('disable-upgrade')) {
if (!opened) {
return;
} else {
this._initDropdown();
}
}
if (this._isEmpty(items)) {
this.$.dropdown.__emptyItems = true;
}
this.$.dropdown.opened = !!(opened && (loading || this._isNotEmpty(items)));
this.$.dropdown.__emptyItems = false;
}
_initDropdown() {
this.$.dropdown.removeAttribute('disable-upgrade');
this._templateChanged();
this._loadingChanged(this.loading);
this.$.dropdown.$.overlay.addEventListener('touchend', e => this._fireTouchAction(e));
this.$.dropdown.$.overlay.addEventListener('touchmove', e => this._fireTouchAction(e));
// Prevent blurring the input when clicking inside the overlay.
this.$.dropdown.$.overlay.addEventListener('mousedown', e => e.preventDefault());
// IE11: when scrolling with mouse, the focus goes to the scroller.
// This causes the overlay closing due to defocusing the input field.
// Prevent focusing the scroller by setting `unselectable="on"`.
if (/Trident/.test(navigator.userAgent)) {
this._scroller.setAttribute('unselectable', 'on');
}
}
_templateChanged(e) {
if (this.$.dropdown.hasAttribute('disable-upgrade')) {
return;
}
this._selector = this.$.dropdown.$.overlay.content.querySelector('#selector');
this._scroller = this.$.dropdown.$.overlay.content.querySelector('#scroller');
}
_loadingChanged(loading) {
if (this.$.dropdown.hasAttribute('disable-upgrade')) {
return;
}
if (loading) {
this.$.dropdown.$.overlay.setAttribute('loading', '');
} else {
this.$.dropdown.$.overlay.removeAttribute('loading');
}
}
_selectorChanged(selector) {
this._patchWheelOverScrolling();
}
_setOverlayHeight() {
if (!this.opened || !this.positionTarget || !this._selector) {
return;
}
const targetRect = this.positionTarget.getBoundingClientRect();
this._scroller.style.maxHeight = (window.ShadyCSS ?
window.ShadyCSS.getComputedStyleValue(this, '--vaadin-combo-box-overlay-max-height') :
getComputedStyle(this).getPropertyValue('--vaadin-combo-box-overlay-max-height')) || '65vh';
const maxHeight = this._maxOverlayHeight(targetRect);
// overlay max height is restrained by the #scroller max height which is set to 65vh in CSS.
this.$.dropdown.$.overlay.style.maxHeight = maxHeight;
// we need to set height for iron-list to make its `firstVisibleIndex` work correctly.
this._selector.style.maxHeight = maxHeight;
this.updateViewportBoundaries();
}
_maxOverlayHeight(targetRect) {
const margin = 8;
const minHeight = 116; // Height of two items in combo-box
if (this.$.dropdown.alignedAbove) {
return Math.max(targetRect.top - margin + Math.min(document.body.scrollTop, 0), minHeight) + 'px';
} else {
return Math.max(document.documentElement.clientHeight - targetRect.bottom - margin, minHeight) + 'px';
}
}
_getFocusedItem(focusedIndex) {
if (focusedIndex >= 0) {
return this._items[focusedIndex];
}
}
_isItemSelected(item, selectedItem, itemIdPath) {
if (item instanceof Vaadin.ComboBoxPlaceholder) {
return false;
} else if (itemIdPath && item !== undefined && selectedItem !== undefined) {
return this.get(itemIdPath, item) === this.get(itemIdPath, selectedItem);
} else {
return item === selectedItem;
}
}
_onItemClick(e) {
if (e.detail && e.detail.sourceEvent && e.detail.sourceEvent.stopPropagation) {
this._stopPropagation(e.detail.sourceEvent);
}
this.dispatchEvent(new CustomEvent('selection-changed', {detail: {item: e.model.item}}));
}
/**
* Gets the index of the item with the provided label.
* @return {number}
*/
indexOfLabel(label) {
if (this._items && label) {
for (let i = 0; i < this._items.length; i++) {
if (this.getItemLabel(this._items[i]).toString().toLowerCase() ===
label.toString().toLowerCase()) {
return i;
}
}
}
return -1;
}
/**
* If dataProvider is used, dispatch a request for the item’s index if
* the item is a placeholder object.
*
* @return {number}
*/
__requestItemByIndex(item, index, resetScrolling) {
if ((item instanceof Vaadin.ComboBoxPlaceholder) && index !==
undefined && !resetScrolling) {
this.dispatchEvent(new CustomEvent('index-requested', {detail:
{index: index, currentScrollerPos: this._oldScrollerPosition}}));
}
return index;
}
/**
* Gets the label string for the item based on the `_itemLabelPath`.
* @return {string}
*/
getItemLabel(item, itemLabelPath) {
itemLabelPath = itemLabelPath || this._itemLabelPath;
let label = item && itemLabelPath ? this.get(itemLabelPath, item) : undefined;
if (label === undefined || label === null) {
label = item ? item.toString() : '';
}
return label;
}
_isItemFocused(focusedIndex, itemIndex) {
return focusedIndex == itemIndex;
}
_getAriaSelected(focusedIndex, itemIndex) {
return this._isItemFocused(focusedIndex, itemIndex).toString();
}
_getAriaRole(itemIndex) {
return itemIndex !== undefined ? 'option' : false;
}
_focusedIndexChanged(index) {
if (index >= 0) {
this._scrollIntoView(index);
}
}
_scrollIntoView(index) {
if (!(this.opened && index >= 0)) {
return;
}
const visibleItemsCount = this._visibleItemsCount();
if (visibleItemsCount === undefined) {
// Scroller is not visible. Moving is unnecessary.
return;
}
let targetIndex = index;
if (index > this._selector.lastVisibleIndex - 1) {
// Index is below the bottom, scrolling down. Make the item appear at the bottom.
// First scroll to target (will be at the top of the scroller) to make sure it's rendered.
this._selector.scrollToIndex(index);
// Then calculate the index for the following scroll (to get the target to bottom of the scroller).
targetIndex = index - visibleItemsCount + 1;
} else if (index > this._selector.firstVisibleIndex) {
// The item is already visible, scrolling is unnecessary per se. But we need to trigger iron-list to set
// the correct scrollTop on the scrollTarget. Scrolling to firstVisibleIndex.
targetIndex = this._selector.firstVisibleIndex;
}
this._selector.scrollToIndex(Math.max(0, targetIndex));
// Sometimes the item is partly below the bottom edge, detect and adjust.
const pidx = this._selector._getPhysicalIndex(index),
physicalItem = this._selector._physicalItems[pidx];
if (!physicalItem) {
return;
}
const physicalItemRect = physicalItem.getBoundingClientRect(),
scrollerRect = this._scroller.getBoundingClientRect(),
scrollTopAdjust = physicalItemRect.bottom - scrollerRect.bottom + this._viewportTotalPaddingBottom;
if (scrollTopAdjust > 0) {
this._scroller.scrollTop += scrollTopAdjust;
}
}
ensureItemsRendered() {
this._selector._render();
}
adjustScrollPosition() {
if (this.opened && this._items) {
this._scrollIntoView(this._focusedIndex);
}
}
/**
* We want to prevent the kinetic scrolling energy from being transferred from the overlay contents over to the parent.
* Further improvement ideas: after the contents have been scrolled to the top or bottom and scrolling has stopped, it could allow
* scrolling the parent similarly to touch scrolling.
*/
_patchWheelOverScrolling() {
const selector = this._selector;
selector.addEventListener('wheel', e => {
const scroller = selector._scroller || selector.scrollTarget;
const scrolledToTop = scroller.scrollTop === 0;
const scrolledToBottom = (scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight) <= 1;
if (scrolledToTop && e.deltaY < 0) {
e.preventDefault();
} else if (scrolledToBottom && e.deltaY > 0) {
e.preventDefault();
}
});
}
updateViewportBoundaries() {
this._cachedViewportTotalPaddingBottom = undefined;
this._selector.updateViewportBoundaries();
}
get _viewportTotalPaddingBottom() {
if (this._cachedViewportTotalPaddingBottom === undefined) {
const itemsStyle = window.getComputedStyle(this._selector.$.items);
this._cachedViewportTotalPaddingBottom = [
itemsStyle.paddingBottom,
itemsStyle.borderBottomWidth
].map(v => {
return parseInt(v, 10);
}).reduce((sum, v) => {
return sum + v;
});
}
return this._cachedViewportTotalPaddingBottom;
}
_visibleItemsCount() {
if (!this._selector) {
return;
}
// Ensure items are rendered
this._selector.flushDebouncer('_debounceTemplate');
// Ensure items are positioned
this._selector.scrollToIndex(this._selector.firstVisibleIndex);
// Ensure viewport boundaries are up-to-date
this.updateViewportBoundaries();
return this._selector.lastVisibleIndex - this._selector.firstVisibleIndex + 1;
}
_selectItem(item) {
item = (typeof item === 'number') ? this._items[item] : item;
if (this._selector.selectedItem !== item) {
this._selector.selectItem(item);
}
}
_preventDefault(e) {
if (e.cancelable) {
e.preventDefault();
}
}
_stopPropagation(e) {
e.stopPropagation();
}
_hidden(itemsChange) {
return !this.loading && (this._isEmpty(this._items));
}
}
customElements.define(ComboBoxDropdownWrapperElement.is, ComboBoxDropdownWrapperElement);
})();
</script>