@internetarchive/collection-browser 3.4.1-alpha-webdev7761.0 → 3.4.1-alpha-webdev7761.2

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.
@@ -0,0 +1,1112 @@
1
+ import { __decorate } from "tslib";
2
+ import { html, LitElement, css, } from 'lit';
3
+ import { customElement, property, state, query } from 'lit/decorators.js';
4
+ import { classMap } from 'lit/directives/class-map.js';
5
+ import { ifDefined } from 'lit/directives/if-defined.js';
6
+ import { live } from 'lit/directives/live.js';
7
+ import { when } from 'lit/directives/when.js';
8
+ import { msg } from '@lit/localize';
9
+ import { hasAnyOf, } from './models';
10
+ import caretClosed from './caret-closed';
11
+ import caretOpen from './caret-open';
12
+ /**
13
+ * Tests whether the given `haystack` string has the given `needle` as a subsequence.
14
+ * Returns `true` if the characters of `needle` appear in order within `haystack`,
15
+ * regardless of whether they are contiguous. Returns `false` otherwise.
16
+ *
17
+ * E.g., `ace` is a subsequence of `archive` (but not a contiguous substring).
18
+ *
19
+ * Note: The empty string is a subsequence of any string, including itself.
20
+ *
21
+ * @param needle The potential subsequence to check for inside `haystack`.
22
+ * @param haystack The string to be tested for containing the `needle` subsequence.
23
+ * @returns Whether `haystack` has `needle` as a subsequence.
24
+ */
25
+ const isSubsequence = (needle, haystack) => {
26
+ const needleLen = needle.length;
27
+ const haystackLen = haystack.length;
28
+ if (needleLen === 0)
29
+ return true;
30
+ let needleIdx = 0;
31
+ let haystackIdx = 0;
32
+ while (haystackIdx < haystackLen) {
33
+ if (haystack[haystackIdx] === needle[needleIdx])
34
+ needleIdx += 1;
35
+ if (needleIdx >= needleLen)
36
+ return true;
37
+ haystackIdx += 1;
38
+ }
39
+ return false;
40
+ };
41
+ /**
42
+ * Map from filter preset keys to their associated filtering function.
43
+ * @see {@linkcode IAComboBox.filter}
44
+ */
45
+ const FILTER_PRESETS = {
46
+ all: () => true,
47
+ prefix: (filterText, optionText) => optionText.startsWith(filterText),
48
+ suffix: (filterText, optionText) => optionText.endsWith(filterText),
49
+ substring: (filterText, optionText) => optionText.includes(filterText),
50
+ subsequence: isSubsequence,
51
+ };
52
+ const DEFAULT_BEHAVIOR = 'list';
53
+ const DEFAULT_FILTER_PRESET = 'substring';
54
+ const STRING_IDENTITY_FN = (str) => str;
55
+ const STRING_LOWER_CASE_FN = (str) => str.toLocaleLowerCase();
56
+ /**
57
+ * A flexible component combining the features of a dropdown menu and a text input,
58
+ * allowing users to either select from a predefined list of options or type
59
+ * freeform text to filter down & find specific options.
60
+ */
61
+ let IAComboBox = class IAComboBox extends LitElement {
62
+ constructor() {
63
+ super();
64
+ /**
65
+ * Array of options representing values that this combo box can take.
66
+ *
67
+ * If this combo box's `behavior` property is `select-only` or `list`, these options
68
+ * represent _all_ of the allowed values that the user may choose from.
69
+ *
70
+ * If this combo box's `behavior` property is `freeform`, this array simply represents
71
+ * a non-exhaustive list of _suggested_ values, which the user may either choose from
72
+ * or enter their own value.
73
+ * @see {@linkcode IAComboBox.behavior}
74
+ */
75
+ this.options = [];
76
+ /**
77
+ * What style of behavior to use for the combo box.
78
+ *
79
+ * Currently, the options are
80
+ * - `select-only` (behaving similar to a `<select>`, disallowing text entry and only
81
+ * allowing selection from the predefined, unfiltered options)
82
+ * - `list` (the default, allowing text entry to filter the dropdown list, but still
83
+ * requiring values to be set from the predefined options)
84
+ * - `freeform` (allows text entry to filter the dropdown list, and also allows setting
85
+ * custom values not included in the list)
86
+ */
87
+ this.behavior = DEFAULT_BEHAVIOR;
88
+ /**
89
+ * Maximum number of options to include in the autocomplete menu when filtering.
90
+ *
91
+ * Default value is `Infinity`, presenting all matching options regardless of count.
92
+ */
93
+ this.maxAutocompleteEntries = Number.POSITIVE_INFINITY;
94
+ /**
95
+ * Specifies how the options should be filtered when text is entered into the combo box.
96
+ * Has no effect if `behavior` is `select-only`, as the component is not text-editable.
97
+ *
98
+ * Default is `substring`, showing only options whose `text` contains the value entered
99
+ * as a substring at any position. The possible preset options are:
100
+ * - `all`: Does not filter the dropdown entries. They will always all be shown (up to
101
+ * the limit specified by `maxAutocompleteEntries`).
102
+ * - `prefix`: Only includes options whose text _starts_ with the entered value.
103
+ * - `suffix`: Only includes options whose text _ends_ with the entered value.
104
+ * - `substring`: Only includes options whose text contains the entered value as a
105
+ * contiguous substring.
106
+ * - `subsequence`: Only shows options whose text has the characters of the entered
107
+ * value in order, though they do not need to be contiguous.
108
+ * E.g., `ace` is a subsequence of `archive` (but not a substring).
109
+ *
110
+ * If custom filtering outside of these presets is desired, an arbitrary filtering function
111
+ * may instead be bound to this property directly.
112
+ *
113
+ * @see {@link IAComboBox.caseSensitive} to enable case-sensitive filtering.
114
+ */
115
+ this.filter = DEFAULT_FILTER_PRESET;
116
+ /**
117
+ * Whether filtering should be case-sensitive. Default is `false`, performing only
118
+ * case-insensitive filtering.
119
+ */
120
+ this.caseSensitive = false;
121
+ /**
122
+ * Whether the filtered options should be listed in lexicographically-sorted order.
123
+ * Default is `false`, displaying them in the same order as the provided options array.
124
+ */
125
+ this.sort = false;
126
+ /**
127
+ * Whether the combo box allows multiple options to be selected at once.
128
+ * Default is `false`, allowing only a single option to be selected.
129
+ */
130
+ // @property({ type: Boolean, reflect: true }) multiple = false; // TODO
131
+ /**
132
+ * Whether pressing the Up/Down arrow keys should wrap focus back to the text input box
133
+ * while focus is already on the first/last option, respectively.
134
+ *
135
+ * Default is `false`, doing nothing upon such key presses.
136
+ */
137
+ this.wrapArrowKeys = false;
138
+ /**
139
+ * Whether the options list should remain open after an option is selected.
140
+ *
141
+ * Default is `false`, closing the options list when a selection is made.
142
+ */
143
+ this.stayOpen = false;
144
+ /**
145
+ * Whether the combo box's option menu is currently expanded. Default is `false`.
146
+ */
147
+ this.open = false;
148
+ /**
149
+ * Whether the combo box should be rendered in its disabled state, preventing all
150
+ * interactions such as editing the text field or opening the options menu.
151
+ * Default is `false`.
152
+ */
153
+ this.disabled = false;
154
+ /**
155
+ * If used within a form, whether this combo box is required to have a value selected
156
+ * before the form may be submitted. Default is `false`.
157
+ */
158
+ this.required = false;
159
+ /**
160
+ * For `select-only` or `list` behavior, this value is the ID of the selected option,
161
+ * or `null` if there is no selection.
162
+ *
163
+ * For `freeform` behavior, this may be any string entered into the text field, and
164
+ * need not correspond to an option ID.
165
+ */
166
+ this.value = null;
167
+ /**
168
+ * Whether any part of this component currently has focus.
169
+ */
170
+ this.hasFocus = false;
171
+ /**
172
+ * Which option in the dropdown menu is currently highlighted by the user. Not to be
173
+ * confused with the _selected_ option that has been committed, this field only
174
+ * represents the user's current navigation state within the menu, which they may
175
+ * subsequently select by, e.g., hitting Enter.
176
+ */
177
+ this.highlightedOption = null;
178
+ /**
179
+ * The text than has been entered into the text input box.
180
+ */
181
+ this.enteredText = '';
182
+ /**
183
+ * The text that we are currently using the filter the dropdown menu options.
184
+ */
185
+ this.filterText = '';
186
+ /**
187
+ * Set when part of the component blurs, and cleared when any part of it is focused.
188
+ * If still set on the next tick after a blur event, this serves as a signal that focus
189
+ * has moved away from the component as a whole and should be closed.
190
+ */
191
+ this.losingFocus = false;
192
+ /**
193
+ * A cache of the mapping from option IDs to their corresponding options, so that
194
+ * we can more efficiently look up options by ID.
195
+ */
196
+ this.optionsByID = new Map();
197
+ /**
198
+ * A cache of the values against which each option should be filtered, to minimize
199
+ * the work needed at filter time to handle case-insensitivity etc.
200
+ */
201
+ this.optionFilteringValues = new Map();
202
+ /**
203
+ * A cache of the current set of options that is pre-sorted if the component's
204
+ * `sort` flag is set, or as provided otherwise. Just ensures we don't have to
205
+ * sort all the options again every time we filter them.
206
+ */
207
+ this.optionsRespectingSortFlag = [];
208
+ /**
209
+ * A cache of the current set of filtered options, so that we don't have to
210
+ * recalculate it unnecessarily whenever the component is opened/closed/etc.
211
+ */
212
+ this.filteredOptions = [];
213
+ this.internals = this.attachInternals();
214
+ }
215
+ render() {
216
+ return html `
217
+ <div
218
+ id="container"
219
+ class=${classMap({ focused: this.hasFocus })}
220
+ part="container"
221
+ >
222
+ ${this.labelTemplate}
223
+ <div
224
+ id="main-widget-row"
225
+ class=${classMap({ disabled: this.disabled })}
226
+ part="combo-box"
227
+ >
228
+ ${this.textInputTemplate} ${this.caretButtonTemplate}
229
+ </div>
230
+ ${this.optionsListTemplate}
231
+ </div>
232
+ `;
233
+ }
234
+ willUpdate(changed) {
235
+ if (changed.has('options') || changed.has('caseSensitive')) {
236
+ // Need to update the cached values against which our filters are matched
237
+ this.rebuildOptionFilteringValues();
238
+ }
239
+ if (changed.has('options')) {
240
+ // Need to update the cached mapping of IDs to options
241
+ this.rebuildOptionIDMap();
242
+ }
243
+ if (changed.has('options') || changed.has('sort')) {
244
+ // Sort the options upfront if needed
245
+ this.rebuildSortedOptions();
246
+ }
247
+ if (hasAnyOf(changed, [
248
+ 'options',
249
+ 'behavior',
250
+ 'maxAutocompleteEntries',
251
+ 'filter',
252
+ 'filterText',
253
+ 'caseSensitive',
254
+ 'sort',
255
+ ])) {
256
+ // If anything about the options or how they are filtered has changed, we need to
257
+ // update our cache of the filtered options
258
+ this.rebuildFilteredOptions();
259
+ }
260
+ if (changed.has('value')) {
261
+ this.handleValueChanged();
262
+ }
263
+ if (changed.has('open')) {
264
+ if (this.open) {
265
+ // Highlight selection on open, if possible
266
+ if (this.value)
267
+ this.setHighlightedOption(this.selectedOption);
268
+ }
269
+ else {
270
+ // Clear highlight on close
271
+ this.setHighlightedOption(null);
272
+ }
273
+ }
274
+ if (changed.has('required')) {
275
+ this.updateFormValidity();
276
+ }
277
+ }
278
+ updated(changed) {
279
+ var _a, _b, _c, _d;
280
+ if (changed.has('open')) {
281
+ if (this.open) {
282
+ this.positionOptionsMenu();
283
+ (_b = (_a = this.optionsList).showPopover) === null || _b === void 0 ? void 0 : _b.call(_a);
284
+ this.optionsList.classList.add('visible');
285
+ }
286
+ else {
287
+ (_d = (_c = this.optionsList).hidePopover) === null || _d === void 0 ? void 0 : _d.call(_c);
288
+ this.optionsList.classList.remove('visible');
289
+ }
290
+ }
291
+ }
292
+ //
293
+ // TEMPLATES
294
+ //
295
+ /**
296
+ * Template for the main label for the combo box.
297
+ *
298
+ * Uses the contents of the default (unnamed) slot as the label text.
299
+ */
300
+ get labelTemplate() {
301
+ return html `<label id="label" for="text-input"><slot></slot></label>`;
302
+ }
303
+ /**
304
+ * Template for the text input field that users can edit to filter the available
305
+ * options or (if freeform behavior) to enter a custom value.
306
+ */
307
+ get textInputTemplate() {
308
+ var _a;
309
+ const textInputClasses = classMap({
310
+ editable: this.behavior !== 'select-only',
311
+ });
312
+ return html `
313
+ <input
314
+ type="text"
315
+ id="text-input"
316
+ class=${textInputClasses}
317
+ .value=${live(this.enteredText)}
318
+ placeholder=${ifDefined(this.placeholder)}
319
+ part="text-input"
320
+ role="combobox"
321
+ autocomplete="off"
322
+ aria-autocomplete="list"
323
+ aria-controls="options-list"
324
+ aria-expanded=${this.open}
325
+ aria-activedescendant=${ifDefined((_a = this.highlightedOption) === null || _a === void 0 ? void 0 : _a.id)}
326
+ ?disabled=${this.disabled}
327
+ ?required=${this.required}
328
+ @click=${this.handleComboBoxClick}
329
+ @keydown=${this.handleComboBoxKeyDown}
330
+ @input=${this.handleTextBoxInput}
331
+ @focus=${this.handleFocus}
332
+ @blur=${this.handleBlur}
333
+ />
334
+ `;
335
+ }
336
+ /**
337
+ * Template for the caret open/closed icons to show beside the text input.
338
+ * The icons are wrapped in named slots to allow consumers to override them.
339
+ */
340
+ get caretTemplate() {
341
+ return html `
342
+ <slot name="caret-closed" ?hidden=${this.open}> ${caretClosed} </slot>
343
+ <slot name="caret-open" ?hidden=${!this.open}> ${caretOpen} </slot>
344
+ `;
345
+ }
346
+ /**
347
+ * Template for the caret button to be shown beside the text input.
348
+ */
349
+ get caretButtonTemplate() {
350
+ return html `
351
+ <button
352
+ type="button"
353
+ id="caret-button"
354
+ part="caret-button"
355
+ tabindex="-1"
356
+ aria-controls="options-list"
357
+ aria-expanded=${this.open}
358
+ ?disabled=${this.disabled}
359
+ @click=${this.handleComboBoxClick}
360
+ @keydown=${this.handleComboBoxKeyDown}
361
+ @focus=${this.handleFocus}
362
+ @blur=${this.handleBlur}
363
+ >
364
+ ${this.caretTemplate}
365
+ </button>
366
+ `;
367
+ }
368
+ /**
369
+ * Template for the options list that is displayed when the combo box is open.
370
+ */
371
+ get optionsListTemplate() {
372
+ return html `
373
+ <ul
374
+ id="options-list"
375
+ part="options-list"
376
+ role="listbox"
377
+ popover
378
+ ?hidden=${!this.open}
379
+ @focus=${this.handleFocus}
380
+ @blur=${this.handleBlur}
381
+ >
382
+ <slot name="options-list-top"></slot>
383
+ ${when(this.open, () => this.optionTemplates)}
384
+ <slot name="options-list-bottom"></slot>
385
+ </ul>
386
+ `;
387
+ }
388
+ /**
389
+ * Array of templates for all of the filtered options to be shown in the options menu.
390
+ */
391
+ get optionTemplates() {
392
+ // If there are no options matching the filter, just show a message saying as much.
393
+ if (this.filteredOptions.length === 0 && this.maxAutocompleteEntries > 0) {
394
+ return [this.emptyOptionsTemplate];
395
+ }
396
+ // Otherwise build a list item for each filtered option
397
+ return this.filteredOptions.map((opt) => {
398
+ var _a;
399
+ const optionClasses = classMap({
400
+ option: true,
401
+ highlight: opt === this.highlightedOption,
402
+ });
403
+ return html `
404
+ <li
405
+ id=${opt.id}
406
+ class=${optionClasses}
407
+ part="option"
408
+ tabindex="-1"
409
+ @pointerenter=${this.handleOptionPointerEnter}
410
+ @pointermove=${this.handleOptionPointerMove}
411
+ @click=${this.handleOptionClick}
412
+ @focus=${this.handleFocus}
413
+ @blur=${this.handleBlur}
414
+ >
415
+ ${(_a = opt.content) !== null && _a !== void 0 ? _a : opt.text}
416
+ </li>
417
+ `;
418
+ });
419
+ }
420
+ /**
421
+ * Info message shown in the listbox when no options match the entered text.
422
+ * Renders within an `empty-options` named slot so that its content can be customized.
423
+ */
424
+ get emptyOptionsTemplate() {
425
+ return html `
426
+ <li id="empty-options" part="empty-options">
427
+ <slot name="empty-options">${msg('No matching options')}</slot>
428
+ </li>
429
+ `;
430
+ }
431
+ //
432
+ // EVENT HANDLERS & MUTATORS
433
+ //
434
+ /**
435
+ * Handler for when the pointer device enters an option element in the dropdown.
436
+ */
437
+ handleOptionPointerEnter(e) {
438
+ this.handleOptionPointerMove(e);
439
+ }
440
+ /**
441
+ * Handler for when the pointer device is moved within an option in the dropdown.
442
+ */
443
+ handleOptionPointerMove(e) {
444
+ const target = e.target;
445
+ const option = this.getOptionFor(target.id);
446
+ if (option)
447
+ this.setHighlightedOption(option);
448
+ }
449
+ /**
450
+ * Handler for when the user clicks on an option in the dropdown.
451
+ */
452
+ handleOptionClick(e) {
453
+ const target = e.target;
454
+ const option = this.getOptionFor(target.id);
455
+ if (option) {
456
+ this.setSelectedOption(option.id);
457
+ this.closeOptionsMenu();
458
+ }
459
+ }
460
+ /**
461
+ * Handler for `keydown` events on various special keys.
462
+ */
463
+ handleComboBoxKeyDown(e) {
464
+ switch (e.key) {
465
+ case 'Enter':
466
+ this.handleEnterPressed();
467
+ break;
468
+ case 'Escape':
469
+ this.handleEscapePressed();
470
+ break;
471
+ case 'ArrowUp':
472
+ if (e.altKey) {
473
+ this.handleAltUpArrowPressed();
474
+ }
475
+ else {
476
+ this.handleUpArrowPressed();
477
+ }
478
+ break;
479
+ case 'ArrowDown':
480
+ if (e.altKey) {
481
+ this.handleAltDownArrowPressed();
482
+ }
483
+ else {
484
+ this.handleDownArrowPressed();
485
+ }
486
+ break;
487
+ case 'Tab':
488
+ this.textInput.focus();
489
+ return;
490
+ default:
491
+ // Do nothing and allow propagation otherwise
492
+ return;
493
+ }
494
+ e.stopPropagation();
495
+ e.preventDefault();
496
+ }
497
+ /**
498
+ * Handler for `input` events in the text input box.
499
+ */
500
+ async handleTextBoxInput() {
501
+ this.enteredText = this.textInput.value;
502
+ this.setFilterText(this.textInput.value);
503
+ this.openOptionsMenu();
504
+ await this.updateComplete;
505
+ this.highlightFirstOption();
506
+ }
507
+ /**
508
+ * Handler for when the Enter key is pressed
509
+ */
510
+ handleEnterPressed() {
511
+ // Just open the options menu if it's currently closed
512
+ if (!this.open) {
513
+ this.openOptionsMenu();
514
+ return;
515
+ }
516
+ if (this.highlightedOption) {
517
+ // If an option is highlighted, select it
518
+ this.setSelectedOption(this.highlightedOption.id);
519
+ }
520
+ else if (this.behavior === 'freeform') {
521
+ // Otherwise, in the freeform behavior we just accept the current value regardless
522
+ this.setValue(this.enteredText);
523
+ }
524
+ // Close the options list if needed
525
+ if (!this.stayOpen)
526
+ this.open = false;
527
+ }
528
+ /**
529
+ * Handler for when the Escape key is pressed
530
+ */
531
+ handleEscapePressed() {
532
+ // Close the options menu if it's currently open
533
+ if (this.open) {
534
+ this.closeOptionsMenu();
535
+ return;
536
+ }
537
+ // Otherwise, deselect any selected option & clear any filter text
538
+ this.clearSelectedOption();
539
+ }
540
+ /**
541
+ * Handler for when the Up Arrow key is pressed (without modifiers).
542
+ * @see {@linkcode handleAltUpArrowPressed()} for behavior under the Alt modifier.
543
+ */
544
+ handleUpArrowPressed() {
545
+ if (!this.open)
546
+ this.openOptionsMenu();
547
+ this.highlightPreviousOption();
548
+ }
549
+ /**
550
+ * Handler for when the Down Arrow key is pressed (without modifiers).
551
+ * @see {@linkcode handleAltDownArrowPressed()} for behavior under the Alt modifier.
552
+ */
553
+ handleDownArrowPressed() {
554
+ if (!this.open)
555
+ this.openOptionsMenu();
556
+ this.highlightNextOption();
557
+ }
558
+ /**
559
+ * Handler for when the Alt + Up Arrow key combo is pressed
560
+ */
561
+ handleAltUpArrowPressed() {
562
+ this.closeOptionsMenu();
563
+ }
564
+ /**
565
+ * Handler for when the Alt + Down Arrow key combo is pressed
566
+ */
567
+ handleAltDownArrowPressed() {
568
+ this.openOptionsMenu();
569
+ }
570
+ /**
571
+ * Handler for clicks on the combo box input field or caret button.
572
+ */
573
+ handleComboBoxClick() {
574
+ this.toggleOptionsMenu();
575
+ }
576
+ /**
577
+ * Handler for when any part of the combo box receives focus.
578
+ */
579
+ handleFocus() {
580
+ if (this.behavior === 'select-only') {
581
+ this.caretButton.focus();
582
+ }
583
+ else {
584
+ this.textInput.focus();
585
+ }
586
+ this.hasFocus = true;
587
+ this.losingFocus = false;
588
+ }
589
+ /**
590
+ * Handler for when any part of the combo box loses focus.
591
+ */
592
+ handleBlur() {
593
+ this.hasFocus = false;
594
+ this.losingFocus = true;
595
+ setTimeout(() => {
596
+ var _a;
597
+ if (this.losingFocus && !((_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.activeElement)) {
598
+ this.losingFocus = false;
599
+ this.closeOptionsMenu();
600
+ if (this.behavior === 'freeform')
601
+ this.setValue(this.enteredText);
602
+ }
603
+ }, 0);
604
+ }
605
+ /**
606
+ * Handler for when the `value` of this component is changed externally
607
+ */
608
+ handleValueChanged() {
609
+ if (this.behavior !== 'freeform' && this.value !== null) {
610
+ // The value must correspond to a valid option or null
611
+ if (!this.getOptionFor(this.value))
612
+ this.clearSelectedOption();
613
+ }
614
+ }
615
+ /**
616
+ * Highlights the first option shown in the filtered list.
617
+ */
618
+ highlightFirstOption() {
619
+ this.setHighlightedOption(this.firstFilteredOption);
620
+ }
621
+ /**
622
+ * Highlights the last option shown in the filtered list.
623
+ */
624
+ highlightLastOption() {
625
+ this.setHighlightedOption(this.lastFilteredOption);
626
+ }
627
+ /**
628
+ * Highlights the option before the currently highlighted one in the list, or the last one
629
+ * if none is highlighted.
630
+ */
631
+ highlightPreviousOption() {
632
+ const { filteredOptions, lastFilteredIndex } = this;
633
+ // If no option is highlighted yet, highlight the last one
634
+ if (!this.highlightedOption) {
635
+ this.highlightLastOption();
636
+ return;
637
+ }
638
+ // Otherwise, move to the previous option (wrapping if needed)
639
+ const { highlightedIndex } = this;
640
+ const previousIndex = this.wrapArrowKeys && highlightedIndex === 0
641
+ ? lastFilteredIndex // Wrap around to the end
642
+ : Math.max(highlightedIndex - 1, 0);
643
+ this.setHighlightedOption(filteredOptions[previousIndex]);
644
+ }
645
+ /**
646
+ * Highlights the option after the currently highlighted one in the list, or the first one
647
+ * if none is highlighted.
648
+ */
649
+ highlightNextOption() {
650
+ const { filteredOptions, lastFilteredIndex } = this;
651
+ // If no option is highlighted yet, highlight the first one
652
+ if (!this.highlightedOption) {
653
+ this.highlightFirstOption();
654
+ return;
655
+ }
656
+ // Otherwise, move to the next option (wrapping if needed)
657
+ const { highlightedIndex } = this;
658
+ const nextIndex = this.wrapArrowKeys && highlightedIndex === lastFilteredIndex
659
+ ? 0 // Wrap back to the start
660
+ : Math.min(highlightedIndex + 1, lastFilteredIndex);
661
+ this.setHighlightedOption(filteredOptions[nextIndex]);
662
+ }
663
+ /**
664
+ * Highlights the given option and scrolls it into view if necessary.
665
+ * If `null` is provided, any current highlight will be cleared.
666
+ */
667
+ async setHighlightedOption(option) {
668
+ this.highlightedOption = option;
669
+ await this.updateComplete;
670
+ const { optionsList, highlightedElement } = this;
671
+ if (!highlightedElement)
672
+ return;
673
+ // TODO: Not ideal as this will trigger a reflow...
674
+ // But may not be an issue in practice given the highlight isn't changing in a hot loop.
675
+ // If we have issues with this let's see if we can hook up an IntersectionObserver.
676
+ const elmtRect = highlightedElement.getBoundingClientRect();
677
+ const listRect = optionsList.getBoundingClientRect();
678
+ if (elmtRect.top < listRect.top || elmtRect.bottom > listRect.bottom) {
679
+ highlightedElement.scrollIntoView({ block: 'nearest' });
680
+ }
681
+ }
682
+ /**
683
+ * Changes this combo box's selected option to the one matching the specified ID.
684
+ *
685
+ * Throws a `RangeError` if given an ID that does not correspond to any option
686
+ * held by this combo box.
687
+ */
688
+ setSelectedOption(id) {
689
+ var _a;
690
+ const option = this.getOptionFor(id);
691
+ if (!option)
692
+ throw new RangeError('Unknown option ID');
693
+ const prevValue = this.value;
694
+ this.value = option.id;
695
+ this.internals.setFormValue(this.value);
696
+ this.setTextValue(option.text);
697
+ if (this.value !== prevValue)
698
+ this.emitChangeEvent();
699
+ // Invoke the option's select callback if defined
700
+ (_a = option.onSelected) === null || _a === void 0 ? void 0 : _a.call(option, option);
701
+ }
702
+ /**
703
+ * Clears any currently selected option from this combo box, setting it to null
704
+ * and clearing any value in the text box.
705
+ */
706
+ clearSelectedOption() {
707
+ const prevValue = this.value;
708
+ this.value = null;
709
+ this.internals.setFormValue(this.value);
710
+ this.setTextValue('');
711
+ if (this.value !== prevValue)
712
+ this.emitChangeEvent();
713
+ }
714
+ /**
715
+ * Set this combo box's value to the given string if possible.
716
+ *
717
+ * In `freeform` behavior, this always succeeds.
718
+ *
719
+ * In other behavior modes, this method is identical to `setSelectedOption`,
720
+ * interpreting the input as an option ID and throwing an error if no such
721
+ * option exists.
722
+ *
723
+ * @see {@linkcode IAComboBox.setSelectedOption}
724
+ */
725
+ setValue(value) {
726
+ if (this.behavior === 'freeform') {
727
+ const prevValue = this.value;
728
+ this.value = value;
729
+ this.internals.setFormValue(this.value);
730
+ this.setTextValue(value);
731
+ if (this.value !== prevValue)
732
+ this.emitChangeEvent();
733
+ }
734
+ else {
735
+ this.setSelectedOption(value);
736
+ }
737
+ }
738
+ /**
739
+ * Changes the value of the text input box, and updates the filter accordingly.
740
+ */
741
+ setTextValue(value) {
742
+ this.textInput.value = value;
743
+ this.enteredText = value;
744
+ this.setFilterText(value);
745
+ }
746
+ openOptionsMenu() {
747
+ this.open = true;
748
+ this.emitToggleEvent();
749
+ }
750
+ closeOptionsMenu() {
751
+ this.open = false;
752
+ this.emitToggleEvent();
753
+ }
754
+ toggleOptionsMenu() {
755
+ this.open = !this.open;
756
+ this.emitToggleEvent();
757
+ }
758
+ updateFormValidity() {
759
+ if (this.required && !this.value) {
760
+ this.internals.setValidity({ valueMissing: true }, msg('A value is required'));
761
+ }
762
+ else {
763
+ // All good
764
+ this.internals.setValidity({});
765
+ }
766
+ }
767
+ emitChangeEvent() {
768
+ this.dispatchEvent(new CustomEvent('change', {
769
+ detail: this.value,
770
+ }));
771
+ }
772
+ emitToggleEvent() {
773
+ this.dispatchEvent(new CustomEvent('toggle', {
774
+ detail: this.open,
775
+ }));
776
+ }
777
+ //
778
+ // HELPERS
779
+ //
780
+ /**
781
+ * Sets the size and position of the options menu to match the size and position of
782
+ * the combo box widget. Prefers to position below the main widget, but will flip
783
+ * to the top if needed & if there's more room above.
784
+ */
785
+ positionOptionsMenu() {
786
+ const { mainWidgetRow, optionsList } = this;
787
+ const mainWidgetRect = mainWidgetRow.getBoundingClientRect();
788
+ const { innerHeight, scrollX, scrollY } = window;
789
+ const usableHeightAbove = mainWidgetRect.top;
790
+ const usableHeightBelow = innerHeight - mainWidgetRect.bottom;
791
+ // We still want to respect any CSS var specified by the consumer
792
+ const maxHeightVar = 'var(--comboBoxListMaxHeight, 250px)';
793
+ const optionsListStyles = {
794
+ top: `${mainWidgetRect.bottom + scrollY}px`,
795
+ left: `${mainWidgetRect.left + scrollX}px`,
796
+ width: `var(--comboBoxListWidth, ${mainWidgetRect.width}px)`,
797
+ maxHeight: `min(${usableHeightBelow}px, ${maxHeightVar})`,
798
+ };
799
+ Object.assign(optionsList.style, optionsListStyles);
800
+ // Wait a tick for it to appear, then check if we should flip it upwards instead
801
+ setTimeout(() => {
802
+ const listRect = optionsList.getBoundingClientRect();
803
+ const overflowingViewport = listRect.bottom >= innerHeight;
804
+ const moreSpaceAbove = usableHeightAbove > usableHeightBelow;
805
+ if (overflowingViewport && moreSpaceAbove) {
806
+ optionsList.style.top = 'auto';
807
+ optionsList.style.bottom = `${innerHeight - mainWidgetRect.top - scrollY}px`;
808
+ optionsList.style.maxHeight = `min(${usableHeightAbove}px, ${maxHeightVar})`;
809
+ }
810
+ }, 0);
811
+ }
812
+ /**
813
+ * A function to transform option & filter text based on the combo box's
814
+ * current case sensitivity.
815
+ */
816
+ get caseTransform() {
817
+ return this.caseSensitive ? STRING_IDENTITY_FN : STRING_LOWER_CASE_FN;
818
+ }
819
+ /**
820
+ * Sets the current filter text based on the provided string. The resulting filter
821
+ * text might not exactly match the provided value, depending on the current case
822
+ * sensitivity.
823
+ */
824
+ setFilterText(baseFilterText) {
825
+ const { caseTransform } = this;
826
+ this.filterText = caseTransform(baseFilterText);
827
+ }
828
+ /**
829
+ * Returns the combo box option having the given ID, or null if none exists.
830
+ */
831
+ getOptionFor(id) {
832
+ var _a;
833
+ return (_a = this.optionsByID.get(id)) !== null && _a !== void 0 ? _a : null;
834
+ }
835
+ /**
836
+ * Clears any previously-cached mapping of IDs to options, and rebuilds the
837
+ * map based on the current set of options.
838
+ */
839
+ rebuildOptionIDMap() {
840
+ this.optionsByID.clear();
841
+ for (const option of this.options) {
842
+ this.optionsByID.set(option.id, option);
843
+ }
844
+ }
845
+ /**
846
+ * Applies any required sort to the options and caches the result to be used
847
+ * at filter/display time.
848
+ */
849
+ rebuildSortedOptions() {
850
+ if (this.sort) {
851
+ this.optionsRespectingSortFlag = this.options.sort((a, b) => {
852
+ const aValue = this.optionFilteringValues.get(a);
853
+ const bValue = this.optionFilteringValues.get(b);
854
+ return aValue.localeCompare(bValue);
855
+ });
856
+ }
857
+ else {
858
+ this.optionsRespectingSortFlag = this.options;
859
+ }
860
+ }
861
+ /**
862
+ * Clears any previously-cached option filtering values, and rebuilds the
863
+ * map based on the current component properties.
864
+ */
865
+ rebuildOptionFilteringValues() {
866
+ this.optionFilteringValues.clear();
867
+ const { caseTransform } = this;
868
+ for (const option of this.options) {
869
+ const filteringValue = caseTransform(option.text);
870
+ this.optionFilteringValues.set(option, filteringValue);
871
+ }
872
+ }
873
+ /**
874
+ * Returns the filtered array of options by applying the specified filter function
875
+ * with the current filter text, up to the limit specified by `maxAutocompleteEntries`.
876
+ */
877
+ rebuildFilteredOptions() {
878
+ // We don't want to filter the results in select-only mode
879
+ const resolvedFilterOption = this.behavior === 'select-only' ? 'all' : this.filter;
880
+ const filterFn = typeof resolvedFilterOption === 'string'
881
+ ? FILTER_PRESETS[resolvedFilterOption]
882
+ : resolvedFilterOption;
883
+ const filtered = this.optionsRespectingSortFlag
884
+ .filter((opt) => {
885
+ const optionFilteringValue = this.optionFilteringValues.get(opt);
886
+ if (!optionFilteringValue)
887
+ return false;
888
+ return filterFn(this.filterText, optionFilteringValue, opt);
889
+ })
890
+ .slice(0, this.maxAutocompleteEntries);
891
+ this.filteredOptions = filtered;
892
+ }
893
+ /**
894
+ * The first option appearing in the filtered list, or null if there are none.
895
+ */
896
+ get firstFilteredOption() {
897
+ var _a;
898
+ return (_a = this.filteredOptions[0]) !== null && _a !== void 0 ? _a : null;
899
+ }
900
+ /**
901
+ * The last option appearing in the filtered list, or null if there are none.
902
+ */
903
+ get lastFilteredOption() {
904
+ var _a;
905
+ return (_a = this.filteredOptions[this.lastFilteredIndex]) !== null && _a !== void 0 ? _a : null;
906
+ }
907
+ /**
908
+ * The index of the last filtered option, or -1 if no options match the filter.
909
+ */
910
+ get lastFilteredIndex() {
911
+ return this.filteredOptions.length - 1;
912
+ }
913
+ /**
914
+ * The IAComboBoxOption that is currently selected, or null if none is selected.
915
+ */
916
+ get selectedOption() {
917
+ if (this.value == null)
918
+ return null;
919
+ return this.getOptionFor(this.value);
920
+ }
921
+ /**
922
+ * The index of the currently highlighted option in the filtered list, or -1 if
923
+ * no option is currently highlighted.
924
+ */
925
+ get highlightedIndex() {
926
+ if (!this.highlightedOption)
927
+ return -1;
928
+ return this.filteredOptions.indexOf(this.highlightedOption);
929
+ }
930
+ /**
931
+ * The HTML element representing the currently-highlighted option, or null if
932
+ * no option is highlighted.
933
+ */
934
+ get highlightedElement() {
935
+ if (!this.highlightedOption)
936
+ return null;
937
+ return this.shadowRoot.getElementById(this.highlightedOption.id);
938
+ }
939
+ static get styles() {
940
+ return css `
941
+ #label {
942
+ display: block;
943
+ width: fit-content;
944
+ }
945
+
946
+ #main-widget-row {
947
+ display: inline-flex;
948
+ align-items: stretch;
949
+ flex-wrap: nowrap;
950
+ background: white;
951
+ border: 1px solid black;
952
+ }
953
+
954
+ .focused #main-widget-row {
955
+ outline: black auto 1px;
956
+ outline-offset: 3px;
957
+ }
958
+
959
+ #text-input {
960
+ appearance: none;
961
+ background: transparent;
962
+ border: none;
963
+ padding: var(--comboBoxPadding, 5px);
964
+ width: 100%;
965
+ font-size: inherit;
966
+ outline: none;
967
+ }
968
+
969
+ #text-input:not(.editable) {
970
+ cursor: pointer;
971
+ }
972
+
973
+ #caret-button {
974
+ display: inline-flex;
975
+ align-items: center;
976
+ appearance: none;
977
+ background: transparent;
978
+ border: none;
979
+ padding: var(--comboBoxPadding, 5px);
980
+ outline: none;
981
+ cursor: pointer;
982
+ }
983
+
984
+ #options-list {
985
+ position: absolute;
986
+ list-style-type: none;
987
+ margin: 1px 0 0;
988
+ border: none;
989
+ padding: 0;
990
+ background: white;
991
+ max-height: 400px;
992
+ box-shadow: 0 0 1px 1px #ddd;
993
+ opacity: 0;
994
+ transition: opacity 0.125s ease;
995
+ }
996
+
997
+ #options-list.visible {
998
+ opacity: 1;
999
+ }
1000
+
1001
+ #empty-options {
1002
+ padding: 5px;
1003
+ color: #606060;
1004
+ font-style: italic;
1005
+ text-align: center;
1006
+ }
1007
+
1008
+ .caret {
1009
+ width: 14px;
1010
+ height: 14px;
1011
+ }
1012
+
1013
+ .option {
1014
+ padding: 5px;
1015
+ cursor: pointer;
1016
+ }
1017
+
1018
+ .highlight {
1019
+ background-color: #dbe0ff;
1020
+ }
1021
+
1022
+ .disabled,
1023
+ .disabled * {
1024
+ cursor: not-allowed !important;
1025
+ }
1026
+
1027
+ .sr-only {
1028
+ position: absolute !important;
1029
+ width: 1px !important;
1030
+ height: 1px !important;
1031
+ margin: -1px !important;
1032
+ padding: 0 !important;
1033
+ border: 0 !important;
1034
+ overflow: hidden !important;
1035
+ white-space: nowrap !important;
1036
+ clip: rect(1px, 1px, 1px, 1px) !important;
1037
+ -webkit-clip-path: inset(50%) !important;
1038
+ clip-path: inset(50%) !important;
1039
+ user-select: none !important;
1040
+ }
1041
+ `;
1042
+ }
1043
+ };
1044
+ IAComboBox.formAssociated = true;
1045
+ __decorate([
1046
+ property({ type: Array })
1047
+ ], IAComboBox.prototype, "options", void 0);
1048
+ __decorate([
1049
+ property({ type: String })
1050
+ ], IAComboBox.prototype, "placeholder", void 0);
1051
+ __decorate([
1052
+ property({ type: String })
1053
+ ], IAComboBox.prototype, "behavior", void 0);
1054
+ __decorate([
1055
+ property({ type: Number, attribute: 'max-autocomplete-entries' })
1056
+ ], IAComboBox.prototype, "maxAutocompleteEntries", void 0);
1057
+ __decorate([
1058
+ property({ type: String })
1059
+ ], IAComboBox.prototype, "filter", void 0);
1060
+ __decorate([
1061
+ property({ type: Boolean, reflect: true, attribute: 'case-sensitive' })
1062
+ ], IAComboBox.prototype, "caseSensitive", void 0);
1063
+ __decorate([
1064
+ property({ type: Boolean, reflect: true })
1065
+ ], IAComboBox.prototype, "sort", void 0);
1066
+ __decorate([
1067
+ property({ type: Boolean, reflect: true, attribute: 'wrap-arrow-keys' })
1068
+ ], IAComboBox.prototype, "wrapArrowKeys", void 0);
1069
+ __decorate([
1070
+ property({ type: Boolean, reflect: true, attribute: 'stay-open' })
1071
+ ], IAComboBox.prototype, "stayOpen", void 0);
1072
+ __decorate([
1073
+ property({ type: Boolean, reflect: true })
1074
+ ], IAComboBox.prototype, "open", void 0);
1075
+ __decorate([
1076
+ property({ type: Boolean, reflect: true })
1077
+ ], IAComboBox.prototype, "disabled", void 0);
1078
+ __decorate([
1079
+ property({ type: Boolean, reflect: true })
1080
+ ], IAComboBox.prototype, "required", void 0);
1081
+ __decorate([
1082
+ property({ type: String })
1083
+ ], IAComboBox.prototype, "value", void 0);
1084
+ __decorate([
1085
+ state()
1086
+ ], IAComboBox.prototype, "hasFocus", void 0);
1087
+ __decorate([
1088
+ state()
1089
+ ], IAComboBox.prototype, "highlightedOption", void 0);
1090
+ __decorate([
1091
+ state()
1092
+ ], IAComboBox.prototype, "enteredText", void 0);
1093
+ __decorate([
1094
+ state()
1095
+ ], IAComboBox.prototype, "filterText", void 0);
1096
+ __decorate([
1097
+ query('#main-widget-row')
1098
+ ], IAComboBox.prototype, "mainWidgetRow", void 0);
1099
+ __decorate([
1100
+ query('#text-input')
1101
+ ], IAComboBox.prototype, "textInput", void 0);
1102
+ __decorate([
1103
+ query('#caret-button')
1104
+ ], IAComboBox.prototype, "caretButton", void 0);
1105
+ __decorate([
1106
+ query('#options-list')
1107
+ ], IAComboBox.prototype, "optionsList", void 0);
1108
+ IAComboBox = __decorate([
1109
+ customElement('ia-combo-box')
1110
+ ], IAComboBox);
1111
+ export { IAComboBox };
1112
+ //# sourceMappingURL=ia-combo-box.js.map