Open History to see the last commit
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 }
26}
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 // The menu exists before the updater is configured; a click then waits for it.
95 yield* updates.whenConfigured;
96 const disabledReason = yield* updates.disabledReason;
97 if (Option.isSome(disabledReason)) {
98 yield* logUpdaterInfo("manual update check requested, but updates are disabled", {
99 disabledReason: disabledReason.value,
100 });
101 yield* electronDialog.showMessageBox({
102 type: "info",
103 title: "Updates unavailable",
104 message: "Automatic updates are not available right now.",
105 detail: disabledReason.value,
106 buttons: ["OK"],
107 });
108 return;
109 }
110
111 // The result dialogs need no main window. Opening one before the backend
112 // answers strands the renderer on a failed auth bootstrap.
113 const desktopWindow = yield* DesktopWindow.DesktopWindow;
114 yield* desktopWindow.activate;
115 yield* checkForUpdatesFromMenu;
116}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
117
118/** @public Service construction is part of the canonical Effect module API. */
119export const make = Effect.gen(function* () {
120 const electronMenu = yield* ElectronMenu.ElectronMenu;
121 const environment = yield* DesktopEnvironment.DesktopEnvironment;
122 const context = yield* Effect.context<DesktopApplicationMenuRuntimeServices>();
123 const runPromise = Effect.runPromiseWith(context);
124
125 const runMenuEffect = <E>(
126 action: string,
127 effect: Effect.Effect<void, E, DesktopApplicationMenuRuntimeServices>,
128 ) => {
129 void runPromise(
130 effect.pipe(
131 Effect.annotateLogs({ action }),
132 Effect.withSpan("desktop.menu.action"),
133 Effect.catchCause((cause) => {
134 const error = new DesktopApplicationMenuActionError({ action, cause });
135 return logMenuError(error.message, { error });
136 }),
137 ),
138 );
139 };
140
141 const configure = Effect.gen(function* () {
142 const checkForUpdatesClick = () => {
143 runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick);
144 };
145 const settingsClick = () => {
146 runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
147 };
148 // Chromium already pastes as plain text for this chord, so the accelerator
149 // needs nothing from the menu: the composer and the terminal each arm
150 // themselves from the same keydown. Routing it through the renderer anyway
151 // lands a second, injected paste and doubles the text.
152 const pasteAsTextClick = (
153 _item: Electron.MenuItem,
154 _window: Electron.BaseWindow | undefined,
155 event: Electron.KeyboardEvent,
156 ) => {
157 if (event.triggeredByAccelerator === true) return;
158 runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text"));
159 };
160 const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
161 runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
162 };
163 const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => {
164 runMenuEffect(command, runMainContentsCommand(command));
165 };
166 const template: Electron.MenuItemConstructorOptions[] = [];
167
168 if (environment.platform === "darwin") {
169 template.push({
170 label: environment.displayName,
171 submenu: [
172 { role: "about", label: `About ${environment.displayName}` },
173 {
174 label: "Check for Updates...",
175 click: checkForUpdatesClick,
176 },
177 { type: "separator" },
178 {
179 label: "Settings...",
180 accelerator: "CmdOrCtrl+,",
181 click: settingsClick,
182 },
183 { type: "separator" },
184 { role: "services" },
185 { type: "separator" },
186 { role: "hide", label: `Hide ${environment.displayName}` },
187 { role: "hideOthers" },
188 { role: "unhide" },
189 { type: "separator" },
190 { role: "quit", label: `Quit ${environment.displayName}` },
191 ],
192 });
193 }
194
195 template.push(
196 {
197 label: "File",
198 submenu: [
199 ...(environment.platform === "darwin"
200 ? []
201 : [
202 {
203 label: "Settings...",
204 accelerator: "CmdOrCtrl+,",
205 click: settingsClick,
206 },
207 { type: "separator" as const },
208 ]),
209 { role: environment.platform === "darwin" ? "close" : "quit" },
210 ],
211 },
212 {
213 label: "Edit",
214 submenu: [
215 { role: "undo" },
216 { role: "redo" },
217 { type: "separator" },
218 { role: "cut" },
219 { role: "copy" },
220 { role: "paste" },
221 {
222 label: "Paste as Text",
223 accelerator: "CmdOrCtrl+Shift+V",
224 click: pasteAsTextClick,
225 },
226 { role: "delete" },
227 { type: "separator" },
228 { role: "selectAll" },
229 ...(environment.platform === "darwin"
230 ? [
231 { type: "separator" as const },
232 {
233 label: "Speech",
234 submenu: [{ role: "startSpeaking" as const }, { role: "stopSpeaking" as const }],
235 },
236 ]
237 : []),
238 ],
239 },
240 {
241 label: "View",
242 submenu: [
243 /*
244 Not the reload, DevTools or zoom roles: those act on the focused
245 webContents, so with a browser page focused they reload or zoom
246 the guest page and the app UI appears stuck.
247 */
248 { label: "Reload", accelerator: "CmdOrCtrl+R", click: mainContentsClick("reload") },
249 {
250 label: "Force Reload",
251 accelerator: "Shift+CmdOrCtrl+R",
252 click: mainContentsClick("forceReload"),
253 },
254 {
255 label: "Toggle Developer Tools",
256 accelerator: environment.platform === "darwin" ? "Alt+Command+I" : "Ctrl+Shift+I",
257 click: mainContentsClick("toggleDevTools"),
258 },
259 { type: "separator" },
260 { label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
261 { label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
262 {
263 label: "Zoom In",
264 accelerator: "CmdOrCtrl+Plus",
265 visible: false,
266 click: zoomClick("in"),
267 },
268 { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
269 // The numeric keypad sends its own key codes, so the number-row
270 // accelerators above never match it.
271 {
272 label: "Actual Size",
273 accelerator: "CmdOrCtrl+num0",
274 visible: false,
275 click: zoomClick("reset"),
276 },
277 {
278 label: "Zoom In",
279 accelerator: "CmdOrCtrl+numadd",
280 visible: false,
281 click: zoomClick("in"),
282 },
283 {
284 label: "Zoom Out",
285 accelerator: "CmdOrCtrl+numsub",
286 visible: false,
287 click: zoomClick("out"),
288 },
289 { type: "separator" },
290 { role: "togglefullscreen" },
291 ],
292 },
293 { role: "windowMenu" },
294 {
295 role: "help",
296 submenu: [
297 {
298 label: "Check for Updates...",
299 click: checkForUpdatesClick,
300 },
301 ],
302 },
303 );
304
305 yield* electronMenu.setApplicationMenu(template);
306 }).pipe(Effect.withSpan("desktop.menu.configure"));
307
308 return DesktopApplicationMenu.of({
309 configure,
310 });
311});
312
313export const layer = Layer.effect(DesktopApplicationMenu, make);