-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathvscode-multi-select.ts
More file actions
486 lines (416 loc) · 13.3 KB
/
Copy pathvscode-multi-select.ts
File metadata and controls
486 lines (416 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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
import {html, LitElement, nothing, TemplateResult} from 'lit';
import {property, query} from 'lit/decorators.js';
import {ifDefined} from 'lit/directives/if-defined.js';
import {customElement} from '../includes/VscElement.js';
import {chevronDownIcon} from '../includes/vscode-select/template-elements.js';
import {VscodeSelectBase} from '../includes/vscode-select/vscode-select-base.js';
import styles from './vscode-multi-select.styles.js';
import {AssociatedFormControl} from '../includes/AssociatedFormControl.js';
export type VscMultiSelectCreateOptionEvent = CustomEvent<{value: string}>;
/**
* Allows to select multiple items from a list of options.
*
* When participating in a form, it supports the `:invalid` pseudo class. Otherwise the error styles
* can be applied through the `invalid` property.
*
* @tag vscode-multi-select
*
* @prop {boolean} invalid
* @attr {boolean} invalid
* @attr name - Name which is used as a variable name in the data of the form-container.
*
* @cssprop [--dropdown-z-index=2]
* @cssprop [--vscode-badge-background=#616161]
* @cssprop [--vscode-badge-foreground=#f8f8f8]
* @cssprop [--vscode-settings-dropdownBorder=#3c3c3c]
* @cssprop [--vscode-settings-checkboxBackground=#313131]
* @cssprop [--vscode-settings-dropdownBackground=#313131]
* @cssprop [--vscode-settings-dropdownForeground=#cccccc]
* @cssprop [--vscode-settings-dropdownListBorder=#454545]
* @cssprop [--vscode-focusBorder=#0078d4]
* @cssprop [--vscode-foreground=#cccccc]
* @cssprop [--vscode-font-family=sans-serif]
* @cssprop [--vscode-font-size=13px]
* @cssprop [--vscode-font-weight=normal]
* @cssprop [--vscode-inputValidation-errorBackground=#5a1d1d]
* @cssprop [--vscode-inputValidation-errorBorder=#be1100]
* @cssprop [--vscode-list-activeSelectionBackground=#04395e]
* @cssprop [--vscode-list-activeSelectionForeground=#ffffff]
* @cssprop [--vscode-list-focusOutline=#0078d4]
* @cssprop [--vscode-list-focusHighlightForeground=#2aaaff]
* @cssprop [--vscode-list-highlightForeground=#2aaaff]
* @cssprop [--vscode-list-hoverBackground=#2a2d2e]
* @cssprop [--vscode-list-hoverForeground=#ffffff]
*/
@customElement('vscode-multi-select')
export class VscodeMultiSelect
extends VscodeSelectBase
implements AssociatedFormControl
{
static override styles = styles;
/** @internal */
static override shadowRootOptions: ShadowRootInit = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
static formAssociated = true;
@property({type: Array, attribute: 'default-value'})
defaultValue: string[] = [];
@property({type: Boolean, reflect: true})
required = false;
@property({reflect: true})
name: string | undefined = undefined;
/**
* Label suffix used in the selected-count badge (e.g. "3 Selected").
* Override to localise the badge text.
*/
@property({attribute: 'selected-text'})
selectedText = 'Selected';
/**
* Tooltip for the "select all" button in the dropdown controls.
*/
@property({attribute: 'select-all-title'})
selectAllTitle = 'Select all';
/**
* Tooltip for the "deselect all" button in the dropdown controls.
*/
@property({attribute: 'deselect-all-title'})
deselectAllTitle = 'Deselect all';
/**
* Label for the accept/OK button in the dropdown controls.
*/
@property({attribute: 'accept-button-text'})
acceptButtonText = 'OK';
@property({type: Array, attribute: false})
set selectedIndexes(val: number[]) {
this._opts.selectedIndexes = val;
}
get selectedIndexes(): number[] {
return this._opts.selectedIndexes;
}
@property({type: Array})
set value(val: string[]) {
this._opts.multiSelectValue = val;
if (this._opts.selectedIndexes.length > 0) {
this._requestedValueToSetLater = [];
} else {
this._requestedValueToSetLater = Array.isArray(val) ? val : [val];
}
this._setFormValue();
this._manageRequired();
}
get value(): string[] {
return this._opts.multiSelectValue;
}
get form() {
return this._internals.form;
}
/** @internal */
get type() {
return 'select-multiple';
}
get validity(): ValidityState {
return this._internals.validity;
}
get validationMessage(): string {
return this._internals.validationMessage;
}
get willValidate() {
return this._internals.willValidate;
}
checkValidity(): boolean {
return this._internals.checkValidity();
}
reportValidity(): boolean {
return this._internals.reportValidity();
}
selectAll() {
this._opts.selectAll();
}
selectNone() {
this._opts.selectNone();
}
private _internals: ElementInternals;
constructor() {
super();
this._opts.multiSelect = true;
this._internals = this.attachInternals();
}
override connectedCallback(): void {
super.connectedCallback();
this.updateComplete.then(() => {
this._setDefaultValue();
this._manageRequired();
});
}
/** @internal */
formResetCallback(): void {
this.updateComplete.then(() => {
this.value = this.defaultValue;
});
}
/** @internal */
formStateRestoreCallback(
state: FormData,
_mode: 'restore' | 'autocomplete'
): void {
const entries = Array.from(state.entries()).map((e) => String(e[1]));
this.updateComplete.then(() => {
this.value = entries;
});
}
@query('.face')
private _faceElement!: HTMLDivElement;
private _setDefaultValue() {
if (Array.isArray(this.defaultValue) && this.defaultValue.length > 0) {
const val = this.defaultValue.map((v) => String(v));
this.value = val;
}
}
protected override _dispatchChangeEvent(): void {
super._dispatchChangeEvent();
}
protected override _onFaceClick(): void {
super._onFaceClick();
this._opts.activeIndex = 0;
}
protected override _toggleComboboxDropdown(): void {
super._toggleComboboxDropdown();
this._opts.activeIndex = -1;
}
protected override _manageRequired() {
const {value} = this;
if (value.length === 0 && this.required) {
this._internals.setValidity(
{
valueMissing: true,
},
'Please select an item in the list.',
this._faceElement
);
} else {
this._internals.setValidity({});
}
}
private _setFormValue() {
const fd = new FormData();
this._values.forEach((v) => {
fd.append(this.name ?? '', v);
});
this._internals.setFormValue(fd);
}
private _requestedValueToSetLater: string[] = [];
protected override async _createAndSelectSuggestedOption() {
super._createAndSelectSuggestedOption();
const nextIndex = this._createSuggestedOption();
await this.updateComplete;
this.selectedIndexes = [...this.selectedIndexes, nextIndex];
this._dispatchChangeEvent();
const opCreateEvent: VscMultiSelectCreateOptionEvent = new CustomEvent(
'vsc-multi-select-create-option',
{detail: {value: this._opts.getOptionByIndex(nextIndex)?.value ?? ''}}
);
this.dispatchEvent(opCreateEvent);
this.open = false;
this._isPlaceholderOptionActive = false;
}
//#region event handlers
protected override _onSlotChange(): void {
super._onSlotChange();
if (this._requestedValueToSetLater.length > 0) {
this._opts.expandMultiSelection(this._requestedValueToSetLater);
this._requestedValueToSetLater = this._requestedValueToSetLater.filter(
(v) => this._opts.findOptionIndex(v) === -1
);
}
}
protected override _onOptionClick = (ev: MouseEvent) => {
const composedPath = ev.composedPath();
const optEl = composedPath.find((et) => {
if ('matches' in et) {
return (et as HTMLElement).matches('li.option');
}
return false;
});
if (!optEl) {
return;
}
const isPlaceholderOption = (optEl as HTMLElement).classList.contains(
'placeholder'
);
if (isPlaceholderOption) {
this._createAndSelectSuggestedOption();
return;
}
const index = Number((optEl as HTMLElement).dataset.index);
this._opts.toggleOptionSelected(index);
this._setFormValue();
this._manageRequired();
this._dispatchChangeEvent();
};
protected override _onEnterKeyDown(ev: KeyboardEvent): void {
super._onEnterKeyDown(ev);
if (!this.open) {
this._opts.filterPattern = '';
this.open = true;
} else {
if (this._isPlaceholderOptionActive) {
this._createAndSelectSuggestedOption();
} else {
this._opts.toggleActiveMultiselectOption();
this._setFormValue();
this._manageRequired();
this._dispatchChangeEvent();
}
}
}
private _onMultiAcceptClick(): void {
this.open = false;
}
private _onMultiDeselectAllClick(): void {
this._opts.selectedIndexes = [];
this._values = [];
this._options = this._options.map((op) => ({...op, selected: false}));
this._manageRequired();
this._dispatchChangeEvent();
}
private _onMultiSelectAllClick(): void {
this._opts.selectedIndexes = [];
this._values = [];
this._options = this._options.map((op) => ({...op, selected: true}));
this._options.forEach((op, index) => {
this._selectedIndexes.push(index);
this._values.push(op.value);
this._dispatchChangeEvent();
});
this._setFormValue();
this._manageRequired();
}
protected override _onComboboxInputBlur(): void {
super._onComboboxInputBlur();
this._opts.filterPattern = '';
}
//#endregion
//#region render functions
private _renderLabel() {
switch (this._opts.selectedIndexes.length) {
case 0:
return html`<span class="select-face-badge no-item">0 ${this.selectedText}</span>`;
default:
return html`<span class="select-face-badge"
>${this._opts.selectedIndexes.length} ${this.selectedText}</span
>`;
}
}
protected override _renderComboboxFace(): TemplateResult {
const activeDescendant =
this._opts.activeIndex > -1 ? `op-${this._opts.activeIndex}` : '';
const expanded = this.open ? 'true' : 'false';
return html`
<div class="combobox-face face">
${this._opts.multiSelect ? this._renderLabel() : nothing}
<input
aria-activedescendant=${activeDescendant}
aria-autocomplete="list"
aria-controls="select-listbox"
aria-expanded=${expanded}
aria-haspopup="listbox"
aria-label=${ifDefined(this.label)}
class="combobox-input"
role="combobox"
spellcheck="false"
type="text"
autocomplete="off"
.value=${this._opts.filterPattern}
@focus=${this._onComboboxInputFocus}
@blur=${this._onComboboxInputBlur}
@input=${this._onComboboxInputInput}
@click=${this._onComboboxInputClick}
@keydown=${this._onComboboxInputSpaceKeyDown}
/>
<button
aria-label=${this.openButtonAriaLabel}
class="combobox-button"
type="button"
@click=${this._onComboboxButtonClick}
@keydown=${this._onComboboxButtonKeyDown}
tabindex="-1"
>
${chevronDownIcon}
</button>
</div>
`;
}
protected override _renderSelectFace(): TemplateResult {
const activeDescendant =
this._opts.activeIndex > -1 ? `op-${this._opts.activeIndex}` : '';
const expanded = this.open ? 'true' : 'false';
return html`
<div
aria-activedescendant=${ifDefined(
this._opts.multiSelect ? undefined : activeDescendant
)}
aria-controls="select-listbox"
aria-expanded=${ifDefined(
this._opts.multiSelect ? undefined : expanded
)}
aria-haspopup="listbox"
aria-label=${ifDefined(this.label ?? undefined)}
class="select-face face multiselect"
@click=${this._onFaceClick}
.tabIndex=${this.disabled ? -1 : 0}
>
${this._renderLabel()} ${chevronDownIcon}
</div>
`;
}
protected override _renderDropdownControls(): TemplateResult {
return this._filteredOptions.length > 0
? html`
<div class="dropdown-controls">
<button
type="button"
@click=${this._onMultiSelectAllClick}
title=${this.selectAllTitle}
class="action-icon"
id="select-all"
>
<vscode-icon name="checklist"></vscode-icon>
</button>
<button
type="button"
@click=${this._onMultiDeselectAllClick}
title=${this.deselectAllTitle}
class="action-icon"
id="select-none"
>
<vscode-icon name="clear-all"></vscode-icon>
</button>
<vscode-button
class="button-accept"
@click=${this._onMultiAcceptClick}
>${this.acceptButtonText}</vscode-button
>
</div>
`
: html`${nothing}`;
}
override render(): TemplateResult {
return html`
<div class="multi-select">
<slot class="main-slot" @slotchange=${this._onSlotChange}></slot>
${this.combobox ? this._renderComboboxFace() : this._renderSelectFace()}
${this._renderDropdown()}
</div>
`;
}
//#endregion
}
declare global {
interface HTMLElementTagNameMap {
'vscode-multi-select': VscodeMultiSelect;
}
interface GlobalEventHandlersEventMap {
'vsc-multi-select-create-option': VscMultiSelectCreateOptionEvent;
}
}