@reliability-design/web 1.4.3 → 1.4.4

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.
@@ -1,1170 +1,1237 @@
1
- import { LitElement, html, css, nothing, PropertyValues } from "lit";
2
- import { customElement, property, state, query } from "lit/decorators.js";
3
- import { repeat } from "lit/directives/repeat.js";
4
- import "@reliability-design/icons/rel-icon";
5
- import "../rel-chip/rel-chip.js";
6
- import "../rel-checkbox/rel-checkbox.js";
7
- import type { FieldLabelStyle } from "../rel-textfield/rel-textfield.js";
8
-
9
- export type SelectState = "default" | "error" | "disabled";
10
- export type SelectSize = "small" | "medium" | "large";
11
- export type SelectBorder = "rounded" | "sharp";
12
- /** Alias of the shared field type — kept so existing imports keep resolving. */
13
- export type SelectLabelStyle = FieldLabelStyle;
14
-
15
- export interface SelectOptionObject {
16
- value: string;
17
- label?: string;
18
- supportingText?: string;
19
- /** rel-icon name rendered as a prefix (leading icon) on the menu item. */
20
- icon?: string;
21
- }
22
- export type SelectOption = string | SelectOptionObject;
23
-
24
- interface NormalizedOption {
25
- value: string;
26
- label: string;
27
- supportingText: string;
28
- icon: string;
29
- }
30
-
31
- function normalizeOption(o: SelectOption): NormalizedOption {
32
- if (typeof o === "string") return { value: o, label: o, supportingText: "", icon: "" };
33
- return {
34
- value: o.value,
35
- label: o.label ?? o.value,
36
- supportingText: o.supportingText ?? "",
37
- icon: o.icon ?? "",
38
- };
39
- }
40
-
41
- @customElement("rel-select")
42
- export class RelSelect extends LitElement {
43
- @property({ type: String }) label: string = "";
44
-
45
- // Lit's default attribute name is the property name fully lowercased (no
46
- // hyphens) — e.g. labelStyle would otherwise only respond to "labelstyle".
47
- // Every multi-word property below gets an explicit kebab-case `attribute`
48
- // so it works the way HTML usage actually looks.
49
- @property({ type: String, attribute: "label-style", reflect: true })
50
- labelStyle: SelectLabelStyle = "default";
51
-
52
- /**
53
- * Accessible name for the trigger. Required when `labelStyle="none"`, since no
54
- * `<label>` renders and a placeholder is not a valid naming mechanism.
55
- */
56
- @property({ type: String, attribute: "field-aria-label" }) fieldAriaLabel?: string;
57
- /** IDREF list of external element(s) naming the trigger. Wins over `fieldAriaLabel`. */
58
- @property({ type: String, attribute: "field-aria-labelledby" }) fieldAriaLabelledby?: string;
59
-
60
- @property({ type: Array }) options: SelectOption[] = [];
61
-
62
- /** Enables multi-select: selected values render as removable chips and options as checkboxes. */
63
- @property({ type: Boolean }) multiple: boolean = false;
64
-
65
- /** Selected value — single-select mode only. */
66
- @property({ type: String }) selected: string = "";
67
-
68
- /** Selected values — multi-select mode only. */
69
- @property({ type: Array, attribute: "selected-values" }) selectedValues: string[] = [];
70
-
71
- @property({ type: String }) state: SelectState = "default";
72
-
73
- @property({ type: String, attribute: "supporting-text" }) supportingText: string = "";
74
-
75
- @property({ type: String, reflect: true }) size: SelectSize = "medium";
76
-
77
- @property({ type: String }) border: SelectBorder = "rounded";
78
-
79
- @property({ type: String, attribute: "left-icon" }) leftIcon: string = "";
80
-
81
- @property({ type: String, attribute: "right-icon" }) rightIcon: string = "";
82
-
83
- @property({ type: String }) placeholder: string = "Select option";
84
-
85
- @property({ type: String, attribute: "search-placeholder" }) searchPlaceholder: string = "Search option";
86
-
87
- @property({ type: String, attribute: "select-all-label" }) selectAllLabel: string = "Select all";
88
-
89
- /**
90
- * Optional hard cap on visible chips. By default (no cap) the visible
91
- * count adapts to the trigger's width: chips collapse into the "+N" badge
92
- * one by one instead of wrapping to a second line.
93
- */
94
- @property({ type: Number, attribute: "max-visible-chips" }) maxVisibleChips: number = Infinity;
95
-
96
- // Boolean props default true and toggled off via ="false" are a classic Lit
97
- // trap: for type:Boolean, attribute *presence* (not its string value)
98
- // decides truthiness, so searchable="false" would still read as true. Named
99
- // negatively instead, so the natural HTML idiom — just adding the bare
100
- // attribute, no value — does what it looks like it does.
101
- /** Hides the in-panel search field. Figma's "Single Option" dropdown has no search bar at all — use this for short, non-searchable lists. */
102
- @property({ type: Boolean, attribute: "no-search" }) noSearch: boolean = false;
103
-
104
- @state() private open = false;
105
- @state() private highlightedIndex = -1;
106
- @state() private panelStyle = "";
107
- @state() private searchValue = "";
108
- @state() private internalState: "default" | "focused" = "default";
109
-
110
- /** How many chips currently fit in the trigger width (width-adaptive). */
111
- @state() private visibleChipCount = Infinity;
112
-
113
- @query(".select-trigger") private triggerEl!: HTMLButtonElement;
114
- @query(".search-input") private searchInputEl!: HTMLInputElement;
115
- @query(".select-listbox") private listboxEl!: HTMLDivElement;
116
- @query(".select-value") private valueEl!: HTMLElement;
117
- @query(".select-chips-measure") private chipsMeasureEl!: HTMLElement;
118
-
119
- /** Must match the `gap` of .select-chips / .select-chips-measure. */
120
- private static readonly CHIP_GAP = 6;
121
-
122
- private chipResizeObserver?: ResizeObserver;
123
-
124
- private uniqueId = `select-${Math.random().toString(36).slice(2)}`;
125
-
126
- static styles = css`
127
- :host {
128
- color: var(--rel-text-default);
129
- display: block;
130
- font-family: var(--rel-fonts-font-family);
131
- width: 100%;
132
- }
133
-
134
- .select-wrapper {
135
- display: flex;
136
- flex-direction: column;
137
- gap: var(--rel-spacing-2xs);
138
- width: 100%;
139
- }
140
-
141
- /* Dims everything inside uniformly (label, trigger, icons, value text,
142
- supporting text) — matches rel-button's :host([disabled]) opacity
143
- approach instead of relying on one barely-different background tint. */
144
- .select-wrapper.disabled {
145
- opacity: 0.5;
146
- }
147
-
148
- .select-label {
149
- color: var(--rel-select-label-color, var(--rel-text-label));
150
-
151
- font-family: var(--rel-body-sm-regular-font-family);
152
-
153
- font-weight: var(--rel-body-sm-regular-font-weight);
154
-
155
- font-size: var(--rel-body-sm-regular-font-size);
156
-
157
- line-height: var(--rel-body-sm-regular-line-height);
158
-
159
- letter-spacing: var(--rel-body-sm-regular-letter-spacing);
160
-
161
- }
162
-
163
- /* ── labelStyle="none" ──
164
- No label renders. An empty spacer holds the label row's full height so the
165
- trigger still bottom-aligns with labelled siblings in a form row.
166
- The reserve covers label line-height + the wrapper gap, and the negative
167
- margin cancels the flex gap that would otherwise sit below it — so
168
- --rel-field-label-reserve: 0 collapses the row to genuinely zero
169
- (toolbars, table cells), not just to the leftover gap. */
170
- .label-reserve {
171
- flex: none;
172
- height: var(
173
- --rel-field-label-reserve,
174
- calc(var(--rel-body-sm-regular-line-height) + var(--rel-spacing-2xs))
175
- );
176
- margin-bottom: calc(-1 * var(--rel-spacing-2xs));
177
- }
178
-
179
- /* Error only colors the border/focus ring and the supporting text below
180
- the field — label, floating label, placeholder, and icons stay normal. */
181
-
182
- /* Container */
183
- .select-container {
184
- position: relative;
185
- }
186
-
187
- /* Trigger button — visually a text field, semantically a combobox button */
188
- .select-trigger {
189
- display: flex;
190
- align-items: center;
191
- width: 100%;
192
- box-sizing: border-box;
193
- gap: 8px;
194
- background: var(--rel-select-bg, var(--rel-bg-neutral));
195
- border: 1px solid var(--rel-select-border-default, var(--rel-border-default));
196
- cursor: pointer;
197
- font-family: inherit;
198
- transition: border-color 0.15s ease;
199
- text-align: left;
200
- }
201
-
202
- .border-rounded .select-trigger {
203
- border-radius: var(--rel-select-radius, var(--rel-border-radius-xs));
204
- }
205
-
206
- .border-sharp .select-trigger {
207
- border-radius: 0;
208
- }
209
-
210
- .select-trigger:focus-visible,
211
- .select-wrapper.open .select-trigger {
212
- outline: none;
213
- border-color: var(--rel-select-border-focus, var(--rel-border-strong));
214
- }
215
-
216
- .select-wrapper.error .select-trigger {
217
- border-color: var(--rel-select-border-error, var(--rel-border-danger));
218
- }
219
-
220
- .select-wrapper.disabled .select-trigger {
221
- cursor: not-allowed;
222
- background: var(--rel-select-bg-disabled, var(--rel-bg-neutral-elevated-1));
223
- border-color: var(--rel-select-border-default, var(--rel-border-default));
224
- }
225
-
226
- /* Sizes */
227
- .select-wrapper.small .select-trigger {
228
- padding: var(--rel-spacing-xs) var(--rel-spacing-sm);
229
- min-height: 40px;
230
- font-family: var(--rel-body-sm-regular-font-family);
231
- font-weight: var(--rel-body-sm-regular-font-weight);
232
- font-size: var(--rel-body-sm-regular-font-size);
233
- line-height: var(--rel-body-sm-regular-line-height);
234
- letter-spacing: var(--rel-body-sm-regular-letter-spacing);
235
- }
236
-
237
- .select-wrapper.medium .select-trigger {
238
- padding: 12px;
239
- min-height: 48px;
240
- font-family: var(--rel-body-md-regular-font-family);
241
- font-weight: var(--rel-body-md-regular-font-weight);
242
- font-size: var(--rel-body-md-regular-font-size);
243
- line-height: var(--rel-body-md-regular-line-height);
244
- letter-spacing: var(--rel-body-md-regular-letter-spacing);
245
- }
246
-
247
- .select-wrapper.large .select-trigger {
248
- padding: var(--rel-spacing-md);
249
- min-height: 56px;
250
- font-family: var(--rel-body-lg-regular-font-family);
251
- font-weight: var(--rel-body-lg-regular-font-weight);
252
- font-size: var(--rel-body-lg-regular-font-size);
253
- line-height: var(--rel-body-lg-regular-line-height);
254
- letter-spacing: var(--rel-body-lg-regular-letter-spacing);
255
- }
256
-
257
- /* Icons */
258
- .select-trigger .icon {
259
- display: flex;
260
- align-items: center;
261
- flex-shrink: 0;
262
- color: var(--rel-select-icon-color, var(--rel-text-default));
263
- }
264
-
265
- .select-trigger .icon.chevron {
266
- transition: transform 0.15s ease;
267
- }
268
-
269
- .select-wrapper.open .icon.chevron {
270
- transform: rotate(180deg);
271
- }
272
-
273
- .select-wrapper.disabled .icon {
274
- color: var(--rel-text-disabled);
275
- }
276
-
277
- /* Value area */
278
- .select-value {
279
- flex: 1;
280
- min-width: 0;
281
- display: flex;
282
- align-items: center;
283
- gap: 6px;
284
- flex-wrap: nowrap;
285
- color: var(--rel-select-value-color, var(--rel-text-default));
286
- overflow: hidden;
287
- }
288
-
289
- .select-value.placeholder {
290
- color: var(--rel-select-placeholder-color, var(--rel-text-placeholder));
291
- }
292
-
293
- .select-wrapper.disabled .select-value.placeholder {
294
- color: var(--rel-select-placeholder-disabled-color, var(--rel-text-disabled));
295
- }
296
-
297
- .select-value-text {
298
- overflow: hidden;
299
- text-overflow: ellipsis;
300
- white-space: nowrap;
301
- }
302
-
303
- /* Chips never wrap — the number of rendered chips adapts to the
304
- available width instead (see computeVisibleChips), collapsing the
305
- remainder into a trailing "+N" chip. overflow:hidden guards the one
306
- frame between a resize and the recomputation catching up. */
307
- .select-chips {
308
- display: flex;
309
- align-items: center;
310
- gap: 6px;
311
- flex-wrap: nowrap;
312
- min-width: 0;
313
- overflow: hidden;
314
- }
315
-
316
- /* Invisible copy of ALL selected chips (plus a worst-case "+N" chip),
317
- laid out unconstrained so computeVisibleChips can read each chip's
318
- natural width — including chips currently collapsed into "+N", whose
319
- widths are needed again when the field grows. */
320
- .select-chips-measure {
321
- position: absolute;
322
- top: 0;
323
- left: 0;
324
- display: flex;
325
- align-items: center;
326
- gap: 6px;
327
- width: max-content;
328
- visibility: hidden;
329
- pointer-events: none;
330
- }
331
-
332
- /* rel-chip's outer element is a tabindex="0" span, not a native button —
333
- a disabled native <button> ancestor doesn't suppress clicks on that
334
- automatically the way it would for a nested native form control, so
335
- this has to be switched off explicitly. The cursor still correctly
336
- falls through to the disabled trigger underneath. */
337
- .select-wrapper.disabled .select-chips {
338
- pointer-events: none;
339
- }
340
-
341
- /* Floating label — single element that animates between resting (inside,
342
- at the value position) and floated (small, on the border line), same
343
- mechanism as rel-textfield's [floatinglabel]. */
344
- .floating-label {
345
- position: absolute;
346
- left: 12px;
347
- top: 50%;
348
- transform: translateY(-50%);
349
- background: var(--rel-select-bg, var(--rel-bg-neutral));
350
- padding: 0 4px;
351
- color: var(--rel-select-placeholder-color, var(--rel-text-placeholder));
352
- pointer-events: none;
353
- z-index: 1;
354
- white-space: nowrap;
355
- transition: top 0.15s ease, left 0.15s ease, font-size 0.15s ease, color 0.15s ease;
356
- font-family: var(--rel-body-md-regular-font-family);
357
- font-weight: var(--rel-body-md-regular-font-weight);
358
- font-size: var(--rel-body-md-regular-font-size);
359
- line-height: var(--rel-body-md-regular-line-height);
360
- letter-spacing: var(--rel-body-md-regular-letter-spacing);
361
- }
362
-
363
- .floating-label.has-left-icon {
364
- left: 40px;
365
- }
366
-
367
- .select-wrapper.focused .floating-label,
368
- .select-wrapper.has-value .floating-label,
369
- .select-wrapper.open .floating-label {
370
- top: 0;
371
- left: 12px;
372
- font-size: var(--rel-body-sm-medium-font-size);
373
- line-height: var(--rel-body-sm-medium-line-height);
374
- letter-spacing: var(--rel-body-sm-medium-letter-spacing);
375
- font-weight: var(--rel-body-xs-medium-font-weight);
376
- color: var(--rel-select-label-color, var(--rel-text-label));
377
- }
378
-
379
- /* The real placeholder hides while the float-label rests in its spot,
380
- and fades in once the label has moved up to the border. */
381
- .select-wrapper.floating .select-value.placeholder {
382
- opacity: 0;
383
- transition: opacity 0.1s ease;
384
- }
385
-
386
- .select-wrapper.floating.focused .select-value.placeholder,
387
- .select-wrapper.floating.open .select-value.placeholder {
388
- opacity: 1;
389
- }
390
-
391
- /* Supporting text */
392
- .select-support {
393
- margin-top: var(--rel-spacing-3xs);
394
- font-size: 13px;
395
- color: var(--rel-select-supporting-color, var(--rel-text-caption));
396
- }
397
-
398
- .select-support.error {
399
- color: var(--rel-text-danger);
400
- }
401
-
402
- /* ── Dropdown listbox ── */
403
- .select-listbox {
404
- position: fixed;
405
- z-index: 1001;
406
- display: none;
407
- box-sizing: border-box;
408
- background: var(--rel-select-bg, var(--rel-bg-neutral));
409
- border: 1px solid var(--rel-select-menu-border, var(--rel-border-default));
410
- border-radius: var(--rel-select-menu-radius, var(--rel-border-radius-sm));
411
- /* A border alone doesn't read clearly against a similarly-light page,
412
- and a shadow alone barely shows on a dark background — together
413
- they hold up in both themes. */
414
- box-shadow: var(--rel-select-menu-shadow, var(--rel-shadows-shadow-300));
415
- max-height: 360px;
416
- overflow-y: auto;
417
- }
418
-
419
- .select-listbox[data-open] {
420
- display: block;
421
- }
422
-
423
- .select-search {
424
- position: sticky;
425
- top: 0;
426
- background: var(--rel-select-bg, var(--rel-bg-neutral));
427
- padding: var(--rel-spacing-xs);
428
- border-bottom: 1px solid var(--rel-select-divider, var(--rel-border-subtle));
429
- }
430
-
431
- /* Base = "small" textfield sizing, shared by both small AND medium
432
- select — only "large" select bumps the search field up to "medium". */
433
- .search-input-wrap {
434
- display: flex;
435
- align-items: center;
436
- gap: 8px;
437
- border: 1px solid var(--rel-select-search-border, var(--rel-border-default));
438
- border-radius: 4px;
439
- padding: var(--rel-spacing-xs) var(--rel-spacing-sm);
440
- }
441
-
442
- .search-input-wrap .icon {
443
- display: flex;
444
- align-items: center;
445
- flex-shrink: 0;
446
- color: var(--rel-select-icon-color, var(--rel-text-default));
447
- }
448
-
449
- .search-input {
450
- flex: 1;
451
- min-width: 0;
452
- border: none;
453
- outline: none;
454
- background: transparent;
455
- color: var(--rel-select-value-color, var(--rel-text-default));
456
- font-family: var(--rel-body-sm-regular-font-family);
457
- font-weight: var(--rel-body-sm-regular-font-weight);
458
- font-size: var(--rel-body-sm-regular-font-size);
459
- line-height: var(--rel-body-sm-regular-line-height);
460
- letter-spacing: var(--rel-body-sm-regular-letter-spacing);
461
- }
462
-
463
- .search-input::placeholder {
464
- color: var(--rel-select-placeholder-color, var(--rel-text-placeholder));
465
- }
466
-
467
- :host([size="large"]) .search-input-wrap {
468
- padding: 12px;
469
- }
470
-
471
- :host([size="large"]) .search-input {
472
-
473
- font-family: var(--rel-body-md-regular-font-family);
474
-
475
- font-weight: var(--rel-body-md-regular-font-weight);
476
-
477
- font-size: var(--rel-body-md-regular-font-size);
478
-
479
- line-height: var(--rel-body-md-regular-line-height);
480
-
481
- letter-spacing: var(--rel-body-md-regular-letter-spacing);
482
-
483
- }
484
-
485
- .select-options {
486
- padding: 4px 0;
487
- }
488
-
489
- .select-option {
490
- display: flex;
491
- align-items: center;
492
- justify-content: space-between;
493
- gap: 12px;
494
- padding: var(--rel-spacing-xs) 12px;
495
- color: var(--rel-select-value-color, var(--rel-text-default));
496
- cursor: pointer;
497
- font-family: var(--rel-body-md-regular-font-family);
498
- font-weight: var(--rel-body-md-regular-font-weight);
499
- font-size: var(--rel-body-md-regular-font-size);
500
- line-height: var(--rel-body-md-regular-line-height);
501
- letter-spacing: var(--rel-body-md-regular-letter-spacing);
502
- }
503
-
504
- /* Groups the optional prefix icon with the label so the trailing
505
- check indicator stays pinned to the right edge of the row. */
506
- .select-option-content {
507
- flex: 1;
508
- min-width: 0;
509
- display: flex;
510
- align-items: center;
511
- gap: var(--rel-spacing-xs);
512
- }
513
-
514
- .select-option-icon {
515
- flex-shrink: 0;
516
- color: var(--rel-select-icon-color, var(--rel-text-default));
517
- }
518
-
519
- .select-option-label {
520
- overflow: hidden;
521
- text-overflow: ellipsis;
522
- white-space: nowrap;
523
- }
524
-
525
- .select-option-check {
526
- flex-shrink: 0;
527
- color: var(--rel-select-value-color, var(--rel-text-default));
528
- }
529
-
530
- .select-option:hover,
531
- .select-option.highlighted {
532
- background: var(--rel-select-option-hover, var(--rel-bg-neutral-elevated-1));
533
- }
534
-
535
- .select-option[aria-selected="true"] {
536
- font-weight: var(--rel-body-md-medium-font-weight);
537
- }
538
-
539
- :host([size="large"]) .select-option[aria-selected="true"] {
540
- font-weight: var(--rel-body-lg-medium-font-weight);
541
- }
542
-
543
- .checkbox-option {
544
- padding: 12px;
545
- }
546
-
547
- .checkbox-option:hover,
548
- .checkbox-option.highlighted {
549
- background: var(--rel-select-option-hover, var(--rel-bg-neutral-elevated-1));
550
- }
551
-
552
- .select-all-row {
553
- border-bottom: 1px solid var(--rel-select-divider, var(--rel-border-subtle));
554
- padding: 12px;
555
- }
556
-
557
- .select-empty {
558
- padding: var(--rel-spacing-xs) 12px;
559
- color: var(--rel-select-placeholder-color, var(--rel-text-body));
560
- font-family: var(--rel-body-sm-regular-font-family);
561
- font-weight: var(--rel-body-sm-regular-font-weight);
562
- font-size: var(--rel-body-sm-regular-font-size);
563
- line-height: var(--rel-body-sm-regular-line-height);
564
- letter-spacing: var(--rel-body-sm-regular-letter-spacing);
565
- }
566
-
567
- `;
568
-
569
- connectedCallback() {
570
- super.connectedCallback();
571
- // firstUpdated only runs once — re-observe if the element is re-attached.
572
- if (this.chipResizeObserver && this.triggerEl) {
573
- this.chipResizeObserver.observe(this.triggerEl);
574
- }
575
- }
576
-
577
- disconnectedCallback() {
578
- super.disconnectedCallback();
579
- this.removeGlobalListeners();
580
- this.chipResizeObserver?.disconnect();
581
- }
582
-
583
- protected firstUpdated() {
584
- this.chipResizeObserver = new ResizeObserver(() => this.computeVisibleChips());
585
- this.chipResizeObserver.observe(this.triggerEl);
586
- }
587
-
588
- protected willUpdate(changed: PropertyValues<this>) {
589
- if (changed.has("multiple") && this.multiple === false) {
590
- this.selectedValues = [];
591
- }
592
- }
593
-
594
- private _warnedNoName = false;
595
-
596
- protected updated(changed: PropertyValues<this>) {
597
- if (
598
- !this._warnedNoName &&
599
- this.labelStyle === "none" &&
600
- !this.fieldAriaLabel &&
601
- !this.fieldAriaLabelledby &&
602
- !this.getAttribute("aria-label")
603
- ) {
604
- this._warnedNoName = true;
605
- console.warn(
606
- '<rel-select label-style="none"> has no accessible name. Set ' +
607
- "`field-aria-label` or `field-aria-labelledby` — a placeholder is not a " +
608
- "valid naming mechanism.",
609
- this
610
- );
611
- }
612
-
613
- if (
614
- changed.has("selectedValues") ||
615
- changed.has("options") ||
616
- changed.has("multiple") ||
617
- changed.has("size")
618
- ) {
619
- // rAF: rel-chip renders in its own (microtask) update cycle, so its
620
- // width isn't measurable synchronously here — by the next frame it is.
621
- requestAnimationFrame(() => this.computeVisibleChips());
622
- }
623
- }
624
-
625
- /**
626
- * Width-adaptive chip collapsing: measures every selected chip in the
627
- * hidden .select-chips-measure row and works out how many fit in the value
628
- * area, always reserving room for the trailing "+N" chip when not all fit.
629
- * At least one chip stays visible no matter how narrow the field gets.
630
- */
631
- private computeVisibleChips() {
632
- if (!this.isConnected || !this.multiple || this.selectedValues.length === 0) return;
633
- const measure = this.chipsMeasureEl;
634
- const container = this.valueEl;
635
- if (!measure || !container) return;
636
-
637
- const available = container.clientWidth;
638
- if (available <= 0) return; // hidden (display:none) — RO will refire when visible
639
-
640
- const children = Array.from(measure.children) as HTMLElement[];
641
- if (children.length < 2) return;
642
-
643
- const gap = RelSelect.CHIP_GAP;
644
- // Last measure child is the worst-case "+N" chip (N = total selected,
645
- // i.e. the widest label the badge can ever need).
646
- const overflowWidth = children[children.length - 1].offsetWidth;
647
- const chipWidths = children.slice(0, -1).map((c) => c.offsetWidth);
648
- const total = chipWidths.reduce((sum, w) => sum + w, 0) + gap * (chipWidths.length - 1);
649
-
650
- let fit: number;
651
- if (total <= available) {
652
- fit = chipWidths.length;
653
- } else {
654
- fit = 0;
655
- let used = 0;
656
- for (let i = 0; i < chipWidths.length; i++) {
657
- const w = chipWidths[i] + (i > 0 ? gap : 0);
658
- if (used + w + gap + overflowWidth <= available) {
659
- used += w;
660
- fit = i + 1;
661
- } else {
662
- break;
663
- }
664
- }
665
- fit = Math.max(1, fit);
666
- }
667
-
668
- if (fit !== this.visibleChipCount) this.visibleChipCount = fit;
669
- }
670
-
671
- private get normalizedOptions(): NormalizedOption[] {
672
- return this.options.map(normalizeOption);
673
- }
674
-
675
- /** Options matching the current search text (substring match, case-insensitive). */
676
- private get filteredOptions(): NormalizedOption[] {
677
- const opts = this.normalizedOptions;
678
- if (!this.searchValue) return opts;
679
- const v = this.searchValue.toLowerCase();
680
- return opts.filter((o) => o.label.toLowerCase().includes(v));
681
- }
682
-
683
- private get hasValue(): boolean {
684
- return this.multiple ? this.selectedValues.length > 0 : !!this.selected;
685
- }
686
-
687
- /** Icon size scales with the select's own size, matching the trigger. */
688
- private get iconSize(): "xs" | "sm" | "md" {
689
- return this.size === "small" ? "xs" : this.size === "large" ? "md" : "sm";
690
- }
691
-
692
- /** The search field uses "small" sizing for both small and medium select — only "large" select bumps it to "medium". */
693
- private get searchIconSize(): "sm" | "md" {
694
- return this.size === "large" ? "md" : "sm";
695
- }
696
-
697
- private get selectAllStatus(): "checked" | "unchecked" | "indeterminate" {
698
- const filtered = this.filteredOptions;
699
- if (filtered.length === 0) return "unchecked";
700
- const selectedCount = filtered.filter((o) => this.selectedValues.includes(o.value)).length;
701
- if (selectedCount === 0) return "unchecked";
702
- if (selectedCount === filtered.length) return "checked";
703
- return "indeterminate";
704
- }
705
-
706
- private addGlobalListeners() {
707
- document.addEventListener("pointerdown", this.onOutsidePointerDown);
708
- window.addEventListener("resize", this.updatePosition);
709
- window.addEventListener("scroll", this.onPageScroll, true);
710
- }
711
-
712
- private removeGlobalListeners() {
713
- document.removeEventListener("pointerdown", this.onOutsidePointerDown);
714
- window.removeEventListener("resize", this.updatePosition);
715
- window.removeEventListener("scroll", this.onPageScroll, true);
716
- }
717
-
718
- private onOutsidePointerDown = (e: PointerEvent) => {
719
- if (!this.open) return;
720
- const path = e.composedPath();
721
- if (path.includes(this)) return;
722
- this.closeListbox();
723
- };
724
-
725
- // Continuously re-deriving a fixed-position panel's coordinates from
726
- // every page scroll event is fragile (it's what was causing the panel to
727
- // jump to the top of the viewport). Instead, close the panel on any
728
- // *outside* scroll, same as clicking outside — scrolling the option list
729
- // itself (target is the listbox) is the one case that should NOT close it.
730
- private onPageScroll = (e: Event) => {
731
- if (!this.open) return;
732
- if (e.composedPath()[0] === this.listboxEl) return;
733
- this.closeListbox();
734
- };
735
-
736
- private emitChange() {
737
- this.dispatchEvent(
738
- new CustomEvent("changed", {
739
- detail: { value: this.multiple ? this.selectedValues : this.selected },
740
- bubbles: true,
741
- composed: true,
742
- })
743
- );
744
- }
745
-
746
- private openListbox() {
747
- if (this.state === "disabled" || this.open) return;
748
- this.open = true;
749
- this.searchValue = "";
750
- // No pre-highlight — the first item showing a hover-style highlight
751
- // before the user has touched anything reads as an unintended default.
752
- // Highlight only kicks in once they actually hover or press an arrow key.
753
- this.highlightedIndex = -1;
754
- this.addGlobalListeners();
755
- requestAnimationFrame(() => {
756
- this.updatePosition();
757
- // preventScroll: focusing the search field must not let the browser
758
- // scroll the page into view — that would move the trigger (normal
759
- // flow) out from under the panel (fixed position, already computed
760
- // above), breaking the anchor. When there's no search field, focus
761
- // simply stays on the trigger, which already has the nav keydown
762
- // handling wired up for this case.
763
- if (!this.noSearch) {
764
- this.searchInputEl?.focus({ preventScroll: true });
765
- }
766
- });
767
- }
768
-
769
- private closeListbox() {
770
- if (!this.open) return;
771
- this.open = false;
772
- this.removeGlobalListeners();
773
- this.triggerEl?.focus();
774
- }
775
-
776
- private updatePosition = () => {
777
- if (!this.triggerEl || !this.listboxEl) return;
778
-
779
- this.listboxEl.setAttribute("data-open", "");
780
-
781
- const t = this.triggerEl.getBoundingClientRect();
782
- const c = this.listboxEl.getBoundingClientRect();
783
-
784
- let top = t.bottom + 4;
785
- if (top + c.height > window.innerHeight - 8) {
786
- top = Math.max(8, t.top - c.height - 4);
787
- }
788
-
789
- // Use t.width (the trigger's width, which is also what we set the panel's
790
- // own width to below) rather than c.width — c.width reflects the
791
- // *previous* render's panelStyle, so on the very next measurement it can
792
- // be a frame stale, nudging left by a few px even when there's no real
793
- // overflow. Checking against t.width directly removes that drift.
794
- let left = t.left;
795
- if (left + t.width > window.innerWidth - 8) {
796
- left = Math.max(8, window.innerWidth - t.width - 8);
797
- }
798
-
799
- this.panelStyle = `top:${top}px;left:${left}px;width:${t.width}px;`;
800
- };
801
-
802
- private selectSingleOption(option: NormalizedOption) {
803
- this.selected = option.value;
804
- if (this.state === "error") this.state = "default";
805
- this.closeListbox();
806
- this.emitChange();
807
- }
808
-
809
- private toggleMultiOption(option: NormalizedOption) {
810
- const idx = this.selectedValues.indexOf(option.value);
811
- this.selectedValues =
812
- idx >= 0
813
- ? this.selectedValues.filter((v) => v !== option.value)
814
- : [...this.selectedValues, option.value];
815
- if (this.state === "error") this.state = "default";
816
- this.emitChange();
817
- }
818
-
819
- private toggleSelectAll() {
820
- const filtered = this.filteredOptions;
821
- const status = this.selectAllStatus;
822
- if (status === "checked") {
823
- const filteredValues = new Set(filtered.map((o) => o.value));
824
- this.selectedValues = this.selectedValues.filter((v) => !filteredValues.has(v));
825
- } else {
826
- const toAdd = filtered.map((o) => o.value).filter((v) => !this.selectedValues.includes(v));
827
- this.selectedValues = [...this.selectedValues, ...toAdd];
828
- }
829
- if (this.state === "error") this.state = "default";
830
- this.emitChange();
831
- }
832
-
833
- private removeChip(value: string) {
834
- if (this.state === "disabled") return;
835
- this.selectedValues = this.selectedValues.filter((v) => v !== value);
836
- this.emitChange();
837
- }
838
-
839
- private onTriggerClick() {
840
- if (this.open) this.closeListbox();
841
- else this.openListbox();
842
- }
843
-
844
- private onTriggerKeyDown(e: KeyboardEvent) {
845
- if (this.state === "disabled") return;
846
- if (!this.open) {
847
- if (["ArrowDown", "ArrowUp", "Enter", " "].includes(e.key)) {
848
- e.preventDefault();
849
- this.openListbox();
850
- }
851
- return;
852
- }
853
- // No search field to hold focus/keydown in this mode — the trigger
854
- // itself keeps focus while open, so it needs the same nav handling.
855
- if (this.noSearch) this.handleListNavigation(e);
856
- }
857
-
858
- private onSearchInput = (e: InputEvent) => {
859
- this.searchValue = (e.target as HTMLInputElement).value;
860
- this.highlightedIndex = this.filteredOptions.length > 0 ? 0 : -1;
861
- requestAnimationFrame(() => this.updatePosition());
862
- };
863
-
864
- private onSearchKeyDown(e: KeyboardEvent) {
865
- this.handleListNavigation(e);
866
- }
867
-
868
- private handleListNavigation(e: KeyboardEvent) {
869
- const filtered = this.filteredOptions;
870
- switch (e.key) {
871
- case "ArrowDown":
872
- e.preventDefault();
873
- this.highlightedIndex = Math.min(filtered.length - 1, this.highlightedIndex + 1);
874
- break;
875
- case "ArrowUp":
876
- e.preventDefault();
877
- this.highlightedIndex = Math.max(0, this.highlightedIndex - 1);
878
- break;
879
- case "Enter":
880
- e.preventDefault();
881
- if (this.highlightedIndex >= 0 && filtered[this.highlightedIndex]) {
882
- const opt = filtered[this.highlightedIndex];
883
- if (this.multiple) this.toggleMultiOption(opt);
884
- else this.selectSingleOption(opt);
885
- }
886
- break;
887
- case "Escape":
888
- e.preventDefault();
889
- this.closeListbox();
890
- break;
891
- case "Tab":
892
- this.closeListbox();
893
- break;
894
- }
895
- }
896
-
897
- private renderChips() {
898
- const values = this.selectedValues;
899
- const visible = values.slice(0, Math.min(this.visibleChipCount, this.maxVisibleChips));
900
- const overflow = values.length - visible.length;
901
- const opts = this.normalizedOptions;
902
-
903
- return html`
904
- <span class="select-chips">
905
- ${repeat(
906
- visible,
907
- (v) => v,
908
- (v) => {
909
- const opt = opts.find((o) => o.value === v);
910
- // Keyed by value: rel-chip tracks its own "removed" flag
911
- // internally once its (x) is clicked, so reusing DOM nodes
912
- // positionally (plain .map()) could hand a freshly-shown value
913
- // a node that still remembers being removed as a *different*
914
- // value. Keying forces a fresh node per value instead.
915
- return html`
916
- <rel-chip
917
- label="${opt?.label ?? v}"
918
- size="sm"
919
- variant="subtle"
920
- border="default"
921
- ?removable=${this.state !== "disabled"}
922
- @click=${(e: Event) => e.stopPropagation()}
923
- @removed=${(e: Event) => {
924
- e.stopPropagation();
925
- this.removeChip(v);
926
- }}
927
- ></rel-chip>
928
- `;
929
- }
930
- )}
931
- ${overflow > 0
932
- ? html`<rel-chip label="+${overflow}" size="sm" variant="fill" border="default"></rel-chip>`
933
- : nothing}
934
- </span>
935
- `;
936
- }
937
-
938
- /**
939
- * Hidden, unconstrained copy of every selected chip used purely for width
940
- * measurement (see computeVisibleChips). Chips mirror the visible ones'
941
- * width-affecting props (removable adds the ✕ icon). The trailing chip is
942
- * the widest "+N" badge that could ever be needed.
943
- */
944
- private renderChipsMeasure() {
945
- const values = this.selectedValues;
946
- const opts = this.normalizedOptions;
947
- return html`
948
- <span class="select-chips-measure" aria-hidden="true">
949
- ${values.map((v) => {
950
- const opt = opts.find((o) => o.value === v);
951
- return html`
952
- <rel-chip
953
- label="${opt?.label ?? v}"
954
- size="sm"
955
- variant="subtle"
956
- border="default"
957
- ?removable=${this.state !== "disabled"}
958
- ></rel-chip>
959
- `;
960
- })}
961
- <rel-chip label="+${values.length}" size="sm" variant="fill" border="default"></rel-chip>
962
- </span>
963
- `;
964
- }
965
-
966
- render() {
967
- const opts = this.normalizedOptions;
968
- const filtered = this.filteredOptions;
969
- const isDisabled = this.state === "disabled";
970
- const labelHidden = this.labelStyle === "none";
971
- const showFloatingChrome = this.labelStyle === "floating" && !!this.label;
972
- // With no visible label the ARIA name comes from fieldAriaLabel instead.
973
- const accessibleName = (labelHidden ? this.fieldAriaLabel : this.label) || "";
974
-
975
- const wrapperClasses = [
976
- "select-wrapper",
977
- this.size,
978
- this.state,
979
- `border-${this.border}`,
980
- showFloatingChrome ? "floating" : "",
981
- this.internalState === "focused" ? "focused" : "",
982
- this.hasValue ? "has-value" : "",
983
- this.open ? "open" : "",
984
- ]
985
- .filter(Boolean)
986
- .join(" ");
987
-
988
- const listboxId = `${this.uniqueId}-listbox`;
989
- const activeOptionId =
990
- this.open && this.highlightedIndex >= 0 ? `${this.uniqueId}-option-${this.highlightedIndex}` : "";
991
-
992
- const selectedSingle = opts.find((o) => o.value === this.selected);
993
-
994
- return html`
995
- <div class="${wrapperClasses}">
996
- ${labelHidden
997
- ? html`<div class="label-reserve" aria-hidden="true"></div>`
998
- : !showFloatingChrome && this.label
999
- ? html`<label part="label" class="select-label" for="${this.uniqueId}">${this.label}</label>`
1000
- : ""}
1001
-
1002
- <div class="select-container">
1003
- ${showFloatingChrome
1004
- ? html`<span class="floating-label${this.leftIcon ? " has-left-icon" : ""}"
1005
- >${this.label}</span
1006
- >`
1007
- : ""}
1008
-
1009
- <button
1010
- id="${this.uniqueId}"
1011
- type="button"
1012
- part="trigger" class="select-trigger"
1013
- role="combobox"
1014
- aria-haspopup="listbox"
1015
- aria-expanded="${this.open}"
1016
- aria-controls="${listboxId}"
1017
- aria-activedescendant="${activeOptionId}"
1018
- aria-invalid="${this.state === "error"}"
1019
- aria-label="${this.fieldAriaLabelledby ? nothing : accessibleName || this.placeholder}"
1020
- aria-labelledby="${this.fieldAriaLabelledby ?? nothing}"
1021
- ?disabled="${isDisabled}"
1022
- @click="${this.onTriggerClick}"
1023
- @keydown="${this.onTriggerKeyDown}"
1024
- @focus="${() => (this.internalState = "focused")}"
1025
- @blur="${() => (this.internalState = "default")}"
1026
- >
1027
- ${this.leftIcon
1028
- ? html`<rel-icon name="${this.leftIcon}" size="${this.iconSize}" class="icon left"></rel-icon>`
1029
- : ""}
1030
-
1031
- ${this.multiple
1032
- ? this.selectedValues.length > 0
1033
- ? html`<span part="value" class="select-value">${this.renderChips()}</span>`
1034
- : html`<span part="value" class="select-value placeholder">
1035
- <span class="select-value-text">${this.placeholder}</span>
1036
- </span>`
1037
- : html`<span part="value" class="select-value ${selectedSingle ? "" : "placeholder"}">
1038
- <span class="select-value-text"
1039
- >${selectedSingle ? selectedSingle.label : this.placeholder}</span
1040
- >
1041
- </span>`}
1042
-
1043
- <rel-icon
1044
- name="${this.rightIcon || "chevron-down"}"
1045
- size="${this.iconSize}"
1046
- class="icon ${this.rightIcon ? "" : "chevron"}"
1047
- ></rel-icon>
1048
- </button>
1049
-
1050
- ${this.multiple && this.selectedValues.length > 0 ? this.renderChipsMeasure() : nothing}
1051
- </div>
1052
-
1053
- ${this.supportingText
1054
- ? html`<span part="helper" class="select-support ${this.state === "error" ? "error" : ""}">
1055
- ${this.supportingText}
1056
- </span>`
1057
- : ""}
1058
- </div>
1059
-
1060
- <div
1061
- id="${listboxId}"
1062
- part="panel list" class="select-listbox"
1063
- role="listbox"
1064
- aria-multiselectable="${this.multiple}"
1065
- aria-label="${accessibleName || "Options"}"
1066
- style="${this.panelStyle}"
1067
- ?data-open="${this.open}"
1068
- >
1069
- ${!this.noSearch
1070
- ? html`<div class="select-search">
1071
- <div class="search-input-wrap">
1072
- <rel-icon name="search" size="${this.searchIconSize}" class="icon"></rel-icon>
1073
- <input
1074
- part="input" class="search-input"
1075
- type="text"
1076
- placeholder="${this.searchPlaceholder}"
1077
- .value="${this.searchValue}"
1078
- @input="${this.onSearchInput}"
1079
- @keydown="${(e: KeyboardEvent) => this.onSearchKeyDown(e)}"
1080
- />
1081
- </div>
1082
- </div>`
1083
- : ""}
1084
-
1085
- ${filtered.length === 0
1086
- ? html`<div class="select-empty">
1087
- ${opts.length === 0 ? "No options available" : "No matches found"}
1088
- </div>`
1089
- : this.multiple
1090
- ? html`
1091
- <div class="select-all-row">
1092
- <rel-checkbox
1093
- label="${this.selectAllLabel}"
1094
- status="${this.selectAllStatus}"
1095
- @rel-change=${(e: Event) => {
1096
- e.stopPropagation();
1097
- this.toggleSelectAll();
1098
- }}
1099
- ></rel-checkbox>
1100
- </div>
1101
- <div class="select-options">
1102
- ${repeat(
1103
- filtered,
1104
- (option) => option.value,
1105
- (option, index) => html`
1106
- <div
1107
- id="${this.uniqueId}-option-${index}"
1108
- class="checkbox-option ${index === this.highlightedIndex ? "highlighted" : ""}"
1109
- role="option"
1110
- aria-selected="${this.selectedValues.includes(option.value)}"
1111
- @pointerenter="${() => (this.highlightedIndex = index)}"
1112
- >
1113
- <rel-checkbox
1114
- label="${option.label}"
1115
- icon="${option.icon}"
1116
- supportingtext="${option.supportingText}"
1117
- status="${this.selectedValues.includes(option.value) ? "checked" : "unchecked"}"
1118
- @rel-change=${(e: Event) => {
1119
- e.stopPropagation();
1120
- this.toggleMultiOption(option);
1121
- }}
1122
- ></rel-checkbox>
1123
- </div>
1124
- `
1125
- )}
1126
- </div>
1127
- `
1128
- : html`
1129
- <div class="select-options">
1130
- ${repeat(
1131
- filtered,
1132
- (option) => option.value,
1133
- (option, index) => html`
1134
- <div
1135
- id="${this.uniqueId}-option-${index}"
1136
- part="option" class="select-option ${index === this.highlightedIndex ? "highlighted" : ""}"
1137
- role="option"
1138
- aria-selected="${option.value === this.selected}"
1139
- @mousedown="${(e: Event) => e.preventDefault()}"
1140
- @click="${() => this.selectSingleOption(option)}"
1141
- @pointerenter="${() => (this.highlightedIndex = index)}"
1142
- >
1143
- <span class="select-option-content">
1144
- ${option.icon
1145
- ? html`<rel-icon
1146
- name="${option.icon}"
1147
- size="sm"
1148
- class="select-option-icon"
1149
- ></rel-icon>`
1150
- : nothing}
1151
- <span class="select-option-label">${option.label}</span>
1152
- </span>
1153
- ${option.value === this.selected
1154
- ? html`<rel-icon name="check" size="sm" class="select-option-check"></rel-icon>`
1155
- : ""}
1156
- </div>
1157
- `
1158
- )}
1159
- </div>
1160
- `}
1161
- </div>
1162
- `;
1163
- }
1164
- }
1165
-
1166
- declare global {
1167
- interface HTMLElementTagNameMap {
1168
- "rel-select": RelSelect;
1169
- }
1170
- }
1
+ import { LitElement, html, css, nothing, PropertyValues } from "lit";
2
+ import { customElement, property, state, query } from "lit/decorators.js";
3
+ import { repeat } from "lit/directives/repeat.js";
4
+ import "@reliability-design/icons/rel-icon";
5
+ import "../rel-chip/rel-chip.js";
6
+ import "../rel-checkbox/rel-checkbox.js";
7
+ import type { FieldLabelStyle } from "../rel-textfield/rel-textfield.js";
8
+
9
+ export type SelectState = "default" | "error" | "disabled";
10
+ export type SelectSize = "small" | "medium" | "large";
11
+ export type SelectBorder = "rounded" | "sharp";
12
+ /** Alias of the shared field type — kept so existing imports keep resolving. */
13
+ export type SelectLabelStyle = FieldLabelStyle;
14
+
15
+ export interface SelectOptionObject {
16
+ value: string;
17
+ label?: string;
18
+ supportingText?: string;
19
+ /** rel-icon name rendered as a prefix (leading icon) on the menu item. */
20
+ icon?: string;
21
+ }
22
+ export type SelectOption = string | SelectOptionObject;
23
+
24
+ interface NormalizedOption {
25
+ value: string;
26
+ label: string;
27
+ supportingText: string;
28
+ icon: string;
29
+ }
30
+
31
+ function normalizeOption(o: SelectOption): NormalizedOption {
32
+ if (typeof o === "string") return { value: o, label: o, supportingText: "", icon: "" };
33
+ return {
34
+ value: o.value,
35
+ label: o.label ?? o.value,
36
+ supportingText: o.supportingText ?? "",
37
+ icon: o.icon ?? "",
38
+ };
39
+ }
40
+
41
+ @customElement("rel-select")
42
+ export class RelSelect extends LitElement {
43
+ @property({ type: String }) label: string = "";
44
+
45
+ // Lit's default attribute name is the property name fully lowercased (no
46
+ // hyphens) — e.g. labelStyle would otherwise only respond to "labelstyle".
47
+ // Every multi-word property below gets an explicit kebab-case `attribute`
48
+ // so it works the way HTML usage actually looks.
49
+ @property({ type: String, attribute: "label-style", reflect: true })
50
+ labelStyle: SelectLabelStyle = "default";
51
+
52
+ /**
53
+ * Accessible name for the trigger. Required when `labelStyle="none"`, since no
54
+ * `<label>` renders and a placeholder is not a valid naming mechanism.
55
+ */
56
+ @property({ type: String, attribute: "field-aria-label" }) fieldAriaLabel?: string;
57
+ /** IDREF list of external element(s) naming the trigger. Wins over `fieldAriaLabel`. */
58
+ @property({ type: String, attribute: "field-aria-labelledby" }) fieldAriaLabelledby?: string;
59
+
60
+ @property({ type: Array }) options: SelectOption[] = [];
61
+
62
+ /** Enables multi-select: selected values render as removable chips and options as checkboxes. */
63
+ @property({ type: Boolean }) multiple: boolean = false;
64
+
65
+ /** Selected value — single-select mode only. */
66
+ @property({ type: String }) selected: string = "";
67
+
68
+ /** Selected values — multi-select mode only. */
69
+ @property({ type: Array, attribute: "selected-values" }) selectedValues: string[] = [];
70
+
71
+ @property({ type: String }) state: SelectState = "default";
72
+
73
+ @property({ type: String, attribute: "supporting-text" }) supportingText: string = "";
74
+
75
+ @property({ type: String, reflect: true }) size: SelectSize = "medium";
76
+
77
+ @property({ type: String }) border: SelectBorder = "rounded";
78
+
79
+ @property({ type: String, attribute: "left-icon" }) leftIcon: string = "";
80
+
81
+ @property({ type: String, attribute: "right-icon" }) rightIcon: string = "";
82
+
83
+ @property({ type: String }) placeholder: string = "Select option";
84
+
85
+ @property({ type: String, attribute: "search-placeholder" }) searchPlaceholder: string = "Search option";
86
+
87
+ @property({ type: String, attribute: "select-all-label" }) selectAllLabel: string = "Select all";
88
+
89
+ /**
90
+ * Optional hard cap on visible chips. By default (no cap) the visible
91
+ * count adapts to the trigger's width: chips collapse into the "+N" badge
92
+ * one by one instead of wrapping to a second line.
93
+ */
94
+ @property({ type: Number, attribute: "max-visible-chips" }) maxVisibleChips: number = Infinity;
95
+
96
+ // Boolean props default true and toggled off via ="false" are a classic Lit
97
+ // trap: for type:Boolean, attribute *presence* (not its string value)
98
+ // decides truthiness, so searchable="false" would still read as true. Named
99
+ // negatively instead, so the natural HTML idiom — just adding the bare
100
+ // attribute, no value — does what it looks like it does.
101
+ /** Hides the in-panel search field. Figma's "Single Option" dropdown has no search bar at all — use this for short, non-searchable lists. */
102
+ @property({ type: Boolean, attribute: "no-search" }) noSearch: boolean = false;
103
+
104
+ @state() private open = false;
105
+ @state() private highlightedIndex = -1;
106
+ @state() private panelStyle = "";
107
+ @state() private searchValue = "";
108
+ @state() private internalState: "default" | "focused" = "default";
109
+
110
+ /** How many chips currently fit in the trigger width (width-adaptive). */
111
+ @state() private visibleChipCount = Infinity;
112
+
113
+ @query(".select-trigger") private triggerEl!: HTMLButtonElement;
114
+ @query(".search-input") private searchInputEl!: HTMLInputElement;
115
+ @query(".select-listbox") private listboxEl!: HTMLDivElement;
116
+ @query(".select-value") private valueEl!: HTMLElement;
117
+ @query(".select-chips-measure") private chipsMeasureEl!: HTMLElement;
118
+
119
+ /** Must match the `gap` of .select-chips / .select-chips-measure. */
120
+ private static readonly CHIP_GAP = 6;
121
+
122
+ private chipResizeObserver?: ResizeObserver;
123
+
124
+ private uniqueId = `select-${Math.random().toString(36).slice(2)}`;
125
+
126
+ static styles = css`
127
+ :host {
128
+ color: var(--rel-text-default);
129
+ display: block;
130
+ font-family: var(--rel-fonts-font-family);
131
+ width: 100%;
132
+ }
133
+
134
+ .select-wrapper {
135
+ display: flex;
136
+ flex-direction: column;
137
+ gap: var(--rel-spacing-2xs);
138
+ width: 100%;
139
+ }
140
+
141
+ /* Dims everything inside uniformly (label, trigger, icons, value text,
142
+ supporting text) — matches rel-button's :host([disabled]) opacity
143
+ approach instead of relying on one barely-different background tint. */
144
+ .select-wrapper.disabled {
145
+ opacity: 0.5;
146
+ }
147
+
148
+ .select-label {
149
+ color: var(--rel-select-label-color, var(--rel-text-label));
150
+
151
+ font-family: var(--rel-body-sm-regular-font-family);
152
+
153
+ font-weight: var(--rel-body-sm-regular-font-weight);
154
+
155
+ font-size: var(--rel-body-sm-regular-font-size);
156
+
157
+ line-height: var(--rel-body-sm-regular-line-height);
158
+
159
+ letter-spacing: var(--rel-body-sm-regular-letter-spacing);
160
+
161
+ }
162
+
163
+ /* ── labelStyle="none" ──
164
+ No label renders. An empty spacer holds the label row's full height so the
165
+ trigger still bottom-aligns with labelled siblings in a form row.
166
+ The reserve covers label line-height + the wrapper gap, and the negative
167
+ margin cancels the flex gap that would otherwise sit below it — so
168
+ --rel-field-label-reserve: 0 collapses the row to genuinely zero
169
+ (toolbars, table cells), not just to the leftover gap. */
170
+ .label-reserve {
171
+ flex: none;
172
+ height: var(
173
+ --rel-field-label-reserve,
174
+ calc(var(--rel-body-sm-regular-line-height) + var(--rel-spacing-2xs))
175
+ );
176
+ margin-bottom: calc(-1 * var(--rel-spacing-2xs));
177
+ }
178
+
179
+ /* Error only colors the border/focus ring and the supporting text below
180
+ the field — label, floating label, placeholder, and icons stay normal. */
181
+
182
+ /* Container */
183
+ .select-container {
184
+ position: relative;
185
+ }
186
+
187
+ /* Trigger button — visually a text field, semantically a combobox button */
188
+ .select-trigger {
189
+ display: flex;
190
+ align-items: center;
191
+ width: 100%;
192
+ box-sizing: border-box;
193
+ gap: 8px;
194
+ background: var(--rel-select-bg, var(--rel-bg-neutral));
195
+ border: 1px solid var(--rel-select-border-default, var(--rel-border-default));
196
+ cursor: pointer;
197
+ font-family: inherit;
198
+ transition: border-color 0.15s ease;
199
+ text-align: left;
200
+ }
201
+
202
+ .border-rounded .select-trigger {
203
+ border-radius: var(--rel-select-radius, var(--rel-border-radius-xs));
204
+ }
205
+
206
+ .border-sharp .select-trigger {
207
+ border-radius: 0;
208
+ }
209
+
210
+ .select-trigger:focus-visible,
211
+ .select-wrapper.open .select-trigger {
212
+ outline: none;
213
+ border-color: var(--rel-select-border-focus, var(--rel-border-strong));
214
+ }
215
+
216
+ .select-wrapper.error .select-trigger {
217
+ border-color: var(--rel-select-border-error, var(--rel-border-danger));
218
+ }
219
+
220
+ .select-wrapper.disabled .select-trigger {
221
+ cursor: not-allowed;
222
+ background: var(--rel-select-bg-disabled, var(--rel-bg-neutral-elevated-1));
223
+ border-color: var(--rel-select-border-default, var(--rel-border-default));
224
+ }
225
+
226
+ /* Sizes */
227
+ .select-wrapper.small .select-trigger {
228
+ padding: var(--rel-spacing-xs) var(--rel-spacing-sm);
229
+ min-height: 40px;
230
+ font-family: var(--rel-body-sm-regular-font-family);
231
+ font-weight: var(--rel-body-sm-regular-font-weight);
232
+ font-size: var(--rel-body-sm-regular-font-size);
233
+ line-height: var(--rel-body-sm-regular-line-height);
234
+ letter-spacing: var(--rel-body-sm-regular-letter-spacing);
235
+ }
236
+
237
+ .select-wrapper.medium .select-trigger {
238
+ padding: 12px;
239
+ min-height: 48px;
240
+ font-family: var(--rel-body-md-regular-font-family);
241
+ font-weight: var(--rel-body-md-regular-font-weight);
242
+ font-size: var(--rel-body-md-regular-font-size);
243
+ line-height: var(--rel-body-md-regular-line-height);
244
+ letter-spacing: var(--rel-body-md-regular-letter-spacing);
245
+ }
246
+
247
+ .select-wrapper.large .select-trigger {
248
+ padding: var(--rel-spacing-md);
249
+ min-height: 56px;
250
+ font-family: var(--rel-body-lg-regular-font-family);
251
+ font-weight: var(--rel-body-lg-regular-font-weight);
252
+ font-size: var(--rel-body-lg-regular-font-size);
253
+ line-height: var(--rel-body-lg-regular-line-height);
254
+ letter-spacing: var(--rel-body-lg-regular-letter-spacing);
255
+ }
256
+
257
+ /* Icons */
258
+ .select-trigger .icon {
259
+ display: flex;
260
+ align-items: center;
261
+ flex-shrink: 0;
262
+ color: var(--rel-select-icon-color, var(--rel-text-default));
263
+ }
264
+
265
+ .select-trigger .icon.chevron {
266
+ transition: transform 0.15s ease;
267
+ }
268
+
269
+ .select-wrapper.open .icon.chevron {
270
+ transform: rotate(180deg);
271
+ }
272
+
273
+ .select-wrapper.disabled .icon {
274
+ color: var(--rel-text-disabled);
275
+ }
276
+
277
+ /* Value area */
278
+ .select-value {
279
+ flex: 1;
280
+ min-width: 0;
281
+ display: flex;
282
+ align-items: center;
283
+ gap: 6px;
284
+ flex-wrap: nowrap;
285
+ color: var(--rel-select-value-color, var(--rel-text-default));
286
+ overflow: hidden;
287
+ }
288
+
289
+ .select-value.placeholder {
290
+ color: var(--rel-select-placeholder-color, var(--rel-text-placeholder));
291
+ }
292
+
293
+ .select-wrapper.disabled .select-value.placeholder {
294
+ color: var(--rel-select-placeholder-disabled-color, var(--rel-text-disabled));
295
+ }
296
+
297
+ .select-value-text {
298
+ overflow: hidden;
299
+ text-overflow: ellipsis;
300
+ white-space: nowrap;
301
+ }
302
+
303
+ /* Chips never wrap — the number of rendered chips adapts to the
304
+ available width instead (see computeVisibleChips), collapsing the
305
+ remainder into a trailing "+N" chip. overflow:hidden guards the one
306
+ frame between a resize and the recomputation catching up. */
307
+ .select-chips {
308
+ display: flex;
309
+ align-items: center;
310
+ gap: 6px;
311
+ flex-wrap: nowrap;
312
+ min-width: 0;
313
+ overflow: hidden;
314
+ }
315
+
316
+ /* Invisible copy of ALL selected chips (plus a worst-case "+N" chip),
317
+ laid out unconstrained so computeVisibleChips can read each chip's
318
+ natural width — including chips currently collapsed into "+N", whose
319
+ widths are needed again when the field grows. */
320
+ .select-chips-measure {
321
+ position: absolute;
322
+ top: 0;
323
+ left: 0;
324
+ display: flex;
325
+ align-items: center;
326
+ gap: 6px;
327
+ width: max-content;
328
+ visibility: hidden;
329
+ pointer-events: none;
330
+ }
331
+
332
+ /* rel-chip's outer element is a tabindex="0" span, not a native button —
333
+ a disabled native <button> ancestor doesn't suppress clicks on that
334
+ automatically the way it would for a nested native form control, so
335
+ this has to be switched off explicitly. The cursor still correctly
336
+ falls through to the disabled trigger underneath. */
337
+ .select-wrapper.disabled .select-chips {
338
+ pointer-events: none;
339
+ }
340
+
341
+ /* Floating label — single element that animates between resting (inside,
342
+ at the value position) and floated (small, on the border line), same
343
+ mechanism as rel-textfield's [floatinglabel]. */
344
+ .floating-label {
345
+ position: absolute;
346
+ left: 12px;
347
+ top: 50%;
348
+ transform: translateY(-50%);
349
+ background: var(--rel-select-bg, var(--rel-bg-neutral));
350
+ padding: 0 4px;
351
+ color: var(--rel-select-placeholder-color, var(--rel-text-placeholder));
352
+ pointer-events: none;
353
+ z-index: 1;
354
+ white-space: nowrap;
355
+ transition: top 0.15s ease, left 0.15s ease, font-size 0.15s ease, color 0.15s ease;
356
+ font-family: var(--rel-body-md-regular-font-family);
357
+ font-weight: var(--rel-body-md-regular-font-weight);
358
+ font-size: var(--rel-body-md-regular-font-size);
359
+ line-height: var(--rel-body-md-regular-line-height);
360
+ letter-spacing: var(--rel-body-md-regular-letter-spacing);
361
+ }
362
+
363
+ .floating-label.has-left-icon {
364
+ left: 40px;
365
+ }
366
+
367
+ .select-wrapper.focused .floating-label,
368
+ .select-wrapper.has-value .floating-label,
369
+ .select-wrapper.open .floating-label {
370
+ top: 0;
371
+ left: 12px;
372
+ font-size: var(--rel-body-sm-medium-font-size);
373
+ line-height: var(--rel-body-sm-medium-line-height);
374
+ letter-spacing: var(--rel-body-sm-medium-letter-spacing);
375
+ font-weight: var(--rel-body-xs-medium-font-weight);
376
+ color: var(--rel-select-label-color, var(--rel-text-label));
377
+ }
378
+
379
+ /* The real placeholder hides while the float-label rests in its spot,
380
+ and fades in once the label has moved up to the border. */
381
+ .select-wrapper.floating .select-value.placeholder {
382
+ opacity: 0;
383
+ transition: opacity 0.1s ease;
384
+ }
385
+
386
+ .select-wrapper.floating.focused .select-value.placeholder,
387
+ .select-wrapper.floating.open .select-value.placeholder {
388
+ opacity: 1;
389
+ }
390
+
391
+ /* Supporting text */
392
+ .select-support {
393
+ margin-top: var(--rel-spacing-3xs);
394
+ font-size: 13px;
395
+ color: var(--rel-select-supporting-color, var(--rel-text-caption));
396
+ }
397
+
398
+ .select-support.error {
399
+ color: var(--rel-text-danger);
400
+ }
401
+
402
+ /* ── Dropdown listbox ── */
403
+ .select-listbox {
404
+ position: fixed;
405
+ z-index: 1001;
406
+ display: none;
407
+ /* Reset native [popover] UA styles (the listbox is promoted to the
408
+ top layer so transformed ancestors — e.g. a centered rel-modal
409
+ panel — can't hijack its containing block or clip it). */
410
+ inset: auto;
411
+ margin: 0;
412
+ padding: 0;
413
+ width: auto;
414
+ height: auto;
415
+ color: inherit;
416
+ box-sizing: border-box;
417
+ background: var(--rel-select-bg, var(--rel-bg-neutral));
418
+ border: 1px solid var(--rel-select-menu-border, var(--rel-border-default));
419
+ border-radius: var(--rel-select-menu-radius, var(--rel-border-radius-sm));
420
+ /* A border alone doesn't read clearly against a similarly-light page,
421
+ and a shadow alone barely shows on a dark background — together
422
+ they hold up in both themes. */
423
+ box-shadow: var(--rel-select-menu-shadow, var(--rel-shadows-shadow-300));
424
+ max-height: 360px;
425
+ overflow-y: auto;
426
+ }
427
+
428
+ .select-listbox[data-open] {
429
+ display: block;
430
+ }
431
+
432
+ /* Search and Select All pin together while the options scroll beneath.
433
+ z-index is load-bearing: multiselect rows contain rel-checkbox, whose
434
+ .row wrapper is position:relative (Tab-scroll fix), so without it the
435
+ positioned rows paint over the sticky header in DOM order. */
436
+ .select-header {
437
+ position: sticky;
438
+ top: 0;
439
+ z-index: 1;
440
+ background: var(--rel-select-bg, var(--rel-bg-neutral));
441
+ }
442
+
443
+ .select-search {
444
+ padding: var(--rel-spacing-xs);
445
+ border-bottom: 1px solid var(--rel-select-divider, var(--rel-border-subtle));
446
+ }
447
+
448
+ /* Base = "small" textfield sizing, shared by both small AND medium
449
+ select — only "large" select bumps the search field up to "medium". */
450
+ .search-input-wrap {
451
+ display: flex;
452
+ align-items: center;
453
+ gap: 8px;
454
+ border: 1px solid var(--rel-select-search-border, var(--rel-border-default));
455
+ border-radius: 4px;
456
+ padding: var(--rel-spacing-xs) var(--rel-spacing-sm);
457
+ }
458
+
459
+ .search-input-wrap .icon {
460
+ display: flex;
461
+ align-items: center;
462
+ flex-shrink: 0;
463
+ color: var(--rel-select-icon-color, var(--rel-text-default));
464
+ }
465
+
466
+ .search-input {
467
+ flex: 1;
468
+ min-width: 0;
469
+ border: none;
470
+ outline: none;
471
+ background: transparent;
472
+ color: var(--rel-select-value-color, var(--rel-text-default));
473
+ font-family: var(--rel-body-sm-regular-font-family);
474
+ font-weight: var(--rel-body-sm-regular-font-weight);
475
+ font-size: var(--rel-body-sm-regular-font-size);
476
+ line-height: var(--rel-body-sm-regular-line-height);
477
+ letter-spacing: var(--rel-body-sm-regular-letter-spacing);
478
+ }
479
+
480
+ .search-input::placeholder {
481
+ color: var(--rel-select-placeholder-color, var(--rel-text-placeholder));
482
+ }
483
+
484
+ :host([size="large"]) .search-input-wrap {
485
+ padding: 12px;
486
+ }
487
+
488
+ :host([size="large"]) .search-input {
489
+
490
+ font-family: var(--rel-body-md-regular-font-family);
491
+
492
+ font-weight: var(--rel-body-md-regular-font-weight);
493
+
494
+ font-size: var(--rel-body-md-regular-font-size);
495
+
496
+ line-height: var(--rel-body-md-regular-line-height);
497
+
498
+ letter-spacing: var(--rel-body-md-regular-letter-spacing);
499
+
500
+ }
501
+
502
+ .select-options {
503
+ padding: 4px 0;
504
+ }
505
+
506
+ .select-option {
507
+ display: flex;
508
+ align-items: center;
509
+ justify-content: space-between;
510
+ gap: 12px;
511
+ padding: var(--rel-spacing-xs) 12px;
512
+ color: var(--rel-select-value-color, var(--rel-text-default));
513
+ cursor: pointer;
514
+ font-family: var(--rel-body-md-regular-font-family);
515
+ font-weight: var(--rel-body-md-regular-font-weight);
516
+ font-size: var(--rel-body-md-regular-font-size);
517
+ line-height: var(--rel-body-md-regular-line-height);
518
+ letter-spacing: var(--rel-body-md-regular-letter-spacing);
519
+ }
520
+
521
+ /* Groups the optional prefix icon with the label so the trailing
522
+ check indicator stays pinned to the right edge of the row. */
523
+ .select-option-content {
524
+ flex: 1;
525
+ min-width: 0;
526
+ display: flex;
527
+ align-items: center;
528
+ gap: var(--rel-spacing-xs);
529
+ }
530
+
531
+ .select-option-icon {
532
+ flex-shrink: 0;
533
+ color: var(--rel-select-icon-color, var(--rel-text-default));
534
+ }
535
+
536
+ .select-option-label {
537
+ overflow: hidden;
538
+ text-overflow: ellipsis;
539
+ white-space: nowrap;
540
+ }
541
+
542
+ .select-option-check {
543
+ flex-shrink: 0;
544
+ color: var(--rel-select-value-color, var(--rel-text-default));
545
+ }
546
+
547
+ .select-option:hover,
548
+ .select-option.highlighted {
549
+ background: var(--rel-select-option-hover, var(--rel-bg-neutral-elevated-1));
550
+ }
551
+
552
+ .select-option[aria-selected="true"] {
553
+ font-weight: var(--rel-body-md-medium-font-weight);
554
+ }
555
+
556
+ :host([size="large"]) .select-option[aria-selected="true"] {
557
+ font-weight: var(--rel-body-lg-medium-font-weight);
558
+ }
559
+
560
+ .checkbox-option {
561
+ padding: 12px;
562
+ }
563
+
564
+ .checkbox-option:hover,
565
+ .checkbox-option.highlighted {
566
+ background: var(--rel-select-option-hover, var(--rel-bg-neutral-elevated-1));
567
+ }
568
+
569
+ .select-all-row {
570
+ border-bottom: 1px solid var(--rel-select-divider, var(--rel-border-subtle));
571
+ padding: 12px;
572
+ }
573
+
574
+ .select-empty {
575
+ padding: var(--rel-spacing-xs) 12px;
576
+ color: var(--rel-select-placeholder-color, var(--rel-text-body));
577
+ font-family: var(--rel-body-sm-regular-font-family);
578
+ font-weight: var(--rel-body-sm-regular-font-weight);
579
+ font-size: var(--rel-body-sm-regular-font-size);
580
+ line-height: var(--rel-body-sm-regular-line-height);
581
+ letter-spacing: var(--rel-body-sm-regular-letter-spacing);
582
+ }
583
+
584
+ `;
585
+
586
+ connectedCallback() {
587
+ super.connectedCallback();
588
+ // firstUpdated only runs once — re-observe if the element is re-attached.
589
+ if (this.chipResizeObserver && this.triggerEl) {
590
+ this.chipResizeObserver.observe(this.triggerEl);
591
+ }
592
+ }
593
+
594
+ disconnectedCallback() {
595
+ super.disconnectedCallback();
596
+ this.removeGlobalListeners();
597
+ this.hideNativePopover();
598
+ this.chipResizeObserver?.disconnect();
599
+ }
600
+
601
+ protected firstUpdated() {
602
+ this.chipResizeObserver = new ResizeObserver(() => this.computeVisibleChips());
603
+ this.chipResizeObserver.observe(this.triggerEl);
604
+ }
605
+
606
+ protected willUpdate(changed: PropertyValues<this>) {
607
+ if (changed.has("multiple") && this.multiple === false) {
608
+ this.selectedValues = [];
609
+ }
610
+ }
611
+
612
+ private _warnedNoName = false;
613
+
614
+ protected updated(changed: PropertyValues<this>) {
615
+ if (
616
+ !this._warnedNoName &&
617
+ this.labelStyle === "none" &&
618
+ !this.fieldAriaLabel &&
619
+ !this.fieldAriaLabelledby &&
620
+ !this.getAttribute("aria-label")
621
+ ) {
622
+ this._warnedNoName = true;
623
+ console.warn(
624
+ '<rel-select label-style="none"> has no accessible name. Set ' +
625
+ "`field-aria-label` or `field-aria-labelledby` — a placeholder is not a " +
626
+ "valid naming mechanism.",
627
+ this
628
+ );
629
+ }
630
+
631
+ if (
632
+ changed.has("selectedValues") ||
633
+ changed.has("options") ||
634
+ changed.has("multiple") ||
635
+ changed.has("size")
636
+ ) {
637
+ // rAF: rel-chip renders in its own (microtask) update cycle, so its
638
+ // width isn't measurable synchronously here — by the next frame it is.
639
+ requestAnimationFrame(() => this.computeVisibleChips());
640
+ }
641
+ }
642
+
643
+ /**
644
+ * Width-adaptive chip collapsing: measures every selected chip in the
645
+ * hidden .select-chips-measure row and works out how many fit in the value
646
+ * area, always reserving room for the trailing "+N" chip when not all fit.
647
+ * At least one chip stays visible no matter how narrow the field gets.
648
+ */
649
+ private computeVisibleChips() {
650
+ if (!this.isConnected || !this.multiple || this.selectedValues.length === 0) return;
651
+ const measure = this.chipsMeasureEl;
652
+ const container = this.valueEl;
653
+ if (!measure || !container) return;
654
+
655
+ const available = container.clientWidth;
656
+ if (available <= 0) return; // hidden (display:none) — RO will refire when visible
657
+
658
+ const children = Array.from(measure.children) as HTMLElement[];
659
+ if (children.length < 2) return;
660
+
661
+ const gap = RelSelect.CHIP_GAP;
662
+ // Last measure child is the worst-case "+N" chip (N = total selected,
663
+ // i.e. the widest label the badge can ever need).
664
+ const overflowWidth = children[children.length - 1].offsetWidth;
665
+ const chipWidths = children.slice(0, -1).map((c) => c.offsetWidth);
666
+ const total = chipWidths.reduce((sum, w) => sum + w, 0) + gap * (chipWidths.length - 1);
667
+
668
+ let fit: number;
669
+ if (total <= available) {
670
+ fit = chipWidths.length;
671
+ } else {
672
+ fit = 0;
673
+ let used = 0;
674
+ for (let i = 0; i < chipWidths.length; i++) {
675
+ const w = chipWidths[i] + (i > 0 ? gap : 0);
676
+ if (used + w + gap + overflowWidth <= available) {
677
+ used += w;
678
+ fit = i + 1;
679
+ } else {
680
+ break;
681
+ }
682
+ }
683
+ fit = Math.max(1, fit);
684
+ }
685
+
686
+ if (fit !== this.visibleChipCount) this.visibleChipCount = fit;
687
+ }
688
+
689
+ private get normalizedOptions(): NormalizedOption[] {
690
+ return this.options.map(normalizeOption);
691
+ }
692
+
693
+ /** Options matching the current search text (substring match, case-insensitive). */
694
+ private get filteredOptions(): NormalizedOption[] {
695
+ const opts = this.normalizedOptions;
696
+ if (!this.searchValue) return opts;
697
+ const v = this.searchValue.toLowerCase();
698
+ return opts.filter((o) => o.label.toLowerCase().includes(v));
699
+ }
700
+
701
+ private get hasValue(): boolean {
702
+ return this.multiple ? this.selectedValues.length > 0 : !!this.selected;
703
+ }
704
+
705
+ /** Icon size scales with the select's own size, matching the trigger. */
706
+ private get iconSize(): "xs" | "sm" | "md" {
707
+ return this.size === "small" ? "xs" : this.size === "large" ? "md" : "sm";
708
+ }
709
+
710
+ /** The search field uses "small" sizing for both small and medium select — only "large" select bumps it to "medium". */
711
+ private get searchIconSize(): "sm" | "md" {
712
+ return this.size === "large" ? "md" : "sm";
713
+ }
714
+
715
+ private get selectAllStatus(): "checked" | "unchecked" | "indeterminate" {
716
+ const filtered = this.filteredOptions;
717
+ if (filtered.length === 0) return "unchecked";
718
+ const selectedCount = filtered.filter((o) => this.selectedValues.includes(o.value)).length;
719
+ if (selectedCount === 0) return "unchecked";
720
+ if (selectedCount === filtered.length) return "checked";
721
+ return "indeterminate";
722
+ }
723
+
724
+ private addGlobalListeners() {
725
+ document.addEventListener("pointerdown", this.onOutsidePointerDown);
726
+ window.addEventListener("resize", this.updatePosition);
727
+ window.addEventListener("scroll", this.onPageScroll, true);
728
+ }
729
+
730
+ private removeGlobalListeners() {
731
+ document.removeEventListener("pointerdown", this.onOutsidePointerDown);
732
+ window.removeEventListener("resize", this.updatePosition);
733
+ window.removeEventListener("scroll", this.onPageScroll, true);
734
+ }
735
+
736
+ private onOutsidePointerDown = (e: PointerEvent) => {
737
+ if (!this.open) return;
738
+ const path = e.composedPath();
739
+ if (path.includes(this)) return;
740
+ this.closeListbox();
741
+ };
742
+
743
+ // Continuously re-deriving a fixed-position panel's coordinates from
744
+ // every page scroll event is fragile (it's what was causing the panel to
745
+ // jump to the top of the viewport). Instead, close the panel on any
746
+ // *outside* scroll, same as clicking outside — scrolling the option list
747
+ // itself (target is the listbox) is the one case that should NOT close it.
748
+ private onPageScroll = (e: Event) => {
749
+ if (!this.open) return;
750
+ if (e.composedPath()[0] === this.listboxEl) return;
751
+ this.closeListbox();
752
+ };
753
+
754
+ private emitChange() {
755
+ this.dispatchEvent(
756
+ new CustomEvent("changed", {
757
+ detail: { value: this.multiple ? this.selectedValues : this.selected },
758
+ bubbles: true,
759
+ composed: true,
760
+ })
761
+ );
762
+ }
763
+
764
+ private openListbox() {
765
+ if (this.state === "disabled" || this.open) return;
766
+ this.open = true;
767
+ this.searchValue = "";
768
+ // No pre-highlight — the first item showing a hover-style highlight
769
+ // before the user has touched anything reads as an unintended default.
770
+ // Highlight only kicks in once they actually hover or press an arrow key.
771
+ this.highlightedIndex = -1;
772
+ this.addGlobalListeners();
773
+ requestAnimationFrame(() => {
774
+ this.showNativePopover();
775
+ this.updatePosition();
776
+ // preventScroll: focusing the search field must not let the browser
777
+ // scroll the page into view — that would move the trigger (normal
778
+ // flow) out from under the panel (fixed position, already computed
779
+ // above), breaking the anchor. When there's no search field, focus
780
+ // simply stays on the trigger, which already has the nav keydown
781
+ // handling wired up for this case.
782
+ if (!this.noSearch) {
783
+ this.searchInputEl?.focus({ preventScroll: true });
784
+ }
785
+ });
786
+ }
787
+
788
+ private closeListbox() {
789
+ if (!this.open) return;
790
+ this.open = false;
791
+ this.removeGlobalListeners();
792
+ this.hideNativePopover();
793
+ this.triggerEl?.focus();
794
+ }
795
+
796
+ /* A transformed ancestor (e.g. rel-modal's centered panel with
797
+ * translate(-50%,-50%)) becomes the containing block for position:fixed
798
+ * descendants, breaking viewport-based coordinates and letting the
799
+ * panel's overflow:hidden clip the listbox. Promoting the listbox to
800
+ * the browser top layer sidesteps both — same fix as rel-popover /
801
+ * rel-autocomplete. `manual` keeps light-dismiss and Escape handling
802
+ * under this component's own control. */
803
+
804
+ private showNativePopover() {
805
+ const p = this.listboxEl;
806
+ if (!p || typeof p.showPopover !== "function") return;
807
+ try {
808
+ if (!p.matches(":popover-open")) p.showPopover();
809
+ } catch {
810
+ /* older engines / detached element — fixed-position fallback applies */
811
+ }
812
+ }
813
+
814
+ private hideNativePopover() {
815
+ const p = this.listboxEl;
816
+ if (!p || typeof p.hidePopover !== "function") return;
817
+ try {
818
+ if (p.matches(":popover-open")) p.hidePopover();
819
+ } catch {
820
+ /* already hidden or unsupported — nothing to do */
821
+ }
822
+ }
823
+
824
+ private updatePosition = () => {
825
+ if (!this.triggerEl || !this.listboxEl) return;
826
+
827
+ this.listboxEl.setAttribute("data-open", "");
828
+
829
+ const t = this.triggerEl.getBoundingClientRect();
830
+ const c = this.listboxEl.getBoundingClientRect();
831
+
832
+ let top = t.bottom + 4;
833
+ if (top + c.height > window.innerHeight - 8) {
834
+ top = Math.max(8, t.top - c.height - 4);
835
+ }
836
+
837
+ // Use t.width (the trigger's width, which is also what we set the panel's
838
+ // own width to below) rather than c.width — c.width reflects the
839
+ // *previous* render's panelStyle, so on the very next measurement it can
840
+ // be a frame stale, nudging left by a few px even when there's no real
841
+ // overflow. Checking against t.width directly removes that drift.
842
+ let left = t.left;
843
+ if (left + t.width > window.innerWidth - 8) {
844
+ left = Math.max(8, window.innerWidth - t.width - 8);
845
+ }
846
+
847
+ // Without top-layer support a transformed ancestor may be the containing
848
+ // block for position:fixed, shifting the listbox away from the viewport
849
+ // coordinates computed above. Apply, re-measure, and cancel the offset.
850
+ this.listboxEl.style.top = `${top}px`;
851
+ this.listboxEl.style.left = `${left}px`;
852
+ this.listboxEl.style.width = `${t.width}px`;
853
+ const applied = this.listboxEl.getBoundingClientRect();
854
+ top -= applied.top - top;
855
+ left -= applied.left - left;
856
+ this.listboxEl.style.top = `${top}px`;
857
+ this.listboxEl.style.left = `${left}px`;
858
+
859
+ this.panelStyle = `top:${top}px;left:${left}px;width:${t.width}px;`;
860
+ };
861
+
862
+ private selectSingleOption(option: NormalizedOption) {
863
+ this.selected = option.value;
864
+ if (this.state === "error") this.state = "default";
865
+ this.closeListbox();
866
+ this.emitChange();
867
+ }
868
+
869
+ private toggleMultiOption(option: NormalizedOption) {
870
+ const idx = this.selectedValues.indexOf(option.value);
871
+ this.selectedValues =
872
+ idx >= 0
873
+ ? this.selectedValues.filter((v) => v !== option.value)
874
+ : [...this.selectedValues, option.value];
875
+ if (this.state === "error") this.state = "default";
876
+ this.emitChange();
877
+ }
878
+
879
+ private toggleSelectAll() {
880
+ const filtered = this.filteredOptions;
881
+ const status = this.selectAllStatus;
882
+ if (status === "checked") {
883
+ const filteredValues = new Set(filtered.map((o) => o.value));
884
+ this.selectedValues = this.selectedValues.filter((v) => !filteredValues.has(v));
885
+ } else {
886
+ const toAdd = filtered.map((o) => o.value).filter((v) => !this.selectedValues.includes(v));
887
+ this.selectedValues = [...this.selectedValues, ...toAdd];
888
+ }
889
+ if (this.state === "error") this.state = "default";
890
+ this.emitChange();
891
+ }
892
+
893
+ private removeChip(value: string) {
894
+ if (this.state === "disabled") return;
895
+ this.selectedValues = this.selectedValues.filter((v) => v !== value);
896
+ this.emitChange();
897
+ }
898
+
899
+ private onTriggerClick() {
900
+ if (this.open) this.closeListbox();
901
+ else this.openListbox();
902
+ }
903
+
904
+ private onTriggerKeyDown(e: KeyboardEvent) {
905
+ if (this.state === "disabled") return;
906
+ if (!this.open) {
907
+ if (["ArrowDown", "ArrowUp", "Enter", " "].includes(e.key)) {
908
+ e.preventDefault();
909
+ this.openListbox();
910
+ }
911
+ return;
912
+ }
913
+ // No search field to hold focus/keydown in this mode — the trigger
914
+ // itself keeps focus while open, so it needs the same nav handling.
915
+ if (this.noSearch) this.handleListNavigation(e);
916
+ }
917
+
918
+ private onSearchInput = (e: InputEvent) => {
919
+ this.searchValue = (e.target as HTMLInputElement).value;
920
+ this.highlightedIndex = this.filteredOptions.length > 0 ? 0 : -1;
921
+ requestAnimationFrame(() => this.updatePosition());
922
+ };
923
+
924
+ private onSearchKeyDown(e: KeyboardEvent) {
925
+ this.handleListNavigation(e);
926
+ }
927
+
928
+ private handleListNavigation(e: KeyboardEvent) {
929
+ const filtered = this.filteredOptions;
930
+ switch (e.key) {
931
+ case "ArrowDown":
932
+ e.preventDefault();
933
+ this.highlightedIndex = Math.min(filtered.length - 1, this.highlightedIndex + 1);
934
+ break;
935
+ case "ArrowUp":
936
+ e.preventDefault();
937
+ this.highlightedIndex = Math.max(0, this.highlightedIndex - 1);
938
+ break;
939
+ case "Enter":
940
+ e.preventDefault();
941
+ if (this.highlightedIndex >= 0 && filtered[this.highlightedIndex]) {
942
+ const opt = filtered[this.highlightedIndex];
943
+ if (this.multiple) this.toggleMultiOption(opt);
944
+ else this.selectSingleOption(opt);
945
+ }
946
+ break;
947
+ case "Escape":
948
+ e.preventDefault();
949
+ this.closeListbox();
950
+ break;
951
+ case "Tab":
952
+ this.closeListbox();
953
+ break;
954
+ }
955
+ }
956
+
957
+ private renderChips() {
958
+ const values = this.selectedValues;
959
+ const visible = values.slice(0, Math.min(this.visibleChipCount, this.maxVisibleChips));
960
+ const overflow = values.length - visible.length;
961
+ const opts = this.normalizedOptions;
962
+
963
+ return html`
964
+ <span class="select-chips">
965
+ ${repeat(
966
+ visible,
967
+ (v) => v,
968
+ (v) => {
969
+ const opt = opts.find((o) => o.value === v);
970
+ // Keyed by value: rel-chip tracks its own "removed" flag
971
+ // internally once its (x) is clicked, so reusing DOM nodes
972
+ // positionally (plain .map()) could hand a freshly-shown value
973
+ // a node that still remembers being removed as a *different*
974
+ // value. Keying forces a fresh node per value instead.
975
+ return html`
976
+ <rel-chip
977
+ label="${opt?.label ?? v}"
978
+ size="sm"
979
+ variant="subtle"
980
+ border="default"
981
+ ?removable=${this.state !== "disabled"}
982
+ @click=${(e: Event) => e.stopPropagation()}
983
+ @removed=${(e: Event) => {
984
+ e.stopPropagation();
985
+ this.removeChip(v);
986
+ }}
987
+ ></rel-chip>
988
+ `;
989
+ }
990
+ )}
991
+ ${overflow > 0
992
+ ? html`<rel-chip label="+${overflow}" size="sm" variant="fill" border="default"></rel-chip>`
993
+ : nothing}
994
+ </span>
995
+ `;
996
+ }
997
+
998
+ /**
999
+ * Hidden, unconstrained copy of every selected chip used purely for width
1000
+ * measurement (see computeVisibleChips). Chips mirror the visible ones'
1001
+ * width-affecting props (removable adds the ✕ icon). The trailing chip is
1002
+ * the widest "+N" badge that could ever be needed.
1003
+ */
1004
+ private renderChipsMeasure() {
1005
+ const values = this.selectedValues;
1006
+ const opts = this.normalizedOptions;
1007
+ return html`
1008
+ <span class="select-chips-measure" aria-hidden="true">
1009
+ ${values.map((v) => {
1010
+ const opt = opts.find((o) => o.value === v);
1011
+ return html`
1012
+ <rel-chip
1013
+ label="${opt?.label ?? v}"
1014
+ size="sm"
1015
+ variant="subtle"
1016
+ border="default"
1017
+ ?removable=${this.state !== "disabled"}
1018
+ ></rel-chip>
1019
+ `;
1020
+ })}
1021
+ <rel-chip label="+${values.length}" size="sm" variant="fill" border="default"></rel-chip>
1022
+ </span>
1023
+ `;
1024
+ }
1025
+
1026
+ render() {
1027
+ const opts = this.normalizedOptions;
1028
+ const filtered = this.filteredOptions;
1029
+ const isDisabled = this.state === "disabled";
1030
+ const labelHidden = this.labelStyle === "none";
1031
+ const showFloatingChrome = this.labelStyle === "floating" && !!this.label;
1032
+ // With no visible label the ARIA name comes from fieldAriaLabel instead.
1033
+ const accessibleName = (labelHidden ? this.fieldAriaLabel : this.label) || "";
1034
+
1035
+ const wrapperClasses = [
1036
+ "select-wrapper",
1037
+ this.size,
1038
+ this.state,
1039
+ `border-${this.border}`,
1040
+ showFloatingChrome ? "floating" : "",
1041
+ this.internalState === "focused" ? "focused" : "",
1042
+ this.hasValue ? "has-value" : "",
1043
+ this.open ? "open" : "",
1044
+ ]
1045
+ .filter(Boolean)
1046
+ .join(" ");
1047
+
1048
+ const listboxId = `${this.uniqueId}-listbox`;
1049
+ const activeOptionId =
1050
+ this.open && this.highlightedIndex >= 0 ? `${this.uniqueId}-option-${this.highlightedIndex}` : "";
1051
+
1052
+ const selectedSingle = opts.find((o) => o.value === this.selected);
1053
+
1054
+ return html`
1055
+ <div class="${wrapperClasses}">
1056
+ ${labelHidden
1057
+ ? html`<div class="label-reserve" aria-hidden="true"></div>`
1058
+ : !showFloatingChrome && this.label
1059
+ ? html`<label part="label" class="select-label" for="${this.uniqueId}">${this.label}</label>`
1060
+ : ""}
1061
+
1062
+ <div class="select-container">
1063
+ ${showFloatingChrome
1064
+ ? html`<span class="floating-label${this.leftIcon ? " has-left-icon" : ""}"
1065
+ >${this.label}</span
1066
+ >`
1067
+ : ""}
1068
+
1069
+ <button
1070
+ id="${this.uniqueId}"
1071
+ type="button"
1072
+ part="trigger" class="select-trigger"
1073
+ role="combobox"
1074
+ aria-haspopup="listbox"
1075
+ aria-expanded="${this.open}"
1076
+ aria-controls="${listboxId}"
1077
+ aria-activedescendant="${activeOptionId}"
1078
+ aria-invalid="${this.state === "error"}"
1079
+ aria-label="${this.fieldAriaLabelledby ? nothing : accessibleName || this.placeholder}"
1080
+ aria-labelledby="${this.fieldAriaLabelledby ?? nothing}"
1081
+ ?disabled="${isDisabled}"
1082
+ @click="${this.onTriggerClick}"
1083
+ @keydown="${this.onTriggerKeyDown}"
1084
+ @focus="${() => (this.internalState = "focused")}"
1085
+ @blur="${() => (this.internalState = "default")}"
1086
+ >
1087
+ ${this.leftIcon
1088
+ ? html`<rel-icon name="${this.leftIcon}" size="${this.iconSize}" class="icon left"></rel-icon>`
1089
+ : ""}
1090
+
1091
+ ${this.multiple
1092
+ ? this.selectedValues.length > 0
1093
+ ? html`<span part="value" class="select-value">${this.renderChips()}</span>`
1094
+ : html`<span part="value" class="select-value placeholder">
1095
+ <span class="select-value-text">${this.placeholder}</span>
1096
+ </span>`
1097
+ : html`<span part="value" class="select-value ${selectedSingle ? "" : "placeholder"}">
1098
+ <span class="select-value-text"
1099
+ >${selectedSingle ? selectedSingle.label : this.placeholder}</span
1100
+ >
1101
+ </span>`}
1102
+
1103
+ <rel-icon
1104
+ name="${this.rightIcon || "chevron-down"}"
1105
+ size="${this.iconSize}"
1106
+ class="icon ${this.rightIcon ? "" : "chevron"}"
1107
+ ></rel-icon>
1108
+ </button>
1109
+
1110
+ ${this.multiple && this.selectedValues.length > 0 ? this.renderChipsMeasure() : nothing}
1111
+ </div>
1112
+
1113
+ ${this.supportingText
1114
+ ? html`<span part="helper" class="select-support ${this.state === "error" ? "error" : ""}">
1115
+ ${this.supportingText}
1116
+ </span>`
1117
+ : ""}
1118
+ </div>
1119
+
1120
+ <div
1121
+ id="${listboxId}"
1122
+ part="panel list" class="select-listbox"
1123
+ popover="manual"
1124
+ role="listbox"
1125
+ aria-multiselectable="${this.multiple}"
1126
+ aria-label="${accessibleName || "Options"}"
1127
+ style="${this.panelStyle}"
1128
+ ?data-open="${this.open}"
1129
+ >
1130
+ ${!this.noSearch || (this.multiple && filtered.length > 0)
1131
+ ? html`<div class="select-header">
1132
+ ${!this.noSearch
1133
+ ? html`<div class="select-search">
1134
+ <div class="search-input-wrap">
1135
+ <rel-icon name="search" size="${this.searchIconSize}" class="icon"></rel-icon>
1136
+ <input
1137
+ part="input" class="search-input"
1138
+ type="text"
1139
+ placeholder="${this.searchPlaceholder}"
1140
+ .value="${this.searchValue}"
1141
+ @input="${this.onSearchInput}"
1142
+ @keydown="${(e: KeyboardEvent) => this.onSearchKeyDown(e)}"
1143
+ />
1144
+ </div>
1145
+ </div>`
1146
+ : ""}
1147
+ ${this.multiple && filtered.length > 0
1148
+ ? html`<div class="select-all-row">
1149
+ <rel-checkbox
1150
+ label="${this.selectAllLabel}"
1151
+ status="${this.selectAllStatus}"
1152
+ @rel-change=${(e: Event) => {
1153
+ e.stopPropagation();
1154
+ this.toggleSelectAll();
1155
+ }}
1156
+ ></rel-checkbox>
1157
+ </div>`
1158
+ : ""}
1159
+ </div>`
1160
+ : ""}
1161
+
1162
+ ${filtered.length === 0
1163
+ ? html`<div class="select-empty">
1164
+ ${opts.length === 0 ? "No options available" : "No matches found"}
1165
+ </div>`
1166
+ : this.multiple
1167
+ ? html`
1168
+ <div class="select-options">
1169
+ ${repeat(
1170
+ filtered,
1171
+ (option) => option.value,
1172
+ (option, index) => html`
1173
+ <div
1174
+ id="${this.uniqueId}-option-${index}"
1175
+ class="checkbox-option ${index === this.highlightedIndex ? "highlighted" : ""}"
1176
+ role="option"
1177
+ aria-selected="${this.selectedValues.includes(option.value)}"
1178
+ @pointerenter="${() => (this.highlightedIndex = index)}"
1179
+ >
1180
+ <rel-checkbox
1181
+ label="${option.label}"
1182
+ icon="${option.icon}"
1183
+ supportingtext="${option.supportingText}"
1184
+ status="${this.selectedValues.includes(option.value) ? "checked" : "unchecked"}"
1185
+ @rel-change=${(e: Event) => {
1186
+ e.stopPropagation();
1187
+ this.toggleMultiOption(option);
1188
+ }}
1189
+ ></rel-checkbox>
1190
+ </div>
1191
+ `
1192
+ )}
1193
+ </div>
1194
+ `
1195
+ : html`
1196
+ <div class="select-options">
1197
+ ${repeat(
1198
+ filtered,
1199
+ (option) => option.value,
1200
+ (option, index) => html`
1201
+ <div
1202
+ id="${this.uniqueId}-option-${index}"
1203
+ part="option" class="select-option ${index === this.highlightedIndex ? "highlighted" : ""}"
1204
+ role="option"
1205
+ aria-selected="${option.value === this.selected}"
1206
+ @mousedown="${(e: Event) => e.preventDefault()}"
1207
+ @click="${() => this.selectSingleOption(option)}"
1208
+ @pointerenter="${() => (this.highlightedIndex = index)}"
1209
+ >
1210
+ <span class="select-option-content">
1211
+ ${option.icon
1212
+ ? html`<rel-icon
1213
+ name="${option.icon}"
1214
+ size="sm"
1215
+ class="select-option-icon"
1216
+ ></rel-icon>`
1217
+ : nothing}
1218
+ <span class="select-option-label">${option.label}</span>
1219
+ </span>
1220
+ ${option.value === this.selected
1221
+ ? html`<rel-icon name="check" size="sm" class="select-option-check"></rel-icon>`
1222
+ : ""}
1223
+ </div>
1224
+ `
1225
+ )}
1226
+ </div>
1227
+ `}
1228
+ </div>
1229
+ `;
1230
+ }
1231
+ }
1232
+
1233
+ declare global {
1234
+ interface HTMLElementTagNameMap {
1235
+ "rel-select": RelSelect;
1236
+ }
1237
+ }