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