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

SidebarUpdatePill.tsx

263 lines9.5 KB

1import { DownloadIcon, RotateCwIcon, TriangleAlertIcon, XIcon } from "lucide-react";
2import { useCallback, useState } from "react";
3import { isElectron } from "../../env";
4import { ensureLocalApi } from "../../localApi";
5import { useDesktopUpdateState } from "../../state/desktopUpdate";
6import { stackedThreadToast, toastManager } from "../ui/toast";
7import {
8 getArm64IntelBuildWarningDescription,
9 getDesktopUpdateActionError,
10 getDesktopUpdateButtonTooltip,
11 getDesktopUpdateInstallConfirmationMessage,
12 isDesktopUpdateButtonDisabled,
13 resolveDesktopUpdateButtonAction,
14 shouldShowArm64IntelBuildWarning,
15 shouldShowDesktopUpdateButton,
16 shouldToastDesktopUpdateActionResult,
17} from "../desktopUpdate.logic";
18import { showDesktopUpdateDownloadedToast } from "../desktopUpdate.toast";
19import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
20import { Separator } from "../ui/separator";
21import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
22​
23function keyReleaseNoteItems(items: ReadonlyArray<string>) {
24 const occurrences = new Map<string, number>();
25 return items.map((item) => {
26 const occurrence = occurrences.get(item) ?? 0;
27 occurrences.set(item, occurrence + 1);
28 return { item, key: JSON.stringify([item, occurrence]) };
29 });
31​
32function SidebarUpdateReleaseNotesTooltip({
33 state,
34 tooltip,
35}: {
36 readonly state: NonNullable<ReturnType<typeof useDesktopUpdateState>>;
37 readonly tooltip: string;
38}) {
39 if (state.channel !== "nightly" || state.releaseNotes.length === 0) {
40 return <>{tooltip}</>;
41 }
42​
43 return (
44 <div className="w-120 max-w-[calc(100vw-2rem)] text-left">
45 <div className="px-1">
46 <div className="text-sm leading-5 font-medium">{tooltip}</div>
47 </div>
48 <div className="max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
49 {state.releaseNotes.map((releaseNote, index) => (
50 <div key={releaseNote.version}>
51 {index > 0 && <Separator className="my-3 bg-border/60" />}
52 <section>
53 <h3 className="text-muted-foreground text-xs leading-4 font-semibold">
54 {index === 0 ? "What's changed" : `Changes in ${releaseNote.version}`}
55 </h3>
56 <ul className="mt-2 space-y-1.5 pl-4 text-xs leading-5 text-popover-foreground/90">
57 {keyReleaseNoteItems(releaseNote.items).map(({ item, key }) => (
58 <li className="list-disc break-words" key={key}>
59 {item}
60 </li>
61 ))}
62 </ul>
63 </section>
64 </div>
65 ))}
66 </div>
67 </div>
68 );
70​
71export function SidebarUpdatePill() {
72 const state = useDesktopUpdateState();
73 const [dismissed, setDismissed] = useState(false);
74 const [isActionPending, setIsActionPending] = useState(false);
75​
76 const visible = isElectron && shouldShowDesktopUpdateButton(state) && !dismissed;
77 const tooltip = state ? getDesktopUpdateButtonTooltip(state) : "Update available";
78 const disabled = isDesktopUpdateButtonDisabled(state);
79 const action = state ? resolveDesktopUpdateButtonAction(state) : "none";
80​
81 const showArm64Warning = isElectron && shouldShowArm64IntelBuildWarning(state);
82 const arm64Description =
83 state && showArm64Warning ? getArm64IntelBuildWarningDescription(state) : null;
84​
85 const handleAction = useCallback(async () => {
86 const bridge = window.desktopBridge;
87 if (!bridge || !state) return;
88 if (disabled || action === "none" || isActionPending) return;
89​
90 setIsActionPending(true);
91​
92 if (action === "download") {
93 void bridge
94 .downloadUpdate()
95 .then((result) => {
96 if (result.completed) {
97 showDesktopUpdateDownloadedToast(bridge, result.state);
98 }
99 if (!shouldToastDesktopUpdateActionResult(result)) return;
100 const actionError = getDesktopUpdateActionError(result);
101 if (!actionError) return;
102 toastManager.add(
103 stackedThreadToast({
104 type: "error",
105 title: "Could not download update",
106 description: actionError,
107 }),
108 );
109 })
110 .catch((error) => {
111 toastManager.add(
112 stackedThreadToast({
113 type: "error",
114 title: "Could not start update download",
115 description: error instanceof Error ? error.message : "An unexpected error occurred.",
116 }),
117 );
118 })
119 .finally(() => setIsActionPending(false));
120 return;
121 }
122​
123 if (action === "install") {
124 let confirmed = false;
125 try {
126 confirmed = await ensureLocalApi().dialogs.confirm(
127 getDesktopUpdateInstallConfirmationMessage(state, navigator.platform),
128 );
129 } catch (error) {
130 setIsActionPending(false);
131 toastManager.add(
132 stackedThreadToast({
133 type: "error",
134 title: "Could not confirm update",
135 description: error instanceof Error ? error.message : "Update confirmation failed.",
136 }),
137 );
138 return;
139 }
140 if (!confirmed) {
141 setIsActionPending(false);
142 return;
143 }
144 void bridge
145 .installUpdate()
146 .then((result) => {
147 if (!shouldToastDesktopUpdateActionResult(result)) return;
148 const actionError = getDesktopUpdateActionError(result);
149 if (!actionError) return;
150 toastManager.add(
151 stackedThreadToast({
152 type: "error",
153 title: "Could not install update",
154 description: actionError,
155 }),
156 );
157 })
158 .catch((error) => {
159 toastManager.add(
160 stackedThreadToast({
161 type: "error",
162 title: "Could not install update",
163 description: error instanceof Error ? error.message : "An unexpected error occurred.",
164 }),
165 );
166 })
167 .finally(() => setIsActionPending(false));
168 }
169 }, [action, disabled, isActionPending, state]);
170​
171 if (!visible && !showArm64Warning) return null;
172​
173 return (
174 <div className="flex flex-col gap-1">
175 {showArm64Warning && arm64Description && (
176 <Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
177 <TriangleAlertIcon />
178 <AlertTitle>Intel build on Apple Silicon</AlertTitle>
179 <AlertDescription>{arm64Description}</AlertDescription>
180 </Alert>
181 )}
182 {visible && (
183 <div
184 className={`group/update relative flex h-7 w-full items-center rounded-lg bg-update-surface text-xs font-medium text-update-foreground ${
185 disabled ? " cursor-not-allowed opacity-60" : ""
186 }`}
187 >
188 <div className="pointer-events-none absolute inset-0 rounded-lg transition-colors group-has-[button.update-main:hover]/update:bg-update/12" />
189 <Tooltip>
190 <TooltipTrigger
191 render={
192 <button
193 type="button"
194 aria-label={tooltip}
195 aria-disabled={disabled || isActionPending || undefined}
196 disabled={disabled || isActionPending}
197 className="update-main relative flex h-full flex-1 items-center gap-2 px-2 enabled:cursor-pointer"
198 onClick={handleAction}
199 >
200 {action === "install" ? (
201 <>
202 <RotateCwIcon className="size-3.5" />
203 <span>Restart to update</span>
204 </>
205 ) : state?.status === "downloading" ? (
206 <>
207 <DownloadIcon className="size-3.5" />
208 <span>
209 Downloading
210 {typeof state.downloadPercent === "number"
211 ? ` (${Math.floor(state.downloadPercent)}%)`
212 : "…"}
213 </span>
214 </>
215 ) : (
216 <>
217 <DownloadIcon className="size-3.5" />
218 <span>Update available</span>
219 </>
220 )}
221 </button>
222 }
223 />
224 <TooltipPopup
225 align="start"
226 className={
227 state?.channel === "nightly" && state.releaseNotes.length > 0
228 ? // pointer-events-auto overrides the positioner's pointer-events-none so the
229 // release notes stay open (and scrollable) when the cursor moves into them.
230 "pointer-events-auto max-w-none text-balance"
231 : undefined
232 }
233 side="top"
234 >
235 {state ? (
236 <SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
237 ) : (
238 tooltip
239 )}
240 </TooltipPopup>
241 </Tooltip>
242 {action === "download" && (
243 <Tooltip>
244 <TooltipTrigger
245 render={
246 <button
247 type="button"
248 aria-label="Dismiss update"
249 className="mr-1 inline-flex size-5 items-center justify-center rounded-md text-update-foreground transition-colors"
250 onClick={() => setDismissed(true)}
251 >
252 <XIcon className="size-3.5" />
253 </button>
254 }
255 />
256 <TooltipPopup side="top">Dismiss until next launch</TooltipPopup>
257 </Tooltip>
258 )}
259 </div>
260 )}
261 </div>
262 );