Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Data from "effect/Data";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7
8import type * as Electron from "electron";
9
10import * as DesktopAssets from "../app/DesktopAssets.ts";
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12import * as DesktopObservability from "../app/DesktopObservability.ts";
13import * as DesktopState from "../app/DesktopState.ts";
14import * as PreviewManager from "../preview/Manager.ts";
15import * as ElectronMenu from "../electron/ElectronMenu.ts";
16import * as ElectronShell from "../electron/ElectronShell.ts";
17import * as ElectronTheme from "../electron/ElectronTheme.ts";
18import * as ElectronWindow from "../electron/ElectronWindow.ts";
19import * as IpcChannels from "../ipc/channels.ts";
20import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
21
22const TITLEBAR_HEIGHT = 40;
23const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
24const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
25const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
26
27type WindowTitleBarOptions = Pick<
28 Electron.BrowserWindowConstructorOptions,
29 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
30>;
31
32type DesktopWindowRuntimeServices =
33 | DesktopEnvironment.DesktopEnvironment
34 | DesktopAssets.DesktopAssets
35 | DesktopServerExposure.DesktopServerExposure
36 | DesktopState.DesktopState
37 | ElectronMenu.ElectronMenu
38 | ElectronShell.ElectronShell
39 | ElectronTheme.ElectronTheme
40 | ElectronWindow.ElectronWindow
41 | PreviewManager.PreviewManager;
42
43export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
44 "DesktopWindowDevServerUrlMissingError",
45)<{}> {
46 override get message() {
47 return "VITE_DEV_SERVER_URL is required in desktop development.";
48 }
49}
50
51export type DesktopWindowError =
52 | DesktopWindowDevServerUrlMissingError
53 | ElectronWindow.ElectronWindowCreateError
54 | PreviewManager.PreviewManagerError;
55
56export interface DesktopWindowShape {
57 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
58 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
59 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
60 readonly activate: Effect.Effect<void, DesktopWindowError>;
61 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
62 readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
63 readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
64 readonly syncAppearance: Effect.Effect<void>;
65}
66
67export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
68 "@t3tools/desktop/window/DesktopWindow",
69) {}
70
71const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
72 DesktopObservability.makeComponentLogger("desktop-window");
73
74function resolveDesktopDevServerUrl(
75 environment: DesktopEnvironment.DesktopEnvironmentShape,
76): Effect.Effect<string, DesktopWindowDevServerUrlMissingError> {
77 return Option.match(environment.devServerUrl, {
78 onNone: () => Effect.fail(new DesktopWindowDevServerUrlMissingError()),
79 onSome: (url) => Effect.succeed(url.href),
80 });
81}
82
83function getIconOption(
84 iconPaths: DesktopAssets.DesktopIconPaths,
85 platform: NodeJS.Platform,
86): { icon: string } | Record<string, never> {
87 if (platform === "darwin") return {}; // macOS uses .icns from app bundle
88 const ext = platform === "win32" ? "ico" : "png";
89 return Option.match(iconPaths[ext], {
90 onNone: () => ({}),
91 onSome: (icon) => ({ icon }),
92 });
93}
94
95function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
96 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
97}
98
99export function isSameOriginRendererNavigation(input: {
100 readonly applicationUrl: string;
101 readonly navigationUrl: string;
102}): boolean {
103 try {
104 return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
105 } catch {
106 return false;
107 }
108}
109
110function getWindowTitleBarOptions(
111 shouldUseDarkColors: boolean,
112 platform: NodeJS.Platform,
113): WindowTitleBarOptions {
114 if (platform === "darwin") {
115 return {
116 titleBarStyle: "hiddenInset",
117 trafficLightPosition: { x: 16, y: 18 },
118 };
119 }
120
121 return {
122 titleBarStyle: "hidden",
123 titleBarOverlay: {
124 color: TITLEBAR_COLOR,
125 height: TITLEBAR_HEIGHT,
126 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
127 },
128 };
129}
130
131function syncWindowAppearance(
132 window: Electron.BrowserWindow,
133 shouldUseDarkColors: boolean,
134 platform: NodeJS.Platform,
135): Effect.Effect<void> {
136 return Effect.sync(() => {
137 if (window.isDestroyed()) {
138 return;
139 }
140
141 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
142 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
143 if (typeof titleBarOverlay === "object") {
144 window.setTitleBarOverlay(titleBarOverlay);
145 }
146 });
147}
148
149type RevealSubscription = (listener: () => void) => void;
150
151function bindFirstRevealTrigger(
152 subscribers: readonly RevealSubscription[],
153 reveal: () => void,
154): void {
155 let revealed = false;
156 const fire = () => {
157 if (revealed) return;
158 revealed = true;
159 reveal();
160 };
161 for (const subscribe of subscribers) {
162 subscribe(fire);
163 }
164}
165
166const make = Effect.gen(function* () {
167 const environment = yield* DesktopEnvironment.DesktopEnvironment;
168 const assets = yield* DesktopAssets.DesktopAssets;
169 const electronMenu = yield* ElectronMenu.ElectronMenu;
170 const electronShell = yield* ElectronShell.ElectronShell;
171 const electronTheme = yield* ElectronTheme.ElectronTheme;
172 const electronWindow = yield* ElectronWindow.ElectronWindow;
173 const previewManager = yield* PreviewManager.PreviewManager;
174 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
175 const state = yield* DesktopState.DesktopState;
176 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
177 const runPromise = Effect.runPromiseWith(context);
178
179 const createWindow = Effect.fn("desktop.window.createWindow")(function* (
180 backendHttpUrl: URL,
181 ): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
182 yield* previewManager.getBrowserSession();
183 const applicationUrl = environment.isDevelopment
184 ? yield* resolveDesktopDevServerUrl(environment)
185 : backendHttpUrl.href;
186 const iconPaths = yield* assets.iconPaths;
187 const iconOption = getIconOption(iconPaths, environment.platform);
188 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
189 const window = yield* electronWindow.create({
190 width: 1100,
191 height: 780,
192 minWidth: 840,
193 minHeight: 620,
194 show: false,
195 autoHideMenuBar: true,
196 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
197 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
198 ...iconOption,
199 title: environment.displayName,
200 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
201 webPreferences: {
202 preload: environment.preloadPath,
203 contextIsolation: true,
204 nodeIntegration: false,
205 sandbox: true,
206 webviewTag: true,
207 },
208 });
209
210 if (environment.platform === "darwin") {
211 window.setAutoHideCursor(false);
212 }
213
214 yield* previewManager.setMainWindow(window);
215 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
216 if (
217 typeof params.partition !== "string" ||
218 !previewManager.isBrowserPartition(params.partition)
219 ) {
220 event.preventDefault();
221 return;
222 }
223 webPreferences.sandbox = true;
224 webPreferences.nodeIntegration = false;
225 webPreferences.nodeIntegrationInSubFrames = false;
226 webPreferences.contextIsolation = false;
227 });
228
229 window.webContents.on("context-menu", (event, params) => {
230 event.preventDefault();
231
232 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
233
234 if (params.misspelledWord) {
235 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
236 menuTemplate.push({
237 label: suggestion,
238 click: () => window.webContents.replaceMisspelling(suggestion),
239 });
240 }
241 if (params.dictionarySuggestions.length === 0) {
242 menuTemplate.push({ label: "No suggestions", enabled: false });
243 }
244 menuTemplate.push({ type: "separator" });
245 }
246
247 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
248 menuTemplate.push(
249 {
250 label: "Copy Link",
251 click: () => {
252 void runPromise(electronShell.copyText(params.linkURL));
253 },
254 },
255 { type: "separator" },
256 );
257 }
258
259 if (params.mediaType === "image") {
260 menuTemplate.push({
261 label: "Copy Image",
262 click: () => window.webContents.copyImageAt(params.x, params.y),
263 });
264 menuTemplate.push({ type: "separator" });
265 }
266
267 menuTemplate.push(
268 { role: "cut", enabled: params.editFlags.canCut },
269 { role: "copy", enabled: params.editFlags.canCopy },
270 { role: "paste", enabled: params.editFlags.canPaste },
271 { role: "selectAll", enabled: params.editFlags.canSelectAll },
272 );
273
274 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
275 });
276
277 const syncZoomCssVariables = () => {
278 if (window.isDestroyed()) return;
279 window.webContents.send(
280 IpcChannels.ZOOM_FACTOR_CHANGED_CHANNEL,
281 window.webContents.getZoomFactor(),
282 );
283 };
284 window.webContents.on("zoom-changed", syncZoomCssVariables);
285 window.webContents.on("did-finish-load", syncZoomCssVariables);
286
287 window.webContents.setWindowOpenHandler(({ url }) => {
288 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
289 void runPromise(electronShell.openExternal(url));
290 }
291 return { action: "deny" };
292 });
293 window.webContents.on("will-navigate", (event, url) => {
294 if (
295 isSameOriginRendererNavigation({
296 applicationUrl,
297 navigationUrl: url,
298 })
299 ) {
300 return;
301 }
302
303 event.preventDefault();
304 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
305 void runPromise(electronShell.openExternal(url));
306 }
307 });
308
309 window.on("page-title-updated", (event) => {
310 event.preventDefault();
311 window.setTitle(environment.displayName);
312 });
313 window.webContents.on("did-finish-load", () => {
314 window.setTitle(environment.displayName);
315 });
316 window.webContents.on(
317 "did-fail-load",
318 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
319 if (!isMainFrame) {
320 return;
321 }
322 void runPromise(
323 logWindowWarning("main window failed to load", {
324 errorCode,
325 errorDescription,
326 url: validatedURL,
327 }),
328 );
329 },
330 );
331 window.webContents.on("render-process-gone", (_event, details) => {
332 void runPromise(
333 logWindowWarning("main window render process gone", {
334 reason: details.reason,
335 exitCode: details.exitCode,
336 }),
337 );
338 });
339
340 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
341 if (environment.platform === "linux") {
342 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
343 }
344 bindFirstRevealTrigger(revealSubscribers, () => {
345 void runPromise(electronWindow.reveal(window));
346 });
347
348 if (environment.isDevelopment) {
349 void window.loadURL(applicationUrl);
350 window.webContents.openDevTools({ mode: "detach" });
351 } else {
352 void window.loadURL(applicationUrl);
353 }
354
355 window.on("closed", () => {
356 void runPromise(electronWindow.clearMain(Option.some(window)));
357 });
358
359 return window;
360 });
361
362 const createMain = Effect.gen(function* () {
363 const backendConfig = yield* serverExposure.backendConfig;
364 const window = yield* createWindow(backendConfig.httpBaseUrl);
365 yield* electronWindow.setMain(window);
366 yield* logWindowInfo("main window created");
367 return window;
368 }).pipe(Effect.withSpan("desktop.window.createMain"));
369
370 const ensureMain = Effect.gen(function* () {
371 const existingWindow = yield* electronWindow.currentMainOrFirst;
372 if (Option.isSome(existingWindow)) {
373 return existingWindow.value;
374 }
375 return yield* createMain;
376 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
377
378 const revealOrCreateMain = Effect.gen(function* () {
379 const window = yield* ensureMain;
380 yield* electronWindow.reveal(window);
381 return window;
382 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
383
384 const createMainIfBackendReady = Effect.gen(function* () {
385 const backendReady = yield* Ref.get(state.backendReady);
386 if (!backendReady) return;
387 const existingWindow = yield* electronWindow.currentMainOrFirst;
388 if (Option.isSome(existingWindow)) return;
389 yield* createMain;
390 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
391
392 return DesktopWindow.of({
393 createMain,
394 ensureMain,
395 revealOrCreateMain,
396 activate: Effect.gen(function* () {
397 const existingWindow = yield* electronWindow.currentMainOrFirst;
398 if (Option.isSome(existingWindow)) {
399 yield* electronWindow.reveal(existingWindow.value);
400 } else {
401 yield* createMainIfBackendReady;
402 }
403 }).pipe(Effect.withSpan("desktop.window.activate")),
404 createMainIfBackendReady,
405 handleBackendReady: Effect.gen(function* () {
406 yield* Ref.set(state.backendReady, true);
407 yield* logWindowInfo("backend ready", { source: "http" });
408 yield* createMainIfBackendReady;
409 }).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
410 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
411 yield* Effect.annotateCurrentSpan({ action });
412 const existingWindow = yield* electronWindow.focusedMainOrFirst;
413 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
414
415 const send = () => {
416 if (targetWindow.isDestroyed()) return;
417 targetWindow.webContents.send(IpcChannels.MENU_ACTION_CHANNEL, action);
418 void runPromise(electronWindow.reveal(targetWindow));
419 };
420
421 if (targetWindow.webContents.isLoadingMainFrame()) {
422 targetWindow.webContents.once("did-finish-load", send);
423 return;
424 }
425
426 send();
427 }),
428 syncAppearance: Effect.gen(function* () {
429 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
430 yield* electronWindow.syncAllAppearance((window) =>
431 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
432 );
433 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
434 });
435});
436
437export const layer = Layer.effect(DesktopWindow, make);