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

DesktopApplicationMenu.ts

321 lines11.0 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6​
7import type * as Electron from "electron";
8​
9import { makeComponentLogger } from "../app/DesktopObservability.ts";
10import * as ElectronDialog from "../electron/ElectronDialog.ts";
11import * as ElectronMenu from "../electron/ElectronMenu.ts";
12import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
13import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
14import * as DesktopWindow from "./DesktopWindow.ts";
15​
16export class DesktopApplicationMenuActionError extends Schema.TaggedError<DesktopApplicationMenuActionError>()(
17 "DesktopApplicationMenuActionError",
18 {
19 action: Schema.String,
20 cause: Schema.Defect(),
21 },
22) {
23 override get message(): string {
24 return `Desktop menu action "${this.action}" failed.`;
25 }
27​
28export class DesktopApplicationMenu extends Context.Service<
29 DesktopApplicationMenu,
30 {
31 readonly configure: Effect.Effect<void>;
32 }
33>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
34​
35type DesktopApplicationMenuRuntimeServices =
36 | DesktopUpdates.DesktopUpdates
37 | DesktopWindow.DesktopWindow
38 | ElectronDialog.ElectronDialog;
39​
40const { logInfo: logUpdaterInfo } = makeComponentLogger("desktop-updater");
41​
42const { logError: logMenuError } = makeComponentLogger("desktop-menu");
43​
44const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function* (
45 action: string,
46): Effect.fn.Return<void, DesktopWindow.DesktopWindowError, DesktopWindow.DesktopWindow> {
47 const desktopWindow = yield* DesktopWindow.DesktopWindow;
48 yield* desktopWindow.dispatchMenuAction(action, {
49 reveal: action !== "paste-as-text",
50 });
51});
52​
53const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
54 direction: DesktopWindow.MainWindowZoomDirection,
55): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
56 const desktopWindow = yield* DesktopWindow.DesktopWindow;
57 yield* desktopWindow.zoomMain(direction);
58});
59​
60const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(function* (
61 command: DesktopWindow.MainWindowContentsCommand,
62): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
63 const desktopWindow = yield* DesktopWindow.DesktopWindow;
64 yield* desktopWindow.runMainContentsCommand(command);
65});
66​
67const checkForUpdatesFromMenu = Effect.gen(function* () {
68 const updates = yield* DesktopUpdates.DesktopUpdates;
69 const electronDialog = yield* ElectronDialog.ElectronDialog;
70 const result = yield* updates.check("menu");
71 const updateState = result.state;
72​
73 if (updateState.status === "up-to-date") {
74 yield* electronDialog.showMessageBox({
75 type: "info",
76 title: "You're up to date!",
77 message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
78 buttons: ["OK"],
79 });
80 } else if (updateState.status === "error") {
81 yield* electronDialog.showMessageBox({
82 type: "warning",
83 title: "Update check failed",
84 message: "Could not check for updates.",
85 detail: updateState.message ?? "An unknown error occurred. Please try again later.",
86 buttons: ["OK"],
87 });
88 }
89}).pipe(Effect.withSpan("desktop.menu.checkForUpdates"));
90​
91const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
92 const updates = yield* DesktopUpdates.DesktopUpdates;
93 const electronDialog = yield* ElectronDialog.ElectronDialog;
94 const disabledReason = yield* updates.disabledReason;
95 if (Option.isSome(disabledReason)) {
96 yield* logUpdaterInfo("manual update check requested, but updates are disabled", {
97 disabledReason: disabledReason.value,
98 });
99 yield* electronDialog.showMessageBox({
100 type: "info",
101 title: "Updates unavailable",
102 message: "Automatic updates are not available right now.",
103 detail: disabledReason.value,
104 buttons: ["OK"],
105 });
106 return;
107 }
108​
109 // The result dialogs need no main window. Opening one before the backend
110 // answers strands the renderer on a failed auth bootstrap.
111 const desktopWindow = yield* DesktopWindow.DesktopWindow;
112 yield* desktopWindow.activate;
113 yield* checkForUpdatesFromMenu;
114}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
115​
116/** @public Service construction is part of the canonical Effect module API. */
117export const make = Effect.gen(function* () {
118 const electronMenu = yield* ElectronMenu.ElectronMenu;
119 const environment = yield* DesktopEnvironment.DesktopEnvironment;
120 const context = yield* Effect.context<DesktopApplicationMenuRuntimeServices>();
121 const runPromise = Effect.runPromiseWith(context);
122​
123 const runMenuEffect = <E>(
124 action: string,
125 effect: Effect.Effect<void, E, DesktopApplicationMenuRuntimeServices>,
126 ) => {
127 void runPromise(
128 effect.pipe(
129 Effect.annotateLogs({ action }),
130 Effect.withSpan("desktop.menu.action"),
131 Effect.catchCause((cause) => {
132 const error = new DesktopApplicationMenuActionError({ action, cause });
133 return logMenuError(error.message, { error });
134 }),
135 ),
136 );
137 };
138​
139 const configure = Effect.gen(function* () {
140 const checkForUpdatesClick = () => {
141 runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick);
142 };
143 const settingsClick = () => {
144 runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
145 };
146 // Chromium already pastes as plain text for this chord, so the accelerator
147 // needs nothing from the menu: the composer and the terminal each arm
148 // themselves from the same keydown. Routing it through the renderer anyway
149 // lands a second, injected paste and doubles the text.
150 const pasteAsTextClick = (
151 _item: Electron.MenuItem,
152 _window: Electron.BaseWindow | undefined,
153 event: Electron.KeyboardEvent,
154 ) => {
155 if (event.triggeredByAccelerator === true) return;
156 runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text"));
157 };
158 const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
159 runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
160 };
161 const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => {
162 runMenuEffect(command, runMainContentsCommand(command));
163 };
164 const template: Electron.MenuItemConstructorOptions[] = [];
165​
166 if (environment.platform === "darwin") {
167 template.push({
168 label: environment.displayName,
169 submenu: [
170 { role: "about", label: `About ${environment.displayName}` },
171 {
172 label: "Check for Updates...",
173 click: checkForUpdatesClick,
174 },
175 { type: "separator" },
176 {
177 label: "Settings...",
178 accelerator: "CmdOrCtrl+,",
179 click: settingsClick,
180 },
181 { type: "separator" },
182 { role: "services" },
183 { type: "separator" },
184 { role: "hide", label: `Hide ${environment.displayName}` },
185 { role: "hideOthers" },
186 { role: "unhide" },
187 { type: "separator" },
188 { role: "quit", label: `Quit ${environment.displayName}` },
189 ],
190 });
191 }
192​
193 template.push(
194 {
195 label: "File",
196 submenu: [
197 ...(environment.platform === "darwin"
198 ? []
199 : [
200 {
201 label: "Settings...",
202 accelerator: "CmdOrCtrl+,",
203 click: settingsClick,
204 },
205 { type: "separator" as const },
206 ]),
207 { role: environment.platform === "darwin" ? "close" : "quit" },
208 ],
209 },
210 {
211 label: "Edit",
212 submenu: [
213 { role: "undo" },
214 { role: "redo" },
215 { type: "separator" },
216 { role: "cut" },
217 { role: "copy" },
218 { role: "paste" },
219 {
220 label: "Paste as Text",
221 accelerator: "CmdOrCtrl+Shift+V",
222 click: pasteAsTextClick,
223 },
224 { role: "delete" },
225 { type: "separator" },
226 { role: "selectAll" },
227 ...(environment.platform === "darwin"
228 ? [
229 { type: "separator" as const },
230 {
231 label: "Speech",
232 submenu: [{ role: "startSpeaking" as const }, { role: "stopSpeaking" as const }],
233 },
234 ]
235 : []),
236 ],
237 },
238 {
239 label: "View",
240 submenu: [
241 /*
242 Not the reload, DevTools or zoom roles: those act on the focused
243 webContents, so with a browser page focused they reload or zoom
244 the guest page and the app UI appears stuck.
245 */
246 { label: "Reload", accelerator: "CmdOrCtrl+R", click: mainContentsClick("reload") },
247 {
248 label: "Force Reload",
249 accelerator: "Shift+CmdOrCtrl+R",
250 click: mainContentsClick("forceReload"),
251 },
252 {
253 label: "Toggle Developer Tools",
254 accelerator: environment.platform === "darwin" ? "Alt+Command+I" : "Ctrl+Shift+I",
255 click: mainContentsClick("toggleDevTools"),
256 },
257 { type: "separator" },
258 { label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
259 { label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
260 {
261 label: "Zoom In",
262 accelerator: "CmdOrCtrl+Plus",
263 visible: false,
264 click: zoomClick("in"),
265 },
266 ...(environment.platform === "darwin"
267 ? [
268 {
269 label: "Zoom In",
270 accelerator: "CmdOrCtrl+Shift+=",
271 visible: false,
272 click: zoomClick("in"),
273 },
274 ]
275 : []),
276 { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
277 // The numeric keypad sends its own key codes, so the number-row
278 // accelerators above never match it.
279 {
280 label: "Actual Size",
281 accelerator: "CmdOrCtrl+num0",
282 visible: false,
283 click: zoomClick("reset"),
284 },
285 {
286 label: "Zoom In",
287 accelerator: "CmdOrCtrl+numadd",
288 visible: false,
289 click: zoomClick("in"),
290 },
291 {
292 label: "Zoom Out",
293 accelerator: "CmdOrCtrl+numsub",
294 visible: false,
295 click: zoomClick("out"),
296 },
297 { type: "separator" },
298 { role: "togglefullscreen" },
299 ],
300 },
301 { role: "windowMenu" },
302 {
303 role: "help",
304 submenu: [
305 {
306 label: "Check for Updates...",
307 click: checkForUpdatesClick,
308 },
309 ],
310 },
311 );
312​
313 yield* electronMenu.setApplicationMenu(template);
314 }).pipe(Effect.withSpan("desktop.menu.configure"));
315​
316 return DesktopApplicationMenu.of({
317 configure,
318 });
319});
320​
321export const layer = Layer.effect(DesktopApplicationMenu, make);