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