From f746ee7cd6c10199eb2589897a80d620bb0b3f18 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Tue, 3 Nov 2026 17:02:47 -0500 Subject: [PATCH] Prepare Showcode desktop 3.0 with native menus and release notes --- docs/native-desktop-audit.md | 62 ++++++++++ main/BrowserWindowHandler.js | 66 ++++++----- main/desktop.js | 172 ++++++++++++++++++++++++++++ main/index.js | 23 +--- main/mainWindow.js | 10 +- main/menu.js | 154 ++++++++++++++++++++++++- main/preload.cjs | 49 +++++++- main/releaseNotes.js | 43 +++++++ main/updater.js | 38 ++++++- main/windowIntegrations.js | 78 +++++++++++++ package-lock.json | 4 +- package.json | 2 +- showcode | 2 +- tests/desktop.test.js | 214 +++++++++++++++++++++++++++++++++++ tests/menu.test.js | 10 +- tests/preload.test.js | 62 ++++++++++ tests/releaseNotes.test.js | 56 +++++++++ tests/updater.test.js | 29 ++++- 18 files changed, 996 insertions(+), 78 deletions(-) create mode 100644 docs/native-desktop-audit.md create mode 100644 main/desktop.js create mode 100644 main/releaseNotes.js create mode 100644 main/windowIntegrations.js create mode 100644 tests/desktop.test.js create mode 100644 tests/preload.test.js create mode 100644 tests/releaseNotes.test.js diff --git a/docs/native-desktop-audit.md b/docs/native-desktop-audit.md new file mode 100644 index 0000000..782107c --- /dev/null +++ b/docs/native-desktop-audit.md @@ -0,0 +1,62 @@ +# Native desktop audit + +Audited on October 13, 2026. Showcode uses Electron 41 with a shared Nuxt renderer in the `showcode` submodule. The best opportunities are the boundaries between the editor and the operating system. Replacing the code editor or preview controls would require separate native implementations on each platform. + +## Patched + +| Surface | Previous behavior | Desktop behavior | +| ------------------------------ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Application menus | File only closed the window; app actions lived in HTML menus | Native File, Window, and Help actions for projects, the saved library, templates, exports, preferences, help, and changelog | +| Keyboard shortcuts | Browser listeners handled Save and New Project | Native menu accelerators handle Save, Save As, New/Close/Reopen Tab, tab switching, import, export, copy image, and preferences | +| Recent projects | Only the in-app dropdown listed recent saved projects | The native File menu also lists recent saved projects, with live enablement based on the active tab | +| Toolbar File button | HTML dropdown | Removed on macOS; File actions live in the native menu bar. Other desktop platforms open the native File menu from the button. | +| macOS tabs | A separate toolbar beneath the title bar | Tabs share a 44px title bar with native traffic lights. A bounded scrolling tab strip, fixed New Project button, and reserved Showcode drag area keep crowded windows usable. | +| Tab context menu | HTML context menu | Native menu with Save, Save As, Rename, Duplicate, Close, close-neighbor actions, and Reopen | +| Image export menu | HTML dropdown | Native PNG, JPEG, and SVG menu | +| Image and JSON exports | Browser downloads | Native save dialog with format filters, directory selection, and overwrite handling; Electron writes the chosen file | +| Project and background imports | Browser file input | Native open dialog; Electron reads only the selected file | +| Image clipboard | Browser ClipboardItem permissions and compatibility checks | Electron decodes the generated image and writes it to the system clipboard | +| Delete/reset confirmations | Browser confirm dialogs | Native modal dialogs attached to the app window, with Cancel as the default | +| Modified-tab closing | HTML save/discard dialog | Native Save Project / Cancel / Discard dialog | +| Template renaming | Browser prompt | Existing app rename dialog; Electron has no built-in native text-entry prompt | +| External links | Could open another Electron window or navigate away from the editor | HTTP, HTTPS, and mail links open in the user's default browser or mail app | +| Windows window controls | Hand-drawn HTML minimize/maximize/close buttons | Native titlebar overlay and system caption controls, with colors matching the app | +| macOS window behavior | Closing hid the whole app; Dock activation did not explicitly restore an existing hidden window | Closing hides the window; Dock activation shows and focuses it; titlebar double-click respects the system preference | +| Emoji picker | Global shortcuts registered even when another app was active | App-local Edit → Emoji & Symbols action, enabled only when supported | +| Text editing menus | No general native text-field context menu | Native Undo, Redo, Cut, Copy, Paste, and Select All for editable fields; Monaco retains its own editor menu | +| Native document state | Only the HTML title showed a modified marker | macOS also receives the active project's document-edited state | + +The browser version keeps its existing file downloads, clipboard, dialogs, and menus. Save and Save As continue to save to Showcode's project library; Export Configuration is the action that writes a portable JSON file. + +## Boundary fixes + +- Native menus are created after Electron is ready. +- Window IPC handlers register once, and window-state events bind once per window. Reloading or recreating a window does not accumulate handlers. +- The preload keeps an explicit channel allowlist, strips privileged IPC event objects, and supports listener cleanup by channel. Menu command callbacks do not return Vue stores across the context bridge. +- Filesystem operations stay in the main process. The renderer passes file contents and suggested filenames, and cannot provide an arbitrary read/write path. +- Invalid JSON and API request files are rejected before creating an imported project tab. +- Existing updater work remains in place. + +## Further native opportunities + +| Opportunity | Recommendation | +| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Project library, templates, settings, and session storage | Move these from localStorage to versioned files under Electron's userData directory. Treat this as a persistence change with migration, backup/recovery, and interrupted-write handling. Existing IndexedDB-to-localStorage migration makes an incidental storage replacement risky. | +| Document files and Finder/Explorer integration | Introduce a dedicated `.showcode` format before adding file associations, open-file/second-instance handling, OS recent documents, represented filenames, and Save directly to an existing file. Associating all `.json` files with Showcode would be too broad. | +| Quit-time persistence | Add a main/renderer handshake to flush debounced editor state before quit or update installation. This should accompany an explicit decision about restoring unsaved tabs versus prompting for each document. | +| Native image sharing and dragging | A macOS Share menu and dragging a rendered image into another app are useful additions. Both need temporary exported files, cleanup, and platform-specific fallbacks. | +| Preferences window | A separate Electron preferences window could remain backed by the same Vue form. It needs synchronized preference state and ownership across windows. | +| Native notifications | Reserve these for background work that finishes while Showcode is inactive. In-app save/copy feedback is better served by the existing toast/button feedback. | +| Code editor, preview, cropping, theme/background pickers, and rename forms | Keep these in Vue/Monaco. Electron does not supply equivalent native components. A full native conversion would be a separate macOS/Windows/Linux UI project. | + +## Validation + +- Main process and preload: `npm test` — 15 passing tests. +- Shared renderer: `cd showcode && npm test -- --run` — 121 passing tests. +- Desktop renderer: `npm run generate` — passed. +- macOS Electron smoke tests use an isolated temporary user profile. File dialogs are stubbed to choose temporary paths; generated images are decoded by Electron, and clipboard writes are intercepted to preserve the user's clipboard. +- The final smoke run passed native New/Save/Recent actions, JSON import/export, PNG export and clipboard conversion, invalid-import handling, tab/export popup cancellation, preferences/help/changelog actions, close cancellation/discard/reopen, external browser routing, reload, Dock reopening, and window recreation. No renderer errors were reported. +- Windows caption controls and Linux native dialogs require checks on those operating systems. No signed installer or update installation was exercised. +- Crowded titlebar checks covered 25 tabs, a 620px window, the fixed New Project button and drag area, automatic active-tab scrolling, and light/dark styling. Physical window dragging still needs a manual check: native automation did not move either the custom titlebar or a standard macOS titlebar control window. + +The native APIs are documented in Electron's [dialog](https://www.electronjs.org/docs/latest/api/dialog), [BrowserWindow](https://www.electronjs.org/docs/latest/api/browser-window), [webContents](https://www.electronjs.org/docs/latest/api/web-contents), and [MenuItem](https://www.electronjs.org/docs/latest/api/menu-item) references. diff --git a/main/BrowserWindowHandler.js b/main/BrowserWindowHandler.js index f1529a7..07e543b 100755 --- a/main/BrowserWindowHandler.js +++ b/main/BrowserWindowHandler.js @@ -8,6 +8,8 @@ import log from "electron-log"; import SystemFontsModule from "system-font-families"; import {__DARWIN__} from "./platform.js"; import WindowStateHandler from "./WindowStateHandler.js"; +import integrateWindow, {doubleClickTitleBar} from "./windowIntegrations.js"; +import {windowForEvent} from "./desktop.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -32,7 +34,12 @@ export default class BrowserWinHandler { this.options = options; this.quitting = false; + this.bindIpc(); this.createInstance(); + + app.on("before-quit", () => { + this.quitting = true; + }); } createInstance() { @@ -81,38 +88,16 @@ export default class BrowserWinHandler { disableBlinkFeatures: "Auxclick", // Disable auxclick event. See: https://developers.google.com/web/updates/2016/10/auxclick webSecurity: !devServerUrl, // Disable on dev to allow loading local resources preload: path.join(__dirname, "preload.cjs"), + contextIsolation: true, + nodeIntegration: false, + sandbox: true, + spellcheck: false, }, }); mainWindowState.manage(this.browserWindow); - - app.on("before-quit", () => { - this.quitting = true; - }); - - ipcMain.on("will-quit", (event) => { - this.quitting = true; - event.returnValue = true; - }); - - ipcMain.on("close", () => this.browserWindow.close()); - ipcMain.on("maximize", () => this.browserWindow.maximize()); - ipcMain.on("minimize", () => this.browserWindow.minimize()); - ipcMain.on("unmaximize", () => this.browserWindow.unmaximize()); - - ipcMain.on("double-click-title-bar", () => { - this.browserWindow.isMaximized() - ? this.browserWindow.unmaximize() - : this.browserWindow.maximize(); - }); - - ipcMain.handle("get-window-state", async () => { - return new WindowStateHandler(this.browserWindow).get(); - }); - - ipcMain.handle("get-system-fonts", async () => { - return await systemFonts.getFonts(); - }); + integrateWindow(this.browserWindow); + new WindowStateHandler(this.browserWindow).bind(); this.browserWindow.on("close", (e) => { // On macOS, when the user closes the window we really @@ -123,9 +108,9 @@ export default class BrowserWinHandler { if (this.browserWindow.isFullScreen()) { this.browserWindow.setFullScreen(false); - this.browserWindow.once("leave-full-screen", () => app.hide()); + this.browserWindow.once("leave-full-screen", () => this.browserWindow.hide()); } else { - app.hide(); + this.browserWindow.hide(); } return; @@ -143,7 +128,28 @@ export default class BrowserWinHandler { recreate() { if (this.browserWindow === null) { this.create(); + } else { + this.browserWindow.show(); + this.browserWindow.focus(); + } + } + + bindIpc() { + for (const action of ["close", "maximize", "minimize", "unmaximize"]) { + ipcMain.on(action, (event) => windowForEvent(event)[action]()); } + + ipcMain.on("double-click-title-bar", (event) => doubleClickTitleBar(windowForEvent(event))); + + ipcMain.handle("get-window-state", (event) => { + return new WindowStateHandler(windowForEvent(event)).get(); + }); + + ipcMain.handle("get-system-fonts", (event) => { + windowForEvent(event); + + return systemFonts.getFonts(); + }); } /** diff --git a/main/desktop.js b/main/desktop.js new file mode 100644 index 0000000..0e316b8 --- /dev/null +++ b/main/desktop.js @@ -0,0 +1,172 @@ +import path from "node:path"; +import {readFile, writeFile} from "node:fs/promises"; +import {BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeImage} from "electron"; +import {acknowledgeReleaseNotes, getReleaseNotesState} from "./releaseNotes.js"; + +const fileTypes = { + json: {name: "Showcode Configuration", extensions: ["json"]}, + png: {name: "PNG Image", extensions: ["png"]}, + jpg: {name: "JPEG Image", extensions: ["jpg", "jpeg"]}, + svg: {name: "SVG Image", extensions: ["svg"]}, +}; + +export function windowForEvent(event) { + const window = BrowserWindow.fromWebContents(event.sender); + + if (!window || event.senderFrame !== event.sender.mainFrame) { + throw new Error("Desktop actions must originate from the application window."); + } + + return window; +} + +function popup(window, items) { + return new Promise((resolve) => { + const menu = Menu.buildFromTemplate( + items.map((item) => ({...item, click: () => resolve(item.id)})), + ); + + menu.popup({window, callback: () => resolve(null)}); + }); +} + +ipcMain.handle("get-release-notes-state", (event) => { + windowForEvent(event); + + return getReleaseNotesState(); +}); + +ipcMain.handle("acknowledge-release-notes", (event, {releaseIds, showAfterUpdate}) => { + windowForEvent(event); + + return acknowledgeReleaseNotes(releaseIds, showAfterUpdate); +}); + +ipcMain.handle("open-file", async (event, kind) => { + const window = windowForEvent(event); + const filters = { + project: [fileTypes.json], + background: [{name: "Images", extensions: ["png", "jpg", "jpeg", "gif", "webp"]}], + }[kind]; + + if (!filters) { + throw new Error("Unsupported file type."); + } + + const {canceled, filePaths} = await dialog.showOpenDialog(window, { + title: kind === "project" ? "Import Showcode Configuration" : "Choose a Background Image", + properties: ["openFile"], + filters, + }); + + if (canceled) { + return null; + } + + return {name: path.basename(filePaths[0]), data: await readFile(filePaths[0])}; +}); + +ipcMain.handle("save-file", async (event, {name, data, extension}) => { + const window = windowForEvent(event); + const filter = fileTypes[extension]; + + if (!filter || !(data instanceof Uint8Array)) { + throw new Error("Unsupported file export."); + } + + const {canceled, filePath} = await dialog.showSaveDialog(window, { + title: extension === "json" ? "Export Showcode Configuration" : "Export Image", + defaultPath: path.basename(name.replaceAll("\\", "/")), + filters: [filter], + properties: ["createDirectory", "showOverwriteConfirmation"], + }); + + if (canceled) { + return false; + } + + await writeFile(filePath, data); + + return true; +}); + +ipcMain.handle("copy-image", (event, data) => { + windowForEvent(event); + + if (!(data instanceof Uint8Array)) { + throw new Error("An image is required."); + } + + const image = nativeImage.createFromBuffer(Buffer.from(data)); + + if (image.isEmpty()) { + throw new Error("The image could not be copied."); + } + + clipboard.writeImage(image); +}); + +ipcMain.handle("confirm-action", async (event, {message, detail, buttonLabel = "Delete"}) => { + const {response} = await dialog.showMessageBox(windowForEvent(event), { + type: "warning", + message, + detail, + buttons: ["Cancel", buttonLabel], + defaultId: 0, + cancelId: 0, + noLink: true, + }); + + return response === 1; +}); + +ipcMain.handle("confirm-close-project", async (event, name) => { + const {response} = await dialog.showMessageBox(windowForEvent(event), { + type: "question", + message: `Save changes to “${name || "Untitled Project"}” before closing?`, + detail: "Save it to your project library, or discard the changes and close this tab.", + buttons: ["Save Project", "Cancel", "Discard"], + defaultId: 0, + cancelId: 1, + noLink: true, + }); + + return ["save", "cancel", "discard"][response]; +}); + +ipcMain.handle("show-tab-menu", (event, state) => { + return popup(windowForEvent(event), [ + {id: "save", label: "Save", enabled: !state.starting}, + {id: "save-as", label: "Save As…", enabled: !state.starting}, + {type: "separator"}, + {id: "rename", label: "Rename…", enabled: !state.starting}, + {id: "duplicate", label: "Duplicate", enabled: !state.starting}, + {type: "separator"}, + {id: "close", label: "Close Tab"}, + {id: "close-others", label: "Close Other Projects", enabled: state.canCloseOthers}, + { + id: "close-projects-to-left", + label: "Close Projects to the Left", + enabled: state.canCloseProjectsToLeft, + }, + { + id: "close-projects-to-right", + label: "Close Projects to the Right", + enabled: state.canCloseProjectsToRight, + }, + {type: "separator"}, + { + id: "reopen-closed", + label: "Reopen Closed Project", + enabled: state.canReopenClosedProject, + }, + ]); +}); + +ipcMain.handle("show-export-menu", (event) => { + return popup(windowForEvent(event), [ + {id: "toPng", label: "PNG"}, + {id: "toJpeg", label: "JPEG"}, + {id: "toSvg", label: "SVG"}, + ]); +}); diff --git a/main/index.js b/main/index.js index 082bbd0..9e17696 100755 --- a/main/index.js +++ b/main/index.js @@ -1,5 +1,5 @@ -import {app, globalShortcut} from "electron"; -import {__DARWIN__, __LINUX__, __WINDOWS__} from "./platform.js"; +import {app} from "electron"; +import {__DARWIN__} from "./platform.js"; // Quit when all windows are closed. app.on("window-all-closed", function () { @@ -12,23 +12,6 @@ app.on("window-all-closed", function () { app.quit(); }); -app.whenReady().then(() => { - if (!app.isEmojiPanelSupported()) { - return; - } - - if (__DARWIN__) { - globalShortcut.register("Super+Shift+Space", () => app.showEmojiPanel()); - } - - if (__LINUX__) { - globalShortcut.register("Control+.", () => app.showEmojiPanel()); - } - - if (__WINDOWS__) { - globalShortcut.register("Super+.", () => app.showEmojiPanel()); - } -}); - +import "./desktop.js"; import "./menu.js"; import "./mainWindow.js"; diff --git a/main/mainWindow.js b/main/mainWindow.js index 561febd..e29a711 100755 --- a/main/mainWindow.js +++ b/main/mainWindow.js @@ -1,26 +1,22 @@ import {__DARWIN__, __WINDOWS__} from "./platform.js"; import BrowserWinHandler from "./BrowserWindowHandler.js"; -import WindowStateHandler from "./WindowStateHandler.js"; const options = {show: false}; if (__DARWIN__) { options.titleBarStyle = "hiddenInset"; - options.trafficLightPosition = {x: 12, y: 8}; + options.trafficLightPosition = {x: 12, y: 16}; options.vibrancy = "sidebar"; options.visualEffectState = "active"; options.backgroundColor = "#00000000"; } else if (__WINDOWS__) { - options.frame = false; + options.titleBarStyle = "hidden"; + options.titleBarOverlay = {height: 28}; } const winHandler = new BrowserWinHandler(options); winHandler.onCreated(async (browserWindow) => { - browserWindow.webContents.on("did-finish-load", () => { - new WindowStateHandler(browserWindow).bind(); - }); - await winHandler.load(); }); diff --git a/main/menu.js b/main/menu.js index f45e34f..98243ad 100644 --- a/main/menu.js +++ b/main/menu.js @@ -1,12 +1,34 @@ -import {app, shell, Menu} from "electron"; +import {app, ipcMain, shell, Menu} from "electron"; import {__DARWIN__} from "./platform.js"; import {checkForUpdates} from "./updater.js"; +import BrowserEventHandler from "./BrowserEventHandler.js"; +import winHandler from "./mainWindow.js"; +import {windowForEvent} from "./desktop.js"; +import {setWindowAppearance} from "./windowIntegrations.js"; const updateMenuItem = { label: "Check for updates...", click: () => checkForUpdates({notifyIfCurrent: true}), }; +function command(id, label, accelerator) { + return { + id, + label, + accelerator, + enabled: false, + click: () => { + const window = winHandler.browserWindow; + + if (window) { + window.show(); + window.focus(); + BrowserEventHandler.send(window, "desktop-command", id); + } + }, + }; +} + const template = [ ...(__DARWIN__ ? [ @@ -16,6 +38,8 @@ const template = [ {role: "about", label: "About Showcode"}, updateMenuItem, {type: "separator"}, + command("preferences", "Preferences…", "CommandOrControl+,"), + {type: "separator"}, {role: "services"}, {type: "separator"}, {role: "hide"}, @@ -28,8 +52,43 @@ const template = [ ] : []), { + id: "file", label: "File", - submenu: [__DARWIN__ ? {role: "close"} : {role: "quit"}], + submenu: [ + command("new-project", "New Project", "CommandOrControl+T"), + command("open-saved-projects-modal", "Open Saved Project…", "CommandOrControl+O"), + {id: "recent-projects", label: "Open Recent", submenu: []}, + command("open-templates-modal", "Open Saved Templates…"), + command("import-config", "Import Configuration…", "CommandOrControl+Shift+O"), + {type: "separator"}, + command("save-project", "Save", "CommandOrControl+S"), + command("save-project-as", "Save As…", "CommandOrControl+Shift+S"), + command("save-as-template", "Save As Template"), + {type: "separator"}, + { + id: "export-image", + label: "Export Image", + submenu: [ + command("export-png", "PNG…", "CommandOrControl+Shift+E"), + command("export-jpg", "JPEG…"), + command("export-svg", "SVG…"), + ], + }, + command("copy-image", "Copy Image", "CommandOrControl+Shift+C"), + command("export-config", "Export JSON Configuration…"), + command("export-json", "Export JSON (API Request)…"), + {type: "separator"}, + command("close-project", "Close Tab", "CommandOrControl+W"), + command("reopen-closed-project", "Reopen Closed Project", "CommandOrControl+Shift+T"), + {type: "separator"}, + ...(__DARWIN__ + ? [{role: "close", accelerator: "CommandOrControl+Shift+W"}] + : [ + command("preferences", "Preferences…", "CommandOrControl+,"), + {type: "separator"}, + {role: "quit"}, + ]), + ], }, { label: "Edit", @@ -52,6 +111,8 @@ const template = [ }, ] : [{role: "delete"}, {type: "separator"}, {role: "selectAll"}]), + {type: "separator"}, + {id: "emoji", label: "Emoji & Symbols", click: () => app.showEmojiPanel()}, ], }, { @@ -71,6 +132,9 @@ const template = [ { label: "Window", submenu: [ + command("next-project", "Next Tab", "Control+Tab"), + command("previous-project", "Previous Tab", "Control+Shift+Tab"), + {type: "separator"}, {role: "minimize"}, {role: "zoom"}, ...(__DARWIN__ @@ -81,7 +145,17 @@ const template = [ { role: "help", submenu: [ + command("help", "Showcode Help"), + command("updates", "What's New"), + command("changelog", "Full Changelog"), + {type: "separator"}, ...(__DARWIN__ ? [] : [updateMenuItem, {type: "separator"}]), + { + label: "API Documentation", + click: async () => { + await shell.openExternal("https://api.showcode.app/docs"); + }, + }, { label: "GitHub Issues", click: async () => { @@ -107,6 +181,78 @@ const template = [ }, ]; -const menu = Menu.buildFromTemplate(template); +let menu; + +const projectCommands = [ + "save-project", + "save-project-as", + "save-as-template", + "export-image", + "export-png", + "export-jpg", + "export-svg", + "copy-image", + "export-config", + "export-json", +]; + +const applicationCommands = [ + "new-project", + "open-saved-projects-modal", + "open-templates-modal", + "import-config", + "preferences", + "help", + "updates", + "changelog", + "close-project", +]; + +ipcMain.on("set-menu-state", (event, state) => { + const window = windowForEvent(event); + const recent = template + .find((item) => item.id === "file") + .submenu.find((item) => item.id === "recent-projects"); + + recent.enabled = state.recentProjects.length > 0; + recent.submenu = state.recentProjects.map(({id, name}) => ({ + ...command(`open-recent-${id}`, name || "Untitled Project"), + enabled: true, + })); + + // Electron requires a new menu when its structure changes. + menu = Menu.buildFromTemplate(template); + + for (const id of applicationCommands) { + menu.getMenuItemById(id).enabled = true; + } + + for (const id of projectCommands) { + menu.getMenuItemById(id).enabled = state.hasProject; + } + + menu.getMenuItemById("reopen-closed-project").enabled = state.canReopen; + menu.getMenuItemById("next-project").enabled = state.canSwitch; + menu.getMenuItemById("previous-project").enabled = state.canSwitch; + + menu.getMenuItemById("emoji").enabled = app.isEmojiPanelSupported(); + Menu.setApplicationMenu(menu); + + if (__DARWIN__) { + window.setDocumentEdited(state.modified); + } +}); + +ipcMain.handle("show-file-menu", (event) => { + menu.getMenuItemById("file").submenu.popup({window: windowForEvent(event)}); +}); + +ipcMain.on("set-window-appearance", (event, theme) => { + setWindowAppearance(windowForEvent(event), theme === "dark"); +}); -Menu.setApplicationMenu(menu); +app.whenReady().then(() => { + menu = Menu.buildFromTemplate(template); + Menu.setApplicationMenu(menu); + menu.getMenuItemById("emoji").enabled = app.isEmojiPanelSupported(); +}); diff --git a/main/preload.cjs b/main/preload.cjs index ddb4000..215a103 100644 --- a/main/preload.cjs +++ b/main/preload.cjs @@ -1,10 +1,35 @@ const {contextBridge, ipcRenderer} = require("electron"); -const validSendChannels = ["minimize", "maximize", "unmaximize", "close", "double-click-title-bar"]; +const validSendChannels = [ + "minimize", + "maximize", + "unmaximize", + "close", + "double-click-title-bar", + "set-menu-state", + "set-window-appearance", +]; -const validInvokeChannels = ["get-system-fonts", "get-window-state"]; +const validInvokeChannels = [ + "get-system-fonts", + "get-window-state", + "get-update-state", + "get-release-notes-state", + "acknowledge-release-notes", + "install-update", + "open-file", + "save-file", + "copy-image", + "confirm-action", + "confirm-close-project", + "show-tab-menu", + "show-export-menu", + "show-file-menu", +]; -const validReceiveChannels = ["window-state-changed"]; +const validReceiveChannels = ["window-state-changed", "update-state-changed", "desktop-command"]; + +const listeners = new Map(); contextBridge.exposeInMainWorld("electronIpc", { send: (channel, ...args) => { @@ -20,12 +45,26 @@ contextBridge.exposeInMainWorld("electronIpc", { }, addListener: (channel, listener) => { if (validReceiveChannels.includes(channel)) { - ipcRenderer.addListener(channel, listener); + const wrapped = (_event, ...args) => { + listener(null, ...args); + }; + + if (!listeners.has(channel)) { + listeners.set(channel, new Map()); + } + + listeners.get(channel).set(listener, wrapped); + ipcRenderer.addListener(channel, wrapped); } }, removeListener: (channel, listener) => { if (validReceiveChannels.includes(channel)) { - ipcRenderer.removeListener(channel, listener); + const wrapped = listeners.get(channel)?.get(listener); + + if (wrapped) { + ipcRenderer.removeListener(channel, wrapped); + listeners.get(channel).delete(listener); + } } }, }); diff --git a/main/releaseNotes.js b/main/releaseNotes.js new file mode 100644 index 0000000..7c5f653 --- /dev/null +++ b/main/releaseNotes.js @@ -0,0 +1,43 @@ +import {randomUUID} from "node:crypto"; +import {readFile, rename, writeFile} from "node:fs/promises"; +import path from "node:path"; +import {app} from "electron"; + +function statePath() { + return path.join(app.getPath("userData"), "release-notes.json"); +} + +export async function getReleaseNotesState() { + let state = {seenReleases: [], showAfterUpdate: true}; + + try { + state = {...state, ...JSON.parse(await readFile(statePath(), "utf8"))}; + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + + return {...state, version: app.getVersion()}; +} + +export async function acknowledgeReleaseNotes(releaseIds, showAfterUpdate) { + if ( + !Array.isArray(releaseIds) || + !releaseIds.every((id) => typeof id === "string") || + typeof showAfterUpdate !== "boolean" + ) { + throw new TypeError("Release IDs and an update preference are required."); + } + + const state = await getReleaseNotesState(); + const filename = statePath(); + const temporaryFile = `${filename}.${randomUUID()}.tmp`; + + await writeFile( + temporaryFile, + JSON.stringify({ + seenReleases: [...new Set([...state.seenReleases, ...releaseIds])], + showAfterUpdate, + }), + ); + await rename(temporaryFile, filename); +} diff --git a/main/updater.js b/main/updater.js index 355d68b..b6e6995 100644 --- a/main/updater.js +++ b/main/updater.js @@ -1,7 +1,8 @@ import electronUpdater from "electron-updater"; -import {app, dialog, powerMonitor} from "electron"; +import {app, dialog, ipcMain, powerMonitor} from "electron"; import log from "electron-log"; import winHandler from "./mainWindow.js"; +import BrowserEventHandler from "./BrowserEventHandler.js"; const {autoUpdater} = electronUpdater; const startupDelay = 10 * 1000; @@ -11,6 +12,7 @@ let timer; let checkingForUpdates = false; let userInitiatedCheck = false; let updateReady = false; +let updateState = null; autoUpdater.logger = log; autoUpdater.logger.transports.file.level = app.isPackaged ? "info" : "debug"; @@ -22,6 +24,28 @@ if (!app.isPackaged) { autoUpdater.forceDevUpdateConfig = true; } +function setUpdateState(state) { + updateState = state; + + if (winHandler.browserWindow) { + BrowserEventHandler.send(winHandler.browserWindow, "update-state-changed", state); + } +} + +function installUpdate() { + winHandler.quitting = true; + autoUpdater.quitAndInstall(); +} + +ipcMain.handle("get-update-state", () => updateState); +ipcMain.handle("install-update", async () => { + if (updateReady) { + installUpdate(); + } else { + await checkForUpdates({notifyIfCurrent: true}); + } +}); + async function promptToInstall() { const {response} = await dialog.showMessageBox({ type: "info", @@ -33,8 +57,7 @@ async function promptToInstall() { if (response === 0) { // Allow the updater to close the window instead of hiding it on macOS. - winHandler.quitting = true; - autoUpdater.quitAndInstall(); + installUpdate(); } } @@ -72,12 +95,16 @@ export async function checkForUpdates({notifyIfCurrent = false} = {}) { } autoUpdater.on("update-not-available", () => { + setUpdateState(null); + if (userInitiatedCheck) { void dialog.showMessageBox({message: "You are running the latest version."}); } }); -autoUpdater.on("update-available", () => { +autoUpdater.on("update-available", (info) => { + setUpdateState({status: "downloading", version: info?.version, percent: 0}); + if (userInitiatedCheck) { void dialog.showMessageBox({message: "A new update is available! Downloading now..."}); } @@ -85,16 +112,19 @@ autoUpdater.on("update-available", () => { autoUpdater.on("download-progress", ({percent}) => { winHandler.browserWindow?.setProgressBar(percent / 100); + setUpdateState({status: "downloading", percent: Math.round(percent)}); }); autoUpdater.on("update-downloaded", () => { updateReady = true; winHandler.browserWindow?.setProgressBar(-1); + setUpdateState({status: "downloaded"}); void promptToInstall(); }); autoUpdater.on("error", () => { winHandler.browserWindow?.setProgressBar(-1); + setUpdateState(null); }); function scheduleCheck(delay) { diff --git a/main/windowIntegrations.js b/main/windowIntegrations.js new file mode 100644 index 0000000..9598c8c --- /dev/null +++ b/main/windowIntegrations.js @@ -0,0 +1,78 @@ +import {Menu, nativeTheme, shell, systemPreferences} from "electron"; +import {__DARWIN__, __WINDOWS__} from "./platform.js"; + +export function openExternal(url) { + if (["https:", "http:", "mailto:"].includes(new URL(url).protocol)) { + return shell.openExternal(url); + } +} + +export function doubleClickTitleBar(window) { + const action = __DARWIN__ + ? systemPreferences.getUserDefault("AppleActionOnDoubleClick", "string") + : "Maximize"; + + if (action === "Minimize") { + window.minimize(); + } else if (action !== "None") { + window.isMaximized() ? window.unmaximize() : window.maximize(); + } +} + +export function setWindowAppearance(window, dark) { + if (__WINDOWS__) { + window.setTitleBarOverlay({ + color: dark ? "#18181b" : "#f4f4f5", + symbolColor: dark ? "#fafafa" : "#18181b", + height: 28, + }); + } +} + +export default function (window) { + const {webContents} = window; + + webContents.setWindowOpenHandler(({url}) => { + void openExternal(url); + + return {action: "deny"}; + }); + + webContents.on("will-navigate", (event, url) => { + const current = new URL(webContents.getURL()); + const destination = new URL(url); + + if (current.protocol === destination.protocol && current.host === destination.host) { + return; + } + + event.preventDefault(); + void openExternal(url); + }); + + webContents.on("context-menu", (event, params) => { + // Monaco supplies its own language-aware editor menu. + if (!params.isEditable || params.formControlType === "input-password") { + return; + } + + const {editFlags} = params; + + Menu.buildFromTemplate([ + {role: "undo", enabled: editFlags.canUndo}, + {role: "redo", enabled: editFlags.canRedo}, + {type: "separator"}, + {role: "cut", enabled: editFlags.canCut}, + {role: "copy", enabled: editFlags.canCopy}, + {role: "paste", enabled: editFlags.canPaste}, + {type: "separator"}, + {role: "selectAll", enabled: editFlags.canSelectAll}, + ]).popup({window}); + }); + + const updateAppearance = () => setWindowAppearance(window, nativeTheme.shouldUseDarkColors); + + updateAppearance(); + nativeTheme.on("updated", updateAppearance); + window.once("closed", () => nativeTheme.removeListener("updated", updateAppearance)); +} diff --git a/package-lock.json b/package-lock.json index bfbd285..63c245b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "showcode-app", - "version": "2.0.20", + "version": "3.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "showcode-app", - "version": "2.0.20", + "version": "3.0.0", "license": "MIT", "dependencies": { "electron-log": "^5.4.3", diff --git a/package.json b/package.json index ba4220e..15401bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "showcode-app", - "version": "2.0.20", + "version": "3.0.0", "description": "Create beautiful code screenshots.", "keywords": [], "homepage": "https://github.com/stevebauman/showcode-app", diff --git a/showcode b/showcode index 2a9e69b..0f4beb8 160000 --- a/showcode +++ b/showcode @@ -1 +1 @@ -Subproject commit 2a9e69b42b0fb9526b8dc85768e79e0fd7cb3869 +Subproject commit 0f4beb8d780c734906b680fadb1cf49486cc04c8 diff --git a/tests/desktop.test.js b/tests/desktop.test.js new file mode 100644 index 0000000..29f0882 --- /dev/null +++ b/tests/desktop.test.js @@ -0,0 +1,214 @@ +import assert from "node:assert/strict"; +import {EventEmitter} from "node:events"; +import {mkdtemp, readFile, rm, writeFile} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import {after, beforeEach, mock, test} from "node:test"; + +const handlers = new Map(); +const window = {}; +const sender = {mainFrame: {}}; +const event = {sender, senderFrame: sender.mainFrame}; +const dialog = {showOpenDialog: mock.fn(), showSaveDialog: mock.fn(), showMessageBox: mock.fn()}; +const clipboard = {writeImage: mock.fn()}; +const shell = {openExternal: mock.fn()}; +const menus = []; +const nativeTheme = new EventEmitter(); + +mock.module("electron", { + namedExports: { + app: {}, + BrowserWindow: {fromWebContents: (contents) => (contents === sender ? window : null)}, + ipcMain: {handle: (channel, callback) => handlers.set(channel, callback)}, + dialog, + clipboard, + nativeImage: {createFromBuffer: (buffer) => ({buffer, isEmpty: () => buffer.length === 0})}, + Menu: { + buildFromTemplate: (items) => { + const menu = {items, popup: mock.fn()}; + menus.push(menu); + return menu; + }, + }, + nativeTheme, + shell, + systemPreferences: {getUserDefault: () => "None"}, + }, +}); + +const {windowForEvent} = await import("../main/desktop.js"); +const { + default: integrateWindow, + openExternal, + doubleClickTitleBar, +} = await import("../main/windowIntegrations.js"); +const directory = await mkdtemp(path.join(os.tmpdir(), "showcode-desktop-test-")); + +after(() => rm(directory, {recursive: true, force: true})); +beforeEach(() => { + for (const method of Object.values(dialog)) method.mock.resetCalls(); + clipboard.writeImage.mock.resetCalls(); + shell.openExternal.mock.resetCalls(); + menus.length = 0; +}); + +test("file access rejects child frames and unknown windows", () => { + assert.throws(() => windowForEvent({...event, senderFrame: {}})); + assert.throws(() => windowForEvent({...event, sender: {}})); + assert.equal(windowForEvent(event), window); +}); + +test("release note preferences reject requests outside the application frame", () => { + assert.throws(() => handlers.get("get-release-notes-state")({...event, senderFrame: {}})); + assert.throws(() => + handlers.get("acknowledge-release-notes")( + {...event, sender: {}}, + {releaseIds: ["workspace-refresh"], showAfterUpdate: true}, + ), + ); +}); + +test("cancelling file dialogs does not read or overwrite files", async () => { + dialog.showOpenDialog.mock.mockImplementation(async () => ({canceled: true, filePaths: []})); + dialog.showSaveDialog.mock.mockImplementation(async () => ({canceled: true})); + + assert.equal(await handlers.get("open-file")(event, "project"), null); + assert.equal( + await handlers.get("save-file")(event, { + name: "project.json", + data: new Uint8Array([1]), + extension: "json", + }), + false, + ); +}); + +test("exports write exact binary data only to the path selected in the save dialog", async () => { + const filePath = path.join(directory, "export.png"); + const data = new Uint8Array([137, 80, 78, 71, 0, 255]); + dialog.showSaveDialog.mock.mockImplementation(async () => ({canceled: false, filePath})); + + assert.equal( + await handlers.get("save-file")(event, {name: "../../export.png", data, extension: "png"}), + true, + ); + assert.deepEqual(await readFile(filePath), Buffer.from(data)); + assert.equal(dialog.showSaveDialog.mock.calls[0].arguments[0], window); + assert.equal(dialog.showSaveDialog.mock.calls[0].arguments[1].defaultPath, "export.png"); +}); + +test("imports return the selected file contents without exposing filesystem paths", async () => { + const filePath = path.join(directory, "project.json"); + await writeFile(filePath, '{"tab":{"name":"Example"}}'); + dialog.showOpenDialog.mock.mockImplementation(async () => ({ + canceled: false, + filePaths: [filePath], + })); + + const file = await handlers.get("open-file")(event, "project"); + + assert.equal(file.name, "project.json"); + assert.equal(file.data.toString(), '{"tab":{"name":"Example"}}'); + assert.deepEqual(Object.keys(file), ["name", "data"]); +}); + +test("unsupported file operations are rejected before opening a dialog", async () => { + await assert.rejects(handlers.get("open-file")(event, "directory")); + await assert.rejects( + handlers.get("save-file")(event, { + name: "script.sh", + data: new Uint8Array(), + extension: "sh", + }), + ); + assert.equal(dialog.showOpenDialog.mock.callCount(), 0); + assert.equal(dialog.showSaveDialog.mock.callCount(), 0); +}); + +test("clipboard writes reject empty image data", () => { + assert.throws(() => handlers.get("copy-image")(event, new Uint8Array())); + assert.equal(clipboard.writeImage.mock.callCount(), 0); + + handlers.get("copy-image")(event, new Uint8Array([1, 2, 3])); + assert.deepEqual( + clipboard.writeImage.mock.calls[0].arguments[0].buffer, + Buffer.from([1, 2, 3]), + ); +}); + +test("destructive dialogs default to cancel and distinguish save, discard, and cancel", async () => { + dialog.showMessageBox.mock.mockImplementation(async () => ({response: 0})); + assert.equal(await handlers.get("confirm-action")(event, {message: "Delete?"}), false); + assert.equal(dialog.showMessageBox.mock.calls[0].arguments[1].defaultId, 0); + assert.equal(dialog.showMessageBox.mock.calls[0].arguments[1].cancelId, 0); + + for (const [response, action] of [ + [0, "save"], + [1, "cancel"], + [2, "discard"], + ]) { + dialog.showMessageBox.mock.mockImplementation(async () => ({response})); + assert.equal(await handlers.get("confirm-close-project")(event, "Example"), action); + } +}); + +test("dismissing a native popup returns no action", async () => { + const result = handlers.get("show-export-menu")(event); + menus[0].popup.mock.calls[0].arguments[0].callback(); + + assert.equal(await result, null); +}); + +test("native popup selections resolve to the selected action", async () => { + const result = handlers.get("show-export-menu")(event); + menus[0].items[1].click(); + menus[0].popup.mock.calls[0].arguments[0].callback(); + + assert.equal(await result, "toJpeg"); +}); + +test("external links only launch the browser or mail client for supported protocols", () => { + openExternal("https://showcode.app"); + openExternal("mailto:example@example.com"); + openExternal("file:///tmp/example"); + openExternal("javascript:alert(1)"); + + assert.equal(shell.openExternal.mock.callCount(), 2); +}); + +test("navigation retains internal routes and opens external pages outside the app", () => { + const webContents = new EventEmitter(); + webContents.getURL = () => "app://-/index.html"; + webContents.setWindowOpenHandler = mock.fn(); + const browserWindow = new EventEmitter(); + browserWindow.webContents = webContents; + integrateWindow(browserWindow); + + const internal = {preventDefault: mock.fn()}; + webContents.emit("will-navigate", internal, "app://-/generator"); + assert.equal(internal.preventDefault.mock.callCount(), 0); + + const external = {preventDefault: mock.fn()}; + webContents.emit("will-navigate", external, "https://showcode.app"); + assert.equal(external.preventDefault.mock.callCount(), 1); + assert.equal(shell.openExternal.mock.callCount(), 1); + + assert.deepEqual( + webContents.setWindowOpenHandler.mock.calls[0].arguments[0]({url: "https://showcode.app"}), + {action: "deny"}, + ); + + const listenerCount = nativeTheme.listenerCount("updated"); + browserWindow.emit("closed"); + assert.equal(nativeTheme.listenerCount("updated"), listenerCount - 1); +}); + +test( + "macOS titlebar double-click respects the system's do-nothing preference", + { + skip: process.platform !== "darwin", + }, + () => { + doubleClickTitleBar({}); + }, +); diff --git a/tests/menu.test.js b/tests/menu.test.js index fe38e93..11c9302 100644 --- a/tests/menu.test.js +++ b/tests/menu.test.js @@ -3,14 +3,16 @@ import {mock, test} from "node:test"; const checkForUpdates = mock.fn(); let template; +const app = {name: "Showcode", whenReady: async () => {}, isEmojiPanelSupported: () => false}; mock.module("electron", { namedExports: { - app: {name: "Showcode"}, + app, + ipcMain: {on: () => {}, handle: () => {}}, shell: {}, Menu: { buildFromTemplate: (items) => { template = items; - return {}; + return {getMenuItemById: () => ({})}; }, setApplicationMenu: () => {}, }, @@ -18,6 +20,10 @@ mock.module("electron", { }); mock.module("../main/platform.js", {namedExports: {__DARWIN__: false}}); mock.module("../main/updater.js", {namedExports: {checkForUpdates}}); +mock.module("../main/mainWindow.js", {defaultExport: {}}); +mock.module("../main/BrowserEventHandler.js", {defaultExport: {send: () => {}}}); +mock.module("../main/desktop.js", {namedExports: {windowForEvent: () => {}}}); +mock.module("../main/windowIntegrations.js", {namedExports: {setWindowAppearance: () => {}}}); test("Windows and Linux provide a manual update check in the Help menu", async () => { await import("../main/menu.js"); diff --git a/tests/preload.test.js b/tests/preload.test.js new file mode 100644 index 0000000..861e00a --- /dev/null +++ b/tests/preload.test.js @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import {EventEmitter} from "node:events"; +import {readFileSync} from "node:fs"; +import {test} from "node:test"; +import vm from "node:vm"; + +const source = readFileSync(new URL("../main/preload.cjs", import.meta.url), "utf8"); + +test("the renderer cannot invoke arbitrary IPC channels", async () => { + let bridge; + const sent = []; + vm.runInNewContext(source, { + require: () => ({ + contextBridge: {exposeInMainWorld: (_name, api) => (bridge = api)}, + ipcRenderer: {send: (...args) => sent.push(args)}, + }), + }); + + bridge.send("arbitrary-channel", "payload"); + assert.equal(sent.length, 0); + await assert.rejects(bridge.invoke("arbitrary-channel"), /Invalid invoke channel/); +}); + +test("IPC listeners never expose the privileged event and can be removed per channel", () => { + let bridge; + const ipcRenderer = new EventEmitter(); + vm.runInNewContext(source, { + require: () => ({ + contextBridge: {exposeInMainWorld: (_name, api) => (bridge = api)}, + ipcRenderer, + }), + }); + + const received = []; + const listener = (...args) => received.push(args); + bridge.addListener("desktop-command", listener); + bridge.addListener("window-state-changed", listener); + ipcRenderer.emit("desktop-command", {sender: "privileged"}, "save-project"); + assert.deepEqual(received, [[null, "save-project"]]); + + bridge.removeListener("desktop-command", listener); + bridge.removeListener("window-state-changed", listener); + assert.equal(ipcRenderer.listenerCount("desktop-command"), 0); + assert.equal(ipcRenderer.listenerCount("window-state-changed"), 0); +}); + +test("listener return values stay in the renderer instead of crossing the context bridge", () => { + let bridge; + const ipcRenderer = new EventEmitter(); + vm.runInNewContext(source, { + require: () => ({ + contextBridge: {exposeInMainWorld: (_name, api) => (bridge = api)}, + ipcRenderer, + }), + }); + + bridge.addListener("desktop-command", () => new Proxy({}, {})); + + const [listener] = ipcRenderer.listeners("desktop-command"); + + assert.equal(listener({}, "new-project"), undefined); +}); diff --git a/tests/releaseNotes.test.js b/tests/releaseNotes.test.js new file mode 100644 index 0000000..021c296 --- /dev/null +++ b/tests/releaseNotes.test.js @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import {mkdtemp, readFile, rm} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import {mock, test} from "node:test"; + +const getPath = mock.fn(); +mock.module("electron", { + namedExports: {app: {getPath, getVersion: () => "3.0.0"}}, +}); + +const {getReleaseNotesState, acknowledgeReleaseNotes} = await import("../main/releaseNotes.js"); + +test("a new profile includes the installed version and no acknowledged releases", async (t) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "showcode-release-notes-")); + t.after(() => rm(directory, {recursive: true, force: true})); + getPath.mock.mockImplementation(() => directory); + + assert.deepEqual(await getReleaseNotesState(), { + version: "3.0.0", + seenReleases: [], + showAfterUpdate: true, + }); + assert.deepEqual(getPath.mock.calls.at(-1).arguments, ["userData"]); +}); + +test("acknowledgements preserve earlier releases and the automatic display preference", async (t) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "showcode-release-notes-")); + t.after(() => rm(directory, {recursive: true, force: true})); + getPath.mock.mockImplementation(() => directory); + + await acknowledgeReleaseNotes(["first-release"], true); + await acknowledgeReleaseNotes(["first-release", "workspace-refresh"], false); + + assert.deepEqual(await getReleaseNotesState(), { + version: "3.0.0", + seenReleases: ["first-release", "workspace-refresh"], + showAfterUpdate: false, + }); + assert.deepEqual(JSON.parse(await readFile(path.join(directory, "release-notes.json"))), { + seenReleases: ["first-release", "workspace-refresh"], + showAfterUpdate: false, + }); +}); + +test("invalid acknowledgements leave the saved state intact", async (t) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "showcode-release-notes-")); + t.after(() => rm(directory, {recursive: true, force: true})); + getPath.mock.mockImplementation(() => directory); + await acknowledgeReleaseNotes(["workspace-refresh"], true); + + await assert.rejects(acknowledgeReleaseNotes("workspace-refresh", false), TypeError); + await assert.rejects(acknowledgeReleaseNotes([42], true), TypeError); + await assert.rejects(acknowledgeReleaseNotes([], "false"), TypeError); + assert.equal((await getReleaseNotesState()).showAfterUpdate, true); +}); diff --git a/tests/updater.test.js b/tests/updater.test.js index b943d22..ee9e001 100644 --- a/tests/updater.test.js +++ b/tests/updater.test.js @@ -11,11 +11,20 @@ autoUpdater.quitAndInstall = mock.fn(); const dialog = {showMessageBox: mock.fn()}; const log = {error: mock.fn(), transports: {file: {}}}; const winHandler = {browserWindow: {setProgressBar: mock.fn()}, quitting: false}; - -mock.module("electron", {namedExports: {app, dialog, powerMonitor}}); +const handlers = new Map(); + +mock.module("electron", { + namedExports: { + app, + dialog, + powerMonitor, + ipcMain: {handle: (channel, handler) => handlers.set(channel, handler)}, + }, +}); mock.module("electron-updater", {defaultExport: {autoUpdater}}); mock.module("electron-log", {defaultExport: log}); mock.module("../main/mainWindow.js", {defaultExport: winHandler}); +mock.module("../main/BrowserEventHandler.js", {defaultExport: {send: mock.fn()}}); beforeEach(() => { app.removeAllListeners(); @@ -167,7 +176,9 @@ test("downloaded updates prompt once and only restart when requested", async (t) const {checkForUpdates} = await import("../main/updater.js?install"); autoUpdater.emit("download-progress", {percent: 50}); assert.deepEqual(winHandler.browserWindow.setProgressBar.mock.calls[0].arguments, [0.5]); + assert.deepEqual(handlers.get("get-update-state")(), {status: "downloading", percent: 50}); autoUpdater.emit("update-downloaded"); + assert.deepEqual(handlers.get("get-update-state")(), {status: "downloaded"}); await new Promise(setImmediate); assert.equal(dialog.showMessageBox.mock.callCount(), 1); assert.equal(autoUpdater.quitAndInstall.mock.callCount(), 0); @@ -182,3 +193,17 @@ test("downloaded updates prompt once and only restart when requested", async (t) assert.equal(winHandler.quitting, true); assert.equal(autoUpdater.quitAndInstall.mock.callCount(), 1); }); + +test("the toolbar can install a downloaded update", async (t) => { + t.mock.timers.enable({apis: ["setTimeout"]}); + await import("../main/updater.js?toolbar-install"); + + assert.equal(handlers.get("get-update-state")(), null); + + autoUpdater.emit("update-downloaded"); + await new Promise(setImmediate); + await handlers.get("install-update")(); + + assert.equal(winHandler.quitting, true); + assert.equal(autoUpdater.quitAndInstall.mock.callCount(), 1); +});