@internetarchive/elements 0.1.0 → 0.1.1-webdev-8119.0

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