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

DesktopApplicationMenu.ts

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