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

SidebarUpdateCapsule.tsx

201 lines7.6 KB

1import { useAtomValue } from "@effect/atom-react";
2import { Atom } from "effect/reactivity";
3import { type ReactNode, useCallback, useMemo, useSyncExternalStore } from "react";
4​
5import { cn } from "~/lib/utils";
6import { serverEnvironment } from "~/state/server";
7import { useServerUpdate } from "../ServerUpdateAction";
8import { Button } from "../ui/button";
9import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
10import {
11 describeUpdateCapsule,
12 formatUpdateElapsed,
13 RUN_STATUS_LABELS,
14 resolveUpdateRunMachineStatus,
15 type UpdateEverythingRun,
16 type UpdateRunLocalState,
17 type UpdateRunMachineView,
18} from "./updateEverything.logic";
19import {
20 dismissSettledUpdateRunMachines,
21 postponeUpdateRestart,
22 retryFailedUpdateRunServers,
23} from "./updateEverythingRun";
24​
25/** The current time, rounded down to `intervalMs` so it changes once per
26 interval. With null it is read only when something else renders. */
27function useNow(intervalMs: number | null): number {
28 const step = intervalMs ?? 60_000;
29 const subscribe = useCallback(
30 (onChange: () => void) => {
31 if (intervalMs === null) return () => {};
32 const timer = setInterval(onChange, intervalMs);
33 return () => clearInterval(timer);
34 },
35 [intervalMs],
36 );
37 return useSyncExternalStore(subscribe, () => Math.floor(Date.now() / step) * step);
39​
40function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray<UpdateRunMachineView> {
41 const viewsAtom = useMemo(
42 () =>
43 Atom.make((get) =>
44 run.machines.map((machine) => ({
45 machine,
46 status: resolveUpdateRunMachineStatus(
47 machine,
48 run.phase,
49 get(serverEnvironment.updateStateAtom(machine.environmentId)),
50 ),
51 })),
52 ),
53 [run],
54 );
55 return useAtomValue(viewsAtom);
57​
58function localStatusLabel(run: UpdateEverythingRun, local: UpdateRunLocalState, now: number) {
59 if (run.phase === "countdown" && run.restartAt !== null) {
60 return `restarts in ${Math.max(0, Math.ceil((run.restartAt - now) / 1000))}s`;
61 }
62 if (run.phase === "installing") return "restarting";
63 if (local?.status === "downloading") {
64 return `downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`;
65 }
66 return "restarts after the servers";
68​
69/**
70 * The sidebar update button while an "update everything" pass runs. It grows
71 * left into the free footer space and names the most urgent thing: this
72 * app's restart countdown, a slow machine, progress, or a failure. Click it
73 * for every machine. Time labels change once a second only during the
74 * countdown, and otherwise once every 30 seconds.
75 */
76export function SidebarUpdateCapsule({
77 run,
78 local,
79 icon,
80 onRestart,
81}: {
82 readonly run: UpdateEverythingRun;
83 readonly local: UpdateRunLocalState;
84 readonly icon: ReactNode;
85 /** Installs this app's downloaded update after the user postponed it. */
86 readonly onRestart?: () => Promise<void>;
87}) {
88 const machines = useUpdateRunMachineViews(run);
89 const hasActiveMachine = machines.some(
90 ({ status }) => status !== "done" && status !== "failed" && status !== "waiting",
91 );
92 const now = useNow(run.phase === "countdown" ? 1_000 : hasActiveMachine ? 30_000 : null);
93 const view = describeUpdateCapsule(run, machines, local, now);
94 const updateServer = useServerUpdate();
95 const failed = machines.some(({ status }) => status === "failed");
96 const settled = !hasActiveMachine && run.localVersion === null;
97​
98 const actionLabel =
99 view.action === "later" ? "Later" : view.action === "retry" ? "Retry" : "Dismiss";
100 const runAction = () => {
101 if (view.action === "later") postponeUpdateRestart();
102 else if (view.action === "retry") retryFailedUpdateRunServers(updateServer);
103 else dismissSettledUpdateRunMachines();
104 };
105​
106 return (
107 <Popover>
108 <div
109 className={cn(
110 "relative flex h-8 min-w-0 flex-1 items-center rounded-full bg-sidebar-control-surface text-sidebar-foreground",
111 view.tone === "slow" && "ring-1 ring-warning/40 ring-inset",
112 view.tone === "failed" && "ring-1 ring-destructive/40 ring-inset",
113 )}
114 >
115 <PopoverTrigger
116 render={
117 <button
118 type="button"
119 aria-label={
120 view.slow ? `${view.label} ${view.slow.status} ${view.slow.elapsed}` : view.label
121 }
122 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"
123 />
124 }
125 />
126 <span className="pointer-events-none relative min-w-0 flex-1 truncate pl-3 text-xs">
127 <span className={cn(view.tone === "failed" && "text-destructive")}>{view.label}</span>
128 {view.slow ? (
129 <span className="text-warning tabular-nums"> {view.slow.elapsed}</span>
130 ) : null}
131 </span>
132 {/* The footer leaves little room, so an action takes the icon's place. */}
133 {view.action !== null ? (
134 <button
135 type="button"
136 className="relative shrink-0 cursor-pointer pr-3 pl-1.5 text-xs underline decoration-muted-foreground/60 underline-offset-3 hover:decoration-current"
137 onClick={runAction}
138 >
139 {actionLabel}
140 </button>
141 ) : (
142 <span className="pointer-events-none relative grid size-8 shrink-0 place-items-center">
143 {icon}
144 </span>
145 )}
146 </div>
147 <PopoverPopup side="top" align="end" padding="compact" width="sm">
148 <div className="flex flex-col gap-1 text-xs">
149 {run.localVersion !== null ? (
150 <div className="flex items-center justify-between gap-3">
151 <span>This app</span>
152 <span className="text-muted-foreground tabular-nums">
153 {localStatusLabel(run, local, now)}
154 </span>
155 </div>
156 ) : onRestart ? (
157 <div className="flex items-center justify-between gap-3">
158 <span>This app</span>
159 <Button size="xs" variant="outline" onClick={() => void onRestart()}>
160 Restart to update
161 </Button>
162 </div>
163 ) : null}
164 {machines.map(({ machine, status }) => (
165 <div key={machine.environmentId} className="flex min-w-0 flex-col">
166 <div className="flex items-center justify-between gap-3">
167 <span className="truncate">{machine.label}</span>
168 <span
169 className={cn(
170 "shrink-0 tabular-nums",
171 status === "failed" ? "text-destructive" : "text-muted-foreground",
172 )}
173 >
174 {RUN_STATUS_LABELS[status]}
175 {status !== "done" && status !== "failed" && status !== "waiting"
176 ? ` ${formatUpdateElapsed(now - machine.startedAt)}`
177 : ""}
178 </span>
179 </div>
180 {machine.failure !== null ? (
181 <span className="break-words text-muted-foreground">{machine.failure}</span>
182 ) : null}
183 </div>
184 ))}
185 {settled && failed ? (
186 <div className="mt-1 flex justify-end gap-1">
187 {view.action === "retry" ? (
188 <Button size="xs" variant="outline" onClick={runAction}>
189 Retry
190 </Button>
191 ) : null}
192 <Button size="xs" variant="ghost" onClick={dismissSettledUpdateRunMachines}>
193 Dismiss
194 </Button>
195 </div>
196 ) : null}
197 </div>
198 </PopoverPopup>
199 </Popover>
200 );