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

useDeviceControls.ts

129 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, useMemo, 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 target = useMemo(
40 () => ({ hostId: device.hostId, deviceId: device.id }),
41 [device.hostId, device.id],
42 );
43​
44 useEffect(() => {
45 const revision = ++generation.current;
46 if (!visible) return;
47 const request = { environmentId, input: target };
48 visibleRead.current = request;
49 void readDetail(request).then((result) => {
50 if (generation.current !== revision) return;
51 if (result._tag === "Success") {
52 setDetail(result.value);
53 setError(null);
54 } else {
55 setDetail(null);
56 setError(formatEnvironmentQueryError(result.cause));
57 }
58 });
59 return () => {
60 visibleRead.current = null;
61 generation.current++;
62 };
63 }, [environmentId, readDetail, target, visible]);
64​
65 useEffect(() => {
66 if (!access || !visible) return;
67 let active = true;
68 const unsubscribe = subscribeDeviceForeground(
69 { access, platform: device.platform, deviceId: device.id },
70 (app) => {
71 if (active) setForeground(app);
72 },
73 );
74 return () => {
75 active = false;
76 unsubscribe();
77 setForeground(undefined);
78 };
79 }, [access, device.id, device.platform, visible]);
80​
81 const available = detail !== null && visible;
82 const act = async (body: ActionBody) => {
83 if (busy.current || !available) return;
84 busy.current = true;
85 const revision = ++generation.current;
86 setPending(true);
87 setError(null);
88 return runAction({
89 environmentId,
90 input: { ...target, ...body } as DeviceActionInput,
91 })
92 .then((result) => {
93 if (generation.current !== revision) {
94 const request = visibleRead.current;
95 if (!request) return;
96 // Reopening can read settings before the host command finishes. Confirm them again
97 // after it settles, keeping actions serialized through this refresh.
98 const refreshRevision = ++generation.current;
99 return readDetail(request).then((refreshed) => {
100 if (generation.current !== refreshRevision) return;
101 if (refreshed._tag === "Success") {
102 setDetail(refreshed.value);
103 setError(null);
104 } else {
105 setDetail(null);
106 setError(formatEnvironmentQueryError(refreshed.cause));
107 }
108 });
109 }
110 if (result._tag === "Success") setDetail(result.value);
111 else setError(formatEnvironmentQueryError(result.cause));
112 })
113 .finally(() => {
114 busy.current = false;
115 setPending(false);
116 });
117 };
118​
119 return {
120 detail,
121 pending,
122 error,
123 act,
124 disabled: pending || !detail || !visible,
125 foregroundApp: foreground === undefined ? (detail?.foregroundApp ?? null) : foreground,
126 };
128​
129export type DeviceControls = ReturnType<typeof useDeviceControls>;