The best way to control Claude Code, Codex and more from any computer or phone

main
ts 290 lines 9.34 KB
Raw
1 import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts";
2 import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8
9 import * as Electron from "electron";
10
11 export interface ElectronMenuPosition {
12 readonly x: number;
13 readonly y: number;
14 }
15
16 export interface ElectronMenuContextInput {
17 readonly window: Electron.BrowserWindow;
18 readonly items: readonly ContextMenuItem[];
19 readonly position: Option.Option<ElectronMenuPosition>;
20 readonly source: Option.Option<ContextMenuSource>;
21 }
22
23 export interface ElectronMenuTemplateInput {
24 readonly window: Electron.BrowserWindow;
25 readonly template: readonly Electron.MenuItemConstructorOptions[];
26 readonly frame?: Electron.WebFrameMain;
27 }
28
29 const ElectronMenuOperation = Schema.Literals([
30 "set-application-menu",
31 "popup-template",
32 "show-context-menu",
33 ]);
34
35 export class ElectronMenuOperationError extends Schema.TaggedError<ElectronMenuOperationError>()(
36 "ElectronMenuOperationError",
37 {
38 operation: ElectronMenuOperation,
39 platform: Schema.String,
40 windowId: Schema.NullOr(Schema.Number),
41 itemCount: Schema.Number,
42 cause: Schema.Defect(),
43 },
44 ) {
45 override get message(): string {
46 const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
47 return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
48 }
49 }
50
51 export class ElectronMenu extends Context.Service<
52 ElectronMenu,
53 {
54 readonly setApplicationMenu: (
55 template: readonly Electron.MenuItemConstructorOptions[],
56 ) => Effect.Effect<void>;
57 readonly showContextMenu: (
58 input: ElectronMenuContextInput,
59 ) => Effect.Effect<Option.Option<string>>;
60 readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
61 }
62 >()("@t3tools/desktop/electron/ElectronMenu") {}
63
64 function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
65 const normalizedItems: ContextMenuItem[] = [];
66
67 for (const sourceItem of source) {
68 if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
69 continue;
70 }
71
72 // Native menus cannot display the web fallback's decorative headers.
73 if (sourceItem.header === true) {
74 continue;
75 }
76
77 const normalizedItem: ContextMenuItem = {
78 id: sourceItem.id,
79 label:
80 typeof sourceItem.detail === "string" && sourceItem.detail.length > 0
81 ? `${sourceItem.label} (${sourceItem.detail})`
82 : sourceItem.label,
83 destructive: sourceItem.destructive === true,
84 disabled: sourceItem.disabled === true,
85 ...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}),
86 ...(typeof sourceItem.checked === "boolean" ? { checked: sourceItem.checked } : {}),
87 };
88
89 if (sourceItem.children) {
90 const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
91 if (normalizedChildren.length === 0) {
92 continue;
93 }
94 normalizedItem.children = normalizedChildren;
95 }
96
97 normalizedItems.push(normalizedItem);
98 }
99
100 return normalizedItems;
101 }
102
103 // popup() takes window points; renderer CSS coordinates must account for page zoom.
104 const normalizePosition = (
105 position: Option.Option<ElectronMenuPosition>,
106 zoomFactor: number,
107 ): Option.Option<ElectronMenuPosition> =>
108 Option.filter(
109 position,
110 ({ x, y }) =>
111 Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
112 ).pipe(
113 Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
114 );
115
116 /** @public */
117 export const make = Effect.gen(function* () {
118 const platform = yield* HostProcess.Platform;
119 let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
120
121 const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
122 if (platform !== "darwin") {
123 return Option.none();
124 }
125 if (destructiveMenuIconCache !== undefined) {
126 return destructiveMenuIconCache;
127 }
128
129 try {
130 const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
131 width: 12,
132 height: 12,
133 });
134 icon.setTemplateImage(true);
135 destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
136 } catch {
137 destructiveMenuIconCache = Option.none();
138 }
139
140 return destructiveMenuIconCache;
141 };
142
143 const buildTemplate = (
144 entries: readonly ContextMenuItem[],
145 complete: (selectedItemId: Option.Option<string>) => void,
146 ): Electron.MenuItemConstructorOptions[] => {
147 const template: Electron.MenuItemConstructorOptions[] = [];
148 let hasInsertedDestructiveSeparator = false;
149 let sectionStartedByExplicitSeparator = false;
150 const appendSeparator = () => {
151 if (template.length === 0 || template.at(-1)?.type === "separator") return;
152 template.push({ type: "separator" });
153 };
154
155 for (const item of entries) {
156 if (item.separatorBefore) {
157 appendSeparator();
158 sectionStartedByExplicitSeparator = true;
159 }
160 if (
161 item.destructive &&
162 !hasInsertedDestructiveSeparator &&
163 !sectionStartedByExplicitSeparator &&
164 template.length > 0
165 ) {
166 appendSeparator();
167 hasInsertedDestructiveSeparator = true;
168 }
169
170 const itemOption: Electron.MenuItemConstructorOptions = {
171 label: item.label,
172 enabled: !item.disabled,
173 ...(typeof item.checked === "boolean" ? { type: "checkbox", checked: item.checked } : {}),
174 };
175 if (item.children && item.children.length > 0) {
176 itemOption.submenu = buildTemplate(item.children, complete);
177 } else {
178 itemOption.click = () => complete(Option.some(item.id));
179 }
180 if (item.destructive && (!item.children || item.children.length === 0)) {
181 const destructiveIcon = getDestructiveMenuIcon();
182 if (Option.isSome(destructiveIcon)) {
183 itemOption.icon = destructiveIcon.value;
184 }
185 }
186
187 template.push(itemOption);
188 }
189
190 return template;
191 };
192
193 return ElectronMenu.of({
194 setApplicationMenu: Effect.fn("ElectronMenu.setApplicationMenu")(function (template) {
195 return Effect.try({
196 try: () => {
197 Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
198 },
199 catch: (cause) =>
200 new ElectronMenuOperationError({
201 operation: "set-application-menu",
202 platform,
203 windowId: null,
204 itemCount: template.length,
205 cause,
206 }),
207 }).pipe(Effect.orDie);
208 }),
209 popupTemplate: Effect.fn("ElectronMenu.popupTemplate")(function (input) {
210 return input.template.length === 0
211 ? Effect.void
212 : Effect.try({
213 try: () =>
214 Electron.Menu.buildFromTemplate([...input.template]).popup({
215 window: input.window,
216 ...(input.frame ? { frame: input.frame } : {}),
217 }),
218 catch: (cause) =>
219 new ElectronMenuOperationError({
220 operation: "popup-template",
221 platform,
222 windowId: input.window.id,
223 itemCount: input.template.length,
224 cause,
225 }),
226 }).pipe(Effect.orDie);
227 }),
228 showContextMenu: Effect.fn("ElectronMenu.showContextMenu")(function (input) {
229 return Effect.callback<Option.Option<string>>((resume) => {
230 const normalizedItems = normalizeContextMenuItems(input.items);
231 if (normalizedItems.length === 0) {
232 resume(Effect.succeedNone);
233 return;
234 }
235
236 let completed = false;
237 const complete = (selectedItemId: Option.Option<string>) => {
238 if (completed) {
239 return;
240 }
241 completed = true;
242 resume(Effect.succeed(selectedItemId));
243 };
244
245 try {
246 const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
247 const popupPosition = normalizePosition(
248 input.position,
249 input.window.webContents.getZoomFactor(),
250 );
251 const popupOptions = Option.match(popupPosition, {
252 onNone: (): Electron.PopupOptions => ({
253 window: input.window,
254 callback: () => complete(Option.none()),
255 }),
256 onSome: (position): Electron.PopupOptions => ({
257 window: input.window,
258 x: position.x,
259 y: position.y,
260 callback: () => complete(Option.none()),
261 }),
262 });
263 menu.popup(
264 Option.isSome(input.source)
265 ? { ...popupOptions, sourceType: input.source.value }
266 : popupOptions,
267 );
268 } catch (cause) {
269 if (completed) {
270 return;
271 }
272 completed = true;
273 resume(
274 Effect.die(
275 new ElectronMenuOperationError({
276 operation: "show-context-menu",
277 platform,
278 windowId: input.window.id,
279 itemCount: normalizedItems.length,
280 cause,
281 }),
282 ),
283 );
284 }
285 });
286 }),
287 });
288 });
289
290 export const layer = Layer.effect(ElectronMenu, make);