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

EasDeviceHostEditor.tsx

320 lines12.0 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useId, useRef, useState } from "react";
3import * as Cause from "effect/Cause";
4import * as Option from "effect/Option";
5import {
6 type DeviceEasAccount,
7 type EasDeviceHostConfig,
8 type EnvironmentId,
9} from "@t3tools/contracts";
10import { XIcon } from "lucide-react";
11​
12import { deviceEasAccountCheck, deviceEnvironment } from "../../state/device";
13import { useAtomCommand } from "../../state/use-atom-command";
14import { Button } from "../ui/button";
15import {
16 Dialog,
17 DialogDescription,
18 DialogFooter,
19 DialogHeader,
20 DialogPanel,
21 DialogPopup,
22 DialogTitle,
23} from "../ui/dialog";
24import { Input } from "../ui/input";
25import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
26import { Spinner } from "../ui/spinner";
27import { parseEasDeviceHostDraft } from "./easDeviceHostsSettings.logic";
28import { SecretInput } from "./SecretInput";
29​
30const FROM_THREAD_PROJECT = "thread-project";
31​
32const CREDENTIAL_SOURCES: Record<DeviceEasAccount["credentialSource"], string> = {
33 settings: "the access token saved here",
34 env: "EXPO_TOKEN on the server",
35 "eas-login": "the server's eas login",
36};
37​
38const failureMessage = (cause: Cause.Cause<unknown>) => {
39 const error = Cause.squash(cause);
40 return error instanceof Error ? error.message : String(error);
41};
42​
43type AccountCheck =
44 | { status: "idle" }
45 | { status: "checking" }
46 | { status: "signed-in"; account: DeviceEasAccount }
47 | { status: "failed"; error: string };
48​
49export function EasDeviceHostEditor(props: {
50 environmentId: EnvironmentId;
51 host: EasDeviceHostConfig;
52 isNew: boolean;
53 busy: boolean;
54 onSave: (host: EasDeviceHostConfig) => void;
55 onClose: () => void;
56}) {
57 const check = useAtomCommand(deviceEnvironment.easAccount, { reportFailure: false });
58 const [draft, setDraft] = useState(props.host);
59 const tokenId = useId();
60 // A saved token arrives redacted; only a replacement or a clear changes it.
61 const [token, setToken] = useState<
62 { kind: "saved" } | { kind: "new"; value: string } | { kind: "cleared" }
63 >(props.host.accessToken ? { kind: "saved" } : { kind: "cleared" });
64 // Checking on open names the saved project and shows a rejected credential
65 // before anything is changed. A manual check or a token edit replaces it.
66 const openCheck = useAtomValue(
67 deviceEasAccountCheck({
68 environmentId: props.environmentId,
69 input: props.host.accessToken
70 ? props.isNew
71 ? {}
72 : { hostId: props.host.id }
73 : { accessToken: "" },
74 }),
75 );
76 const [checked, setAccount] = useState<AccountCheck | null>(null);
77 const account: AccountCheck =
78 checked ??
79 (openCheck._tag === "Initial" || openCheck.waiting
80 ? { status: "checking" }
81 : openCheck._tag === "Success"
82 ? { status: "signed-in", account: openCheck.value }
83 : { status: "failed", error: failureMessage(openCheck.cause) });
84 const next: EasDeviceHostConfig = {
85 ...draft,
86 label: draft.label.trim(),
87 accessToken:
88 token.kind === "saved" ? props.host.accessToken : token.kind === "new" ? token.value : "",
89 };
90 const valid = Option.isSome(parseEasDeviceHostDraft(next));
91 // Why Save is off, for the limits the fields' ranges do not show.
92 const problem = valid
93 ? null
94 : draft.maxSessionMinutes > 0 && draft.idleMinutes >= draft.maxSessionMinutes
95 ? "Idle minutes must be smaller than session minutes."
96 : "Give the host a label and limits within the ranges shown.";
97 const apps = account.status === "signed-in" ? account.account.apps : [];
98​
99 // A check answers for the credential it was asked about: a later check or a
100 // token edit makes an earlier answer stale.
101 const latestCheck = useRef(0);
102 const resetAccount = () => {
103 latestCheck.current++;
104 setAccount({ status: "idle" });
105 };
106 const requestCheck = async () => {
107 const run = ++latestCheck.current;
108 const result = await check({
109 environmentId: props.environmentId,
110 input: {
111 ...(token.kind === "saved" && !props.isNew ? { hostId: props.host.id } : {}),
112 // A cleared token is sent as empty, so the check does not fall back to
113 // the saved one that Save is about to drop.
114 ...(token.kind === "new"
115 ? { accessToken: token.value }
116 : token.kind === "cleared"
117 ? { accessToken: "" }
118 : {}),
119 },
120 });
121 if (run !== latestCheck.current) return;
122 setAccount(
123 result._tag === "Success"
124 ? { status: "signed-in", account: result.value }
125 : { status: "failed", error: failureMessage(result.cause) },
126 );
127 };
128 const checkAccount = () => {
129 setAccount({ status: "checking" });
130 void requestCheck();
131 };
132​
133 const limit = (
134 field: "maxSessionMinutes" | "idleMinutes" | "maxConcurrentSessions",
135 label: string,
136 max: number,
137 ) => (
138 <label className="block space-y-1.5">
139 <span>{label}</span>
140 <Input
141 type="number"
142 min={1}
143 max={max}
144 value={draft[field]}
145 disabled={props.busy}
146 onChange={(event) => {
147 const value = Number(event.target.value);
148 setDraft((current) => ({ ...current, [field]: value }));
149 }}
150 />
151 </label>
152 );
153​
154 return (
155 <Dialog
156 open
157 onOpenChange={(open) => {
158 if (!open && !props.busy) props.onClose();
159 }}
160 >
161 <DialogPopup showCloseButton={!props.busy}>
162 <form
163 className="flex min-h-0 flex-col"
164 onSubmit={(event) => {
165 event.preventDefault();
166 if (valid && !props.busy) props.onSave(next);
167 }}
168 >
169 <DialogHeader>
170 <DialogTitle>{props.isNew ? "Add EAS host" : "Edit EAS host"}</DialogTitle>
171 <DialogDescription>
172 The environment's server signs in to Expo and starts the sessions. Without a token
173 here it uses EXPO_TOKEN, then its eas login.
174 </DialogDescription>
175 </DialogHeader>
176 <DialogPanel>
177 <label className="block space-y-1.5 text-sm">
178 <span>Name</span>
179 <Input
180 autoFocus
181 required
182 value={draft.label}
183 disabled={props.busy}
184 onChange={(event) => {
185 const label = event.target.value;
186 setDraft((current) => ({ ...current, label }));
187 }}
188 />
189 </label>
190 <div className="space-y-1.5 text-sm">
191 <label htmlFor={tokenId} className="block">
192 Expo access token
193 </label>
194 <div className="flex items-center gap-2">
195 <SecretInput
196 id={tokenId}
197 className="min-w-0 flex-1"
198 configured={token.kind === "saved"}
199 value={token.kind === "new" ? token.value : ""}
200 disabled={props.busy}
201 placeholder="Optional"
202 onChange={(event) => {
203 const value = event.target.value;
204 // Emptying the field is not clearing the saved token; the
205 // Clear button is, so a saved token comes back here.
206 setToken(
207 value
208 ? { kind: "new", value }
209 : props.host.accessToken
210 ? { kind: "saved" }
211 : { kind: "cleared" },
212 );
213 resetAccount();
214 }}
215 />
216 {token.kind !== "cleared" ? (
217 <Button
218 type="button"
219 size="icon-sm"
220 variant="ghost-destructive"
221 aria-label="Clear access token"
222 onClick={() => {
223 setToken({ kind: "cleared" });
224 resetAccount();
225 }}
226 >
227 <XIcon className="size-3.5" />
228 </Button>
229 ) : null}
230 </div>
231 </div>
232 <div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 px-3 py-2.5">
233 <p role="status" className="min-w-0 text-xs text-muted-foreground">
234 {account.status === "signed-in"
235 ? `Signed in as ${account.account.signedInAs} with ${CREDENTIAL_SOURCES[account.account.credentialSource]}.`
236 : account.status === "failed"
237 ? account.error
238 : account.status === "checking"
239 ? "Checking the Expo account…"
240 : "Check the Expo account before choosing a project."}
241 </p>
242 <Button
243 type="button"
244 size="sm"
245 variant="outline"
246 disabled={props.busy || account.status === "checking"}
247 onClick={() => void checkAccount()}
248 >
249 {account.status === "checking" ? <Spinner size="xs" /> : null} Check account
250 </Button>
251 </div>
252 <div className="space-y-1.5 text-sm">
253 <span>EAS project</span>
254 <Select
255 value={draft.appId ?? FROM_THREAD_PROJECT}
256 disabled={props.busy}
257 onValueChange={(value) => {
258 if (typeof value !== "string") return;
259 setDraft((current) => {
260 const { appId: _, ...rest } = current;
261 return value === FROM_THREAD_PROJECT ? rest : { ...rest, appId: value };
262 });
263 }}
264 >
265 <SelectTrigger size="sm" aria-label="EAS project">
266 <SelectValue>
267 {(value: string) =>
268 value === FROM_THREAD_PROJECT
269 ? "From the thread's project"
270 : (apps.find((app) => app.id === value)?.fullName ?? value)
271 }
272 </SelectValue>
273 </SelectTrigger>
274 <SelectPopup>
275 <SelectItem value={FROM_THREAD_PROJECT}>From the thread's project</SelectItem>
276 {draft.appId && !apps.some((app) => app.id === draft.appId) ? (
277 <SelectItem value={draft.appId}>{draft.appId}</SelectItem>
278 ) : null}
279 {apps.map((app) => (
280 <SelectItem key={app.id} value={app.id}>
281 {app.fullName}
282 </SelectItem>
283 ))}
284 </SelectPopup>
285 </Select>
286 <p className="text-xs text-muted-foreground">
287 Sessions bill the project's Expo account. "From the thread's project" reads
288 extra.eas.projectId from the project's app config.
289 </p>
290 </div>
291 <div className="grid grid-cols-3 gap-3 text-sm">
292 {limit("maxConcurrentSessions", "Sessions at once", 20)}
293 {limit("maxSessionMinutes", "Session minutes", 115)}
294 {limit("idleMinutes", "Idle minutes", 60)}
295 </div>
296 <p className="text-xs text-muted-foreground">
297 Expo allows sessions of up to 40 minutes on free accounts and 115 on paid ones, and
298 ends one after the idle minutes without activity, so idle minutes must be smaller than
299 session minutes.
300 {props.isNew ? null : " Saving restarts this host, which stops its running sessions."}
301 </p>
302 {problem === null ? null : (
303 <p className="text-xs text-destructive" role="alert">
304 {problem}
305 </p>
306 )}
307 </DialogPanel>
308 <DialogFooter>
309 <Button type="button" variant="ghost" disabled={props.busy} onClick={props.onClose}>
310 Cancel
311 </Button>
312 <Button type="submit" disabled={props.busy || !valid}>
313 {props.busy ? <Spinner size="xs" /> : null} Save host
314 </Button>
315 </DialogFooter>
316 </form>
317 </DialogPopup>
318 </Dialog>
319 );