Something went wrong. Try again.
A reusable desktop shell: your sidecar, your index, safe APIs, installers for every platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132// Windows come in two kinds. Privileged ones get the preload and so the bridge,// and may only show the app's own origins. Unprivileged ones have no preload// at all and may show anything. Both are sandboxed and context-isolated, and// neither can open a new window on its own: links go to the system browser.import { BrowserWindow, app, nativeTheme, shell } from 'electron';import { originOf } from './config.js';
const WINDOW_OPTIONS = ['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'x', 'y', 'center', 'title', 'titleBarStyle', 'trafficLightPosition', 'frame', 'transparent', 'resizable', 'movable', 'minimizable', 'maximizable', 'fullscreenable', 'alwaysOnTop', 'skipTaskbar', 'vibrancy', 'visualEffectState', 'roundedCorners', 'hasShadow', 'titleBarOverlay'];const EXTERNAL = /^(https?|mailto):/i;
export const pick = (obj, keys) => Object.fromEntries(keys.filter((k) => obj[k] !== undefined).map((k) => [k, obj[k]]));
// A colour, or { light, dark } resolved against the system theme.const colour = (bg) => (bg && typeof bg === 'object' ? (nativeTheme.shouldUseDarkColors ? bg.dark : bg.light) : bg);
export function createWindowManager ({ preload, api, env, allowedOrigins, log, network = 'any' }) { const windows = new Map(); // id → { win, privileged, guarded, closing, closeQuits } const bridgeArgs = [`--mollusc-api=${api.join(',')}`, `--mollusc-env=${Buffer.from(JSON.stringify(env)).toString('base64')}`]; let quitting = false; app.on('before-quit', () => { quitting = true; });
function open (url, { privileged = true, hideOnClose = false, ...opts } = {}) { const origin = originOf(url); if (privileged && !allowedOrigins.has(origin)) throw new Error(`A privileged window may only show ${[...allowedOrigins].join(' or ')}, not ${url}`); const win = new BrowserWindow({ ...pick(opts, WINDOW_OPTIONS), backgroundColor: colour(opts.backgroundColor), show: false, webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false, webviewTag: false, ...(privileged && preload ? { preload, additionalArguments: bridgeArgs } : {}), }, }); const entry = { win, privileged, guarded: false, closing: false, closeQuits: false }; windows.set(win.id, entry); win.on('closed', () => windows.delete(win.id)); if (opts.show !== false) { win.once('ready-to-show', () => { if (opts.maximized) win.maximize(); if (opts.fullScreen) win.setFullScreen(true); win.show(); }); } if (opts.backgroundColor && typeof opts.backgroundColor === 'object') { const update = () => { if (!win.isDestroyed()) win.setBackgroundColor(colour(opts.backgroundColor)); }; nativeTheme.on('updated', update); win.on('closed', () => nativeTheme.off('updated', update)); } win.on('close', (e) => { // A popover, say, is hidden rather than closed until the app quits. if (hideOnClose && !quitting) { e.preventDefault(); win.hide(); return; } // A page that listens for close-requested decides for itself (unsaved // work, say), and calls mollusc.window.close() to go ahead. if (entry.guarded && !entry.closing) { e.preventDefault(); entry.closeQuits = quitting; quitting = false; win.webContents.send('mollusc:event', 'close-requested', { quitting: entry.closeQuits }); } }); const wc = win.webContents; // Per window as well as by switch: no ICE over UDP, and the proxy it would // have to use is not there. if (network === 'loopback') wc.setWebRTCIPHandlingPolicy('disable_non_proxied_udp'); for (const ev of ['show', 'hide', 'focus', 'blur']) win.on(ev, () => { if (!wc.isDestroyed()) wc.send('mollusc:event', `window-${ev}`); }); wc.setWindowOpenHandler(({ url: target }) => { external(target); return { action: 'deny' }; }); if (privileged) { wc.on('will-navigate', (e, target) => { if (allowedOrigins.has(originOf(target))) return; e.preventDefault(); external(target); }); } wc.on('will-attach-webview', (e) => e.preventDefault()); wc.on('console-message', (e) => { if (e.level === 'error') log.warn(`renderer: ${e.message}`); }); // A page reloaded (in dev, say) registers its close guard again if it wants one. wc.on('did-start-navigation', (e) => { if (e.isMainFrame && !e.isSameDocument) entry.guarded = false; }); win.loadURL(url).catch((err) => log.error(`load ${url}: ${err.message}`)); return win; }
function external (target) { if (EXTERNAL.test(target)) shell.openExternal(target); else log.warn(`blocked navigation to ${target}`); }
const entries = () => [...windows.values()]; const entryOf = (wc) => entries().find((w) => w.win.webContents === wc); const isPrivileged = (wc) => !!entryOf(wc)?.privileged; const privileged = () => entries().filter((w) => w.privileged).map((w) => w.win);
// The page asked to be told before its window closes. function guard (wc, on = true) { const entry = entryOf(wc); if (entry) entry.guarded = on; } // Closes for real, past any guard; finishes the quit that asked first, if any. function close (wc) { const entry = entryOf(wc); if (!entry) return; entry.closing = true; const quit = entry.closeQuits; entry.win.close(); if (quit) setImmediate(() => app.quit()); }
// An event for the page: to the focused privileged window, else the first one. function send (name, payload) { const focused = BrowserWindow.getFocusedWindow(); const target = focused && isPrivileged(focused.webContents) ? focused : privileged()[0]; target?.webContents.send('mollusc:event', name, payload); return !!target; } function broadcast (name, payload) { for (const win of privileged()) win.webContents.send('mollusc:event', name, payload); } function reload () { for (const { win } of entries()) win.webContents.reloadIgnoringCache(); }
return { open, isPrivileged, privileged, guard, close, send, broadcast, reload, all: () => entries().map((w) => w.win) };}