@vaadin/combo-box 24.0.0-alpha9 → 24.0.0-beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,8 +4,8 @@
4
4
  * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
5
  */
6
6
  import { Overlay } from '@vaadin/overlay/src/vaadin-overlay.js';
7
- import { PositionMixin } from '@vaadin/overlay/src/vaadin-overlay-position-mixin.js';
8
7
  import { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
8
+ import { ComboBoxOverlayMixin } from './vaadin-combo-box-overlay-mixin.js';
9
9
 
10
10
  registerStyles(
11
11
  'vaadin-combo-box-overlay',
@@ -29,9 +29,10 @@ let memoizedTemplate;
29
29
  * An element used internally by `<vaadin-combo-box>`. Not intended to be used separately.
30
30
  *
31
31
  * @extends Overlay
32
+ * @mixes ComboBoxOverlayMixin
32
33
  * @private
33
34
  */
34
- export class ComboBoxOverlay extends PositionMixin(Overlay) {
35
+ export class ComboBoxOverlay extends ComboBoxOverlayMixin(Overlay) {
35
36
  static get is() {
36
37
  return 'vaadin-combo-box-overlay';
37
38
  }
@@ -39,57 +40,23 @@ export class ComboBoxOverlay extends PositionMixin(Overlay) {
39
40
  static get template() {
40
41
  if (!memoizedTemplate) {
41
42
  memoizedTemplate = super.template.cloneNode(true);
42
- memoizedTemplate.content.querySelector('[part~="overlay"]').removeAttribute('tabindex');
43
- }
44
43
 
45
- return memoizedTemplate;
46
- }
44
+ const overlay = memoizedTemplate.content.querySelector('[part~="overlay"]');
45
+ overlay.removeAttribute('tabindex');
47
46
 
48
- static get observers() {
49
- return ['_setOverlayWidth(positionTarget, opened)'];
50
- }
47
+ const loader = document.createElement('div');
48
+ loader.setAttribute('part', 'loader');
51
49
 
52
- connectedCallback() {
53
- super.connectedCallback();
54
-
55
- const comboBox = this._comboBox;
56
-
57
- const hostDir = comboBox && comboBox.getAttribute('dir');
58
- if (hostDir) {
59
- this.setAttribute('dir', hostDir);
50
+ overlay.insertBefore(loader, overlay.firstElementChild);
60
51
  }
61
- }
62
52
 
63
- ready() {
64
- super.ready();
65
- const loader = document.createElement('div');
66
- loader.setAttribute('part', 'loader');
67
- const content = this.shadowRoot.querySelector('[part~="content"]');
68
- content.parentNode.insertBefore(loader, content);
69
- }
70
-
71
- _outsideClickListener(event) {
72
- const eventPath = event.composedPath();
73
- if (!eventPath.includes(this.positionTarget) && !eventPath.includes(this)) {
74
- this.close();
75
- }
53
+ return memoizedTemplate;
76
54
  }
77
55
 
78
- _setOverlayWidth(positionTarget, opened) {
79
- if (positionTarget && opened) {
80
- const propPrefix = this.localName;
81
- this.style.setProperty(`--_${propPrefix}-default-width`, `${positionTarget.clientWidth}px`);
56
+ constructor() {
57
+ super();
82
58
 
83
- const customWidth = getComputedStyle(this._comboBox).getPropertyValue(`--${propPrefix}-width`);
84
-
85
- if (customWidth === '') {
86
- this.style.removeProperty(`--${propPrefix}-width`);
87
- } else {
88
- this.style.setProperty(`--${propPrefix}-width`, customWidth);
89
- }
90
-
91
- this._updatePosition();
92
- }
59
+ this.requiredVerticalSpace = 200;
93
60
  }
94
61
  }
95
62
 
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2015 - 2023 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import type { Constructor } from '@open-wc/dedupe-mixin';
7
+ import type { ComboBoxItemRenderer } from './vaadin-combo-box-item-mixin.js';
8
+
9
+ export declare function ComboBoxScrollerMixin<TItem, TOwner, T extends Constructor<HTMLElement>>(
10
+ base: T,
11
+ ): Constructor<ComboBoxScrollerMixinClass<TItem, TOwner>> & T;
12
+
13
+ export declare class ComboBoxScrollerMixinClass<TItem, TOwner> {
14
+ /**
15
+ * Index of an item that has focus outline and is scrolled into view.
16
+ * The actual focus still remains in the input field.
17
+ */
18
+ focusedIndex: number;
19
+
20
+ /**
21
+ * Path for the id of the item, used to detect whether the item is selected.
22
+ */
23
+ itemIdPath: string | null | undefined;
24
+
25
+ /**
26
+ * A full set of items to filter the visible options from.
27
+ * Set to an empty array when combo-box is not opened.
28
+ */
29
+ items: TItem[];
30
+
31
+ /**
32
+ * Set to true while combo-box fetches new page from the data provider.
33
+ */
34
+ loading: boolean;
35
+
36
+ /**
37
+ * Whether the combo-box is currently opened or not. If set to false,
38
+ * calling `scrollIntoView` does not have any effect.
39
+ */
40
+ opened: boolean;
41
+
42
+ /**
43
+ * Reference to the owner (combo-box owner), used by the item elements.
44
+ */
45
+ owner: TOwner;
46
+
47
+ /**
48
+ * Set true to prevent the overlay from opening automatically.
49
+ * @attr {boolean} auto-open-disabled
50
+ */
51
+ renderer: ComboBoxItemRenderer<TItem, TOwner> | null | undefined;
52
+
53
+ /**
54
+ * The selected item from the `items` array.
55
+ */
56
+ selectedItem: TItem;
57
+
58
+ /**
59
+ * Used to propagate the `theme` attribute from the host element.
60
+ */
61
+ theme: string;
62
+
63
+ /**
64
+ * Function used to set a label for every combo-box item.
65
+ */
66
+ getItemLabel: (item: TItem) => string;
67
+
68
+ /**
69
+ * Requests an update for the virtualizer to re-render items.
70
+ */
71
+ requestContentUpdate(): void;
72
+
73
+ /**
74
+ * Scrolls an item at given index into view and adjusts `scrollTop`
75
+ * so that the element gets fully visible on Arrow Down key press.
76
+ */
77
+ scrollIntoView(index: number): void;
78
+
79
+ protected _isItemSelected(item: TItem, selectedItem: TItem, itemIdPath: string | null | undefined): void;
80
+
81
+ protected _updateElement(el: HTMLElement, index: number): void;
82
+ }
@@ -0,0 +1,361 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2015 - 2023 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import { generateUniqueId } from '@vaadin/component-base/src/unique-id-utils.js';
7
+ import { Virtualizer } from '@vaadin/component-base/src/virtualizer.js';
8
+ import { ComboBoxPlaceholder } from './vaadin-combo-box-placeholder.js';
9
+
10
+ /**
11
+ * @polymerMixin
12
+ */
13
+ export const ComboBoxScrollerMixin = (superClass) =>
14
+ class ComboBoxScrollerMixin extends superClass {
15
+ static get properties() {
16
+ return {
17
+ /**
18
+ * A full set of items to filter the visible options from.
19
+ * Set to an empty array when combo-box is not opened.
20
+ */
21
+ items: {
22
+ type: Array,
23
+ observer: '__itemsChanged',
24
+ },
25
+
26
+ /**
27
+ * Index of an item that has focus outline and is scrolled into view.
28
+ * The actual focus still remains in the input field.
29
+ */
30
+ focusedIndex: {
31
+ type: Number,
32
+ observer: '__focusedIndexChanged',
33
+ },
34
+
35
+ /**
36
+ * Set to true while combo-box fetches new page from the data provider.
37
+ */
38
+ loading: {
39
+ type: Boolean,
40
+ observer: '__loadingChanged',
41
+ },
42
+
43
+ /**
44
+ * Whether the combo-box is currently opened or not. If set to false,
45
+ * calling `scrollIntoView` does not have any effect.
46
+ */
47
+ opened: {
48
+ type: Boolean,
49
+ observer: '__openedChanged',
50
+ },
51
+
52
+ /**
53
+ * The selected item from the `items` array.
54
+ */
55
+ selectedItem: {
56
+ type: Object,
57
+ observer: '__selectedItemChanged',
58
+ },
59
+
60
+ /**
61
+ * Path for the id of the item, used to detect whether the item is selected.
62
+ */
63
+ itemIdPath: {
64
+ type: String,
65
+ },
66
+
67
+ /**
68
+ * Reference to the owner (combo-box owner), used by the item elements.
69
+ */
70
+ owner: {
71
+ type: Object,
72
+ },
73
+
74
+ /**
75
+ * Function used to set a label for every combo-box item.
76
+ */
77
+ getItemLabel: {
78
+ type: Object,
79
+ },
80
+
81
+ /**
82
+ * Function used to render the content of every combo-box item.
83
+ */
84
+ renderer: {
85
+ type: Object,
86
+ observer: '__rendererChanged',
87
+ },
88
+
89
+ /**
90
+ * Used to propagate the `theme` attribute from the host element.
91
+ */
92
+ theme: {
93
+ type: String,
94
+ },
95
+ };
96
+ }
97
+
98
+ constructor() {
99
+ super();
100
+ this.__boundOnItemClick = this.__onItemClick.bind(this);
101
+ }
102
+
103
+ /** @private */
104
+ get _viewportTotalPaddingBottom() {
105
+ if (this._cachedViewportTotalPaddingBottom === undefined) {
106
+ const itemsStyle = window.getComputedStyle(this.$.selector);
107
+ this._cachedViewportTotalPaddingBottom = [itemsStyle.paddingBottom, itemsStyle.borderBottomWidth]
108
+ .map((v) => {
109
+ return parseInt(v, 10);
110
+ })
111
+ .reduce((sum, v) => {
112
+ return sum + v;
113
+ });
114
+ }
115
+
116
+ return this._cachedViewportTotalPaddingBottom;
117
+ }
118
+
119
+ /** @protected */
120
+ ready() {
121
+ super.ready();
122
+
123
+ this.setAttribute('role', 'listbox');
124
+
125
+ // Ensure every instance has unique ID
126
+ this.id = `${this.localName}-${generateUniqueId()}`;
127
+
128
+ // Allow extensions to customize tag name for the items
129
+ this.__hostTagName = this.constructor.is.replace('-scroller', '');
130
+
131
+ this.addEventListener('click', (e) => e.stopPropagation());
132
+
133
+ this.__patchWheelOverScrolling();
134
+
135
+ this.__virtualizer = new Virtualizer({
136
+ createElements: this.__createElements.bind(this),
137
+ updateElement: this._updateElement.bind(this),
138
+ elementsContainer: this,
139
+ scrollTarget: this,
140
+ scrollContainer: this.$.selector,
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Requests an update for the virtualizer to re-render items.
146
+ */
147
+ requestContentUpdate() {
148
+ if (this.__virtualizer) {
149
+ this.__virtualizer.update();
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Scrolls an item at given index into view and adjusts `scrollTop`
155
+ * so that the element gets fully visible on Arrow Down key press.
156
+ * @param {number} index
157
+ */
158
+ scrollIntoView(index) {
159
+ if (!(this.opened && index >= 0)) {
160
+ return;
161
+ }
162
+
163
+ const visibleItemsCount = this._visibleItemsCount();
164
+
165
+ let targetIndex = index;
166
+
167
+ if (index > this.__virtualizer.lastVisibleIndex - 1) {
168
+ // Index is below the bottom, scrolling down. Make the item appear at the bottom.
169
+ // First scroll to target (will be at the top of the scroller) to make sure it's rendered.
170
+ this.__virtualizer.scrollToIndex(index);
171
+ // Then calculate the index for the following scroll (to get the target to bottom of the scroller).
172
+ targetIndex = index - visibleItemsCount + 1;
173
+ } else if (index > this.__virtualizer.firstVisibleIndex) {
174
+ // The item is already visible, scrolling is unnecessary per se. But we need to trigger iron-list to set
175
+ // the correct scrollTop on the scrollTarget. Scrolling to firstVisibleIndex.
176
+ targetIndex = this.__virtualizer.firstVisibleIndex;
177
+ }
178
+ this.__virtualizer.scrollToIndex(Math.max(0, targetIndex));
179
+
180
+ // Sometimes the item is partly below the bottom edge, detect and adjust.
181
+ const lastPhysicalItem = [...this.children].find(
182
+ (el) => !el.hidden && el.index === this.__virtualizer.lastVisibleIndex,
183
+ );
184
+ if (!lastPhysicalItem || index !== lastPhysicalItem.index) {
185
+ return;
186
+ }
187
+ const lastPhysicalItemRect = lastPhysicalItem.getBoundingClientRect();
188
+ const scrollerRect = this.getBoundingClientRect();
189
+ const scrollTopAdjust = lastPhysicalItemRect.bottom - scrollerRect.bottom + this._viewportTotalPaddingBottom;
190
+ if (scrollTopAdjust > 0) {
191
+ this.scrollTop += scrollTopAdjust;
192
+ }
193
+ }
194
+
195
+ /**
196
+ * @param {string | object} item
197
+ * @param {string | object} selectedItem
198
+ * @param {string} itemIdPath
199
+ * @protected
200
+ */
201
+ _isItemSelected(item, selectedItem, itemIdPath) {
202
+ if (item instanceof ComboBoxPlaceholder) {
203
+ return false;
204
+ } else if (itemIdPath && item !== undefined && selectedItem !== undefined) {
205
+ return this.get(itemIdPath, item) === this.get(itemIdPath, selectedItem);
206
+ }
207
+ return item === selectedItem;
208
+ }
209
+
210
+ /** @private */
211
+ __itemsChanged(items) {
212
+ if (this.__virtualizer && items) {
213
+ this.__virtualizer.size = items.length;
214
+ this.__virtualizer.flush();
215
+ this.requestContentUpdate();
216
+ }
217
+ }
218
+
219
+ /** @private */
220
+ __loadingChanged() {
221
+ this.requestContentUpdate();
222
+ }
223
+
224
+ /** @private */
225
+ __openedChanged(opened) {
226
+ if (opened) {
227
+ this.requestContentUpdate();
228
+ }
229
+ }
230
+
231
+ /** @private */
232
+ __selectedItemChanged() {
233
+ this.requestContentUpdate();
234
+ }
235
+
236
+ /** @private */
237
+ __focusedIndexChanged(index, oldIndex) {
238
+ if (index !== oldIndex) {
239
+ this.requestContentUpdate();
240
+ }
241
+
242
+ // Do not jump back to the previously focused item while loading
243
+ // when requesting next page from the data provider on scroll.
244
+ if (index >= 0 && !this.loading) {
245
+ this.scrollIntoView(index);
246
+ }
247
+ }
248
+
249
+ /** @private */
250
+ __rendererChanged(renderer, oldRenderer) {
251
+ if (renderer || oldRenderer) {
252
+ this.requestContentUpdate();
253
+ }
254
+ }
255
+
256
+ /** @private */
257
+ __createElements(count) {
258
+ return [...Array(count)].map(() => {
259
+ const item = document.createElement(`${this.__hostTagName}-item`);
260
+ item.addEventListener('click', this.__boundOnItemClick);
261
+ // Negative tabindex prevents the item content from being focused.
262
+ item.tabIndex = '-1';
263
+ item.style.width = '100%';
264
+ return item;
265
+ });
266
+ }
267
+
268
+ /**
269
+ * @param {HTMLElement} el
270
+ * @param {number} index
271
+ * @protected
272
+ */
273
+ _updateElement(el, index) {
274
+ const item = this.items[index];
275
+ const focusedIndex = this.focusedIndex;
276
+ const selected = this._isItemSelected(item, this.selectedItem, this.itemIdPath);
277
+
278
+ el.setProperties({
279
+ item,
280
+ index,
281
+ label: this.getItemLabel(item),
282
+ selected,
283
+ renderer: this.renderer,
284
+ focused: !this.loading && focusedIndex === index,
285
+ });
286
+
287
+ el.id = `${this.__hostTagName}-item-${index}`;
288
+ el.setAttribute('role', index !== undefined ? 'option' : false);
289
+ el.setAttribute('aria-selected', selected.toString());
290
+ el.setAttribute('aria-posinset', index + 1);
291
+ el.setAttribute('aria-setsize', this.items.length);
292
+
293
+ if (this.theme) {
294
+ el.setAttribute('theme', this.theme);
295
+ } else {
296
+ el.removeAttribute('theme');
297
+ }
298
+
299
+ if (item instanceof ComboBoxPlaceholder) {
300
+ this.__requestItemByIndex(index);
301
+ }
302
+ }
303
+
304
+ /** @private */
305
+ __onItemClick(e) {
306
+ this.dispatchEvent(new CustomEvent('selection-changed', { detail: { item: e.currentTarget.item } }));
307
+ }
308
+
309
+ /**
310
+ * We want to prevent the kinetic scrolling energy from being transferred from the overlay contents over to the parent.
311
+ * Further improvement ideas: after the contents have been scrolled to the top or bottom and scrolling has stopped, it could allow
312
+ * scrolling the parent similarly to touch scrolling.
313
+ * @private
314
+ */
315
+ __patchWheelOverScrolling() {
316
+ this.$.selector.addEventListener('wheel', (e) => {
317
+ const scrolledToTop = this.scrollTop === 0;
318
+ const scrolledToBottom = this.scrollHeight - this.scrollTop - this.clientHeight <= 1;
319
+ if (scrolledToTop && e.deltaY < 0) {
320
+ e.preventDefault();
321
+ } else if (scrolledToBottom && e.deltaY > 0) {
322
+ e.preventDefault();
323
+ }
324
+ });
325
+ }
326
+
327
+ /**
328
+ * Dispatches an `index-requested` event for the given index to notify
329
+ * the data provider that it should start loading the page containing the requested index.
330
+ *
331
+ * The event is dispatched asynchronously to prevent an immediate page request and therefore
332
+ * a possible infinite recursion in case the data provider implements page request cancelation logic
333
+ * by invoking data provider page callbacks with an empty array.
334
+ * The infinite recursion may occur otherwise since invoking a data provider page callback with an empty array
335
+ * triggers a synchronous scroller update and, if the callback corresponds to the currently visible page,
336
+ * the scroller will synchronously request the page again which may lead to looping in the end.
337
+ * That was the case for the Flow counterpart:
338
+ * https://github.com/vaadin/flow-components/issues/3553#issuecomment-1239344828
339
+ * @private
340
+ */
341
+ __requestItemByIndex(index) {
342
+ requestAnimationFrame(() => {
343
+ this.dispatchEvent(
344
+ new CustomEvent('index-requested', {
345
+ detail: {
346
+ index,
347
+ currentScrollerPos: this._oldScrollerPosition,
348
+ },
349
+ }),
350
+ );
351
+ });
352
+ }
353
+
354
+ /** @private */
355
+ _visibleItemsCount() {
356
+ // Ensure items are positioned
357
+ this.__virtualizer.scrollToIndex(this.__virtualizer.firstVisibleIndex);
358
+ const hasItems = this.__virtualizer.size > 0;
359
+ return hasItems ? this.__virtualizer.lastVisibleIndex - this.__virtualizer.firstVisibleIndex + 1 : 0;
360
+ }
361
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2015 - 2023 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import { ComboBoxScrollerMixin } from './vaadin-combo-box-overlay-mixin.js';
7
+
8
+ /**
9
+ * An element used internally by `<vaadin-combo-box>`. Not intended to be used separately.
10
+ */
11
+ declare class ComboBoxScroller extends ComboBoxScrollerMixin(HTMLElement) {}
12
+
13
+ declare global {
14
+ interface HTMLElementTagNameMap {
15
+ 'vaadin-combo-box-scroller': ComboBoxScroller;
16
+ }
17
+ }
18
+
19
+ export { ComboBoxScroller };