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