Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { msg, T, useGT, useMessages } from "gt-react";
3import { type ReactNode, useSyncExternalStore } from "react";
4
5import type { MessageResolver } from "~/i18n/messages";
6import { cn } from "~/lib/utils";
7import { environmentIdsKey } from "~/state/environmentAtomList";
8import { environmentUpdateStatesAtom } from "~/state/server";
9import { useServerUpdate } from "../ServerUpdateAction";
10import { Button } from "../ui/button";
11import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
12import {
13 describeUpdateCapsule,
14 formatUpdateElapsed,
15 RUN_STATUS_LABELS,
16 resolveUpdateRunMachineStatus,
17 type UpdateEverythingRun,
18 type UpdateRunLocalState,
19 type UpdateRunMachineView,
20} from "./updateEverything.logic";
21import {
22 dismissSettledUpdateRunMachines,
23 postponeUpdateRestart,
24 retryFailedUpdateRunServers,
25} from "./updateEverythingRun";
26
27function useNow(intervalMs: number | null): number {
28 const step = intervalMs ?? 60_000;
29 const subscribe = (onChange: () => void) => {
30 if (intervalMs === null) return () => {};
31 const timer = setInterval(onChange, intervalMs);
32 return () => clearInterval(timer);
33 };
34 return useSyncExternalStore(subscribe, () => Math.floor(Date.now() / step) * step);
35}
36
37function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray<UpdateRunMachineView> {
38 const updateStates = useAtomValue(
39 environmentUpdateStatesAtom(
40 environmentIdsKey(run.machines.map(({ environmentId }) => environmentId)),
41 ),
42 );
43 return run.machines.map((machine, index) => ({
44 machine,
45 status: resolveUpdateRunMachineStatus(machine, run.phase, updateStates[index]!),
46 }));
47}
48
49function restartSecondsLeft(run: UpdateEverythingRun, now: number): number | null {
50 return run.phase === "countdown" && run.restartAt !== null
51 ? Math.max(0, Math.ceil((run.restartAt - now) / 1000))
52 : null;
53}
54
55function localStatusLabel(
56 run: UpdateEverythingRun,
57 local: UpdateRunLocalState,
58 now: number,
59 resolve: MessageResolver,
60) {
61 const seconds = restartSecondsLeft(run, now);
62 if (seconds !== null) return resolve(msg("restarts in {seconds}s", { seconds }));
63 if (run.phase === "installing") return resolve(msg("restarting"));
64 if (local?.status === "downloading") {
65 return local.percent === null
66 ? resolve(msg("downloading"))
67 : resolve(msg("downloading {percent}%", { percent: Math.floor(local.percent) }));
68 }
69 return resolve(msg("restarts after the servers"));
70}
71
72export function SidebarUpdateCapsule({
73 run,
74 local,
75 icon,
76 onRestart,
77}: {
78 readonly run: UpdateEverythingRun;
79 readonly local: UpdateRunLocalState;
80 readonly icon: ReactNode;
81 readonly onRestart?: () => Promise<void>;
82}) {
83 const machines = useUpdateRunMachineViews(run);
84 const hasActiveMachine = machines.some(
85 ({ status }) => status !== "done" && status !== "failed" && status !== "waiting",
86 );
87 const now = useNow(run.phase === "countdown" ? 1_000 : hasActiveMachine ? 30_000 : null);
88 const gt = useGT();
89 const m = useMessages();
90 const view = describeUpdateCapsule(run, machines, local, now, m);
91 const updateServer = useServerUpdate();
92 const failed = machines.some(({ status }) => status === "failed");
93 const settled = !hasActiveMachine && run.localVersion === null;
94 const restartSeconds = restartSecondsLeft(run, now);
95 const expandedControlClassName =
96 restartSeconds === null
97 ? "@min-[5rem]/sidebar-update:block"
98 : "@min-[12rem]/sidebar-update:block";
99
100 const actionLabel =
101 view.action === "later" ? gt("Later") : view.action === "retry" ? gt("Retry") : gt("Dismiss");
102 const runAction = () => {
103 if (view.action === "later") postponeUpdateRestart();
104 else if (view.action === "retry") retryFailedUpdateRunServers(updateServer);
105 else dismissSettledUpdateRunMachines();
106 };
107
108 return (
109 <Popover>
110 <div
111 className={cn(
112 "relative ml-auto flex h-8 w-8 shrink-0 items-center justify-end rounded-full bg-sidebar-control-surface text-sidebar-foreground transition-[width] duration-200 ease-out motion-reduce:transition-none",
113 restartSeconds === null
114 ? "@min-[5rem]/sidebar-update:w-full"
115 : "@min-[12rem]/sidebar-update:w-full",
116 view.tone === "slow" && "ring-1 ring-warning/40 ring-inset",
117 view.tone === "failed" && "ring-1 ring-destructive/40 ring-inset",
118 )}
119 >
120 <PopoverTrigger
121 render={
122 <button
123 type="button"
124 aria-label={
125 view.slow ? `${view.label} ${view.slow.status} ${view.slow.elapsed}` : view.label
126 }
127 className="absolute inset-0 cursor-pointer rounded-full outline-hidden ring-ring hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset"
128 />
129 }
130 />
131 <span
132 className={cn(
133 "pointer-events-none relative hidden min-w-0 flex-1 truncate pl-3 text-xs transition-opacity duration-200 ease-out starting:opacity-0 motion-reduce:transition-none",
134 expandedControlClassName,
135 )}
136 >
137 <span className={cn(view.tone === "failed" && "text-destructive")}>{view.label}</span>
138 {view.slow ? (
139 <span className="text-warning tabular-nums"> {view.slow.elapsed}</span>
140 ) : null}
141 </span>
142 {view.action !== null ? (
143 <button
144 type="button"
145 className={cn(
146 "relative hidden shrink-0 cursor-pointer pr-3 pl-1.5 text-xs underline decoration-muted-foreground/60 underline-offset-3 hover:decoration-current transition-opacity duration-200 ease-out starting:opacity-0 motion-reduce:transition-none",
147 expandedControlClassName,
148 )}
149 onClick={runAction}
150 >
151 {actionLabel}
152 </button>
153 ) : null}
154 <span
155 className={cn(
156 "pointer-events-none relative grid size-8 shrink-0 place-items-center",
157 view.action !== null &&
158 (restartSeconds === null
159 ? "@min-[5rem]/sidebar-update:hidden"
160 : "@min-[12rem]/sidebar-update:hidden"),
161 restartSeconds !== null &&
162 "rounded-full text-xs font-medium tabular-nums ring-1 ring-current/22 ring-inset",
163 )}
164 >
165 {restartSeconds !== null ? m(msg("{seconds}s", { seconds: restartSeconds })) : icon}
166 </span>
167 </div>
168 <PopoverPopup side="top" align="end" padding="compact" width="sm">
169 <div className="flex flex-col gap-1 text-xs">
170 {run.localVersion !== null ? (
171 <div className="flex items-center justify-between gap-3">
172 <span>
173 <T>This app</T>
174 </span>
175 <span className="text-muted-foreground tabular-nums">
176 {localStatusLabel(run, local, now, m)}
177 </span>
178 </div>
179 ) : onRestart ? (
180 <div className="flex items-center justify-between gap-3">
181 <span>
182 <T>This app</T>
183 </span>
184 <Button size="xs" variant="outline" onClick={() => void onRestart()}>
185 <T>Restart to update</T>
186 </Button>
187 </div>
188 ) : null}
189 {machines.map(({ machine, status }) => (
190 <div key={machine.environmentId} className="flex min-w-0 flex-col">
191 <div className="flex items-center justify-between gap-3">
192 <span className="truncate">{machine.label}</span>
193 <span
194 className={cn(
195 "shrink-0 tabular-nums",
196 status === "failed" ? "text-destructive" : "text-muted-foreground",
197 )}
198 >
199 {m(RUN_STATUS_LABELS[status])}
200 {status !== "done" && status !== "failed" && status !== "waiting"
201 ? ` ${formatUpdateElapsed(now - machine.startedAt, m)}`
202 : ""}
203 </span>
204 </div>
205 {machine.failure !== null ? (
206 <span className="break-words text-muted-foreground">{machine.failure}</span>
207 ) : null}
208 </div>
209 ))}
210 {view.action !== null ? (
211 <div className="mt-1 flex justify-end gap-1">
212 <Button size="xs" variant="outline" onClick={runAction}>
213 {actionLabel}
214 </Button>
215 {settled && failed && view.action !== "dismiss" ? (
216 <Button size="xs" variant="ghost" onClick={dismissSettledUpdateRunMachines}>
217 <T>Dismiss</T>
218 </Button>
219 ) : null}
220 </div>
221 ) : null}
222 </div>
223 </PopoverPopup>
224 </Popover>
225 );
226}