@glasshome/ui 1.21.0 → 1.21.2

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