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