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
95function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
96 if (process.platform === "darwin") {
97 return {
98 titleBarStyle: "hiddenInset",
99 trafficLightPosition: { x: 16, y: 18 },
100 };
101 }
102
103 return {
104 titleBarStyle: "hidden",
105 titleBarOverlay: {
106 color: TITLEBAR_COLOR,
107 height: TITLEBAR_HEIGHT,
108 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
109 },
110 };
111}
112
113function syncWindowAppearance(
114 window: Electron.BrowserWindow,
115 shouldUseDarkColors: boolean,
116): Effect.Effect<void> {
117 return Effect.sync(() => {
118 if (window.isDestroyed()) {
119 return;
120 }
121
122 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
123 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
124 if (typeof titleBarOverlay === "object") {
125 window.setTitleBarOverlay(titleBarOverlay);
126 }
127 });
128}
129
130type RevealSubscription = (listener: () => void) => void;
131
132function bindFirstRevealTrigger(
133 subscribers: readonly RevealSubscription[],
134 reveal: () => void,
135): void {
136 let revealed = false;
137 const fire = () => {
138 if (revealed) return;
139 revealed = true;
140 reveal();
141 };
142 for (const subscribe of subscribers) {
143 subscribe(fire);
144 }
145}
146
147const make = Effect.gen(function* () {
148 const environment = yield* DesktopEnvironment.DesktopEnvironment;
149 const assets = yield* DesktopAssets.DesktopAssets;
150 const electronMenu = yield* ElectronMenu.ElectronMenu;
151 const electronShell = yield* ElectronShell.ElectronShell;
152 const electronTheme = yield* ElectronTheme.ElectronTheme;
153 const electronWindow = yield* ElectronWindow.ElectronWindow;
154 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
155 const state = yield* DesktopState.DesktopState;
156 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
157 const runPromise = Effect.runPromiseWith(context);
158
159 const createWindow = Effect.fn("desktop.window.createWindow")(function* (
160 backendHttpUrl: URL,
161 ): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
162 const iconPaths = yield* assets.iconPaths;
163 const iconOption = getIconOption(iconPaths);
164 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
165 const window = yield* electronWindow.create({
166 width: 1100,
167 height: 780,
168 minWidth: 840,
169 minHeight: 620,
170 show: false,
171 autoHideMenuBar: true,
172 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
173 ...iconOption,
174 title: environment.displayName,
175 ...getWindowTitleBarOptions(shouldUseDarkColors),
176 webPreferences: {
177 preload: environment.preloadPath,
178 contextIsolation: true,
179 nodeIntegration: false,
180 sandbox: true,
181 },
182 });
183
184 window.webContents.on("context-menu", (event, params) => {
185 event.preventDefault();
186
187 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
188
189 if (params.misspelledWord) {
190 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
191 menuTemplate.push({
192 label: suggestion,
193 click: () => window.webContents.replaceMisspelling(suggestion),
194 });
195 }
196 if (params.dictionarySuggestions.length === 0) {
197 menuTemplate.push({ label: "No suggestions", enabled: false });
198 }
199 menuTemplate.push({ type: "separator" });
200 }
201
202 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
203 menuTemplate.push(
204 {
205 label: "Copy Link",
206 click: () => {
207 void runPromise(electronShell.copyText(params.linkURL));
208 },
209 },
210 { type: "separator" },
211 );
212 }
213
214 if (params.mediaType === "image") {
215 menuTemplate.push({
216 label: "Copy Image",
217 click: () => window.webContents.copyImageAt(params.x, params.y),
218 });
219 menuTemplate.push({ type: "separator" });
220 }
221
222 menuTemplate.push(
223 { role: "cut", enabled: params.editFlags.canCut },
224 { role: "copy", enabled: params.editFlags.canCopy },
225 { role: "paste", enabled: params.editFlags.canPaste },
226 { role: "selectAll", enabled: params.editFlags.canSelectAll },
227 );
228
229 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
230 });
231
232 window.webContents.setWindowOpenHandler(({ url }) => {
233 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
234 void runPromise(electronShell.openExternal(url));
235 }
236 return { action: "deny" };
237 });
238
239 window.on("page-title-updated", (event) => {
240 event.preventDefault();
241 window.setTitle(environment.displayName);
242 });
243 window.webContents.on("did-finish-load", () => {
244 window.setTitle(environment.displayName);
245 });
246 window.webContents.on(
247 "did-fail-load",
248 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
249 if (!isMainFrame) {
250 return;
251 }
252 void runPromise(
253 logWindowWarning("main window failed to load", {
254 errorCode,
255 errorDescription,
256 url: validatedURL,
257 }),
258 );
259 },
260 );
261 window.webContents.on("render-process-gone", (_event, details) => {
262 void runPromise(
263 logWindowWarning("main window render process gone", {
264 reason: details.reason,
265 exitCode: details.exitCode,
266 }),
267 );
268 });
269
270 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
271 if (process.platform === "linux") {
272 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
273 }
274 bindFirstRevealTrigger(revealSubscribers, () => {
275 void runPromise(electronWindow.reveal(window));
276 });
277
278 if (environment.isDevelopment) {
279 const devServerUrl = yield* resolveDesktopDevServerUrl(environment);
280 void window.loadURL(devServerUrl);
281 window.webContents.openDevTools({ mode: "detach" });
282 } else {
283 void window.loadURL(backendHttpUrl.href);
284 }
285
286 window.on("closed", () => {
287 void runPromise(electronWindow.clearMain(Option.some(window)));
288 });
289
290 return window;
291 });
292
293 const createMain = Effect.gen(function* () {
294 const backendConfig = yield* serverExposure.backendConfig;
295 const window = yield* createWindow(backendConfig.httpBaseUrl);
296 yield* electronWindow.setMain(window);
297 yield* logWindowInfo("main window created");
298 return window;
299 }).pipe(Effect.withSpan("desktop.window.createMain"));
300
301 const ensureMain = Effect.gen(function* () {
302 const existingWindow = yield* electronWindow.currentMainOrFirst;
303 if (Option.isSome(existingWindow)) {
304 return existingWindow.value;
305 }
306 return yield* createMain;
307 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
308
309 const revealOrCreateMain = Effect.gen(function* () {
310 const window = yield* ensureMain;
311 yield* electronWindow.reveal(window);
312 return window;
313 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
314
315 const createMainIfBackendReady = Effect.gen(function* () {
316 const backendReady = yield* Ref.get(state.backendReady);
317 if (!backendReady) return;
318 const existingWindow = yield* electronWindow.currentMainOrFirst;
319 if (Option.isSome(existingWindow)) return;
320 yield* createMain;
321 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
322
323 return DesktopWindow.of({
324 createMain,
325 ensureMain,
326 revealOrCreateMain,
327 activate: Effect.gen(function* () {
328 const existingWindow = yield* electronWindow.currentMainOrFirst;
329 if (Option.isSome(existingWindow)) {
330 yield* electronWindow.reveal(existingWindow.value);
331 } else {
332 yield* createMainIfBackendReady;
333 }
334 }).pipe(Effect.withSpan("desktop.window.activate")),
335 createMainIfBackendReady,
336 handleBackendReady: Effect.gen(function* () {
337 yield* Ref.set(state.backendReady, true);
338 yield* logWindowInfo("backend ready", { source: "http" });
339 yield* createMainIfBackendReady;
340 }).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
341 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
342 yield* Effect.annotateCurrentSpan({ action });
343 const existingWindow = yield* electronWindow.focusedMainOrFirst;
344 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
345
346 const send = () => {
347 if (targetWindow.isDestroyed()) return;
348 targetWindow.webContents.send(IpcChannels.MENU_ACTION_CHANNEL, action);
349 void runPromise(electronWindow.reveal(targetWindow));
350 };
351
352 if (targetWindow.webContents.isLoadingMainFrame()) {
353 targetWindow.webContents.once("did-finish-load", send);
354 return;
355 }
356
357 send();
358 }),
359 syncAppearance: Effect.gen(function* () {
360 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
361 yield* electronWindow.syncAllAppearance((window) =>
362 syncWindowAppearance(window, shouldUseDarkColors),
363 );
364 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
365 });
366});
367
368export const layer = Layer.effect(DesktopWindow, make);