@glasshome/ui 1.10.0 → 1.10.1

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.
Files changed (103) hide show
  1. package/package.json +5 -2
  2. package/scripts/check-pack.ts +32 -0
  3. package/src/index.ts +111 -0
  4. package/src/solid/accordion.tsx +60 -0
  5. package/src/solid/alert-dialog.tsx +148 -0
  6. package/src/solid/alert.tsx +118 -0
  7. package/src/solid/area-picker.tsx +225 -0
  8. package/src/solid/aspect-ratio.tsx +21 -0
  9. package/src/solid/avatar.tsx +41 -0
  10. package/src/solid/badge.tsx +74 -0
  11. package/src/solid/bottom-sheet/arbitration.ts +40 -0
  12. package/src/solid/bottom-sheet/bottom-sheet.tsx +457 -0
  13. package/src/solid/bottom-sheet/constants.ts +8 -0
  14. package/src/solid/bottom-sheet/drag-controller.ts +221 -0
  15. package/src/solid/bottom-sheet/focus-trap.ts +56 -0
  16. package/src/solid/bottom-sheet/index.ts +14 -0
  17. package/src/solid/bottom-sheet/keyboard.ts +35 -0
  18. package/src/solid/bottom-sheet/scroll-lock.ts +64 -0
  19. package/src/solid/bottom-sheet/state-machine.ts +40 -0
  20. package/src/solid/bottom-sheet/velocity.ts +42 -0
  21. package/src/solid/breadcrumb.tsx +105 -0
  22. package/src/solid/button-group.tsx +66 -0
  23. package/src/solid/button.tsx +20 -0
  24. package/src/solid/card.tsx +101 -0
  25. package/src/solid/carousel.tsx +302 -0
  26. package/src/solid/charts.tsx +338 -0
  27. package/src/solid/checkbox.tsx +70 -0
  28. package/src/solid/collapsible.tsx +38 -0
  29. package/src/solid/color-slider.tsx +98 -0
  30. package/src/solid/color-wheel.tsx +77 -0
  31. package/src/solid/context-menu.tsx +109 -0
  32. package/src/solid/copy-button.tsx +46 -0
  33. package/src/solid/count-pill.tsx +24 -0
  34. package/src/solid/data-table.tsx +248 -0
  35. package/src/solid/dialog-parts.tsx +242 -0
  36. package/src/solid/dialog.tsx +121 -0
  37. package/src/solid/dock.tsx +186 -0
  38. package/src/solid/dropdown-menu.tsx +130 -0
  39. package/src/solid/empty.tsx +99 -0
  40. package/src/solid/entity-data.ts +78 -0
  41. package/src/solid/entity-selector.tsx +697 -0
  42. package/src/solid/field.tsx +253 -0
  43. package/src/solid/form.tsx +231 -0
  44. package/src/solid/hero-action.tsx +117 -0
  45. package/src/solid/hover-card.tsx +26 -0
  46. package/src/solid/icon-picker.tsx +432 -0
  47. package/src/solid/icon.tsx +20 -0
  48. package/src/solid/image-picker.tsx +380 -0
  49. package/src/solid/index.ts +417 -0
  50. package/src/solid/input-group.tsx +170 -0
  51. package/src/solid/input-otp.tsx +175 -0
  52. package/src/solid/input.tsx +12 -0
  53. package/src/solid/item.tsx +179 -0
  54. package/src/solid/kbd.tsx +30 -0
  55. package/src/solid/label.tsx +19 -0
  56. package/src/solid/list-reorder.ts +148 -0
  57. package/src/solid/logo.tsx +79 -0
  58. package/src/solid/media-copy.ts +37 -0
  59. package/src/solid/media-store.ts +110 -0
  60. package/src/solid/media-tile.tsx +100 -0
  61. package/src/solid/menu-parts.tsx +248 -0
  62. package/src/solid/number-field.tsx +72 -0
  63. package/src/solid/option-card.tsx +218 -0
  64. package/src/solid/ornament.tsx +53 -0
  65. package/src/solid/overlay.tsx +16 -0
  66. package/src/solid/page-header.tsx +102 -0
  67. package/src/solid/pagination.tsx +111 -0
  68. package/src/solid/password-input.tsx +69 -0
  69. package/src/solid/picker-row.tsx +102 -0
  70. package/src/solid/picker-search.tsx +78 -0
  71. package/src/solid/popover.tsx +103 -0
  72. package/src/solid/progress.tsx +31 -0
  73. package/src/solid/radio-group.tsx +60 -0
  74. package/src/solid/resizable.tsx +149 -0
  75. package/src/solid/responsive-dialog.tsx +180 -0
  76. package/src/solid/schema-form.tsx +830 -0
  77. package/src/solid/scope-indicator.tsx +13 -0
  78. package/src/solid/scroll-area.tsx +27 -0
  79. package/src/solid/section-card.tsx +358 -0
  80. package/src/solid/select.tsx +139 -0
  81. package/src/solid/separator.tsx +35 -0
  82. package/src/solid/settings-row.tsx +159 -0
  83. package/src/solid/sheet.tsx +157 -0
  84. package/src/solid/skeleton.tsx +15 -0
  85. package/src/solid/slider.tsx +148 -0
  86. package/src/solid/sliding-indicator.tsx +294 -0
  87. package/src/solid/sonner.tsx +219 -0
  88. package/src/solid/spinner.tsx +20 -0
  89. package/src/solid/step-indicator.tsx +30 -0
  90. package/src/solid/switch.tsx +62 -0
  91. package/src/solid/table.tsx +98 -0
  92. package/src/solid/tabs.tsx +86 -0
  93. package/src/solid/textarea.tsx +16 -0
  94. package/src/solid/toggle-group.tsx +102 -0
  95. package/src/solid/toggle.tsx +57 -0
  96. package/src/solid/tooltip.tsx +38 -0
  97. package/src/solid/widget-card.tsx +117 -0
  98. package/src/solid/widget-identity.tsx +135 -0
  99. package/src/solid/widget-trust-badge.tsx +37 -0
  100. package/src/tokens/hex.ts +50 -0
  101. package/src/tokens/index.ts +8 -0
  102. package/src/tokens/presets.ts +192 -0
  103. package/src/tokens/theme-colors.ts +147 -0
@@ -0,0 +1,697 @@
1
+ import {
2
+ createEffect,
3
+ createMemo,
4
+ createSignal,
5
+ createUniqueId,
6
+ For,
7
+ on,
8
+ onCleanup,
9
+ type ParentComponent,
10
+ Show,
11
+ } from "solid-js";
12
+ import { MENU_LABEL } from "../lib/menu-classes.js";
13
+ import { PICKER_LIST, PICKER_TRIGGER } from "../lib/picker-classes.js";
14
+ import { createIsMobile } from "../lib/use-is-mobile.js";
15
+ import { cn } from "../lib/utils.js";
16
+ import {
17
+ BottomSheet,
18
+ BottomSheetContent,
19
+ BottomSheetHandle,
20
+ BottomSheetOverlay,
21
+ BottomSheetPortal,
22
+ } from "./bottom-sheet/index.js";
23
+ import { type EntityViewLike, useEntityData } from "./entity-data.js";
24
+ import { Icon } from "./icon.js";
25
+ import { PICKER_ROW_HEIGHT, PickerRow } from "./picker-row.js";
26
+ import { PickerSearch } from "./picker-search.js";
27
+ import { Popover, PopoverAnchor, PopoverContent } from "./popover.js";
28
+ import { SlidingIndicator } from "./sliding-indicator.js";
29
+
30
+ interface EntitySelectorProps {
31
+ entityIds: string[];
32
+ onEntityIdsChange: (ids: string[]) => void;
33
+ domain: string;
34
+ /** Restrict the list to entities of this device_class (with a
35
+ * unit-of-measurement fallback for power/energy sensors that lack one). */
36
+ deviceClass?: string;
37
+ multiple?: boolean;
38
+ /** Id of the element naming the trigger, for forms that label it outside. */
39
+ "aria-labelledby"?: string;
40
+ }
41
+
42
+ // Many real-world power/energy sensors carry a unit but no device_class.
43
+ const DEVICE_CLASS_UNIT_FALLBACK: Record<string, readonly string[]> = {
44
+ power: ["W", "kW"],
45
+ energy: ["Wh", "kWh"],
46
+ };
47
+
48
+ const HEADER_HEIGHT = 30;
49
+ const ROW_HEIGHT = PICKER_ROW_HEIGHT;
50
+ const OVERSCAN_PX = 200;
51
+ const NO_AREA_KEY = "__no_area__";
52
+ const FALLBACK_ICON = "mdi:shape-outline";
53
+
54
+ // Rows carry only stable identity (no live EntityView): row objects must keep
55
+ // referential equality across entity state ticks so <For> never remounts DOM
56
+ // (remounting <iconify-icon> blanks the icon for a frame). Live state is read
57
+ // per-row via getEntityView.
58
+ type ListRow =
59
+ | { kind: "header"; key: string; label: string }
60
+ | { kind: "entity"; key: string; id: string; entityIndex: number };
61
+
62
+ function sameRow(a: ListRow, b: ListRow): boolean {
63
+ if (a.kind === "header" && b.kind === "header") return a.label === b.label;
64
+ if (a.kind === "entity" && b.kind === "entity")
65
+ return a.id === b.id && a.entityIndex === b.entityIndex;
66
+ return false;
67
+ }
68
+
69
+ function isUnavailable(view: EntityViewLike) {
70
+ return view.state === "unavailable" || view.state === "unknown";
71
+ }
72
+
73
+ function stateLabel(view: EntityViewLike) {
74
+ if (isUnavailable(view)) return "Unavailable";
75
+ const unit = view.unitOfMeasurement;
76
+ return unit ? `${view.state} ${unit}` : view.state;
77
+ }
78
+
79
+ export function EntitySelector(props: EntitySelectorProps) {
80
+ const data = useEntityData();
81
+ const isMobile = createIsMobile();
82
+ const listboxId = createUniqueId();
83
+ const [open, setOpen] = createSignal(false);
84
+ const [search, setSearch] = createSignal("");
85
+ const [showDiagnostics, setShowDiagnostics] = createSignal(false);
86
+ const [activeIndex, setActiveIndex] = createSignal(0);
87
+
88
+ let inputRef: HTMLInputElement | undefined;
89
+ let scrollRef: HTMLDivElement | undefined;
90
+ const [scrollTop, setScrollTop] = createSignal(0);
91
+ const [viewportHeight, setViewportHeight] = createSignal(320);
92
+
93
+ const domainEntityIds = createMemo(() => data.entityIdsByDomain()[props.domain] ?? []);
94
+ const subscribedIds = createMemo(() => (open() ? domainEntityIds() : props.entityIds));
95
+ const allViews = data.useEntities(subscribedIds);
96
+ const areas = data.useAreas();
97
+ const areaNameById = createMemo(() => new Map(areas().map((a) => [a.id, a.name])));
98
+ const selectedSet = createMemo(() => new Set(props.entityIds));
99
+
100
+ const usableViews = createMemo(() => allViews().filter((v) => !v.isHidden && !v.isDisabled));
101
+
102
+ const classFiltered = createMemo(() => {
103
+ const wanted = props.deviceClass;
104
+ if (!wanted) return usableViews();
105
+ const units = DEVICE_CLASS_UNIT_FALLBACK[wanted];
106
+ return usableViews().filter((v) => {
107
+ if (v.deviceClass === wanted) return true;
108
+ return units != null && v.unitOfMeasurement != null && units.includes(v.unitOfMeasurement);
109
+ });
110
+ });
111
+
112
+ const classExcludedCount = createMemo(() =>
113
+ props.deviceClass ? usableViews().length - classFiltered().length : 0,
114
+ );
115
+
116
+ const classExcludedMessage = () => {
117
+ const n = classExcludedCount();
118
+ const hidden =
119
+ n === 1
120
+ ? `1 ${props.domain} entity was hidden because it does not`
121
+ : `${n} ${props.domain} entities were hidden because they do not`;
122
+ return `No ${props.deviceClass} ${props.domain} entities found. ${hidden} report ${props.deviceClass}.`;
123
+ };
124
+
125
+ const diagnosticCount = createMemo(
126
+ () => classFiltered().filter((v) => v.entityCategory != null).length,
127
+ );
128
+
129
+ const pool = createMemo(() =>
130
+ showDiagnostics() ? classFiltered() : classFiltered().filter((v) => v.entityCategory == null),
131
+ );
132
+
133
+ const searched = createMemo(() => {
134
+ const q = search().trim().toLowerCase();
135
+ if (!q) return pool();
136
+ const names = areaNameById();
137
+ return pool().filter((v) => {
138
+ if (v.id.toLowerCase().includes(q)) return true;
139
+ if (v.friendlyName.toLowerCase().includes(q)) return true;
140
+ if (v.name.toLowerCase().includes(q)) return true;
141
+ if (v.aliases.some((a) => a.toLowerCase().includes(q))) return true;
142
+ const areaName = v.areaId ? names.get(v.areaId) : undefined;
143
+ return areaName?.toLowerCase().includes(q) ?? false;
144
+ });
145
+ });
146
+
147
+ // Reuse previous row objects when nothing changed so downstream memos and
148
+ // <For> see identical references on every entity state tick.
149
+ let prevRows: ListRow[] = [];
150
+ const rows = createMemo<ListRow[]>(() => {
151
+ const byAreaKey = new Map<string, EntityViewLike[]>();
152
+ for (const v of searched()) {
153
+ const key = v.areaId ?? NO_AREA_KEY;
154
+ const bucket = byAreaKey.get(key);
155
+ if (bucket) bucket.push(v);
156
+ else byAreaKey.set(key, [v]);
157
+ }
158
+ const names = areaNameById();
159
+ const groups = Array.from(byAreaKey.entries())
160
+ .map(([key, views]) => ({
161
+ areaKey: key,
162
+ label: key === NO_AREA_KEY ? "Other" : (names.get(key) ?? key),
163
+ noArea: key === NO_AREA_KEY,
164
+ views: views.sort((a, b) => a.friendlyName.localeCompare(b.friendlyName)),
165
+ }))
166
+ .sort((a, b) => {
167
+ if (a.noArea !== b.noArea) return a.noArea ? 1 : -1;
168
+ return a.label.localeCompare(b.label);
169
+ });
170
+
171
+ const flat: ListRow[] = [];
172
+ let entityIndex = 0;
173
+ for (const group of groups) {
174
+ flat.push({ kind: "header", key: `h:${group.areaKey}`, label: group.label });
175
+ for (const view of group.views) {
176
+ flat.push({ kind: "entity", key: `e:${view.id}`, id: view.id, entityIndex });
177
+ entityIndex++;
178
+ }
179
+ }
180
+
181
+ const prevByKey = new Map(prevRows.map((r) => [r.key, r]));
182
+ let changed = flat.length !== prevRows.length;
183
+ const out = flat.map((row, i) => {
184
+ const prev = prevByKey.get(row.key);
185
+ if (prev && sameRow(prev, row)) {
186
+ if (prev !== prevRows[i]) changed = true;
187
+ return prev;
188
+ }
189
+ changed = true;
190
+ return row;
191
+ });
192
+ if (!changed) return prevRows;
193
+ prevRows = out;
194
+ return out;
195
+ });
196
+
197
+ const entityRows = createMemo(
198
+ () => rows().filter((r) => r.kind === "entity") as Extract<ListRow, { kind: "entity" }>[],
199
+ );
200
+
201
+ // Prefix-summed pixel offsets; offsets()[i] is the top of row i.
202
+ const offsets = createMemo(() => {
203
+ const r = rows();
204
+ const out = new Array<number>(r.length + 1);
205
+ out[0] = 0;
206
+ for (let i = 0; i < r.length; i++) {
207
+ const row = r[i];
208
+ const h = row && row.kind === "header" ? HEADER_HEIGHT : ROW_HEIGHT;
209
+ out[i + 1] = (out[i] ?? 0) + h;
210
+ }
211
+ return out;
212
+ });
213
+
214
+ const totalHeight = () => offsets()[rows().length] ?? 0;
215
+
216
+ const visibleSlice = createMemo(() => {
217
+ const off = offsets();
218
+ const count = rows().length;
219
+ if (count === 0) return { start: 0, end: 0 };
220
+ const topEdge = scrollTop() - OVERSCAN_PX;
221
+ const bottomEdge = scrollTop() + viewportHeight() + OVERSCAN_PX;
222
+ let lo = 0;
223
+ let hi = count - 1;
224
+ while (lo < hi) {
225
+ const mid = (lo + hi) >> 1;
226
+ if ((off[mid + 1] ?? 0) > topEdge) hi = mid;
227
+ else lo = mid + 1;
228
+ }
229
+ const start = lo;
230
+ let end = start;
231
+ while (end < count && (off[end] ?? 0) < bottomEdge) end++;
232
+ return { start, end };
233
+ });
234
+
235
+ // Slice arrays are new per scroll tick, but the row objects inside keep
236
+ // their references, so <For> only mounts/unmounts rows entering/leaving
237
+ // the overscan window and repositions the rest.
238
+ const visibleRows = createMemo(() => {
239
+ const { start, end } = visibleSlice();
240
+ return rows().slice(start, end);
241
+ });
242
+
243
+ const rowIndexByKey = createMemo(() => {
244
+ const map = new Map<string, number>();
245
+ rows().forEach((row, i) => {
246
+ map.set(row.key, i);
247
+ });
248
+ return map;
249
+ });
250
+
251
+ const rowTop = (row: ListRow) => {
252
+ const idx = rowIndexByKey().get(row.key);
253
+ return idx == null ? 0 : (offsets()[idx] ?? 0);
254
+ };
255
+
256
+ // The scroll container mounts lazily (popover/sheet open), so the observer
257
+ // attaches via ref callback rather than component onMount.
258
+ const attachScrollRef = (el: HTMLDivElement) => {
259
+ scrollRef = el;
260
+ setScrollTop(el.scrollTop);
261
+ setViewportHeight(el.clientHeight);
262
+ const observer = new ResizeObserver(() => setViewportHeight(el.clientHeight));
263
+ observer.observe(el);
264
+ onCleanup(() => {
265
+ observer.disconnect();
266
+ if (scrollRef === el) scrollRef = undefined;
267
+ });
268
+ };
269
+
270
+ createEffect(
271
+ on(
272
+ search,
273
+ () => {
274
+ setActiveIndex(0);
275
+ scrollRef?.scrollTo({ top: 0 });
276
+ setScrollTop(0);
277
+ },
278
+ { defer: true },
279
+ ),
280
+ );
281
+
282
+ createEffect(() => {
283
+ const max = entityRows().length - 1;
284
+ if (activeIndex() > max) setActiveIndex(Math.max(0, max));
285
+ });
286
+
287
+ const ensureActiveVisible = (entityIndex: number) => {
288
+ if (!scrollRef) return;
289
+ const rowIdx = rows().findIndex((r) => r.kind === "entity" && r.entityIndex === entityIndex);
290
+ if (rowIdx < 0) return;
291
+ const top = offsets()[rowIdx] ?? 0;
292
+ const bottom = top + ROW_HEIGHT;
293
+ if (top < scrollRef.scrollTop) scrollRef.scrollTo({ top });
294
+ else if (bottom > scrollRef.scrollTop + scrollRef.clientHeight)
295
+ scrollRef.scrollTo({ top: bottom - scrollRef.clientHeight });
296
+ };
297
+
298
+ const optionId = (entityIndex: number) => `${listboxId}-option-${entityIndex}`;
299
+ // Only names a row the list is actually rendering: the virtualiser unmounts
300
+ // the rest, and aria-activedescendant must point at a live element.
301
+ const activeOptionId = () =>
302
+ !isMobile() && visibleRows().some((r) => r.kind === "entity" && r.entityIndex === activeIndex())
303
+ ? optionId(activeIndex())
304
+ : undefined;
305
+
306
+ const closePicker = () => {
307
+ setOpen(false);
308
+ setSearch("");
309
+ setActiveIndex(0);
310
+ };
311
+
312
+ const toggleEntity = (entityId: string) => {
313
+ if (props.multiple === false) {
314
+ props.onEntityIdsChange([entityId]);
315
+ closePicker();
316
+ return;
317
+ }
318
+ const current = props.entityIds;
319
+ if (current.includes(entityId)) {
320
+ props.onEntityIdsChange(current.filter((id) => id !== entityId));
321
+ } else {
322
+ props.onEntityIdsChange([...current, entityId]);
323
+ }
324
+ };
325
+
326
+ const removeEntity = (entityId: string) => {
327
+ props.onEntityIdsChange(props.entityIds.filter((id) => id !== entityId));
328
+ };
329
+
330
+ const handleKeyDown = (e: KeyboardEvent) => {
331
+ const total = entityRows().length;
332
+ if (e.key === "ArrowDown" && total > 0) {
333
+ e.preventDefault();
334
+ const next = (activeIndex() + 1) % total;
335
+ setActiveIndex(next);
336
+ ensureActiveVisible(next);
337
+ } else if (e.key === "ArrowUp" && total > 0) {
338
+ e.preventDefault();
339
+ const next = (activeIndex() - 1 + total) % total;
340
+ setActiveIndex(next);
341
+ ensureActiveVisible(next);
342
+ } else if (e.key === "Home" && total > 0) {
343
+ e.preventDefault();
344
+ setActiveIndex(0);
345
+ ensureActiveVisible(0);
346
+ } else if (e.key === "End" && total > 0) {
347
+ e.preventDefault();
348
+ setActiveIndex(total - 1);
349
+ ensureActiveVisible(total - 1);
350
+ } else if (e.key === "Enter" && total > 0) {
351
+ e.preventDefault();
352
+ const row = entityRows()[activeIndex()];
353
+ if (row) toggleEntity(row.id);
354
+ } else if (e.key === "Escape") {
355
+ e.preventDefault();
356
+ closePicker();
357
+ }
358
+ };
359
+
360
+ const triggerLabel = () => {
361
+ const count = props.entityIds.length;
362
+ if (count === 0) return null;
363
+ if (count === 1) {
364
+ const id = props.entityIds[0] ?? "";
365
+ const view = data.getEntityView(id);
366
+ return view?.friendlyName ?? id;
367
+ }
368
+ return `${count} entities selected`;
369
+ };
370
+
371
+ const triggerIcon = () => {
372
+ if (props.entityIds.length !== 1) return null;
373
+ const id = props.entityIds[0] ?? "";
374
+ return data.getEntityView(id)?.icon ?? null;
375
+ };
376
+
377
+ const isSingle = () => props.multiple === false;
378
+ const showTriggerClear = () => isSingle() && props.entityIds.length > 0;
379
+
380
+ const clearSelection = () => {
381
+ props.onEntityIdsChange([]);
382
+ };
383
+
384
+ const TriggerButton = (p: { onClick: () => void }) => (
385
+ <div class="relative">
386
+ <button
387
+ type="button"
388
+ role="combobox"
389
+ data-slot="entity-selector-trigger"
390
+ data-expanded={open() || undefined}
391
+ aria-labelledby={props["aria-labelledby"]}
392
+ aria-expanded={open()}
393
+ aria-controls={listboxId}
394
+ aria-haspopup="listbox"
395
+ class={cn(PICKER_TRIGGER, showTriggerClear() && "pr-14")}
396
+ onClick={p.onClick}
397
+ >
398
+ <Show when={triggerIcon()}>
399
+ {(icon) => (
400
+ <Icon icon={icon()} width={16} height={16} class="shrink-0 text-muted-foreground" />
401
+ )}
402
+ </Show>
403
+ <Show
404
+ when={triggerLabel()}
405
+ fallback={
406
+ <span class="flex-1 truncate text-left text-muted-foreground">
407
+ Select {props.domain} {isSingle() ? "entity" : "entities"}...
408
+ </span>
409
+ }
410
+ >
411
+ {(label) => <span class="flex-1 truncate text-left">{label()}</span>}
412
+ </Show>
413
+ <Icon
414
+ icon="mdi:chevron-down"
415
+ width={16}
416
+ height={16}
417
+ class={`shrink-0 text-muted-foreground transition-transform ${open() ? "rotate-180" : ""}`}
418
+ />
419
+ </button>
420
+ <Show when={showTriggerClear()}>
421
+ <button
422
+ type="button"
423
+ aria-label="Clear selection"
424
+ class="absolute top-1/2 right-8 flex -translate-y-1/2 items-center rounded-sm p-1 text-muted-foreground transition-colors hover:text-foreground"
425
+ onClick={clearSelection}
426
+ >
427
+ <Icon icon="mdi:close-circle" width={16} height={16} />
428
+ </button>
429
+ </Show>
430
+ </div>
431
+ );
432
+
433
+ const EntityRow = (p: { id: string; entityIndex: number; top: number }) => {
434
+ const view = createMemo(() => data.getEntityView(p.id));
435
+ const selected = () => selectedSet().has(p.id);
436
+ const unavailable = () => {
437
+ const v = view();
438
+ return v == null || isUnavailable(v);
439
+ };
440
+ const state = () => {
441
+ const v = view();
442
+ return v ? stateLabel(v) : "";
443
+ };
444
+ return (
445
+ <PickerRow
446
+ role="option"
447
+ id={optionId(p.entityIndex)}
448
+ data-slot="entity-selector-row"
449
+ aria-selected={selected()}
450
+ data-highlighted={(!isMobile() && activeIndex() === p.entityIndex) || undefined}
451
+ class="absolute inset-x-0"
452
+ style={{ top: `${p.top}px`, height: `${ROW_HEIGHT}px` }}
453
+ icon={view()?.icon ?? FALLBACK_ICON}
454
+ title={view()?.friendlyName ?? p.id}
455
+ subtitle={p.id}
456
+ meta={state()}
457
+ selected={selected()}
458
+ multi={!isSingle()}
459
+ dimmed={unavailable()}
460
+ onMouseMove={() => setActiveIndex(p.entityIndex)}
461
+ onClick={() => toggleEntity(p.id)}
462
+ />
463
+ );
464
+ };
465
+
466
+ const PickerContent = () => (
467
+ <div class="flex min-h-0 flex-1 flex-col">
468
+ <PickerSearch
469
+ inputRef={(el) => {
470
+ inputRef = el;
471
+ }}
472
+ type="search"
473
+ role="combobox"
474
+ aria-label={`Search ${props.domain} entities`}
475
+ aria-controls={listboxId}
476
+ aria-expanded
477
+ aria-activedescendant={activeOptionId()}
478
+ placeholder="Search by name, room, or ID..."
479
+ value={search()}
480
+ onValueChange={setSearch}
481
+ onKeyDown={handleKeyDown}
482
+ clearLabel="Clear search"
483
+ size={isMobile() ? "touch" : "default"}
484
+ class="[&_input::-webkit-search-cancel-button]:hidden"
485
+ />
486
+ <div
487
+ ref={attachScrollRef}
488
+ id={listboxId}
489
+ role="listbox"
490
+ aria-multiselectable={!isSingle()}
491
+ aria-label={`${props.domain} entities`}
492
+ data-sheet-scroll=""
493
+ class={cn(
494
+ "min-h-0 flex-1 touch-pan-y overscroll-contain px-1 py-1",
495
+ PICKER_LIST,
496
+ isMobile() && "max-h-none",
497
+ )}
498
+ onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
499
+ >
500
+ <Show
501
+ when={rows().length > 0}
502
+ fallback={
503
+ <div class="flex flex-col items-center gap-2 px-4 py-8 text-center">
504
+ <Show
505
+ when={search().trim()}
506
+ fallback={
507
+ <Show
508
+ when={diagnosticCount() > 0}
509
+ fallback={
510
+ <Show
511
+ when={classExcludedCount() > 0}
512
+ fallback={
513
+ <span class="text-muted-foreground text-sm">
514
+ No {props.domain} entities found in your home
515
+ </span>
516
+ }
517
+ >
518
+ <span class="text-muted-foreground text-sm">{classExcludedMessage()}</span>
519
+ </Show>
520
+ }
521
+ >
522
+ <span class="text-muted-foreground text-sm">
523
+ Only diagnostic {props.domain} entities available
524
+ </span>
525
+ <button
526
+ type="button"
527
+ class="text-primary text-sm hover:underline"
528
+ onClick={() => setShowDiagnostics(true)}
529
+ >
530
+ Show diagnostic entities
531
+ </button>
532
+ </Show>
533
+ }
534
+ >
535
+ <span class="text-muted-foreground text-sm">
536
+ No matches for "{search().trim()}"
537
+ </span>
538
+ <button
539
+ type="button"
540
+ class="text-primary text-sm hover:underline"
541
+ onClick={() => setSearch("")}
542
+ >
543
+ Clear search
544
+ </button>
545
+ </Show>
546
+ </div>
547
+ }
548
+ >
549
+ <SlidingIndicator
550
+ activeSelector="[data-highlighted]"
551
+ orientation="vertical"
552
+ indicatorClass="rounded-sm"
553
+ role="presentation"
554
+ style={{ height: `${totalHeight()}px` }}
555
+ >
556
+ <For each={visibleRows()}>
557
+ {(row) =>
558
+ row.kind === "header" ? (
559
+ <div
560
+ class={cn(MENU_LABEL, "absolute inset-x-0 flex items-end px-2 pb-1")}
561
+ style={{
562
+ top: `${rowTop(row)}px`,
563
+ height: `${HEADER_HEIGHT}px`,
564
+ }}
565
+ aria-hidden="true"
566
+ >
567
+ {row.label}
568
+ </div>
569
+ ) : (
570
+ <EntityRow id={row.id} entityIndex={row.entityIndex} top={rowTop(row)} />
571
+ )
572
+ }
573
+ </For>
574
+ </SlidingIndicator>
575
+ </Show>
576
+ </div>
577
+ <Show when={diagnosticCount() > 0 || props.deviceClass}>
578
+ <div class="flex shrink-0 items-center justify-between gap-2 border-border/50 border-t px-3 py-2">
579
+ <span class="truncate text-muted-foreground text-xs">
580
+ {props.deviceClass ? `Showing ${props.deviceClass} entities only` : ""}
581
+ </span>
582
+ <Show when={diagnosticCount() > 0}>
583
+ <button
584
+ type="button"
585
+ class="shrink-0 text-muted-foreground text-xs transition-colors hover:text-foreground"
586
+ onClick={() => setShowDiagnostics(!showDiagnostics())}
587
+ >
588
+ {showDiagnostics() ? "Hide diagnostic" : `Show diagnostic (${diagnosticCount()})`}
589
+ </button>
590
+ </Show>
591
+ </div>
592
+ </Show>
593
+ </div>
594
+ );
595
+
596
+ const SelectedChips = () => (
597
+ <Show when={!isSingle() && props.entityIds.length > 0}>
598
+ <div class="flex flex-wrap gap-1.5">
599
+ <For each={props.entityIds}>
600
+ {(id) => {
601
+ const view = createMemo(() => data.getEntityView(id));
602
+ const unavailable = () => {
603
+ const v = view();
604
+ return v != null && isUnavailable(v);
605
+ };
606
+ return (
607
+ <span
608
+ class={`inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-border bg-secondary/50 text-secondary-foreground text-xs ${
609
+ unavailable() ? "opacity-60" : ""
610
+ }`}
611
+ >
612
+ <span class="flex min-w-0 items-center gap-1.5 py-1.5 pl-2">
613
+ <Icon
614
+ icon={view()?.icon ?? FALLBACK_ICON}
615
+ width={14}
616
+ height={14}
617
+ class="shrink-0 text-muted-foreground"
618
+ />
619
+ <span class="truncate">{view()?.friendlyName ?? id}</span>
620
+ </span>
621
+ <button
622
+ type="button"
623
+ aria-label={`Remove ${view()?.friendlyName ?? id}`}
624
+ class="flex w-8 shrink-0 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
625
+ onClick={() => removeEntity(id)}
626
+ >
627
+ <Icon icon="lucide:x" width={14} height={14} class="size-3.5" />
628
+ </button>
629
+ </span>
630
+ );
631
+ }}
632
+ </For>
633
+ </div>
634
+ </Show>
635
+ );
636
+
637
+ // One shell per viewport, one list: the sheet and the panel host the same
638
+ // PickerContent, so a fix to the list can never land in only one of them.
639
+ const ContentHost: ParentComponent = (p) => (
640
+ <Show
641
+ when={isMobile()}
642
+ fallback={
643
+ <PopoverContent
644
+ class="flex min-w-72 flex-col"
645
+ onOpenAutoFocus={(e) => {
646
+ e.preventDefault();
647
+ // preventScroll: the panel is portalled at (0,0) until the popper places it,
648
+ // so a plain focus() scrolls the page to the top.
649
+ inputRef?.focus({ preventScroll: true });
650
+ }}
651
+ onInteractOutside={() => closePicker()}
652
+ >
653
+ {p.children}
654
+ </PopoverContent>
655
+ }
656
+ >
657
+ <BottomSheet
658
+ open={open()}
659
+ onOpenChange={(isOpen) => {
660
+ if (!isOpen) closePicker();
661
+ }}
662
+ >
663
+ <BottomSheetPortal>
664
+ <BottomSheetOverlay />
665
+ <BottomSheetContent
666
+ class="h-[85dvh] pb-[env(safe-area-inset-bottom)]"
667
+ ariaLabel={`Select ${props.domain} entities`}
668
+ >
669
+ <BottomSheetHandle />
670
+ {p.children}
671
+ </BottomSheetContent>
672
+ </BottomSheetPortal>
673
+ </BottomSheet>
674
+ </Show>
675
+ );
676
+
677
+ return (
678
+ <div class="flex flex-col gap-2">
679
+ <Popover
680
+ surface="field"
681
+ open={open() && !isMobile()}
682
+ onOpenChange={(isOpen) => {
683
+ if (!isOpen) closePicker();
684
+ }}
685
+ modal
686
+ >
687
+ <PopoverAnchor as="div">
688
+ <TriggerButton onClick={() => (open() ? closePicker() : setOpen(true))} />
689
+ </PopoverAnchor>
690
+ <ContentHost>
691
+ <PickerContent />
692
+ </ContentHost>
693
+ </Popover>
694
+ <SelectedChips />
695
+ </div>
696
+ );
697
+ }