-
Notifications
You must be signed in to change notification settings - Fork 2
/
select.ts
731 lines (624 loc) · 20.3 KB
/
select.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
import { html } from 'lit';
import {
property,
query,
queryAssignedElements,
state,
} from 'lit/decorators.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import IgcSelectGroupComponent from './select-group.js';
import IgcSelectHeaderComponent from './select-header.js';
import IgcSelectItemComponent from './select-item.js';
import { styles } from './themes/select.base.css.js';
import { styles as shared } from './themes/shared/select.common.css.js';
import { all } from './themes/themes.js';
import { themeSymbol, themes } from '../../theming/theming-decorator.js';
import type { Theme } from '../../theming/types.js';
import {
addKeybindings,
altKey,
arrowDown,
arrowLeft,
arrowRight,
arrowUp,
endKey,
enterKey,
escapeKey,
homeKey,
spaceBar,
tabKey,
} from '../common/controllers/key-bindings.js';
import { addRootClickHandler } from '../common/controllers/root-click.js';
import { addRootScrollHandler } from '../common/controllers/root-scroll.js';
import { alternateName } from '../common/decorators/alternateName.js';
import { blazorAdditionalDependencies } from '../common/decorators/blazorAdditionalDependencies.js';
import { blazorSuppress } from '../common/decorators/blazorSuppress.js';
import { watch } from '../common/decorators/watch.js';
import { registerComponent } from '../common/definitions/register.js';
import {
IgcBaseComboBoxLikeComponent,
getActiveItems,
getItems,
getNextActiveItem,
getPreviousActiveItem,
setInitialSelectionState,
} from '../common/mixins/combo-box.js';
import type { AbstractConstructor } from '../common/mixins/constructor.js';
import { EventEmitterMixin } from '../common/mixins/event-emitter.js';
import { FormAssociatedRequiredMixin } from '../common/mixins/form-associated-required.js';
import { findElementFromEventPath, partNameMap } from '../common/util.js';
import { Validator, requiredValidator } from '../common/validators.js';
import IgcIconComponent from '../icon/icon.js';
import IgcInputComponent from '../input/input.js';
import IgcPopoverComponent, { type IgcPlacement } from '../popover/popover.js';
export interface IgcSelectEventMap {
igcChange: CustomEvent<IgcSelectItemComponent>;
igcBlur: CustomEvent<void>;
igcFocus: CustomEvent<void>;
igcOpening: CustomEvent<void>;
igcOpened: CustomEvent<void>;
igcClosing: CustomEvent<void>;
igcClosed: CustomEvent<void>;
}
/**
* Represents a control that provides a menu of options.
*
* @element igc-select
*
* @slot - Renders the list of select items.
* @slot prefix - Renders content before the input.
* @slot suffix - Renders content after input.
* @slot header - Renders a container before the list of options.
* @slot footer - Renders a container after the list of options.
* @slot helper-text - Renders content below the input.
* @slot toggle-icon - Renders content inside the suffix container.
* @slot toggle-icon-expanded - Renders content for the toggle icon when the component is in open state.
*
* @fires igcFocus - Emitted when the select gains focus.
* @fires igcBlur - Emitted when the select loses focus.
* @fires igcChange - Emitted when the control's checked state changes.
* @fires igcOpening - Emitted just before the list of options is opened.
* @fires igcOpened - Emitted after the list of options is opened.
* @fires igcClosing - Emitter just before the list of options is closed.
* @fires igcClosed - Emitted after the list of options is closed.
*
* @csspart list - The list of options wrapper.
* @csspart input - The encapsulated igc-input.
* @csspart label - The encapsulated text label.
* @csspart prefix - The prefix wrapper.
* @csspart suffix - The suffix wrapper.
* @csspart toggle-icon - The toggle icon wrapper.
* @csspart helper-text - The helper text wrapper.
*/
@themes(all, true)
@blazorAdditionalDependencies(
'IgcIconComponent, IgcInputComponent, IgcSelectGroupComponent, IgcSelectHeaderComponent, IgcSelectItemComponent'
)
export default class IgcSelectComponent extends FormAssociatedRequiredMixin(
EventEmitterMixin<
IgcSelectEventMap,
AbstractConstructor<IgcBaseComboBoxLikeComponent>
>(IgcBaseComboBoxLikeComponent)
) {
public static readonly tagName = 'igc-select';
public static styles = [styles, shared];
/* blazorSuppress */
public static register() {
registerComponent(
this,
IgcIconComponent,
IgcInputComponent,
IgcPopoverComponent,
IgcSelectGroupComponent,
IgcSelectHeaderComponent,
IgcSelectItemComponent
);
}
private declare readonly [themeSymbol]: Theme;
private _value!: string;
private _searchTerm = '';
private _lastKeyTime = 0;
private _rootClickController = addRootClickHandler(this, {
hideCallback: () => this._hide(true),
});
private _rootScrollController = addRootScrollHandler(this, {
hideCallback: () => this._hide(true),
});
private get isMaterialTheme() {
return this[themeSymbol] === 'material';
}
private get _activeItems() {
return Array.from(
getActiveItems<IgcSelectItemComponent>(
this,
IgcSelectItemComponent.tagName
)
);
}
@state()
protected _selectedItem: IgcSelectItemComponent | null = null;
@state()
protected _activeItem!: IgcSelectItemComponent;
protected override validators: Validator<this>[] = [requiredValidator];
@query(IgcInputComponent.tagName, true)
protected input!: IgcInputComponent;
@queryAssignedElements({ slot: 'helper-text' })
protected helperText!: Array<HTMLElement>;
@queryAssignedElements({ slot: 'suffix' })
protected inputSuffix!: Array<HTMLElement>;
@queryAssignedElements({ slot: 'prefix' })
protected inputPrefix!: Array<HTMLElement>;
@queryAssignedElements({ slot: 'toggle-icon-expanded' })
protected _expandedIconSlot!: Array<HTMLElement>;
protected get hasExpandedIcon() {
return this._expandedIconSlot.length > 0;
}
protected get hasPrefixes() {
return this.inputPrefix.length > 0;
}
protected get hasSuffixes() {
return this.inputSuffix.length > 0;
}
protected get hasHelperText() {
return this.helperText.length > 0;
}
/**
* The value attribute of the control.
* @attr
*/
@property()
public get value(): string {
return this._value;
}
/* @tsTwoWayProperty(true, "igcChange", "detail.value", false) */
public set value(value: string) {
this._updateValue(value);
const item = this.getItem(this._value);
item ? this.setSelectedItem(item) : this.clearSelectedItem();
}
/**
* The outlined attribute of the control.
* @attr
*/
@property({ reflect: true, type: Boolean })
public outlined = false;
/**
* The autofocus attribute of the control.
* @attr
*/
@property({ type: Boolean })
public override autofocus!: boolean;
/**
* The distance of the select dropdown from its input.
* @attr
*/
@property({ type: Number })
public distance = 0;
/**
* The label attribute of the control.
* @attr
*/
@property()
public label!: string;
/**
* The placeholder attribute of the control.
* @attr
*/
@property()
public placeholder!: string;
/** The preferred placement of the select dropdown around its input.
* @type {'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'right' | 'right-start' | 'right-end' | 'left' | 'left-start' | 'left-end'}
* @attr
*/
@property()
public placement: IgcPlacement = 'bottom-start';
/**
* @deprecated since version 4.3.0
* @hidden @internal @private
*/
public positionStrategy: 'absolute' | 'fixed' = 'fixed';
/**
* Determines the behavior of the component during scrolling of the parent container.
* @attr scroll-strategy
*/
@property({ attribute: 'scroll-strategy' })
public scrollStrategy: 'scroll' | 'block' | 'close' = 'scroll';
/**
* Whether the dropdown's width should be the same as the target's one.
* @deprecated since version 4.3.0
* @hidden @internal @private
* @attr same-width
*/
@property({ type: Boolean, attribute: 'same-width' })
public sameWidth = true;
/**
* Whether the component should be flipped to the opposite side of the target once it's about to overflow the visible area.
* When true, once enough space is detected on its preferred side, it will flip back.
* @deprecated since version 4.3.0
* @hidden @internal @private
* @attr
*/
@property({ type: Boolean })
public flip = true;
/** Returns the items of the igc-select component. */
public get items() {
return Array.from(
getItems<IgcSelectItemComponent>(this, IgcSelectItemComponent.tagName)
);
}
/** Returns the groups of the igc-select component. */
public get groups() {
return Array.from(
getItems<IgcSelectGroupComponent>(this, IgcSelectGroupComponent.tagName)
);
}
/** Returns the selected item from the dropdown or null. */
public get selectedItem() {
return this._selectedItem;
}
@watch('scrollStrategy', { waitUntilFirstUpdate: true })
protected scrollStrategyChanged() {
this._rootScrollController.update({ resetListeners: true });
}
@watch('open', { waitUntilFirstUpdate: true })
protected openChange() {
this._rootClickController.update();
this._rootScrollController.update();
}
constructor() {
super();
addKeybindings(this, {
skip: () => this.disabled,
bindingDefaults: { preventDefault: true, triggers: ['keydownRepeat'] },
})
.set([altKey, arrowDown], this.altArrowDown)
.set([altKey, arrowUp], this.altArrowUp)
.set(arrowDown, this.onArrowDown)
.set(arrowUp, this.onArrowUp)
.set(arrowLeft, this.onArrowUp)
.set(arrowRight, this.onArrowDown)
.set(tabKey, this.onTabKey, { preventDefault: false })
.set(escapeKey, this.onEscapeKey)
.set(homeKey, this.onHomeKey)
.set(endKey, this.onEndKey)
.set(spaceBar, this.onSpaceBarKey)
.set(enterKey, this.onEnterKey);
this.addEventListener('keydown', this.handleSearch);
this.addEventListener('focusin', this.handleFocusIn);
this.addEventListener('focusout', this.handleFocusOut);
}
protected override async firstUpdated() {
await this.updateComplete;
const selected = setInitialSelectionState(this.items);
if (this.value && !selected) {
this._selectItem(this.getItem(this.value), false);
}
if (selected && selected.value !== this.value) {
this._defaultValue = selected.value;
this._selectItem(selected, false);
}
if (this.autofocus) {
this.focus();
}
this.updateValidity();
}
private handleFocusIn({ relatedTarget }: FocusEvent) {
this._dirty = true;
if (this.contains(relatedTarget as Node) || this.open) {
return;
}
this.emitEvent('igcFocus');
}
private handleFocusOut({ relatedTarget }: FocusEvent) {
if (this.contains(relatedTarget as Node)) {
return;
}
this.checkValidity();
this.emitEvent('igcBlur');
}
private handleClick(event: MouseEvent) {
const item = findElementFromEventPath<IgcSelectItemComponent>(
IgcSelectItemComponent.tagName,
event
);
if (item && this._activeItems.includes(item)) {
this._selectItem(item);
}
}
private handleChange(item: IgcSelectItemComponent) {
return this.emitEvent('igcChange', { detail: item });
}
private handleSearch(event: KeyboardEvent) {
if (!/^.$/u.test(event.key)) {
return;
}
event.preventDefault();
const now = Date.now();
if (now - this._lastKeyTime > 500) {
this._searchTerm = '';
}
this._lastKeyTime = now;
this._searchTerm += event.key.toLocaleLowerCase();
const item = this._activeItems.find((item) =>
item.textContent?.trim().toLocaleLowerCase().startsWith(this._searchTerm)
);
if (item) {
this.open ? this.activateItem(item) : this._selectItem(item);
}
}
private onEnterKey() {
this.open && this._activeItem
? this._selectItem(this._activeItem)
: this.handleAnchorClick();
}
private onSpaceBarKey() {
if (!this.open) {
this.handleAnchorClick();
}
}
private onArrowDown() {
const item = getNextActiveItem(this.items, this._activeItem);
this.open ? this._navigateToActiveItem(item) : this._selectItem(item);
}
private onArrowUp() {
const item = getPreviousActiveItem(this.items, this._activeItem);
this.open ? this._navigateToActiveItem(item) : this._selectItem(item);
}
private altArrowDown() {
if (!this.open) {
this._show(true);
}
}
private async altArrowUp() {
if (this.open && (await this._hide(true))) {
this.input.focus();
}
}
protected async onEscapeKey() {
if (await this._hide(true)) {
this.input.focus();
}
}
private onTabKey(event: KeyboardEvent) {
if (this.open) {
event.preventDefault();
this._selectItem(this._activeItem);
this._hide(true);
}
}
protected onHomeKey() {
const item = this._activeItems.at(0);
this.open ? this._navigateToActiveItem(item) : this._selectItem(item);
}
protected onEndKey() {
const item = this._activeItems.at(-1);
this.open ? this._navigateToActiveItem(item) : this._selectItem(item);
}
/** Monitor input slot changes and request update */
protected inputSlotChanged() {
this.requestUpdate();
}
private activateItem(item: IgcSelectItemComponent) {
if (this._activeItem) {
this._activeItem.active = false;
}
this._activeItem = item;
this._activeItem.active = true;
}
private setSelectedItem(item: IgcSelectItemComponent) {
if (this._selectedItem) {
this._selectedItem.selected = false;
}
this._selectedItem = item;
this._selectedItem.selected = true;
return this._selectedItem;
}
private _selectItem(item?: IgcSelectItemComponent, emit = true) {
if (!item) {
this.clearSelectedItem();
this._updateValue();
return null;
}
const items = this.items;
const [previous, current] = [
items.indexOf(this._selectedItem!),
items.indexOf(item),
];
if (previous === current) {
return this._selectedItem;
}
const newItem = this.setSelectedItem(item);
this.activateItem(newItem);
this._updateValue(newItem.value);
if (emit) this.handleChange(newItem);
if (emit && this.open) this.input.focus();
if (emit && !this.keepOpenOnSelect) this._hide(true);
return this._selectedItem;
}
private _navigateToActiveItem(item?: IgcSelectItemComponent) {
if (item) {
this.activateItem(item);
item.scrollIntoView({ behavior: 'auto', block: 'nearest' });
}
}
private _updateValue(value?: string) {
this._value = value as string;
this.setFormValue(this._value ? this._value : null);
this.updateValidity();
this.setInvalidState();
}
private clearSelectedItem() {
if (this._selectedItem) {
this._selectedItem.selected = false;
}
this._selectedItem = null;
}
protected getItem(value: string) {
return this.items.find((item) => item.value === value);
}
private _stopPropagation(e: Event) {
e.stopPropagation();
}
/** Sets focus on the component. */
@alternateName('focusComponent')
public override focus(options?: FocusOptions) {
this.input.focus(options);
}
/** Removes focus from the component. */
@alternateName('blurComponent')
public override blur() {
this.input.blur();
super.blur();
}
/** Checks the validity of the control and moves the focus to it if it is not valid. */
public override reportValidity() {
const valid = super.reportValidity();
if (!valid) this.input.focus();
return valid;
}
/** Navigates to the item with the specified value. If it exists, returns the found item, otherwise - null. */
public navigateTo(value: string): IgcSelectItemComponent | null;
/** Navigates to the item at the specified index. If it exists, returns the found item, otherwise - null. */
public navigateTo(index: number): IgcSelectItemComponent | null;
/** Navigates to the specified item. If it exists, returns the found item, otherwise - null. */
@blazorSuppress()
public navigateTo(value: string | number): IgcSelectItemComponent | null {
const item =
typeof value === 'string' ? this.getItem(value) : this.items[value];
if (item) {
this._navigateToActiveItem(item);
}
return item ?? null;
}
/** Selects the item with the specified value. If it exists, returns the found item, otherwise - null. */
public select(value: string): IgcSelectItemComponent | null;
/** Selects the item at the specified index. If it exists, returns the found item, otherwise - null. */
public select(index: number): IgcSelectItemComponent | null;
/** Selects the specified item. If it exists, returns the found item, otherwise - null. */
@blazorSuppress()
public select(value: string | number): IgcSelectItemComponent | null {
const item =
typeof value === 'string' ? this.getItem(value) : this.items[value];
return item ? this._selectItem(item, false) : null;
}
/** Resets the current value and selection of the component. */
public clearSelection() {
this._updateValue();
this.clearSelectedItem();
}
protected renderInputSlots() {
const prefixName = this.hasPrefixes ? 'prefix' : '';
const suffixName = this.hasSuffixes ? 'suffix' : '';
return html`
<span slot=${prefixName}>
<slot name="prefix" @slotchange=${this.inputSlotChanged}></slot>
</span>
<span slot=${suffixName}>
<slot name="suffix" @slotchange=${this.inputSlotChanged}></slot>
</span>
`;
}
protected renderToggleIcon() {
const parts = partNameMap({ 'toggle-icon': true, filled: this.value! });
const iconHidden = this.open && this.hasExpandedIcon;
const iconExpandedHidden = !this.hasExpandedIcon || !this.open;
const openIcon = this.isMaterialTheme
? 'keyboard_arrow_up'
: 'arrow_drop_up';
const closeIcon = this.isMaterialTheme
? 'keyboard_arrow_down'
: 'arrow_drop_down';
return html`
<span slot="suffix" part=${parts} aria-hidden="true">
<slot
name="toggle-icon"
?hidden=${iconHidden}
@slotchange=${this.inputSlotChanged}
>
<igc-icon
name=${this.open ? openIcon : closeIcon}
collection="internal"
></igc-icon>
</slot>
<slot
name="toggle-icon-expanded"
?hidden=${iconExpandedHidden}
@slotchange=${this.inputSlotChanged}
></slot>
</span>
`;
}
protected renderHelperText() {
return html`
<div
id="helper-text"
part="helper-text"
slot="anchor"
?hidden=${!this.hasHelperText}
>
<slot name="helper-text" @slotchange=${this.inputSlotChanged}></slot>
</div>
`;
}
protected renderInputAnchor() {
const value = this.selectedItem?.textContent?.trim();
return html`
<igc-input
id="input"
slot="anchor"
role="combobox"
readonly
aria-controls="dropdown"
aria-describedby="helper-text"
aria-expanded=${this.open ? 'true' : 'false'}
exportparts="container: input, input: native-input, label, prefix, suffix"
tabIndex=${this.disabled ? -1 : 0}
value=${ifDefined(value)}
placeholder=${ifDefined(this.placeholder)}
label=${ifDefined(this.label)}
.disabled=${this.disabled}
.required=${this.required}
.invalid=${this.invalid}
.outlined=${this.outlined}
@click=${this.handleAnchorClick}
@igcFocus=${this._stopPropagation}
@igcBlur=${this._stopPropagation}
>
${this.renderInputSlots()} ${this.renderToggleIcon()}
</igc-input>
${this.renderHelperText()}
`;
}
protected renderDropdown() {
return html`<div part="base" .inert=${!this.open}>
<div
id="dropdown"
role="listbox"
part="list"
aria-labelledby="input"
@click=${this.handleClick}
>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</div>`;
}
protected override render() {
return html`<igc-popover
?open=${this.open}
flip
shift
same-width
strategy="fixed"
.offset=${this.distance}
.placement=${this.placement}
>${this.renderInputAnchor()} ${this.renderDropdown()}
</igc-popover>`;
}
}
declare global {
interface HTMLElementTagNameMap {
'igc-select': IgcSelectComponent;
}
}