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

ElectronMenu.ts

262 lines8.2 KB

1import type { ContextMenuItem } from "@t3tools/contracts";
2import { HostProcessPlatform } 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>;
21​
22export interface ElectronMenuTemplateInput {
23 readonly window: Electron.BrowserWindow;
24 readonly template: readonly Electron.MenuItemConstructorOptions[];
26​
27const ElectronMenuOperation = Schema.Literals([
28 "set-application-menu",
29 "popup-template",
30 "show-context-menu",
31]);
32​
33export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
34 "ElectronMenuOperationError",
35 {
36 operation: ElectronMenuOperation,
37 platform: Schema.String,
38 windowId: Schema.NullOr(Schema.Number),
39 itemCount: Schema.Number,
40 cause: Schema.Defect(),
41 },
42) {
43 override get message(): string {
44 const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
45 return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
46 }
48​
49export class ElectronMenu extends Context.Service<
50 ElectronMenu,
51 {
52 readonly setApplicationMenu: (
53 template: readonly Electron.MenuItemConstructorOptions[],
54 ) => Effect.Effect<void>;
55 readonly showContextMenu: (
56 input: ElectronMenuContextInput,
57 ) => Effect.Effect<Option.Option<string>>;
58 readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
59 }
60>()("@t3tools/desktop/electron/ElectronMenu") {}
61​
62function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
63 const normalizedItems: ContextMenuItem[] = [];
64​
65 for (const sourceItem of source) {
66 if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
67 continue;
68 }
69​
70 // Header items are decorative section labels for the web fallback only —
71 // Electron's native menu has no equivalent affordance, so we skip them.
72 if (sourceItem.header === true) {
73 continue;
74 }
75​
76 const normalizedItem: ContextMenuItem = {
77 id: sourceItem.id,
78 label: sourceItem.label,
79 destructive: sourceItem.destructive === true,
80 disabled: sourceItem.disabled === true,
81 };
82​
83 if (sourceItem.children) {
84 const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
85 if (normalizedChildren.length === 0) {
86 continue;
87 }
88 normalizedItem.children = normalizedChildren;
89 }
90​
91 normalizedItems.push(normalizedItem);
92 }
93​
94 return normalizedItems;
96​
97// Renderer positions arrive in CSS pixels; popup() expects window points, so
98// page zoom must be factored in or menus drift proportionally to their
99// distance from the window origin.
100const normalizePosition = (
101 position: Option.Option<ElectronMenuPosition>,
102 zoomFactor: number,
103): Option.Option<ElectronMenuPosition> =>
104 Option.filter(
105 position,
106 ({ x, y }) =>
107 Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
108 ).pipe(
109 Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
110 );
111​
112export const make = Effect.gen(function* () {
113 const platform = yield* HostProcessPlatform;
114 let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
115​
116 const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
117 if (platform !== "darwin") {
118 return Option.none();
119 }
120 if (destructiveMenuIconCache !== undefined) {
121 return destructiveMenuIconCache;
122 }
123​
124 try {
125 const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
126 width: 12,
127 height: 12,
128 });
129 icon.setTemplateImage(true);
130 destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
131 } catch {
132 destructiveMenuIconCache = Option.none();
133 }
134​
135 return destructiveMenuIconCache;
136 };
137​
138 const buildTemplate = (
139 entries: readonly ContextMenuItem[],
140 complete: (selectedItemId: Option.Option<string>) => void,
141 ): Electron.MenuItemConstructorOptions[] => {
142 const template: Electron.MenuItemConstructorOptions[] = [];
143 let hasInsertedDestructiveSeparator = false;
144​
145 for (const item of entries) {
146 if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
147 template.push({ type: "separator" });
148 hasInsertedDestructiveSeparator = true;
149 }
150​
151 const itemOption: Electron.MenuItemConstructorOptions = {
152 label: item.label,
153 enabled: !item.disabled,
154 };
155 if (item.children && item.children.length > 0) {
156 itemOption.submenu = buildTemplate(item.children, complete);
157 } else {
158 itemOption.click = () => complete(Option.some(item.id));
159 }
160 if (item.destructive && (!item.children || item.children.length === 0)) {
161 const destructiveIcon = getDestructiveMenuIcon();
162 if (Option.isSome(destructiveIcon)) {
163 itemOption.icon = destructiveIcon.value;
164 }
165 }
166​
167 template.push(itemOption);
168 }
169​
170 return template;
171 };
172​
173 return ElectronMenu.of({
174 setApplicationMenu: (template) =>
175 Effect.try({
176 try: () => {
177 Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
178 },
179 catch: (cause) =>
180 new ElectronMenuOperationError({
181 operation: "set-application-menu",
182 platform,
183 windowId: null,
184 itemCount: template.length,
185 cause,
186 }),
187 }).pipe(Effect.orDie),
188 popupTemplate: (input) =>
189 input.template.length === 0
190 ? Effect.void
191 : Effect.try({
192 try: () =>
193 Electron.Menu.buildFromTemplate([...input.template]).popup({
194 window: input.window,
195 }),
196 catch: (cause) =>
197 new ElectronMenuOperationError({
198 operation: "popup-template",
199 platform,
200 windowId: input.window.id,
201 itemCount: input.template.length,
202 cause,
203 }),
204 }).pipe(Effect.orDie),
205 showContextMenu: (input) =>
206 Effect.callback<Option.Option<string>>((resume) => {
207 const normalizedItems = normalizeContextMenuItems(input.items);
208 if (normalizedItems.length === 0) {
209 resume(Effect.succeed(Option.none()));
210 return;
211 }
212​
213 let completed = false;
214 const complete = (selectedItemId: Option.Option<string>) => {
215 if (completed) {
216 return;
217 }
218 completed = true;
219 resume(Effect.succeed(selectedItemId));
220 };
221​
222 try {
223 const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
224 const popupPosition = normalizePosition(
225 input.position,
226 input.window.webContents.getZoomFactor(),
227 );
228 const popupOptions = Option.match(popupPosition, {
229 onNone: (): Electron.PopupOptions => ({
230 window: input.window,
231 callback: () => complete(Option.none()),
232 }),
233 onSome: (position): Electron.PopupOptions => ({
234 window: input.window,
235 x: position.x,
236 y: position.y,
237 callback: () => complete(Option.none()),
238 }),
239 });
240 menu.popup(popupOptions);
241 } catch (cause) {
242 if (completed) {
243 return;
244 }
245 completed = true;
246 resume(
247 Effect.die(
248 new ElectronMenuOperationError({
249 operation: "show-context-menu",
250 platform,
251 windowId: input.window.id,
252 itemCount: normalizedItems.length,
253 cause,
254 }),
255 ),
256 );
257 }
258 }),
259 });
260});
261​
262export const layer = Layer.effect(ElectronMenu, make);