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