Open History to see the last commit
1import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2import type {
3 DeviceActionInput,
4 DeviceDetail,
5 DevicePermission,
6 DeviceSummary,
7 DeviceTextSize,
8 EnvironmentId,
9} from "@t3tools/contracts";
10import { ChevronDown, X } from "lucide-react";
11import { useCallback, useEffect, useMemo, useState } from "react";
12
13import { Button } from "~/components/ui/button";
14import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "~/components/ui/collapsible";
15import { Input } from "~/components/ui/input";
16import {
17 Select,
18 SelectItem,
19 SelectPopup,
20 SelectTrigger,
21 SelectValue,
22} from "~/components/ui/select";
23import { Spinner } from "~/components/ui/spinner";
24import { Switch } from "~/components/ui/switch";
25import { Toggle, ToggleGroup } from "~/components/ui/toggle-group";
26import { cn } from "~/lib/utils";
27import { deviceEnvironment } from "~/state/device";
28import { formatEnvironmentQueryError } from "~/state/query";
29import { useAtomCommand } from "~/state/use-atom-command";
30import {
31 type DeviceEventLogEntry,
32 type DeviceForegroundInfo,
33 subscribeDeviceEventLog,
34 subscribeDeviceForeground,
35} from "./deviceHubApi";
36
37type ActionBody = DeviceActionInput extends infer A
38 ? A extends { readonly type: string }
39 ? Omit<A, "hostId" | "deviceId">
40 : never
41 : never;
42
43const TEXT_SIZES: ReadonlyArray<{ value: DeviceTextSize; label: string }> = [
44 { value: "small", label: "Small" },
45 { value: "default", label: "Default" },
46 { value: "large", label: "Large" },
47 { value: "extra-large", label: "Extra large" },
48];
49
50const COLOR_FILTERS = [
51 { value: "none", label: "None" },
52 { value: "grayscale", label: "Grayscale" },
53 { value: "red-green", label: "Red / green (protanopia)" },
54 { value: "green-red", label: "Green / red (deuteranopia)" },
55 { value: "blue-yellow", label: "Blue / yellow (tritanopia)" },
56] as const;
57
58const ORIENTATIONS = [
59 { value: "portrait", label: "Portrait" },
60 { value: "landscape_left", label: "Landscape left" },
61 { value: "portrait_upside_down", label: "Upside down" },
62 { value: "landscape_right", label: "Landscape right" },
63] as const;
64
65const IOS_PERMISSIONS: ReadonlyArray<{ value: DevicePermission; label: string }> = [
66 { value: "camera", label: "Camera" },
67 { value: "microphone", label: "Microphone" },
68 { value: "photos", label: "Photos" },
69 { value: "contacts", label: "Contacts" },
70 { value: "calendar", label: "Calendar" },
71 { value: "reminders", label: "Reminders" },
72 { value: "location", label: "Location" },
73 { value: "notifications", label: "Notifications" },
74 { value: "motion", label: "Motion" },
75 { value: "media-library", label: "Media library" },
76 { value: "faceid", label: "Face ID" },
77];
78
79const ANDROID_PERMISSIONS: ReadonlyArray<{ value: DevicePermission; label: string }> = [
80 { value: "camera", label: "Camera" },
81 { value: "microphone", label: "Microphone" },
82 { value: "photos", label: "Photos" },
83 { value: "contacts", label: "Contacts" },
84 { value: "calendar", label: "Calendar" },
85 { value: "location", label: "Location" },
86 { value: "notifications", label: "Notifications" },
87 { value: "motion", label: "Physical activity" },
88];
89
90const LOCATION_PRESETS = [
91 { label: "San Francisco", latitude: 37.7749, longitude: -122.4194 },
92 { label: "New York", latitude: 40.7128, longitude: -74.006 },
93 { label: "London", latitude: 51.5074, longitude: -0.1278 },
94 { label: "Stockholm", latitude: 59.3293, longitude: 18.0686 },
95 { label: "Tokyo", latitude: 35.6762, longitude: 139.6503 },
96] as const;
97
98/**
99 * The Tools drawer for one open device: current settings read from the device,
100 * one control per supported action, and the read-only feeds the hub exposes.
101 * Every change is a `device.action` round trip; the returned detail replaces
102 * local state so the controls never show a value the device did not confirm.
103 */
104export function DeviceToolsPanel(props: {
105 readonly environmentId: EnvironmentId;
106 readonly device: DeviceSummary;
107 readonly access: DeviceHubAccess | null;
108 readonly axOverlay: boolean;
109 readonly onAxOverlayChange: (enabled: boolean) => void;
110 readonly onClose: () => void;
111 readonly className?: string;
112}) {
113 const { environmentId, device } = props;
114 const readDetail = useAtomCommand(deviceEnvironment.detail, { reportFailure: false });
115 const runAction = useAtomCommand(deviceEnvironment.action, { reportFailure: false });
116 const [detail, setDetail] = useState<DeviceDetail | null>(null);
117 const [pending, setPending] = useState(false);
118 const [error, setError] = useState<string | null>(null);
119 const [foreground, setForeground] = useState<DeviceForegroundInfo | null | undefined>(undefined);
120 const isIos = device.platform === "ios";
121
122 const target = useMemo(
123 () => ({ hostId: device.hostId, deviceId: device.id }),
124 [device.hostId, device.id],
125 );
126
127 // The panel is keyed by device, so a mount is always a fresh device.
128 useEffect(() => {
129 let cancelled = false;
130 void readDetail({ environmentId, input: target }).then((result) => {
131 if (cancelled) return;
132 if (result._tag === "Success") setDetail(result.value);
133 else setError(formatEnvironmentQueryError(result.cause));
134 });
135 return () => {
136 cancelled = true;
137 };
138 }, [environmentId, readDetail, target]);
139
140 useEffect(() => {
141 if (!props.access) return;
142 return subscribeDeviceForeground(
143 { access: props.access, platform: device.platform, deviceId: device.id },
144 setForeground,
145 );
146 }, [device.id, device.platform, props.access]);
147
148 const act = useCallback(
149 async (body: ActionBody) => {
150 setPending(true);
151 setError(null);
152 try {
153 const result = await runAction({
154 environmentId,
155 input: { ...target, ...body } as DeviceActionInput,
156 });
157 if (result._tag === "Success") setDetail(result.value);
158 else setError(formatEnvironmentQueryError(result.cause));
159 } finally {
160 setPending(false);
161 }
162 },
163 [environmentId, runAction, target],
164 );
165
166 const settings = detail?.settings;
167 const foregroundApp = foreground === undefined ? (detail?.foregroundApp ?? null) : foreground;
168 const disabled = pending || detail === null;
169
170 return (
171 <div
172 className={cn("flex min-h-0 flex-col border-border bg-background text-sm", props.className)}
173 >
174 <div className="flex h-9 shrink-0 items-center gap-2 border-b px-3">
175 <span className="font-medium">Tools</span>
176 {pending ? <Spinner className="size-3.5" /> : null}
177 <Button
178 size="icon-xs"
179 variant="ghost-muted"
180 aria-label="Close tools"
181 className="ml-auto"
182 onClick={props.onClose}
183 >
184 <X />
185 </Button>
186 </div>
187 <div className="min-h-0 flex-1 overflow-y-auto">
188 {error ? (
189 <p className="border-b bg-destructive/10 px-3 py-2 text-xs text-destructive">{error}</p>
190 ) : null}
191 {detail === null && !error ? (
192 <div className="flex items-center gap-2 px-3 py-3 text-xs text-muted-foreground">
193 <Spinner className="size-3.5" /> Reading device settings…
194 </div>
195 ) : null}
196
197 <Section title="App">
198 <Row label="Foreground">
199 <span className="truncate font-mono text-xs">{foregroundApp?.id ?? "—"}</span>
200 </Row>
201 {foregroundApp ? (
202 <div className="flex gap-1.5">
203 <Button
204 size="xs"
205 variant="outline"
206 disabled={disabled}
207 onClick={() => void act({ type: "terminateApp", appId: foregroundApp.id })}
208 >
209 Terminate
210 </Button>
211 <Button
212 size="xs"
213 variant="outline"
214 disabled={disabled}
215 onClick={() => void act({ type: "launchApp", appId: foregroundApp.id })}
216 >
217 Relaunch
218 </Button>
219 </div>
220 ) : null}
221 <SubmitRow
222 placeholder="https://… or myapp://"
223 action="Open"
224 disabled={disabled}
225 onSubmit={(url) => act({ type: "openUrl", url })}
226 />
227 <SubmitRow
228 placeholder={isIos ? "Bundle ID to launch" : "Package name to launch"}
229 action="Launch"
230 disabled={disabled}
231 onSubmit={(appId) => act({ type: "launchApp", appId })}
232 />
233 </Section>
234
235 <Section title={isIos ? "Simulator" : "Emulator"}>
236 <Row label="Appearance">
237 <ToggleGroup
238 aria-label="Appearance"
239 value={settings?.appearance ? [settings.appearance] : []}
240 disabled={disabled}
241 onValueChange={(value) => {
242 const next = value[0];
243 if (next === "light" || next === "dark")
244 void act({ type: "setAppearance", value: next });
245 }}
246 >
247 <Toggle value="light">Light</Toggle>
248 <Toggle value="dark">Dark</Toggle>
249 </ToggleGroup>
250 </Row>
251 <Row label="Text size">
252 <ChoiceSelect
253 ariaLabel="Text size"
254 value={settings?.textSize ?? null}
255 options={TEXT_SIZES}
256 disabled={disabled}
257 onChange={(value) => act({ type: "setTextSize", value })}
258 />
259 </Row>
260 {isIos ? (
261 <>
262 <Row label="Liquid Glass">
263 <ToggleGroup
264 aria-label="Liquid Glass"
265 value={settings?.liquidGlass ? [settings.liquidGlass] : []}
266 disabled={disabled || settings?.liquidGlass === undefined}
267 onValueChange={(value) => {
268 const next = value[0];
269 if (next === "clear" || next === "tinted") {
270 void act({ type: "setLiquidGlass", value: next });
271 }
272 }}
273 >
274 <Toggle value="clear">Clear</Toggle>
275 <Toggle value="tinted">Tinted</Toggle>
276 </ToggleGroup>
277 </Row>
278 <Row label="Color filter">
279 <ChoiceSelect
280 ariaLabel="Color filter"
281 value={settings?.colorFilter ?? null}
282 options={COLOR_FILTERS}
283 disabled={disabled}
284 onChange={(value) => act({ type: "setColorFilter", value })}
285 />
286 </Row>
287 </>
288 ) : (
289 <Row label="Orientation">
290 <ChoiceSelect
291 ariaLabel="Orientation"
292 value={null}
293 placeholder="Rotate to…"
294 options={ORIENTATIONS}
295 disabled={disabled}
296 onChange={(value) => act({ type: "setOrientation", value })}
297 />
298 </Row>
299 )}
300 <SwitchRow
301 label="Reduce Motion"
302 checked={settings?.reduceMotion}
303 disabled={disabled}
304 onChange={(value) => act({ type: "setToggle", setting: "reduceMotion", value })}
305 />
306 {isIos ? (
307 <>
308 <SwitchRow
309 label="Increase Contrast"
310 checked={settings?.increaseContrast}
311 disabled={disabled}
312 onChange={(value) => act({ type: "setToggle", setting: "increaseContrast", value })}
313 />
314 <SwitchRow
315 label="Reduce Transparency"
316 checked={settings?.reduceTransparency}
317 disabled={disabled}
318 onChange={(value) =>
319 act({ type: "setToggle", setting: "reduceTransparency", value })
320 }
321 />
322 <SwitchRow
323 label="Show Borders"
324 checked={settings?.showBorders}
325 disabled={disabled}
326 onChange={(value) => act({ type: "setToggle", setting: "showBorders", value })}
327 />
328 <SwitchRow
329 label="VoiceOver"
330 checked={settings?.voiceOver}
331 disabled={disabled}
332 onChange={(value) => act({ type: "setToggle", setting: "voiceOver", value })}
333 />
334 </>
335 ) : (
336 <SwitchRow
337 label="Network"
338 checked={settings?.networkEnabled}
339 disabled={disabled}
340 onChange={(value) => act({ type: "setToggle", setting: "networkEnabled", value })}
341 />
342 )}
343 </Section>
344
345 <Section title="Accessibility">
346 <SwitchRow
347 label="Overlay element frames"
348 checked={props.axOverlay}
349 disabled={props.access === null}
350 onChange={(value) => {
351 props.onAxOverlayChange(value);
352 return Promise.resolve();
353 }}
354 />
355 </Section>
356
357 <LocationSection
358 disabled={disabled}
359 canClear={isIos}
360 onSet={(latitude, longitude) => act({ type: "setLocation", latitude, longitude })}
361 onClear={() => act({ type: "clearLocation" })}
362 />
363
364 <PermissionsSection
365 permissions={isIos ? IOS_PERMISSIONS : ANDROID_PERMISSIONS}
366 canReset={isIos}
367 defaultAppId={foregroundApp?.id ?? ""}
368 disabled={disabled}
369 onDecide={(appId, permission, decision) =>
370 act({ type: "setPermission", appId, permission, decision })
371 }
372 />
373
374 {isIos ? (
375 <Section title="Push notification">
376 <SubmitRow
377 placeholder="Alert text"
378 action="Send"
379 disabled={disabled || !foregroundApp}
380 onSubmit={(payload) =>
381 foregroundApp
382 ? act({ type: "sendPush", appId: foregroundApp.id, payload })
383 : Promise.resolve()
384 }
385 />
386 {!foregroundApp ? (
387 <p className="text-xs text-muted-foreground">Open an app first.</p>
388 ) : null}
389 </Section>
390 ) : null}
391
392 {isIos && props.access ? <EventLogSection access={props.access} device={device} /> : null}
393 </div>
394 </div>
395 );
396}
397
398function Section(props: { readonly title: string; readonly children: React.ReactNode }) {
399 return (
400 <section className="flex flex-col gap-2 border-b px-3 py-2.5 last:border-b-0">
401 <h3 className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
402 {props.title}
403 </h3>
404 {props.children}
405 </section>
406 );
407}
408
409function Row(props: { readonly label: string; readonly children: React.ReactNode }) {
410 return (
411 <div className="flex min-h-7 items-center justify-between gap-3">
412 <span className="shrink-0 text-xs text-muted-foreground">{props.label}</span>
413 <div className="flex min-w-0 items-center justify-end">{props.children}</div>
414 </div>
415 );
416}
417
418function SwitchRow(props: {
419 readonly label: string;
420 readonly checked: boolean | undefined;
421 readonly disabled: boolean;
422 readonly onChange: (value: boolean) => Promise<void>;
423}) {
424 return (
425 <Row label={props.label}>
426 <Switch
427 size="sm"
428 aria-label={props.label}
429 checked={props.checked ?? false}
430 disabled={props.disabled || props.checked === undefined}
431 onCheckedChange={(checked) => void props.onChange(checked)}
432 />
433 </Row>
434 );
435}
436
437function ChoiceSelect<V extends string>(props: {
438 readonly ariaLabel: string;
439 readonly value: V | null;
440 readonly options: ReadonlyArray<{ readonly value: V; readonly label: string }>;
441 readonly disabled: boolean;
442 readonly placeholder?: string;
443 readonly onChange: (value: V) => Promise<void>;
444}) {
445 const current = props.options.find((option) => option.value === props.value);
446 return (
447 <Select
448 value={props.value}
449 disabled={props.disabled}
450 onValueChange={(value) => {
451 if (value !== null && value !== props.value) void props.onChange(value as V);
452 }}
453 >
454 <SelectTrigger size="xs" className="w-40" aria-label={props.ariaLabel}>
455 <SelectValue>
456 {current ? (
457 current.label
458 ) : (
459 <span className="text-muted-foreground">{props.placeholder ?? "Unknown"}</span>
460 )}
461 </SelectValue>
462 </SelectTrigger>
463 <SelectPopup align="end" alignItemWithTrigger={false}>
464 {props.options.map((option) => (
465 <SelectItem key={option.value} value={option.value}>
466 {option.label}
467 </SelectItem>
468 ))}
469 </SelectPopup>
470 </Select>
471 );
472}
473
474function SubmitRow(props: {
475 readonly placeholder: string;
476 readonly action: string;
477 readonly disabled: boolean;
478 readonly onSubmit: (value: string) => Promise<void>;
479}) {
480 const [value, setValue] = useState("");
481 const submit = () => {
482 const trimmed = value.trim();
483 if (!trimmed) return;
484 void props.onSubmit(trimmed).then(() => setValue(""));
485 };
486 return (
487 <form
488 className="flex gap-1.5"
489 onSubmit={(event) => {
490 event.preventDefault();
491 submit();
492 }}
493 >
494 <Input
495 size="compact"
496 className="min-w-0 flex-1 font-mono"
497 placeholder={props.placeholder}
498 value={value}
499 disabled={props.disabled}
500 onChange={(event) => setValue(event.target.value)}
501 />
502 <Button
503 type="submit"
504 size="xs"
505 variant="outline"
506 disabled={props.disabled || value.trim().length === 0}
507 >
508 {props.action}
509 </Button>
510 </form>
511 );
512}
513
514function LocationSection(props: {
515 readonly disabled: boolean;
516 readonly canClear: boolean;
517 readonly onSet: (latitude: number, longitude: number) => Promise<void>;
518 readonly onClear: () => Promise<void>;
519}) {
520 const [latitude, setLatitude] = useState("");
521 const [longitude, setLongitude] = useState("");
522 const parsed = { latitude: Number(latitude), longitude: Number(longitude) };
523 const valid =
524 latitude.trim() !== "" &&
525 longitude.trim() !== "" &&
526 Math.abs(parsed.latitude) <= 90 &&
527 Math.abs(parsed.longitude) <= 180;
528 return (
529 <Section title="Location">
530 <div className="flex gap-1.5">
531 <Input
532 size="compact"
533 className="min-w-0 flex-1 font-mono"
534 placeholder="Latitude"
535 inputMode="decimal"
536 value={latitude}
537 disabled={props.disabled}
538 onChange={(event) => setLatitude(event.target.value)}
539 />
540 <Input
541 size="compact"
542 className="min-w-0 flex-1 font-mono"
543 placeholder="Longitude"
544 inputMode="decimal"
545 value={longitude}
546 disabled={props.disabled}
547 onChange={(event) => setLongitude(event.target.value)}
548 />
549 </div>
550 <div className="flex flex-wrap items-center gap-1.5">
551 <Select<string | null>
552 value={null}
553 disabled={props.disabled}
554 onValueChange={(value) => {
555 const preset = LOCATION_PRESETS.find((candidate) => candidate.label === value);
556 if (!preset) return;
557 setLatitude(String(preset.latitude));
558 setLongitude(String(preset.longitude));
559 void props.onSet(preset.latitude, preset.longitude);
560 }}
561 >
562 <SelectTrigger size="xs" className="w-32" aria-label="Location preset">
563 <SelectValue>
564 <span className="text-muted-foreground">Preset…</span>
565 </SelectValue>
566 </SelectTrigger>
567 <SelectPopup align="start" alignItemWithTrigger={false}>
568 {LOCATION_PRESETS.map((preset) => (
569 <SelectItem key={preset.label} value={preset.label}>
570 {preset.label}
571 </SelectItem>
572 ))}
573 </SelectPopup>
574 </Select>
575 <Button
576 size="xs"
577 variant="outline"
578 disabled={props.disabled || !valid}
579 onClick={() => void props.onSet(parsed.latitude, parsed.longitude)}
580 >
581 Set
582 </Button>
583 {props.canClear ? (
584 <Button
585 size="xs"
586 variant="ghost"
587 disabled={props.disabled}
588 onClick={() => {
589 setLatitude("");
590 setLongitude("");
591 void props.onClear();
592 }}
593 >
594 Clear
595 </Button>
596 ) : null}
597 </div>
598 </Section>
599 );
600}
601
602function PermissionsSection(props: {
603 readonly permissions: ReadonlyArray<{ value: DevicePermission; label: string }>;
604 readonly canReset: boolean;
605 readonly defaultAppId: string;
606 readonly disabled: boolean;
607 readonly onDecide: (
608 appId: string,
609 permission: DevicePermission,
610 decision: "grant" | "revoke" | "reset",
611 ) => Promise<void>;
612}) {
613 const [appId, setAppId] = useState("");
614 const [permission, setPermission] = useState<DevicePermission>("camera");
615 const resolvedAppId = appId.trim() || props.defaultAppId;
616 const decide = (decision: "grant" | "revoke" | "reset") =>
617 void props.onDecide(resolvedAppId, permission, decision);
618 return (
619 <Section title="Permissions">
620 <Input
621 size="compact"
622 className="font-mono"
623 placeholder={props.defaultAppId || "App ID"}
624 value={appId}
625 disabled={props.disabled}
626 onChange={(event) => setAppId(event.target.value)}
627 />
628 <div className="flex flex-wrap items-center gap-1.5">
629 <ChoiceSelect
630 ariaLabel="Permission"
631 value={permission}
632 options={props.permissions}
633 disabled={props.disabled}
634 onChange={(value) => {
635 setPermission(value);
636 return Promise.resolve();
637 }}
638 />
639 <Button
640 size="xs"
641 variant="outline"
642 disabled={props.disabled || !resolvedAppId}
643 onClick={() => decide("grant")}
644 >
645 Grant
646 </Button>
647 <Button
648 size="xs"
649 variant="outline"
650 disabled={props.disabled || !resolvedAppId}
651 onClick={() => decide("revoke")}
652 >
653 Revoke
654 </Button>
655 {props.canReset ? (
656 <Button
657 size="xs"
658 variant="ghost"
659 disabled={props.disabled || !resolvedAppId}
660 onClick={() => decide("reset")}
661 >
662 Reset
663 </Button>
664 ) : null}
665 </div>
666 </Section>
667 );
668}
669
670const EVENT_LOG_LIMIT = 100;
671
672function EventLogSection(props: {
673 readonly access: DeviceHubAccess;
674 readonly device: DeviceSummary;
675}) {
676 const [open, setOpen] = useState(false);
677 const [entries, setEntries] = useState<ReadonlyArray<DeviceEventLogEntry>>([]);
678
679 useEffect(() => {
680 if (!open) return;
681 const unsubscribe = subscribeDeviceEventLog(
682 { access: props.access, platform: props.device.platform, deviceId: props.device.id },
683 (incoming, reset) => {
684 setEntries((current) => {
685 const merged = reset ? [...incoming] : [...current, ...incoming];
686 return merged.length > EVENT_LOG_LIMIT ? merged.slice(-EVENT_LOG_LIMIT) : merged;
687 });
688 },
689 );
690 return () => {
691 unsubscribe();
692 setEntries([]);
693 };
694 }, [open, props.access, props.device.id, props.device.platform]);
695
696 return (
697 <Collapsible open={open} onOpenChange={setOpen}>
698 <CollapsibleTrigger className="flex w-full items-center gap-1.5 border-b px-3 py-2.5 text-left text-xs font-medium tracking-wide text-muted-foreground uppercase">
699 Event log
700 <ChevronDown
701 className={cn("ml-auto size-3.5 transition-transform", open && "rotate-180")}
702 />
703 </CollapsibleTrigger>
704 <CollapsiblePanel>
705 <ol className="max-h-64 overflow-y-auto px-3 py-2 font-mono text-[11px] leading-relaxed">
706 {entries.length === 0 ? (
707 <li className="text-muted-foreground">No events yet.</li>
708 ) : (
709 entries.map((entry) => (
710 <li key={entry.id} className="flex gap-2">
711 <span className="shrink-0 text-muted-foreground">
712 {entry.timestamp.slice(11, 19)}
713 </span>
714 <span className="truncate">{entry.summary}</span>
715 </li>
716 ))
717 )}
718 </ol>
719 </CollapsiblePanel>
720 </Collapsible>
721 );
722}