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