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 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 const desktopWindow = yield* DesktopWindow.DesktopWindow;
110 yield* desktopWindow.ensureMain;
111 yield* checkForUpdatesFromMenu;
112}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
113
114/** @public Service construction is part of the canonical Effect module API. */
115export const make = Effect.gen(function* () {
116 const electronMenu = yield* ElectronMenu.ElectronMenu;
117 const environment = yield* DesktopEnvironment.DesktopEnvironment;
118 const context = yield* Effect.context<DesktopApplicationMenuRuntimeServices>();
119 const runPromise = Effect.runPromiseWith(context);
120
121 const runMenuEffect = <E>(
122 action: string,
123 effect: Effect.Effect<void, E, DesktopApplicationMenuRuntimeServices>,
124 ) => {
125 void runPromise(
126 effect.pipe(
127 Effect.annotateLogs({ action }),
128 Effect.withSpan("desktop.menu.action"),
129 Effect.catchCause((cause) => {
130 const error = new DesktopApplicationMenuActionError({ action, cause });
131 return logMenuError(error.message, { error });
132 }),
133 ),
134 );
135 };
136
137 const configure = Effect.gen(function* () {
138 const checkForUpdatesClick = () => {
139 runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick);
140 };
141 const settingsClick = () => {
142 runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
143 };
144 // Chromium already pastes as plain text for this chord, so the accelerator
145 // needs nothing from the menu: the composer and the terminal each arm
146 // themselves from the same keydown. Routing it through the renderer anyway
147 // lands a second, injected paste and doubles the text.
148 const pasteAsTextClick = (
149 _item: Electron.MenuItem,
150 _window: Electron.BaseWindow | undefined,
151 event: Electron.KeyboardEvent,
152 ) => {
153 if (event.triggeredByAccelerator === true) return;
154 runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text"));
155 };
156 const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
157 runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
158 };
159 const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => {
160 runMenuEffect(command, runMainContentsCommand(command));
161 };
162 const template: Electron.MenuItemConstructorOptions[] = [];
163
164 if (environment.platform === "darwin") {
165 template.push({
166 label: environment.displayName,
167 submenu: [
168 { role: "about", label: `About ${environment.displayName}` },
169 {
170 label: "Check for Updates...",
171 click: checkForUpdatesClick,
172 },
173 { type: "separator" },
174 {
175 label: "Settings...",
176 accelerator: "CmdOrCtrl+,",
177 click: settingsClick,
178 },
179 { type: "separator" },
180 { role: "services" },
181 { type: "separator" },
182 { role: "hide", label: `Hide ${environment.displayName}` },
183 { role: "hideOthers" },
184 { role: "unhide" },
185 { type: "separator" },
186 { role: "quit", label: `Quit ${environment.displayName}` },
187 ],
188 });
189 }
190
191 template.push(
192 {
193 label: "File",
194 submenu: [
195 ...(environment.platform === "darwin"
196 ? []
197 : [
198 {
199 label: "Settings...",
200 accelerator: "CmdOrCtrl+,",
201 click: settingsClick,
202 },
203 { type: "separator" as const },
204 ]),
205 { role: environment.platform === "darwin" ? "close" : "quit" },
206 ],
207 },
208 {
209 label: "Edit",
210 submenu: [
211 { role: "undo" },
212 { role: "redo" },
213 { type: "separator" },
214 { role: "cut" },
215 { role: "copy" },
216 { role: "paste" },
217 {
218 label: "Paste as Text",
219 accelerator: "CmdOrCtrl+Shift+V",
220 click: pasteAsTextClick,
221 },
222 { role: "delete" },
223 { type: "separator" },
224 { role: "selectAll" },
225 ...(environment.platform === "darwin"
226 ? [
227 { type: "separator" as const },
228 {
229 label: "Speech",
230 submenu: [{ role: "startSpeaking" as const }, { role: "stopSpeaking" as const }],
231 },
232 ]
233 : []),
234 ],
235 },
236 {
237 label: "View",
238 submenu: [
239 /*
240 Not the reload, DevTools or zoom roles: those act on the focused
241 webContents, so with a browser page focused they reload or zoom
242 the guest page and the app UI appears stuck.
243 */
244 { label: "Reload", accelerator: "CmdOrCtrl+R", click: mainContentsClick("reload") },
245 {
246 label: "Force Reload",
247 accelerator: "Shift+CmdOrCtrl+R",
248 click: mainContentsClick("forceReload"),
249 },
250 {
251 label: "Toggle Developer Tools",
252 accelerator: environment.platform === "darwin" ? "Alt+Command+I" : "Ctrl+Shift+I",
253 click: mainContentsClick("toggleDevTools"),
254 },
255 { type: "separator" },
256 { label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
257 { label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
258 {
259 label: "Zoom In",
260 accelerator: "CmdOrCtrl+Plus",
261 visible: false,
262 click: zoomClick("in"),
263 },
264 { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
265 { type: "separator" },
266 { role: "togglefullscreen" },
267 ],
268 },
269 { role: "windowMenu" },
270 {
271 role: "help",
272 submenu: [
273 {
274 label: "Check for Updates...",
275 click: checkForUpdatesClick,
276 },
277 ],
278 },
279 );
280
281 yield* electronMenu.setApplicationMenu(template);
282 }).pipe(Effect.withSpan("desktop.menu.configure"));
283
284 return DesktopApplicationMenu.of({
285 configure,
286 });
287});
288
289export const layer = Layer.effect(DesktopApplicationMenu, make);