-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathlist-mixin.js
More file actions
353 lines (314 loc) · 9.6 KB
/
list-mixin.js
File metadata and controls
353 lines (314 loc) · 9.6 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
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
/**
* @license
* Copyright (c) 2017 - 2026 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import { timeOut } from '@vaadin/component-base/src/async.js';
import { Debouncer } from '@vaadin/component-base/src/debounce.js';
import { getNormalizedScrollLeft, setNormalizedScrollLeft } from '@vaadin/component-base/src/dir-utils.js';
import { SlotObserver } from '@vaadin/component-base/src/slot-observer.js';
import { isElementHidden } from './focus-utils.js';
import { KeyboardDirectionMixin } from './keyboard-direction-mixin.js';
/**
* A mixin for list elements, facilitating navigation and selection of items.
*
* @polymerMixin
* @mixes KeyboardDirectionMixin
*/
export const ListMixin = (superClass) =>
class ListMixinClass extends KeyboardDirectionMixin(superClass) {
static get properties() {
return {
/**
* If true, the user cannot interact with this element.
* When the element is disabled, the selected item is
* not updated when `selected` property is changed.
*/
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* The index of the item selected in the items array.
* Note: Not updated when used in `multiple` selection mode.
*/
selected: {
type: Number,
reflectToAttribute: true,
notify: true,
sync: true,
},
/**
* Define how items are disposed in the dom.
* Possible values are: `horizontal|vertical`.
* It also changes navigation keys from left/right to up/down.
*/
orientation: {
type: String,
reflectToAttribute: true,
value: '',
},
/**
* A read-only list of items from which a selection can be made.
* It is populated from the elements passed to the light DOM,
* and updated dynamically when adding or removing items.
* @type {!Array<!Element> | undefined}
*/
items: {
type: Array,
readOnly: true,
notify: true,
},
/**
* The search buffer for the keyboard selection feature.
* @private
*/
_searchBuf: {
type: String,
value: '',
},
};
}
static get observers() {
return ['_enhanceItems(items, orientation, selected, disabled)'];
}
/**
* @return {boolean}
* @protected
*/
get _isRTL() {
return !this._vertical && this.getAttribute('dir') === 'rtl';
}
/**
* @return {!HTMLElement}
* @protected
*/
get _scrollerElement() {
// Returning scroller element of the component
console.warn(`Please implement the '_scrollerElement' property in <${this.localName}>`);
return this;
}
/**
* @return {boolean}
* @protected
*/
get _vertical() {
return this.orientation !== 'horizontal';
}
/**
* @param {FocusOptions=} options
* @protected
* @override
*/
focus(options) {
// In initialization (e.g vaadin-select) observer might not been run yet.
if (this._observer) {
this._observer.flush();
}
const items = Array.isArray(this.items) ? this.items : [];
const idx = this._getAvailableIndex(items, 0, null, (item) => item.tabIndex === 0 && !isElementHidden(item));
if (idx >= 0) {
this._focus(idx, options);
} else {
// Call `KeyboardDirectionMixin` logic to focus first non-disabled item.
super.focus(options);
}
}
/** @protected */
ready() {
super.ready();
this.addEventListener('click', (e) => this._onClick(e));
const slot = this.shadowRoot.querySelector('slot:not([name])');
this._observer = new SlotObserver(slot, () => {
this._setItems(this._filterItems([...this.children]));
});
}
/**
* Override method inherited from `KeyboardDirectionMixin`
* to use the stored list of item elements.
*
* @return {Element[]}
* @protected
* @override
*/
_getItems() {
return this.items;
}
/** @private */
_enhanceItems(items, orientation, selected, disabled) {
if (!disabled) {
if (items) {
this.setAttribute('aria-orientation', orientation || 'vertical');
items.forEach((item) => {
if (orientation) {
item.setAttribute('orientation', orientation);
} else {
item.removeAttribute('orientation');
}
});
// When selected is set to -1, focus the first available item.
this._setFocusable(selected < 0 || !selected ? 0 : selected);
const itemToSelect = items[selected];
items.forEach((item) => {
item.selected = item === itemToSelect;
});
if (itemToSelect && !itemToSelect.disabled) {
this._scrollToItem(selected);
}
}
}
}
/**
* @param {!Array<!Element>} array
* @return {!Array<!Element>}
* @protected
*/
_filterItems(array) {
return array.filter((e) => e._hasVaadinItemMixin);
}
/**
* @param {!MouseEvent} event
* @protected
*/
_onClick(event) {
if (event.metaKey || event.shiftKey || event.ctrlKey || event.defaultPrevented) {
return;
}
const item = this._filterItems(event.composedPath())[0];
let idx;
if (item && !item.disabled && (idx = this.items.indexOf(item)) >= 0) {
this.selected = idx;
}
}
/**
* @param {number} currentIdx
* @param {string} key
* @return {number}
* @protected
*/
_searchKey(currentIdx, key) {
this._searchReset = Debouncer.debounce(this._searchReset, timeOut.after(500), () => {
this._searchBuf = '';
});
this._searchBuf += key.toLowerCase();
if (!this.items.some((item) => this.__isMatchingKey(item))) {
this._searchBuf = key.toLowerCase();
}
const idx = this._searchBuf.length === 1 ? currentIdx + 1 : currentIdx;
return this._getAvailableIndex(
this.items,
idx,
1,
(item) => this.__isMatchingKey(item) && getComputedStyle(item).display !== 'none',
);
}
/** @private */
__isMatchingKey(item) {
return item.textContent
.replace(/[^\p{L}\p{Nd}]/gu, '')
.toLowerCase()
.startsWith(this._searchBuf);
}
/**
* Override an event listener from `KeyboardMixin`
* to search items by key.
*
* @param {!KeyboardEvent} event
* @protected
* @override
*/
_onKeyDown(event) {
if (event.metaKey || event.ctrlKey) {
return;
}
const key = event.key;
const currentIdx = this.items.indexOf(this.focused);
if (/[\p{L}\p{Nd}]/u.test(key) && key.length === 1) {
const idx = this._searchKey(currentIdx, key);
if (idx >= 0) {
this._focus(idx);
}
return;
}
super._onKeyDown(event);
}
/**
* @param {number} idx
* @protected
*/
_setFocusable(idx) {
idx = this._getAvailableIndex(this.items, idx, 1);
const item = this.items[idx];
this.items.forEach((e) => {
e.tabIndex = e === item ? 0 : -1;
});
}
/**
* @param {number} idx
* @protected
*/
_focus(idx, options) {
this.items.forEach((e, index) => {
e.focused = index === idx;
});
this._setFocusable(idx);
this._scrollToItem(idx);
super._focus(idx, options);
}
/**
* Scroll the container to have the next item by the edge of the viewport.
* @param {number} idx
* @protected
*/
_scrollToItem(idx) {
const item = this.items[idx];
if (!item) {
return;
}
const props = this._vertical ? ['top', 'bottom'] : this._isRTL ? ['right', 'left'] : ['left', 'right'];
const scrollerRect = this._scrollerElement.getBoundingClientRect();
const nextItemRect = (this.items[idx + 1] || item).getBoundingClientRect();
const prevItemRect = (this.items[idx - 1] || item).getBoundingClientRect();
let scrollDistance = 0;
if (
(!this._isRTL && nextItemRect[props[1]] >= scrollerRect[props[1]]) ||
(this._isRTL && nextItemRect[props[1]] <= scrollerRect[props[1]])
) {
scrollDistance = nextItemRect[props[1]] - scrollerRect[props[1]];
} else if (
(!this._isRTL && prevItemRect[props[0]] <= scrollerRect[props[0]]) ||
(this._isRTL && prevItemRect[props[0]] >= scrollerRect[props[0]])
) {
scrollDistance = prevItemRect[props[0]] - scrollerRect[props[0]];
}
this._scroll(scrollDistance);
}
/**
* @param {number} pixels
* @protected
*/
_scroll(pixels) {
if (this._vertical) {
this._scrollerElement.scrollTop += pixels;
} else {
const dir = this.getAttribute('dir') || 'ltr';
const scrollLeft = getNormalizedScrollLeft(this._scrollerElement, dir) + pixels;
setNormalizedScrollLeft(this._scrollerElement, dir, scrollLeft);
}
}
/**
* Override method inherited from `KeyboardDirectionMixin` to allow
* focusing disabled items that are configured so.
*
* @param {Element} item
* @protected
* @override
*/
_isItemFocusable(item) {
if (item.disabled && item.__shouldAllowFocusWhenDisabled) {
return item.__shouldAllowFocusWhenDisabled();
}
return super._isItemFocusable(item);
}
};