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

SidebarUpdatePill.tsx

366 lines12.3 KB

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;
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 });
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 );
118​
119export function SidebarUpdateArchitectureWarning() {
120 return isElectron ? <SidebarUpdateArchitectureWarningContent /> : null;
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 );
138​
139export function SidebarUpdatePill() {
140 return isElectron ? <SidebarUpdateControl /> : null;
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​
183 const handleAction = useCallback(async () => {
184 const bridge = window.desktopBridge;
185 if (!bridge || !state) return;
186 if (disabled || isActionPending) return;
187​
188 setIsActionPending(true);
189​
190 if (action === "download") {
191 void bridge
192 .downloadUpdate()
193 .then((result) => {
194 if (result.completed) {
195 showDesktopUpdateDownloadedToast(bridge, result.state);
196 }
197 if (!shouldToastDesktopUpdateActionResult(result)) return;
198 const actionError = getDesktopUpdateActionError(result);
199 if (!actionError) return;
200 toastManager.add(
201 stackedThreadToast({
202 type: "error",
203 title: "Could not download update",
204 description: actionError,
205 }),
206 );
207 })
208 .catch((error) => {
209 toastManager.add(
210 stackedThreadToast({
211 type: "error",
212 title: "Could not start update download",
213 description: error instanceof Error ? error.message : "An unexpected error occurred.",
214 }),
215 );
216 })
217 .finally(() => setIsActionPending(false));
218 return;
219 }
220​
221 if (action === "install") {
222 let confirmed = false;
223 try {
224 confirmed = await ensureLocalApi().dialogs.confirm(
225 getDesktopUpdateInstallConfirmationMessage(state),
226 );
227 } catch (error) {
228 setIsActionPending(false);
229 toastManager.add(
230 stackedThreadToast({
231 type: "error",
232 title: "Could not confirm update",
233 description: error instanceof Error ? error.message : "Update confirmation failed.",
234 }),
235 );
236 return;
237 }
238 if (!confirmed) {
239 setIsActionPending(false);
240 return;
241 }
242 void bridge
243 .installUpdate()
244 .then((result) => {
245 if (!shouldToastDesktopUpdateActionResult(result)) return;
246 const actionError = getDesktopUpdateActionError(result);
247 if (!actionError) return;
248 toastManager.add(
249 stackedThreadToast({
250 type: "error",
251 title: "Could not install update",
252 description: actionError,
253 }),
254 );
255 })
256 .catch((error) => {
257 toastManager.add(
258 stackedThreadToast({
259 type: "error",
260 title: "Could not install update",
261 description: error instanceof Error ? error.message : "An unexpected error occurred.",
262 }),
263 );
264 })
265 .finally(() => setIsActionPending(false));
266 return;
267 }
268​
269 if (!prefersReducedMotion) {
270 setIsCheckAnimationLatched(true);
271 setCheckAnimationKey((key) => key + 1);
272 }
273 void bridge
274 .checkForUpdate()
275 .then((result) => {
276 if (result.checked) return;
277 toastManager.add(
278 stackedThreadToast({
279 type: "error",
280 title: "Could not check for updates",
281 description:
282 result.state.message ?? "Automatic updates are not available in this build.",
283 }),
284 );
285 })
286 .catch((error) => {
287 toastManager.add(
288 stackedThreadToast({
289 type: "error",
290 title: "Could not check for updates",
291 description: error instanceof Error ? error.message : "Update check failed.",
292 }),
293 );
294 })
295 .finally(() => setIsActionPending(false));
296 }, [action, disabled, isActionPending, prefersReducedMotion, state]);
297​
298 const handleCheckAnimationIteration = useCallback(() => {
299 setIsCheckAnimationLatched(
300 shouldContinueDesktopUpdateCheckAnimation({
301 isChecking: state?.status === "checking",
302 prefersReducedMotion,
303 }),
304 );
305 }, [prefersReducedMotion, state?.status]);
306​
307 return (
308 <SidebarMenuItem className="ml-auto shrink-0">
309 <Tooltip>
310 <TooltipTrigger
311 render={
312 <button
313 type="button"
314 aria-label={tooltip}
315 aria-disabled={disabled || isActionPending || undefined}
316 disabled={disabled || isActionPending}
317 className={cn(
318 "inline-flex size-8 items-center justify-center rounded-full outline-hidden ring-ring transition-colors enabled:cursor-pointer focus-visible:ring-2 disabled:cursor-not-allowed",
319 showUpdateIconState
320 ? "bg-update-surface text-update-foreground enabled:hover:bg-update/12"
321 : "text-[var(--sidebar-icon-color)] enabled:hover:bg-sidebar-row-hover enabled:hover:text-sidebar-foreground",
322 disabled && !showUpdateIconState && "opacity-60",
323 )}
324 onClick={handleAction}
325 >
326 <DesktopUpdateStatusIcon
327 key={showCheckIcon ? checkAnimationKey : iconStatus}
328 downloadPercent={state?.downloadPercent ?? null}
329 isCheckAnimating={showCheckIcon && !prefersReducedMotion}
330 onCheckAnimationIteration={handleCheckAnimationIteration}
331 status={iconStatus}
332 />
333 </button>
334 }
335 />
336 <TooltipPopup
337 align="center"
338 className={
339 showUpdateDetails && state?.channel === "nightly" && state.releaseNotes.length > 0
340 ? // pointer-events-auto overrides the positioner's pointer-events-none so the
341 // release notes stay open (and scrollable) when the cursor moves into them.
342 "pointer-events-auto max-w-none text-balance"
343 : undefined
344 }
345 side="top"
346 style={
347 showUpdateDetails
348 ? {
349 background:
350 "color-mix(in srgb, var(--update) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
351 borderColor: "var(--update-foreground)",
352 }
353 : undefined
354 }
355 variant={showUpdateDetails ? "glass" : "default"}
356 >
357 {showUpdateDetails && state ? (
358 <SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
359 ) : (
360 tooltip
361 )}
362 </TooltipPopup>
363 </Tooltip>
364 </SidebarMenuItem>
365 );