Open History to see the last commit
1import { TriangleAlertIcon } from "lucide-react";
2import { useCallback, useEffect, useState } from "react";
3import { isElectron } from "../../env";
4import { useMediaQuery } from "../../hooks/useMediaQuery";
5import { cn } from "../../lib/utils";
6import { ensureLocalApi } from "../../localApi";
7import { useDesktopUpdateState } from "../../state/desktopUpdate";
8import { stackedThreadToast, toastManager } from "../ui/toast";
9import {
10 canCheckForUpdate,
11 getArm64IntelBuildWarningDescription,
12 getDesktopUpdateActionError,
13 getDesktopUpdateButtonTooltip,
14 getDesktopUpdateInstallConfirmationMessage,
15 isDesktopUpdateButtonDisabled,
16 resolveDesktopUpdateButtonAction,
17 shouldShowArm64IntelBuildWarning,
18 shouldToastDesktopUpdateActionResult,
19} from "../desktopUpdate.logic";
20import { showDesktopUpdateDownloadedToast } from "../desktopUpdate.toast";
21import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
22import { Separator } from "../ui/separator";
23import { SidebarMenuItem } from "../ui/sidebar";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import {
26 DesktopUpdateStatusIcon,
27 shouldContinueDesktopUpdateCheckAnimation,
28 shouldShowDesktopUpdateCheckIcon,
29} from "./DesktopUpdateStatusIcon";
30
31function resolveSidebarUpdatePresentation({
32 action,
33 isDownloading,
34 showCheckIcon,
35}: {
36 readonly action: ReturnType<typeof resolveDesktopUpdateButtonAction>;
37 readonly isDownloading: boolean;
38 readonly showCheckIcon: boolean;
39}) {
40 const showUpdateDetails = action !== "none" || isDownloading;
41 const iconStatus = showCheckIcon
42 ? "checking"
43 : action === "install"
44 ? "downloaded"
45 : isDownloading
46 ? "downloading"
47 : action === "download"
48 ? "available"
49 : "idle";
50
51 return {
52 iconStatus,
53 showUpdateDetails,
54 showUpdateIconState: showUpdateDetails && !showCheckIcon,
55 } as const;
56}
57
58function keyReleaseNoteItems(items: ReadonlyArray<string>) {
59 const occurrences = new Map<string, number>();
60 return items.map((item) => {
61 const occurrence = occurrences.get(item) ?? 0;
62 occurrences.set(item, occurrence + 1);
63 return { item, key: JSON.stringify([item, occurrence]) };
64 });
65}
66
67function SidebarUpdateReleaseNotesTooltip({
68 state,
69 tooltip,
70}: {
71 readonly state: NonNullable<ReturnType<typeof useDesktopUpdateState>>;
72 readonly tooltip: string;
73}) {
74 if (state.channel !== "nightly" || state.releaseNotes.length === 0) {
75 return <>{tooltip}</>;
76 }
77
78 return (
79 <div className="w-fit max-w-[min(24rem,calc(100vw-2rem))] text-left">
80 <div className="px-1">
81 {state.status === "available" ? (
82 <div>
83 <div className="whitespace-nowrap text-sm leading-5 font-medium">
84 Update ready to download
85 </div>
86 {state.availableVersion ? (
87 <div className="mt-0.5 text-xs leading-4 text-update-foreground">
88 {state.availableVersion}
89 </div>
90 ) : null}
91 </div>
92 ) : (
93 <div className="text-sm leading-5 font-medium">{tooltip}</div>
94 )}
95 </div>
96 <div className="max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
97 {state.releaseNotes.map((releaseNote, index) => (
98 <div key={releaseNote.version}>
99 {index > 0 && <Separator className="my-3 bg-border/60" />}
100 <section>
101 <h3 className="text-foreground text-xs leading-4 font-semibold">
102 {index === 0 ? "What's changed" : `Changes in ${releaseNote.version}`}
103 </h3>
104 <ul className="mt-2 space-y-1.5 pl-4 text-xs leading-5 text-popover-foreground/90">
105 {keyReleaseNoteItems(releaseNote.items).map(({ item, key }) => (
106 <li className="list-disc break-words" key={key}>
107 {item}
108 </li>
109 ))}
110 </ul>
111 </section>
112 </div>
113 ))}
114 </div>
115 </div>
116 );
117}
118
119export function SidebarUpdateArchitectureWarning() {
120 return isElectron ? <SidebarUpdateArchitectureWarningContent /> : null;
121}
122
123function SidebarUpdateArchitectureWarningContent() {
124 const state = useDesktopUpdateState();
125 const visible = shouldShowArm64IntelBuildWarning(state);
126 const description = state && visible ? getArm64IntelBuildWarningDescription(state) : null;
127
128 if (!visible || !description) return null;
129
130 return (
131 <Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
132 <TriangleAlertIcon />
133 <AlertTitle>Intel build on Apple Silicon</AlertTitle>
134 <AlertDescription>{description}</AlertDescription>
135 </Alert>
136 );
137}
138
139export function SidebarUpdatePill() {
140 return isElectron ? <SidebarUpdateControl /> : null;
141}
142
143function SidebarUpdateControl() {
144 const state = useDesktopUpdateState();
145 const [isActionPending, setIsActionPending] = useState(false);
146 const [checkAnimationKey, setCheckAnimationKey] = useState(0);
147 const [isCheckAnimationLatched, setIsCheckAnimationLatched] = useState(false);
148 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
149
150 useEffect(() => {
151 if (prefersReducedMotion) {
152 setIsCheckAnimationLatched(false);
153 } else if (state?.status === "checking") {
154 setIsCheckAnimationLatched(true);
155 }
156 }, [prefersReducedMotion, state?.status]);
157
158 const action = state ? resolveDesktopUpdateButtonAction(state) : "none";
159 const isDownloading = state?.status === "downloading";
160 const showCheckIcon = shouldShowDesktopUpdateCheckIcon({
161 isAnimationLatched: isCheckAnimationLatched,
162 isChecking: state?.status === "checking",
163 prefersReducedMotion,
164 });
165 const { iconStatus, showUpdateDetails, showUpdateIconState } = resolveSidebarUpdatePresentation({
166 action,
167 isDownloading,
168 showCheckIcon,
169 });
170 const tooltip = showUpdateDetails
171 ? state
172 ? getDesktopUpdateButtonTooltip(state)
173 : "Update available"
174 : showCheckIcon
175 ? "Checking for updates…"
176 : "Check for updates";
177 const disabled = showCheckIcon
178 ? true
179 : showUpdateDetails
180 ? isDesktopUpdateButtonDisabled(state)
181 : !canCheckForUpdate(state);
182 const isInteractionDisabled = disabled || isActionPending;
183
184 const handleAction = useCallback(async () => {
185 const bridge = window.desktopBridge;
186 if (!bridge || !state) return;
187 if (isInteractionDisabled) return;
188
189 setIsActionPending(true);
190
191 if (action === "download") {
192 void bridge
193 .downloadUpdate()
194 .then((result) => {
195 if (result.completed) {
196 showDesktopUpdateDownloadedToast(bridge, result.state);
197 }
198 if (!shouldToastDesktopUpdateActionResult(result)) return;
199 const actionError = getDesktopUpdateActionError(result);
200 if (!actionError) return;
201 toastManager.add(
202 stackedThreadToast({
203 type: "error",
204 title: "Could not download update",
205 description: actionError,
206 }),
207 );
208 })
209 .catch((error) => {
210 toastManager.add(
211 stackedThreadToast({
212 type: "error",
213 title: "Could not start update download",
214 description: error instanceof Error ? error.message : "An unexpected error occurred.",
215 }),
216 );
217 })
218 .finally(() => setIsActionPending(false));
219 return;
220 }
221
222 if (action === "install") {
223 let confirmed = false;
224 try {
225 confirmed = await ensureLocalApi().dialogs.confirm(
226 getDesktopUpdateInstallConfirmationMessage(state),
227 );
228 } catch (error) {
229 setIsActionPending(false);
230 toastManager.add(
231 stackedThreadToast({
232 type: "error",
233 title: "Could not confirm update",
234 description: error instanceof Error ? error.message : "Update confirmation failed.",
235 }),
236 );
237 return;
238 }
239 if (!confirmed) {
240 setIsActionPending(false);
241 return;
242 }
243 void bridge
244 .installUpdate()
245 .then((result) => {
246 if (!shouldToastDesktopUpdateActionResult(result)) return;
247 const actionError = getDesktopUpdateActionError(result);
248 if (!actionError) return;
249 toastManager.add(
250 stackedThreadToast({
251 type: "error",
252 title: "Could not install update",
253 description: actionError,
254 }),
255 );
256 })
257 .catch((error) => {
258 toastManager.add(
259 stackedThreadToast({
260 type: "error",
261 title: "Could not install update",
262 description: error instanceof Error ? error.message : "An unexpected error occurred.",
263 }),
264 );
265 })
266 .finally(() => setIsActionPending(false));
267 return;
268 }
269
270 if (!prefersReducedMotion) {
271 setIsCheckAnimationLatched(true);
272 setCheckAnimationKey((key) => key + 1);
273 }
274 void bridge
275 .checkForUpdate()
276 .then((result) => {
277 if (result.checked) return;
278 toastManager.add(
279 stackedThreadToast({
280 type: "error",
281 title: "Could not check for updates",
282 description:
283 result.state.message ?? "Automatic updates are not available in this build.",
284 }),
285 );
286 })
287 .catch((error) => {
288 toastManager.add(
289 stackedThreadToast({
290 type: "error",
291 title: "Could not check for updates",
292 description: error instanceof Error ? error.message : "Update check failed.",
293 }),
294 );
295 })
296 .finally(() => setIsActionPending(false));
297 }, [action, isInteractionDisabled, prefersReducedMotion, state]);
298
299 const handleCheckAnimationIteration = useCallback(() => {
300 setIsCheckAnimationLatched(
301 shouldContinueDesktopUpdateCheckAnimation({
302 isChecking: state?.status === "checking",
303 prefersReducedMotion,
304 }),
305 );
306 }, [prefersReducedMotion, state?.status]);
307
308 return (
309 <SidebarMenuItem className="ml-auto shrink-0">
310 <Tooltip>
311 <TooltipTrigger
312 render={
313 <button
314 type="button"
315 aria-label={tooltip}
316 aria-disabled={isInteractionDisabled || undefined}
317 className={cn(
318 "inline-flex size-8 items-center justify-center rounded-full outline-hidden ring-ring transition-colors focus-visible:ring-2",
319 isInteractionDisabled ? "cursor-not-allowed" : "cursor-pointer",
320 showUpdateIconState
321 ? cn(
322 "bg-update-surface text-update-foreground",
323 !isInteractionDisabled && "hover:bg-update/12",
324 )
325 : cn(
326 "text-[var(--sidebar-icon-color)]",
327 !isInteractionDisabled &&
328 "hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
329 ),
330 disabled && !showUpdateIconState && "opacity-60",
331 )}
332 onClick={handleAction}
333 >
334 <DesktopUpdateStatusIcon
335 key={showCheckIcon ? checkAnimationKey : iconStatus}
336 downloadPercent={state?.downloadPercent ?? null}
337 isCheckAnimating={showCheckIcon && !prefersReducedMotion}
338 onCheckAnimationIteration={handleCheckAnimationIteration}
339 status={iconStatus}
340 />
341 </button>
342 }
343 />
344 <TooltipPopup
345 align="center"
346 className={
347 showUpdateDetails && state?.channel === "nightly" && state.releaseNotes.length > 0
348 ? // pointer-events-auto overrides the positioner's pointer-events-none so the
349 // release notes stay open (and scrollable) when the cursor moves into them.
350 "pointer-events-auto max-w-none text-balance"
351 : undefined
352 }
353 side="top"
354 style={
355 showUpdateDetails
356 ? {
357 background:
358 "color-mix(in srgb, var(--update) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
359 borderColor: "var(--update-foreground)",
360 }
361 : undefined
362 }
363 variant={showUpdateDetails ? "glass" : "default"}
364 >
365 {showUpdateDetails && state ? (
366 <SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
367 ) : (
368 tooltip
369 )}
370 </TooltipPopup>
371 </Tooltip>
372 </SidebarMenuItem>
373 );
374}