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

SidebarUpdatePill.tsx

297 lines10.2 KB

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