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

SidebarUpdatePill.tsx

420 lines14.0 KB

1import type { DesktopUpdateState } from "@t3tools/contracts";
2import { TriangleAlertIcon } from "lucide-react";
3import { type ComponentProps, useCallback, useEffect, useId, useRef, useState } from "react";
4import { flushSync } from "react-dom";
5import { isElectron } from "../../env";
6import { useMediaQuery } from "../../hooks/useMediaQuery";
7import { cn } from "../../lib/utils";
8import { ensureLocalApi } from "../../localApi";
9import { useDesktopUpdateState } from "../../state/desktopUpdate";
10import { stackedThreadToast, toastManager } from "../ui/toast";
11import {
12 canCheckForUpdate,
13 getArm64IntelBuildWarningDescription,
14 getDesktopUpdateActionError,
15 getDesktopUpdateButtonTooltip,
16 getDesktopUpdateInstallConfirmationMessage,
17 isDesktopUpdateButtonDisabled,
18 resolveDesktopUpdateButtonAction,
19 shouldShowArm64IntelBuildWarning,
20 shouldToastDesktopUpdateActionResult,
21} from "../desktopUpdate.logic";
22import { showDesktopUpdateDownloadedToast } from "../desktopUpdate.toast";
23import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
24import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover";
25import { SidebarMenuItem } from "../ui/sidebar";
26import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27import {
28 DesktopUpdateStatusIcon,
29 shouldContinueDesktopUpdateCheckAnimation,
30 shouldShowDesktopUpdateCheckIcon,
31} from "./DesktopUpdateStatusIcon";
32import { SidebarUpdateReleaseNotes } from "./SidebarUpdateReleaseNotes";
33​
34type SidebarUpdatePopoverChangeDetails = Parameters<
35 NonNullable<ComponentProps<typeof Popover>["onOpenChange"]>
36>[1];
37type SidebarUpdatePopoverHandle = ReturnType<typeof PopoverCreateHandle>;
38​
39export function shouldUseSidebarUpdateReleaseNotesPopover(
40 showUpdateDetails: boolean,
41 state: DesktopUpdateState | null,
42): boolean {
43 return showUpdateDetails && state?.channel === "nightly" && state.releaseNotes.length > 0;
45​
46export function handleSidebarUpdateReleaseNotesPopoverOpenChange(
47 _open: boolean,
48 details: Pick<SidebarUpdatePopoverChangeDetails, "reason" | "cancel">,
49): void {
50 // The trigger is the update action, so its presses must not also toggle the Popover.
51 if (details.reason === "trigger-press") details.cancel();
53​
54export function openSidebarUpdateReleaseNotesPopoverOnForwardTab(
55 event: { readonly key: string; readonly shiftKey: boolean },
56 handle: Pick<SidebarUpdatePopoverHandle, "open">,
57 triggerId: string,
58): void {
59 if (event.key !== "Tab" || event.shiftKey) return;
60 // Hover-open popovers do not manage focus. Promote this one before native Tab runs.
61 flushSync(() => handle.open(triggerId));
63​
64function resolveSidebarUpdatePresentation({
65 action,
66 isDownloading,
67 showCheckIcon,
68}: {
69 readonly action: ReturnType<typeof resolveDesktopUpdateButtonAction>;
70 readonly isDownloading: boolean;
71 readonly showCheckIcon: boolean;
72}) {
73 const showUpdateDetails = action !== "none" || isDownloading;
74 const iconStatus = showCheckIcon
75 ? "checking"
76 : action === "install"
77 ? "downloaded"
78 : isDownloading
79 ? "downloading"
80 : action === "download"
81 ? "available"
82 : "idle";
83​
84 return {
85 iconStatus,
86 showUpdateDetails,
87 showUpdateIconState: showUpdateDetails && !showCheckIcon,
88 } as const;
90​
91export function SidebarUpdateArchitectureWarning() {
92 return isElectron ? <SidebarUpdateArchitectureWarningContent /> : null;
94​
95function SidebarUpdateArchitectureWarningContent() {
96 const state = useDesktopUpdateState();
97 const visible = shouldShowArm64IntelBuildWarning(state);
98 const description = state && visible ? getArm64IntelBuildWarningDescription(state) : null;
99​
100 if (!visible || !description) return null;
101​
102 return (
103 <Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
104 <TriangleAlertIcon />
105 <AlertTitle>Intel build on Apple Silicon</AlertTitle>
106 <AlertDescription>{description}</AlertDescription>
107 </Alert>
108 );
110​
111export function SidebarUpdatePill() {
112 return isElectron ? <SidebarUpdateControl /> : null;
114​
115function SidebarUpdateControl() {
116 const state = useDesktopUpdateState();
117 const [isActionPending, setIsActionPending] = useState(false);
118 const [checkAnimationKey, setCheckAnimationKey] = useState(0);
119 const [isCheckAnimationLatched, setIsCheckAnimationLatched] = useState(false);
120 const [releaseNotesPopoverHandle] = useState(() => PopoverCreateHandle());
121 const suppressReleaseNotesFocusOpen = useRef(false);
122 const releaseNotesPopupRef = useRef<HTMLDivElement>(null);
123 const releaseNotesTriggerId = useId();
124 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
125​
126 useEffect(() => {
127 if (prefersReducedMotion) {
128 setIsCheckAnimationLatched(false);
129 } else if (state?.status === "checking") {
130 setIsCheckAnimationLatched(true);
131 }
132 }, [prefersReducedMotion, state?.status]);
133​
134 const action = state ? resolveDesktopUpdateButtonAction(state) : "none";
135 const isDownloading = state?.status === "downloading";
136 const showCheckIcon = shouldShowDesktopUpdateCheckIcon({
137 isAnimationLatched: isCheckAnimationLatched,
138 isChecking: state?.status === "checking",
139 prefersReducedMotion,
140 });
141 const { iconStatus, showUpdateDetails, showUpdateIconState } = resolveSidebarUpdatePresentation({
142 action,
143 isDownloading,
144 showCheckIcon,
145 });
146 const tooltip = showUpdateDetails
147 ? state
148 ? getDesktopUpdateButtonTooltip(state)
149 : "Update available"
150 : showCheckIcon
151 ? "Checking for updates…"
152 : "Check for updates";
153 const disabled = showCheckIcon
154 ? true
155 : showUpdateDetails
156 ? isDesktopUpdateButtonDisabled(state)
157 : !canCheckForUpdate(state);
158 const isInteractionDisabled = disabled || isActionPending;
159 const showReleaseNotesPopover = shouldUseSidebarUpdateReleaseNotesPopover(
160 showUpdateDetails,
161 state,
162 );
163​
164 useEffect(() => {
165 if (!showReleaseNotesPopover) {
166 releaseNotesPopoverHandle.close();
167 return;
168 }
169​
170 const trigger = document.getElementById(releaseNotesTriggerId);
171 if (trigger?.matches(":focus-visible")) {
172 releaseNotesPopoverHandle.open(releaseNotesTriggerId);
173 }
174 }, [releaseNotesPopoverHandle, releaseNotesTriggerId, showReleaseNotesPopover]);
175​
176 const handleAction = useCallback(async () => {
177 const bridge = window.desktopBridge;
178 if (!bridge || !state) return;
179 if (isInteractionDisabled) return;
180​
181 setIsActionPending(true);
182​
183 if (action === "download") {
184 void bridge
185 .downloadUpdate()
186 .then((result) => {
187 if (result.completed) {
188 showDesktopUpdateDownloadedToast(bridge, result.state);
189 }
190 if (!shouldToastDesktopUpdateActionResult(result)) return;
191 const actionError = getDesktopUpdateActionError(result);
192 if (!actionError) return;
193 toastManager.add(
194 stackedThreadToast({
195 type: "error",
196 title: "Could not download update",
197 description: actionError,
198 }),
199 );
200 })
201 .catch((error) => {
202 toastManager.add(
203 stackedThreadToast({
204 type: "error",
205 title: "Could not start update download",
206 description: error instanceof Error ? error.message : "An unexpected error occurred.",
207 }),
208 );
209 })
210 .finally(() => setIsActionPending(false));
211 return;
212 }
213​
214 if (action === "install") {
215 let confirmed = false;
216 try {
217 confirmed = await ensureLocalApi().dialogs.confirm(
218 getDesktopUpdateInstallConfirmationMessage(state),
219 );
220 } catch (error) {
221 setIsActionPending(false);
222 toastManager.add(
223 stackedThreadToast({
224 type: "error",
225 title: "Could not confirm update",
226 description: error instanceof Error ? error.message : "Update confirmation failed.",
227 }),
228 );
229 return;
230 }
231 if (!confirmed) {
232 setIsActionPending(false);
233 return;
234 }
235 void bridge
236 .installUpdate()
237 .then((result) => {
238 if (!shouldToastDesktopUpdateActionResult(result)) return;
239 const actionError = getDesktopUpdateActionError(result);
240 if (!actionError) return;
241 toastManager.add(
242 stackedThreadToast({
243 type: "error",
244 title: "Could not install update",
245 description: actionError,
246 }),
247 );
248 })
249 .catch((error) => {
250 toastManager.add(
251 stackedThreadToast({
252 type: "error",
253 title: "Could not install update",
254 description: error instanceof Error ? error.message : "An unexpected error occurred.",
255 }),
256 );
257 })
258 .finally(() => setIsActionPending(false));
259 return;
260 }
261​
262 if (!prefersReducedMotion) {
263 setIsCheckAnimationLatched(true);
264 setCheckAnimationKey((key) => key + 1);
265 }
266 void bridge
267 .checkForUpdate()
268 .then((result) => {
269 if (result.checked) return;
270 toastManager.add(
271 stackedThreadToast({
272 type: "error",
273 title: "Could not check for updates",
274 description:
275 result.state.message ?? "Automatic updates are not available in this build.",
276 }),
277 );
278 })
279 .catch((error) => {
280 toastManager.add(
281 stackedThreadToast({
282 type: "error",
283 title: "Could not check for updates",
284 description: error instanceof Error ? error.message : "Update check failed.",
285 }),
286 );
287 })
288 .finally(() => setIsActionPending(false));
289 }, [action, isInteractionDisabled, prefersReducedMotion, state]);
290​
291 const handleCheckAnimationIteration = useCallback(() => {
292 setIsCheckAnimationLatched(
293 shouldContinueDesktopUpdateCheckAnimation({
294 isChecking: state?.status === "checking",
295 prefersReducedMotion,
296 }),
297 );
298 }, [prefersReducedMotion, state?.status]);
299​
300 const updateButton = (
301 <button
302 type="button"
303 aria-label={tooltip}
304 aria-disabled={isInteractionDisabled || undefined}
305 className={cn(
306 "inline-flex size-8 items-center justify-center rounded-full outline-hidden ring-ring transition-colors focus-visible:ring-2",
307 isInteractionDisabled ? "cursor-not-allowed" : "cursor-pointer",
308 showUpdateIconState
309 ? cn(
310 "bg-sidebar-control-surface text-sidebar-foreground",
311 !isInteractionDisabled && "hover:bg-sidebar-row-hover",
312 )
313 : cn(
314 "text-[var(--sidebar-icon-color)]",
315 !isInteractionDisabled && "hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
316 ),
317 disabled && !showUpdateIconState && "opacity-60",
318 )}
319 onClick={handleAction}
320 onBlur={() => {
321 suppressReleaseNotesFocusOpen.current = false;
322 }}
323 onFocus={(event) => {
324 if (!showReleaseNotesPopover || !event.currentTarget.matches(":focus-visible")) return;
325 if (suppressReleaseNotesFocusOpen.current) {
326 suppressReleaseNotesFocusOpen.current = false;
327 return;
328 }
329 flushSync(() => releaseNotesPopoverHandle.open(releaseNotesTriggerId));
330 }}
331 onKeyDown={(event) => {
332 if (!showReleaseNotesPopover) return;
333 openSidebarUpdateReleaseNotesPopoverOnForwardTab(
334 event,
335 releaseNotesPopoverHandle,
336 releaseNotesTriggerId,
337 );
338 }}
339 >
340 <DesktopUpdateStatusIcon
341 key={showCheckIcon ? checkAnimationKey : iconStatus}
342 downloadPercent={state?.downloadPercent ?? null}
343 isCheckAnimating={showCheckIcon && !prefersReducedMotion}
344 onCheckAnimationIteration={handleCheckAnimationIteration}
345 status={iconStatus}
346 />
347 </button>
348 );
349​
350 return (
351 <SidebarMenuItem className="ml-auto shrink-0">
352 <Popover
353 handle={releaseNotesPopoverHandle}
354 onOpenChange={(open, details) => {
355 if (open && !showReleaseNotesPopover) {
356 details.cancel();
357 return;
358 }
359 handleSidebarUpdateReleaseNotesPopoverOpenChange(open, details);
360 }}
361 >
362 <Tooltip disabled={showReleaseNotesPopover}>
363 <TooltipTrigger
364 id={releaseNotesTriggerId}
365 render={
366 <PopoverTrigger
367 {...(!showReleaseNotesPopover
368 ? {
369 "aria-controls": undefined,
370 "aria-expanded": undefined,
371 "aria-haspopup": undefined,
372 }
373 : {})}
374 closeDelay={150}
375 handle={releaseNotesPopoverHandle}
376 id={releaseNotesTriggerId}
377 openOnHover={showReleaseNotesPopover}
378 render={updateButton}
379 />
380 }
381 />
382 {!showReleaseNotesPopover ? (
383 <TooltipPopup
384 align="center"
385 side="top"
386 variant={showUpdateDetails ? "glass" : "default"}
387 >
388 {tooltip}
389 </TooltipPopup>
390 ) : null}
391 </Tooltip>
392 {showReleaseNotesPopover && state ? (
393 <PopoverPopup
394 align="center"
395 aria-label="Nightly update release notes"
396 className="max-w-none text-balance shadow-xl shadow-black/25"
397 initialFocus={false}
398 onKeyDownCapture={(event) => {
399 if (
400 event.key === "Escape" &&
401 releaseNotesPopupRef.current?.contains(document.activeElement)
402 ) {
403 suppressReleaseNotesFocusOpen.current = true;
404 }
405 }}
406 ref={releaseNotesPopupRef}
407 side="top"
408 tooltipStyle
409 >
410 <SidebarUpdateReleaseNotes
411 shell={window.desktopBridge}
412 state={state}
413 tooltip={tooltip}
414 />
415 </PopoverPopup>
416 ) : null}
417 </Popover>
418 </SidebarMenuItem>
419 );