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

ElectronMenu.ts

320 lines10.7 KB

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