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