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

useDeviceControls.ts

126 lines4.4 KB

1import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2import type {
3 DeviceActionInput,
4 DeviceDetail,
5 DeviceSummary,
6 EnvironmentId,
7} from "@t3tools/contracts";
8import { useEffect, useRef, useState } from "react";
9import { deviceEnvironment } from "~/state/device";
10import { formatEnvironmentQueryError } from "~/state/query";
11import { useAtomCommand } from "~/state/use-atom-command";
12import { subscribeDeviceForeground, type DeviceForegroundInfo } from "./deviceHubApi";
13​
14type ActionBody = DeviceActionInput extends infer A
15 ? A extends { readonly type: string }
16 ? Omit<A, "hostId" | "deviceId">
17 : never
18 : never;
19​
20/** Mount keyed by device. */
21export function useDeviceControls(options: {
22 environmentId: EnvironmentId;
23 device: DeviceSummary;
24 access: DeviceHubAccess | null;
25 visible: boolean;
26}) {
27 const { environmentId, device, access, visible } = options;
28 const readDetail = useAtomCommand(deviceEnvironment.detail, { reportFailure: false });
29 const runAction = useAtomCommand(deviceEnvironment.action, { reportFailure: false });
30 const [detail, setDetail] = useState<DeviceDetail | null>(null);
31 const [pending, setPending] = useState(false);
32 const [error, setError] = useState<string | null>(null);
33 const [foreground, setForeground] = useState<DeviceForegroundInfo | null | undefined>();
34 // Hiding invalidates UI results, but does not cancel host commands. Keep them serialized
35 // until settlement rather than allowing a reopened panel to race the previous command.
36 const busy = useRef(false);
37 const generation = useRef(0);
38 const visibleRead = useRef<Parameters<typeof readDetail>[0] | null>(null);
39 const { hostId, id: deviceId } = device;
40​
41 useEffect(() => {
42 const revision = ++generation.current;
43 if (!visible) return;
44 const request = { environmentId, input: { hostId, deviceId } };
45 visibleRead.current = request;
46 void readDetail(request).then((result) => {
47 if (generation.current !== revision) return;
48 if (result._tag === "Success") {
49 setDetail(result.value);
50 setError(null);
51 } else {
52 setDetail(null);
53 setError(formatEnvironmentQueryError(result.cause));
54 }
55 });
56 return () => {
57 visibleRead.current = null;
58 generation.current++;
59 };
60 }, [deviceId, environmentId, hostId, readDetail, visible]);
61​
62 useEffect(() => {
63 if (!access || !visible) return;
64 let active = true;
65 const unsubscribe = subscribeDeviceForeground(
66 { access, platform: device.platform, deviceId: device.id },
67 (app) => {
68 if (active) setForeground(app);
69 },
70 );
71 return () => {
72 active = false;
73 unsubscribe();
74 setForeground(undefined);
75 };
76 }, [access, device.id, device.platform, visible]);
77​
78 const available = detail !== null && visible;
79 const act = async (body: ActionBody) => {
80 if (busy.current || !available) return;
81 busy.current = true;
82 const revision = ++generation.current;
83 setPending(true);
84 setError(null);
85 return runAction({
86 environmentId,
87 input: { hostId, deviceId, ...body } as DeviceActionInput,
88 })
89 .then((result) => {
90 if (generation.current !== revision) {
91 const request = visibleRead.current;
92 if (!request) return;
93 // Reopening can read settings before the host command finishes. Confirm them again
94 // after it settles, keeping actions serialized through this refresh.
95 const refreshRevision = ++generation.current;
96 return readDetail(request).then((refreshed) => {
97 if (generation.current !== refreshRevision) return;
98 if (refreshed._tag === "Success") {
99 setDetail(refreshed.value);
100 setError(null);
101 } else {
102 setDetail(null);
103 setError(formatEnvironmentQueryError(refreshed.cause));
104 }
105 });
106 }
107 if (result._tag === "Success") setDetail(result.value);
108 else setError(formatEnvironmentQueryError(result.cause));
109 })
110 .finally(() => {
111 busy.current = false;
112 setPending(false);
113 });
114 };
115​
116 return {
117 detail,
118 pending,
119 error,
120 act,
121 disabled: pending || !detail || !visible,
122 foregroundApp: foreground === undefined ? (detail?.foregroundApp ?? null) : foreground,
123 };
125​
126export type DeviceControls = ReturnType<typeof useDeviceControls>;