Open History to see the last commit
1import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8
9import * as Electron from "electron";
10
11export interface ElectronMenuPosition {
12 readonly x: number;
13 readonly y: number;
14}
15
16export 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
23export interface ElectronMenuTemplateInput {
24 readonly window: Electron.BrowserWindow;
25 readonly template: readonly Electron.MenuItemConstructorOptions[];
26 readonly frame?: Electron.WebFrameMain;
27}
28
29const ElectronMenuOperation = Schema.Literals([
30 "set-application-menu",
31 "popup-template",
32 "show-context-menu",
33]);
34
35export 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
51export class ElectronMenu extends Context.Service<
52 ElectronMenu,
53 {
54 readonly setApplicationMenu: (
55 template: readonly Electron.MenuItemConstructorOptions[],
56 ) => Effect.Effect<void>;
57 readonly pasteAndMatchStyle: Effect.Effect<void>;
58 readonly showContextMenu: (
59 input: ElectronMenuContextInput,
60 ) => Effect.Effect<Option.Option<string>>;
61 readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
62 }
63>()("@t3tools/desktop/electron/ElectronMenu") {}
64
65function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
66 const normalizedItems: ContextMenuItem[] = [];
67
68 for (const sourceItem of source) {
69 if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
70 continue;
71 }
72
73 // Native menus cannot display the web fallback's decorative headers.
74 if (sourceItem.header === true) {
75 continue;
76 }
77
78 const normalizedItem: ContextMenuItem = {
79 id: sourceItem.id,
80 label:
81 typeof sourceItem.detail === "string" && sourceItem.detail.length > 0
82 ? `${sourceItem.label} (${sourceItem.detail})`
83 : sourceItem.label,
84 destructive: sourceItem.destructive === true,
85 disabled: sourceItem.disabled === true,
86 ...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}),
87 ...(typeof sourceItem.checked === "boolean" ? { checked: sourceItem.checked } : {}),
88 ...(typeof sourceItem.iconImage === "string" ? { iconImage: sourceItem.iconImage } : {}),
89 };
90
91 if (sourceItem.children) {
92 const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
93 if (normalizedChildren.length === 0) {
94 continue;
95 }
96 normalizedItem.children = normalizedChildren;
97 }
98
99 normalizedItems.push(normalizedItem);
100 }
101
102 return normalizedItems;
103}
104
105// popup() takes window points; renderer CSS coordinates must account for page zoom.
106const normalizePosition = (
107 position: Option.Option<ElectronMenuPosition>,
108 zoomFactor: number,
109): Option.Option<ElectronMenuPosition> =>
110 Option.filter(
111 position,
112 ({ x, y }) =>
113 Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
114 ).pipe(
115 Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
116 );
117
118// Renderer icons are 32px PNGs; a 2x representation keeps them 16pt and sharp on Retina.
119function menuIconImage(dataUrl: string): Option.Option<Electron.NativeImage> {
120 try {
121 const image = Electron.nativeImage.createEmpty();
122 image.addRepresentation({ scaleFactor: 2, dataURL: dataUrl });
123 return image.isEmpty() ? Option.none() : Option.some(image);
124 } catch {
125 return Option.none();
126 }
127}
128
129/** @public */
130export const make = Effect.gen(function* () {
131 const platform = yield* HostProcess.Platform;
132 let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
133
134 const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
135 if (platform !== "darwin") {
136 return Option.none();
137 }
138 if (destructiveMenuIconCache !== undefined) {
139 return destructiveMenuIconCache;
140 }
141
142 try {
143 const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
144 width: 12,
145 height: 12,
146 });
147 icon.setTemplateImage(true);
148 destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
149 } catch {
150 destructiveMenuIconCache = Option.none();
151 }
152
153 return destructiveMenuIconCache;
154 };
155
156 const buildTemplate = (
157 entries: readonly ContextMenuItem[],
158 complete: (selectedItemId: Option.Option<string>) => void,
159 ): Electron.MenuItemConstructorOptions[] => {
160 const template: Electron.MenuItemConstructorOptions[] = [];
161 let hasInsertedDestructiveSeparator = false;
162 let sectionStartedByExplicitSeparator = false;
163 const appendSeparator = () => {
164 if (template.length === 0 || template.at(-1)?.type === "separator") return;
165 template.push({ type: "separator" });
166 };
167
168 for (const item of entries) {
169 if (item.separatorBefore) {
170 appendSeparator();
171 sectionStartedByExplicitSeparator = true;
172 }
173 if (
174 item.destructive &&
175 !hasInsertedDestructiveSeparator &&
176 !sectionStartedByExplicitSeparator &&
177 template.length > 0
178 ) {
179 appendSeparator();
180 hasInsertedDestructiveSeparator = true;
181 }
182
183 const itemOption: Electron.MenuItemConstructorOptions = {
184 // Electron reads a single & as a mnemonic marker and drops it.
185 label: item.label.replaceAll("&", "&&"),
186 enabled: !item.disabled,
187 ...(typeof item.checked === "boolean" ? { type: "checkbox", checked: item.checked } : {}),
188 };
189 if (item.children && item.children.length > 0) {
190 itemOption.submenu = buildTemplate(item.children, complete);
191 } else {
192 itemOption.click = () => complete(Option.some(item.id));
193 }
194 if (item.iconImage !== undefined) {
195 const image = menuIconImage(item.iconImage);
196 if (Option.isSome(image)) {
197 itemOption.icon = image.value;
198 }
199 }
200 if (item.destructive && (!item.children || item.children.length === 0)) {
201 const destructiveIcon = getDestructiveMenuIcon();
202 if (Option.isSome(destructiveIcon)) {
203 itemOption.icon = destructiveIcon.value;
204 }
205 }
206
207 template.push(itemOption);
208 }
209
210 return template;
211 };
212
213 return ElectronMenu.of({
214 pasteAndMatchStyle: Effect.sync(() => {
215 const focused = Electron.webContents.getFocusedWebContents();
216 // A mounted guest can report focus while the host owns the focused frame.
217 const target = focused?.hostWebContents ?? focused;
218 if (target && !target.isDestroyed()) {
219 target.pasteAndMatchStyle();
220 }
221 }),
222 setApplicationMenu: Effect.fn("ElectronMenu.setApplicationMenu")(function (template) {
223 return Effect.try({
224 try: () => {
225 Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
226 },
227 catch: (cause) =>
228 new ElectronMenuOperationError({
229 operation: "set-application-menu",
230 platform,
231 windowId: null,
232 itemCount: template.length,
233 cause,
234 }),
235 }).pipe(Effect.orDie);
236 }),
237 popupTemplate: Effect.fn("ElectronMenu.popupTemplate")(function (input) {
238 return input.template.length === 0
239 ? Effect.void
240 : Effect.try({
241 try: () =>
242 Electron.Menu.buildFromTemplate([...input.template]).popup({
243 window: input.window,
244 ...(input.frame ? { frame: input.frame } : {}),
245 }),
246 catch: (cause) =>
247 new ElectronMenuOperationError({
248 operation: "popup-template",
249 platform,
250 windowId: input.window.id,
251 itemCount: input.template.length,
252 cause,
253 }),
254 }).pipe(Effect.orDie);
255 }),
256 showContextMenu: Effect.fn("ElectronMenu.showContextMenu")(function (input) {
257 return Effect.callback<Option.Option<string>>((resume) => {
258 const normalizedItems = normalizeContextMenuItems(input.items);
259 if (normalizedItems.length === 0) {
260 resume(Effect.succeedNone);
261 return;
262 }
263
264 let completed = false;
265 const complete = (selectedItemId: Option.Option<string>) => {
266 if (completed) {
267 return;
268 }
269 completed = true;
270 resume(Effect.succeed(selectedItemId));
271 };
272
273 try {
274 const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
275 const popupPosition = normalizePosition(
276 input.position,
277 input.window.webContents.getZoomFactor(),
278 );
279 const popupOptions = Option.match(popupPosition, {
280 onNone: (): Electron.PopupOptions => ({
281 window: input.window,
282 callback: () => complete(Option.none()),
283 }),
284 onSome: (position): Electron.PopupOptions => ({
285 window: input.window,
286 x: position.x,
287 y: position.y,
288 callback: () => complete(Option.none()),
289 }),
290 });
291 menu.popup(
292 Option.isSome(input.source)
293 ? { ...popupOptions, sourceType: input.source.value }
294 : popupOptions,
295 );
296 } catch (cause) {
297 if (completed) {
298 return;
299 }
300 completed = true;
301 resume(
302 Effect.die(
303 new ElectronMenuOperationError({
304 operation: "show-context-menu",
305 platform,
306 windowId: input.window.id,
307 itemCount: normalizedItems.length,
308 cause,
309 }),
310 ),
311 );
312 }
313 });
314 }),
315 });
316});
317
318export const layer = Layer.effect(ElectronMenu, make);