Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DeviceToolsPanel.tsx

725 lines23.9 KB

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 size="sm" /> : 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 size="sm" /> 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 );
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 );
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 );
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 );
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 );
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 font="mono"
497 className="min-w-0 flex-1"
498 placeholder={props.placeholder}
499 value={value}
500 disabled={props.disabled}
501 onChange={(event) => setValue(event.target.value)}
502 />
503 <Button
504 type="submit"
505 size="xs"
506 variant="outline"
507 disabled={props.disabled || value.trim().length === 0}
508 >
509 {props.action}
510 </Button>
511 </form>
512 );
514​
515function LocationSection(props: {
516 readonly disabled: boolean;
517 readonly canClear: boolean;
518 readonly onSet: (latitude: number, longitude: number) => Promise<void>;
519 readonly onClear: () => Promise<void>;
520}) {
521 const [latitude, setLatitude] = useState("");
522 const [longitude, setLongitude] = useState("");
523 const parsed = { latitude: Number(latitude), longitude: Number(longitude) };
524 const valid =
525 latitude.trim() !== "" &&
526 longitude.trim() !== "" &&
527 Math.abs(parsed.latitude) <= 90 &&
528 Math.abs(parsed.longitude) <= 180;
529 return (
530 <Section title="Location">
531 <div className="flex gap-1.5">
532 <Input
533 size="compact"
534 font="mono"
535 className="min-w-0 flex-1"
536 placeholder="Latitude"
537 inputMode="decimal"
538 value={latitude}
539 disabled={props.disabled}
540 onChange={(event) => setLatitude(event.target.value)}
541 />
542 <Input
543 size="compact"
544 font="mono"
545 className="min-w-0 flex-1"
546 placeholder="Longitude"
547 inputMode="decimal"
548 value={longitude}
549 disabled={props.disabled}
550 onChange={(event) => setLongitude(event.target.value)}
551 />
552 </div>
553 <div className="flex flex-wrap items-center gap-1.5">
554 <Select<string | null>
555 value={null}
556 disabled={props.disabled}
557 onValueChange={(value) => {
558 const preset = LOCATION_PRESETS.find((candidate) => candidate.label === value);
559 if (!preset) return;
560 setLatitude(String(preset.latitude));
561 setLongitude(String(preset.longitude));
562 void props.onSet(preset.latitude, preset.longitude);
563 }}
564 >
565 <SelectTrigger size="xs" className="w-32" aria-label="Location preset">
566 <SelectValue>
567 <span className="text-muted-foreground">Preset…</span>
568 </SelectValue>
569 </SelectTrigger>
570 <SelectPopup align="start" alignItemWithTrigger={false}>
571 {LOCATION_PRESETS.map((preset) => (
572 <SelectItem key={preset.label} value={preset.label}>
573 {preset.label}
574 </SelectItem>
575 ))}
576 </SelectPopup>
577 </Select>
578 <Button
579 size="xs"
580 variant="outline"
581 disabled={props.disabled || !valid}
582 onClick={() => void props.onSet(parsed.latitude, parsed.longitude)}
583 >
584 Set
585 </Button>
586 {props.canClear ? (
587 <Button
588 size="xs"
589 variant="ghost"
590 disabled={props.disabled}
591 onClick={() => {
592 setLatitude("");
593 setLongitude("");
594 void props.onClear();
595 }}
596 >
597 Clear
598 </Button>
599 ) : null}
600 </div>
601 </Section>
602 );
604​
605function PermissionsSection(props: {
606 readonly permissions: ReadonlyArray<{ value: DevicePermission; label: string }>;
607 readonly canReset: boolean;
608 readonly defaultAppId: string;
609 readonly disabled: boolean;
610 readonly onDecide: (
611 appId: string,
612 permission: DevicePermission,
613 decision: "grant" | "revoke" | "reset",
614 ) => Promise<void>;
615}) {
616 const [appId, setAppId] = useState("");
617 const [permission, setPermission] = useState<DevicePermission>("camera");
618 const resolvedAppId = appId.trim() || props.defaultAppId;
619 const decide = (decision: "grant" | "revoke" | "reset") =>
620 void props.onDecide(resolvedAppId, permission, decision);
621 return (
622 <Section title="Permissions">
623 <Input
624 size="compact"
625 font="mono"
626 placeholder={props.defaultAppId || "App ID"}
627 value={appId}
628 disabled={props.disabled}
629 onChange={(event) => setAppId(event.target.value)}
630 />
631 <div className="flex flex-wrap items-center gap-1.5">
632 <ChoiceSelect
633 ariaLabel="Permission"
634 value={permission}
635 options={props.permissions}
636 disabled={props.disabled}
637 onChange={(value) => {
638 setPermission(value);
639 return Promise.resolve();
640 }}
641 />
642 <Button
643 size="xs"
644 variant="outline"
645 disabled={props.disabled || !resolvedAppId}
646 onClick={() => decide("grant")}
647 >
648 Grant
649 </Button>
650 <Button
651 size="xs"
652 variant="outline"
653 disabled={props.disabled || !resolvedAppId}
654 onClick={() => decide("revoke")}
655 >
656 Revoke
657 </Button>
658 {props.canReset ? (
659 <Button
660 size="xs"
661 variant="ghost"
662 disabled={props.disabled || !resolvedAppId}
663 onClick={() => decide("reset")}
664 >
665 Reset
666 </Button>
667 ) : null}
668 </div>
669 </Section>
670 );
672​
673const EVENT_LOG_LIMIT = 100;
674​
675function EventLogSection(props: {
676 readonly access: DeviceHubAccess;
677 readonly device: DeviceSummary;
678}) {
679 const [open, setOpen] = useState(false);
680 const [entries, setEntries] = useState<ReadonlyArray<DeviceEventLogEntry>>([]);
681​
682 useEffect(() => {
683 if (!open) return;
684 const unsubscribe = subscribeDeviceEventLog(
685 { access: props.access, platform: props.device.platform, deviceId: props.device.id },
686 (incoming, reset) => {
687 setEntries((current) => {
688 const merged = reset ? [...incoming] : [...current, ...incoming];
689 return merged.length > EVENT_LOG_LIMIT ? merged.slice(-EVENT_LOG_LIMIT) : merged;
690 });
691 },
692 );
693 return () => {
694 unsubscribe();
695 setEntries([]);
696 };
697 }, [open, props.access, props.device.id, props.device.platform]);
698​
699 return (
700 <Collapsible open={open} onOpenChange={setOpen}>
701 <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">
702 Event log
703 <ChevronDown
704 className={cn("ml-auto size-3.5 transition-transform", open && "rotate-180")}
705 />
706 </CollapsibleTrigger>
707 <CollapsiblePanel>
708 <ol className="max-h-64 overflow-y-auto px-3 py-2 font-mono text-[11px] leading-relaxed">
709 {entries.length === 0 ? (
710 <li className="text-muted-foreground">No events yet.</li>
711 ) : (
712 entries.map((entry) => (
713 <li key={entry.id} className="flex gap-2">
714 <span className="shrink-0 text-muted-foreground">
715 {entry.timestamp.slice(11, 19)}
716 </span>
717 <span className="truncate">{entry.summary}</span>
718 </li>
719 ))
720 )}
721 </ol>
722 </CollapsiblePanel>
723 </Collapsible>
724 );