Open History to see the last commit
1import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2import type * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10
11import * as Electron from "electron";
12
13const ElectronWindowCreateOptions = Schema.Struct({
14 title: Schema.NullOr(Schema.String),
15 width: Schema.NullOr(Schema.Number),
16 height: Schema.NullOr(Schema.Number),
17 minWidth: Schema.NullOr(Schema.Number),
18 minHeight: Schema.NullOr(Schema.Number),
19 show: Schema.NullOr(Schema.Boolean),
20 modal: Schema.NullOr(Schema.Boolean),
21 frame: Schema.NullOr(Schema.Boolean),
22 transparent: Schema.NullOr(Schema.Boolean),
23 backgroundColor: Schema.NullOr(Schema.String),
24 webPreferences: Schema.Struct({
25 preload: Schema.NullOr(Schema.String),
26 partition: Schema.NullOr(Schema.String),
27 backgroundThrottling: Schema.NullOr(Schema.Boolean),
28 sandbox: Schema.NullOr(Schema.Boolean),
29 contextIsolation: Schema.NullOr(Schema.Boolean),
30 nodeIntegration: Schema.NullOr(Schema.Boolean),
31 webviewTag: Schema.NullOr(Schema.Boolean),
32 }),
33});
34
35const ElectronWindowOperation = Schema.Literals([
36 "list-windows",
37 "get-focused-window",
38 "inspect-window",
39 "reveal-window",
40 "send-window-message",
41 "destroy-window",
42]);
43
44export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
45 "ElectronWindowCreateError",
46 {
47 options: ElectronWindowCreateOptions,
48 cause: Schema.Defect(),
49 },
50) {
51 override get message(): string {
52 const title = this.options.title === null ? "" : ` "${this.options.title}"`;
53 const dimensions =
54 this.options.width === null || this.options.height === null
55 ? ""
56 : ` (${this.options.width}x${this.options.height})`;
57 return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
58 }
59}
60
61export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
62 "ElectronWindowOperationError",
63 {
64 operation: ElectronWindowOperation,
65 platform: Schema.String,
66 windowId: Schema.NullOr(Schema.Number),
67 channel: Schema.NullOr(Schema.String),
68 cause: Schema.Defect(),
69 },
70) {
71 override get message(): string {
72 const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
73 const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
74 return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
75 }
76}
77
78export class ElectronWindow extends Context.Service<
79 ElectronWindow,
80 {
81 readonly create: (
82 options: Electron.BrowserWindowConstructorOptions,
83 ) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
84 readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
85 readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
86 readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
87 readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
88 readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
89 readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
90 readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
91 readonly destroyAll: Effect.Effect<void>;
92 readonly syncAllAppearance: <E, R>(
93 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
94 ) => Effect.Effect<void, E, R>;
95 }
96>()("@t3tools/desktop/electron/ElectronWindow") {}
97
98/** @public Service construction is part of the canonical Effect module API. */
99export const make = Effect.gen(function* () {
100 const platform = yield* HostProcessPlatform;
101 const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
102
103 const listWindows = Effect.try({
104 try: () => Electron.BrowserWindow.getAllWindows(),
105 catch: (cause) =>
106 new ElectronWindowOperationError({
107 operation: "list-windows",
108 platform,
109 windowId: null,
110 channel: null,
111 cause,
112 }),
113 }).pipe(Effect.orDie);
114
115 const isWindowDestroyed = (window: Electron.BrowserWindow) =>
116 Effect.try({
117 try: () => window.isDestroyed(),
118 catch: (cause) =>
119 new ElectronWindowOperationError({
120 operation: "inspect-window",
121 platform,
122 windowId: window.id,
123 channel: null,
124 cause,
125 }),
126 }).pipe(Effect.orDie);
127
128 const liveMain = Effect.gen(function* () {
129 const main = yield* Ref.get(mainWindowRef);
130 if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
131 return Option.none<Electron.BrowserWindow>();
132 }
133 return main;
134 });
135
136 const currentMainOrFirst = Effect.gen(function* () {
137 const main = yield* liveMain;
138 if (Option.isSome(main)) {
139 return main;
140 }
141
142 const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
143 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
144 return Option.none<Electron.BrowserWindow>();
145 }
146 return first;
147 });
148
149 const focusedMainOrFirst = Effect.gen(function* () {
150 const focused = yield* Effect.try({
151 try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
152 catch: (cause) =>
153 new ElectronWindowOperationError({
154 operation: "get-focused-window",
155 platform,
156 windowId: null,
157 channel: null,
158 cause,
159 }),
160 }).pipe(Effect.orDie);
161 if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
162 return focused;
163 }
164 return yield* currentMainOrFirst;
165 });
166
167 return ElectronWindow.of({
168 create: (options) => {
169 const webPreferences = options.webPreferences;
170 const diagnosticOptions = {
171 title: options.title ?? null,
172 width: options.width ?? null,
173 height: options.height ?? null,
174 minWidth: options.minWidth ?? null,
175 minHeight: options.minHeight ?? null,
176 show: options.show ?? null,
177 modal: options.modal ?? null,
178 frame: options.frame ?? null,
179 transparent: options.transparent ?? null,
180 backgroundColor: options.backgroundColor ?? null,
181 webPreferences: {
182 preload: webPreferences?.preload ?? null,
183 partition: webPreferences?.partition ?? null,
184 backgroundThrottling: webPreferences?.backgroundThrottling ?? null,
185 sandbox: webPreferences?.sandbox ?? null,
186 contextIsolation: webPreferences?.contextIsolation ?? null,
187 nodeIntegration: webPreferences?.nodeIntegration ?? null,
188 webviewTag: webPreferences?.webviewTag ?? null,
189 },
190 } satisfies typeof ElectronWindowCreateOptions.Type;
191
192 return Effect.try({
193 try: () => new Electron.BrowserWindow(options),
194 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
195 });
196 },
197 main: liveMain,
198 currentMainOrFirst,
199 focusedMainOrFirst,
200 setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),
201 clearMain: (window) =>
202 Ref.update(mainWindowRef, (current) => {
203 if (Option.isNone(current)) {
204 return current;
205 }
206 if (Option.isSome(window) && current.value !== window.value) {
207 return current;
208 }
209 return Option.none();
210 }),
211 reveal: (window) =>
212 Effect.try({
213 try: () => {
214 if (window.isDestroyed()) {
215 return;
216 }
217
218 if (window.isMinimized()) {
219 window.restore();
220 }
221
222 if (!window.isVisible()) {
223 window.show();
224 }
225
226 if (platform === "darwin") {
227 Electron.app.focus({ steal: true });
228 }
229
230 window.focus();
231 },
232 catch: (cause) =>
233 new ElectronWindowOperationError({
234 operation: "reveal-window",
235 platform,
236 windowId: window.id,
237 channel: null,
238 cause,
239 }),
240 }).pipe(Effect.orDie),
241 sendAll: (channel, ...args) =>
242 Effect.gen(function* () {
243 for (const window of yield* listWindows) {
244 if (yield* isWindowDestroyed(window)) {
245 continue;
246 }
247 yield* Effect.try({
248 try: () => window.webContents.send(channel, ...args),
249 catch: (cause) =>
250 new ElectronWindowOperationError({
251 operation: "send-window-message",
252 platform,
253 windowId: window.id,
254 channel,
255 cause,
256 }),
257 }).pipe(Effect.orDie);
258 }
259 }),
260 destroyAll: Effect.gen(function* () {
261 let firstFailure: Cause.Cause<never> | undefined;
262 for (const window of yield* listWindows) {
263 const exit = yield* Effect.exit(
264 Effect.try({
265 try: () => window.destroy(),
266 catch: (cause) =>
267 new ElectronWindowOperationError({
268 operation: "destroy-window",
269 platform,
270 windowId: window.id,
271 channel: null,
272 cause,
273 }),
274 }).pipe(Effect.orDie),
275 );
276 if (Exit.isFailure(exit)) {
277 firstFailure ??= exit.cause;
278 }
279 }
280 if (firstFailure !== undefined) {
281 return yield* Effect.failCause(firstFailure);
282 }
283 }),
284 syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
285 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
286 ) {
287 const windows = yield* listWindows;
288 for (const window of windows) {
289 if (yield* isWindowDestroyed(window)) {
290 continue;
291 }
292 yield* sync(window);
293 }
294 }),
295 });
296});
297
298export const layer = Layer.effect(ElectronWindow, make);