### Install Dependencies and Run Development Build Source: https://blackboard.sh/electrobun/llms.txt After initializing a project, install dependencies with 'bun install' and run the development server using 'bun start'. ```bash bun install bun start ``` -------------------------------- ### Initialize New Electrobun Project Source: https://blackboard.sh/electrobun/llms.txt Use 'bunx electrobun init' to start a new project. Specify a template name for a specific project structure. ```bash # Initialize new project bunx electrobun init # Default hello-world template bunx electrobun init photo-booth # Specific template ``` -------------------------------- ### Run Electrobun Development Server Source: https://blackboard.sh/electrobun/llms.txt Start the development server with 'bunx electrobun dev' to build and run your application during development. ```bash # Development build and run bunx electrobun dev ``` -------------------------------- ### Access Build-Time Configuration Source: https://blackboard.sh/electrobun/llms.txt Access build-time configuration settings at runtime, such as the default renderer, available renderers, CEF version, and Bun version. Use `get()` for asynchronous access or `getCached()` for synchronous access after `get()` has been called. ```typescript import { BuildConfig } from "electrobun/bun"; const config = await BuildConfig.get(); // { defaultRenderer, availableRenderers, cefVersion?, bunVersion?, runtime } console.log(config.defaultRenderer); // "native" or "cef" console.log(config.availableRenderers); // ["native"] or ["native", "cef"] console.log(config.runtime?.exitOnLastWindowClosed); console.log(config.runtime?.myCustomSetting); // Synchronous cached access (null if get() hasn't been called yet) const cached = BuildConfig.getCached(); ``` -------------------------------- ### BrowserView Management and RPC Example Source: https://blackboard.sh/electrobun/llms.txt Demonstrates how to manage BrowserViews, define typed RPC, and interact with webview functionalities like loading URLs, executing JavaScript, and handling navigation and download events. ```typescript import { BrowserView } from "electrobun/bun"; // Define typed RPC (supports "*" wildcard message handler) const rpc = BrowserView.defineRPC({ maxRequestTime: 5000, handlers: { requests: { myBunFunction: ({ a, b }) => a + b, }, messages: { "*": (messageName, payload) => { console.log("catch-all", messageName, payload); }, logToBun: ({ msg }) => console.log(msg), }, }, }); // Static methods BrowserView.getAll(); // Get all BrowserViews BrowserView.getById(id); // Get by ID // Call browser functions from Bun const result = await win.webview.rpc.request.someWebviewFunction({ a: 1, b: 2 }); win.webview.rpc.send.sendMessage({ msg: "hello" }); // Built-in RPC: execute JS and get result back const title = await win.webview.rpc.request.evaluateJavascriptWithResponse({ script: "document.title" }); // BrowserView methods win.webview.loadURL("https://example.com"); win.webview.loadHTML("..."); // Takes a string directly, not an object win.webview.executeJavascript('document.title'); win.webview.setPageZoom(1.5); win.webview.getPageZoom(); // WebKit only (macOS) // Navigation rules (evaluated in native code, last matching rule wins) win.webview.setNavigationRules([ "^*", // Block all by default "*://trusted-site.com/*", // Allow trusted site "^http://*", // Block non-HTTPS ]); // Find in page win.webview.findInPage("search text", { forward: true, matchCase: false }); win.webview.stopFindInPage(); // DevTools win.webview.openDevTools(); win.webview.closeDevTools(); win.webview.toggleDevTools(); // Events win.webview.on("will-navigate", (e) => { // e.data: { url, allowed } — allowed reflects navigation rules result }); win.webview.on("did-navigate", (e) => { /* e.data.detail: url */ }); win.webview.on("did-navigate-in-page", (e) => {}); win.webview.on("did-commit-navigation", (e) => {}); win.webview.on("dom-ready", (e) => {}); win.webview.on("new-window-open", (e) => { // e.detail: { url, isCmdClick, modifierFlags?, targetDisposition?, userGesture? } }); // Download events win.webview.on("download-started", (e) => { /* e.detail: { filename, path } */ }); win.webview.on("download-progress", (e) => { /* e.detail: { progress } (0-100) */ }); win.webview.on("download-completed", (e) => { /* e.detail: { filename, path } */ }); win.webview.on("download-failed", (e) => { /* e.detail: { filename, path, error } */ }); ``` -------------------------------- ### Configure Navigation Rules for WebView Source: https://blackboard.sh/electrobun/llms.txt Set navigation rules for a webview to control which URLs can be loaded. This example allows all URLs and specifically permits external sites and their CDNs. ```javascript webview.setNavigationRules([ "^*", "*://external-site.com/*", "*://cdn.external-site.com/*", ]); ``` -------------------------------- ### BrowserView Static Methods Source: https://blackboard.sh/electrobun/llms.txt Provides methods to get all BrowserViews or retrieve a specific one by its ID. ```APIDOC ## BrowserView Static Methods ### Description Methods to manage and retrieve BrowserView instances. ### Methods - `BrowserView.getAll()`: Returns an array of all BrowserView instances. - `BrowserView.getById(id)`: Returns a specific BrowserView instance by its ID. ### Example ```typescript const allViews = BrowserView.getAll(); const viewById = BrowserView.getById('some-id'); ``` ``` -------------------------------- ### Manage Webview Session and Cookies Source: https://blackboard.sh/electrobun/llms.txt Manage cookies and storage data for webview partitions. Use `fromPartition` to get a specific session or `defaultSession` for the main session. Cookies can be retrieved, set, removed, and cleared. ```typescript import { Session } from "electrobun/bun"; // Get session for a partition const session = Session.fromPartition("persist:myapp"); const defaultSession = Session.defaultSession; // Cookies const cookies = session.cookies.get(); // All cookies const filtered = session.cookies.get({ domain: "example.com" }); // Filtered session.cookies.set({ name: "auth_token", value: "abc123", domain: "api.myapp.com", path: "/", secure: true, httpOnly: true, sameSite: "strict", // "no_restriction" | "lax" | "strict" expirationDate: Math.floor(Date.now() / 1000) + 86400, }); session.cookies.remove("https://myapp.com", "auth_token"); session.cookies.clear(); // Clear storage data session.clearStorageData(); // All types session.clearStorageData(['cookies', 'localStorage']); // Specific types // Types: 'cookies' | 'localStorage' | 'sessionStorage' | 'indexedDB' | 'webSQL' | 'cache' | 'all' ``` -------------------------------- ### Get Display and Cursor Information Source: https://blackboard.sh/electrobun/llms.txt Retrieve information about connected displays, including their bounds and work areas, and the current cursor position. Useful for window management and UI positioning. ```typescript import { Screen } from "electrobun/bun"; const primary = Screen.getPrimaryDisplay(); // { id, bounds: { x, y, width, height }, workArea: { x, y, width, height }, scaleFactor, isPrimary } const displays = Screen.getAllDisplays(); // Display[] const cursor = Screen.getCursorScreenPoint(); // { x, y } // Center a window on primary display const x = Math.round((primary.workArea.width - 800) / 2) + primary.workArea.x; const y = Math.round((primary.workArea.height - 600) / 2) + primary.workArea.y; ``` -------------------------------- ### Initialize Electrobun Project Source: https://blackboard.sh/electrobun/llms.txt Use 'bunx electrobun init' to create a new Electrobun project. You can specify a template like 'hello-world' or 'photo-booth'. ```bash bunx electrobun init bunx electrobun init photo-booth ``` -------------------------------- ### Build Electrobun Application for Production Source: https://blackboard.sh/electrobun/llms.txt Generate a production build using 'bunx electrobun build'. Use the '--env' flag to specify build environments like 'canary' or 'stable'. ```bash # Production build bunx electrobun build # Dev build (current platform) bunx electrobun build --env canary # Canary build bunx electrobun build --env stable # Stable build ``` -------------------------------- ### Build Electrobun Application Source: https://blackboard.sh/electrobun/llms.txt Build your Electrobun application for distribution using 'bunx electrobun build'. Use '--env' to specify build environments like 'canary' or 'stable'. ```bash bunx electrobun build bunx electrobun build --env canary bunx electrobun build --env stable ``` -------------------------------- ### Session Source: https://blackboard.sh/electrobun/llms.txt Cookie and storage management for webview partitions. ```APIDOC ## Session ### Description Manages cookies and storage for webview partitions. ### Methods - `fromPartition(partition: string): Session` - `defaultSession: Session` ### Cookie Management - `session.cookies.get(filter?: CookieFilter): Promise` - `session.cookies.set(details: CookieSetDetails): Promise` - `session.cookies.remove(url: string, name: string): Promise` - `session.cookies.clear(): Promise` ### Storage Management - `session.clearStorageData(types?: StorageDataType[]): Promise` ### Storage Data Types `'cookies' | 'localStorage' | 'sessionStorage' | 'indexedDB' | 'webSQL' | 'cache' | 'all'` ``` -------------------------------- ### System Tray Management Source: https://blackboard.sh/electrobun/llms.txt Create and manage system tray icons and menus using the `Tray` class. This includes setting the title, image, menu items with actions, and handling tray click events. ```typescript import { Tray } from "electrobun/bun"; const tray = new Tray({ title: "My App", image: "views://assets/icon-template.png", template: true, // macOS template image (adapts to light/dark mode) width: 22, height: 22, }); tray.setTitle("Updated Title"); tray.setMenu([ { type: "normal", label: "Open", action: "open" }, { type: "divider" }, { type: "normal", label: "Settings", action: "settings", submenu: [ { type: "normal", label: "Preferences", action: "prefs" }, ]}, { type: "normal", label: "Quit", action: "quit" }, ]); tray.setImage("views://assets/new-icon.png"); tray.setVisible(false); // Hide tray icon tray.setVisible(true); // Show tray icon tray.getBounds(); // { x, y, width, height } tray.remove(); // Permanently remove tray.on("tray-clicked", (e) => { // action is "" for icon click, or the menu item action name console.log("Tray clicked:", e.data.action); if (e.data.action === "quit") Utils.quit(); }); ``` -------------------------------- ### Bun-side RPC Implementation Source: https://blackboard.sh/electrobun/llms.txt Sets up the RPC handlers on the Bun side for handling requests and messages from the browser. It also shows how to initiate calls to the browser. ```typescript // src/bun/index.ts - Bun side import { BrowserView, BrowserWindow } from "electrobun/bun"; import type { MyRPCType } from "../shared/types"; const rpc = BrowserView.defineRPC({ handlers: { requests: { addNumbers: ({ a, b }) => a + b, }, messages: { logToBun: ({ msg }) => console.log("Browser says:", msg), }, }, }); const win = new BrowserWindow({ url: "views://main/index.html", rpc }); // Call browser function const title = await win.webview.rpc.request.getDocumentTitle({}); ``` -------------------------------- ### Electrobun Import Patterns Source: https://blackboard.sh/electrobun/llms.txt Import necessary modules for the main process using 'electrobun/bun' and for browser contexts using 'electrobun/view'. ```typescript // Main process (Bun) - use electrobun/bun import Electrobun from "electrobun/bun"; import { BrowserWindow, BrowserView, Tray, ContextMenu, ApplicationMenu, Updater, Utils, GlobalShortcut, Screen, Session, BuildConfig, PATHS } from "electrobun/bun"; // Browser context - use electrobun/view import { Electroview } from "electrobun/view"; ``` -------------------------------- ### BuildConfig Source: https://blackboard.sh/electrobun/llms.txt Access build-time configuration at runtime. ```APIDOC ## BuildConfig ### Description Allows access to build-time configuration settings during runtime. ### Methods - `get(): Promise` - `getCached(): BuildConfig | null` ### BuildConfig Object Structure `{ defaultRenderer, availableRenderers, cefVersion?, bunVersion?, runtime }` ### Runtime Object Structure (Optional) `{ exitOnLastWindowClosed, myCustomSetting, ... }` ``` -------------------------------- ### Context Menu Creation Source: https://blackboard.sh/electrobun/llms.txt Display custom context menus using `ContextMenu.showContextMenu` with roles, labels, actions, tooltips, and accelerators. Listen for clicks via `Electrobun.events.on('context-menu-clicked')`. ```typescript import { ContextMenu } from "electrobun/bun"; import Electrobun from "electrobun/bun"; ContextMenu.showContextMenu([ { role: "undo" }, { role: "redo" }, { type: "separator" }, { label: "Custom Item", action: "custom-1", tooltip: "Do something", accelerator: "s" }, { label: "With Data", action: "custom-2", data: { key: "value" } }, { label: "Disabled Item", action: "custom-3", enabled: false }, { type: "separator" }, { role: "cut" }, { role: "copy" }, { role: "paste" }, { role: "selectAll" }, ]); Electrobun.events.on("context-menu-clicked", (e) => { console.log("Clicked:", e.data.action); }); ``` -------------------------------- ### BrowserView Instance Methods Source: https://blackboard.sh/electrobun/llms.txt Methods for controlling a specific BrowserView instance, such as loading URLs, executing JavaScript, and managing zoom levels. ```APIDOC ## BrowserView Instance Methods ### Description Control and interact with individual BrowserView instances. ### Methods - `win.webview.loadURL(url)`: Loads the specified URL in the webview. - `win.webview.loadHTML(html)`: Loads the specified HTML string in the webview. - `win.webview.executeJavascript(script)`: Executes the given JavaScript code in the webview. - `win.webview.setPageZoom(zoom)`: Sets the page zoom level (WebKit only). - `win.webview.getPageZoom()`: Gets the current page zoom level (WebKit only). - `win.webview.setNavigationRules(rules)`: Sets navigation rules to control URL loading. - `win.webview.findInPage(text, options)`: Finds text within the page. - `win.webview.stopFindInPage()`: Stops the current find operation. - `win.webview.openDevTools()`: Opens the developer tools. - `win.webview.closeDevTools()`: Closes the developer tools. - `win.webview.toggleDevTools()`: Toggles the developer tools. ### Example ```typescript win.webview.loadURL('https://example.com'); win.webview.executeJavascript('console.log("Hello")'); win.webview.setNavigationRules(['^*', '*://trusted.com/*']); ``` ``` -------------------------------- ### BrowserWindow API Source: https://blackboard.sh/electrobun/llms.txt This section details the creation and methods of the BrowserWindow class, allowing for the management of application windows. ```APIDOC ## BrowserWindow Create and control browser windows. ### Constructor ```typescript new BrowserWindow(options: { title?: string; url?: string; html?: string; frame?: { width: number; height: number; x: number; y: number }; titleBarStyle?: "default" | "hidden" | "hiddenInset"; transparent?: boolean; passthrough?: boolean; styleMask?: { Titled?: boolean; Closable?: boolean; Resizable?: boolean; Miniaturizable?: boolean; Borderless?: boolean; FullSizeContentView?: boolean; FullScreen?: boolean; UnifiedTitleAndToolbar?: boolean; UtilityWindow?: boolean; }; preload?: string; rpc?: any; // Replace 'any' with the actual RPC handler type if known sandbox?: boolean; renderer?: "native" | "cef"; navigationRules?: string | null; }); ``` ### Methods - **setTitle(title: string): void** Sets the title of the browser window. - **close(): void** Closes the browser window. - **focus(): void** Brings the browser window to the front and gives it focus. - **minimize(): void** Minimizes the browser window. - **unminimize(): void** Restores the browser window from a minimized state. - **isMinimized(): boolean** Returns `true` if the window is minimized, `false` otherwise. - **maximize(): void** Maximizes the browser window. - **unmaximize(): void** Restores the browser window from a maximized state. - **isMaximized(): boolean** Returns `true` if the window is maximized, `false` otherwise. - **setFullScreen(fullscreen: boolean): void** Sets the full-screen state of the browser window. - **isFullScreen(): boolean** Returns `true` if the window is in full-screen mode, `false` otherwise. - **setAlwaysOnTop(alwaysOnTop: boolean): void** Sets whether the window should always be on top of other windows. - **isAlwaysOnTop(): boolean** Returns `true` if the window is always on top, `false` otherwise. - **setPosition(x: number, y: number): void** Sets the position of the browser window. - **setSize(width: number, height: number): void** Sets the size of the browser window. - **setFrame(x: number, y: number, width: number, height: number): void** Sets the position and size of the browser window. - **getFrame(): { x: number; y: number; width: number; height: number }** Returns the current frame (position and size) of the browser window. - **getPosition(): { x: number; y: number }** Returns the current position of the browser window. - **getSize(): { width: number; height: number }** Returns the current size of the browser window. - **setVisibleOnAllWorkspaces(visible: boolean): void** (macOS only) Sets whether the window is visible on all workspaces. - **isVisibleOnAllWorkspaces(): boolean** (macOS only) Returns `true` if the window is visible on all workspaces, `false` otherwise. - **setPageZoom(zoom: number): void** (WebKit only on macOS) Sets the page zoom level. - **getPageZoom(): number** (WebKit only on macOS) Returns the current page zoom level. Returns 1.0 on other platforms. - **show(): void** Makes the browser window visible. ### Events - **close**: Fired when the window is about to close. Event handlers for the window close before global handlers. - `e.data.id`: The ID of the window. - **resize**: Fired when the window is resized. - `e.data`: An object containing `{ id, x, y, width, height }`. - **move**: Fired when the window is moved. - `e.data`: An object containing `{ id, x, y }`. - **focus**: Fired when the window gains focus. - `e.data.id`: The ID of the window. - **blur**: Fired when the window loses focus. - `e.data.id`: The ID of the window. ### Accessing Webview - **win.webview.loadURL(url: string): void** Loads a URL in the window's default webview. ``` -------------------------------- ### PATHS Source: https://blackboard.sh/electrobun/llms.txt Global paths for accessing bundled resources. ```APIDOC ## PATHS ### Description Provides global paths for accessing bundled resources within the application. ### Properties - `PATHS.RESOURCES_FOLDER`: Path to static bundled resources. Do not write here as it affects code signing. - `PATHS.VIEWS_FOLDER`: Path to the views folder, typically `RESOURCES_FOLDER + '/app/views/'`, which maps to the `views://` scheme. ``` -------------------------------- ### Application Menu Source: https://blackboard.sh/electrobun/llms.txt Defines and manages the application's menu bar. Supports custom menus and standard roles. Note: Not supported on Linux. ```APIDOC ## ApplicationMenu.setApplicationMenu ### Description Sets the entire application menu structure. This is typically called once during application initialization. ### Parameters - `menuItems` (Array): An array of menu items to define the application's menu bar. ### MenuItem Properties - `label` (string): The text displayed for the menu item. - `submenu` (Array): A nested array of menu items for a dropdown submenu. - `action` (string): A custom action identifier for menu items. - `role` (string): Predefined roles for standard menu items (e.g., "quit", "undo"). - `type` (string): "separator" to add a visual separator line. - `accelerator` (string): Keyboard shortcut for the menu item. - `enabled` (boolean): Whether the menu item is enabled. - `checked` (boolean): Whether the menu item is checked (for toggles). - `hidden` (boolean): Whether the menu item is hidden. - `tooltip` (string): Tooltip text for the menu item. ### Event Handling Listens for `application-menu-clicked` events to handle user interactions with menu items. ```typescript Electrobun.events.on("application-menu-clicked", (e) => { console.log("Menu action:", e.data.action); }); ``` ``` -------------------------------- ### Create and Control BrowserWindow Source: https://blackboard.sh/electrobun/llms.txt Instantiate and manage application windows using the BrowserWindow class. Configure window properties like title, URL, size, and style. Control window behavior through methods and handle events like close, resize, and focus. ```typescript import { BrowserWindow } from "electrobun/bun"; const win = new BrowserWindow({ title: "My App", url: "views://mainview/index.html", // Use views:// for bundled content html: "...", // Or load HTML string directly frame: { width: 1200, height: 800, x: 100, y: 100 }, titleBarStyle: "default" | "hidden" | "hiddenInset", transparent: false, passthrough: false, // When true, mouse events pass through transparent regions styleMask: { Titled: true, Closable: true, Resizable: true, Miniaturizable: true, Borderless: false, FullSizeContentView: false, FullScreen: false, UnifiedTitleAndToolbar: false, UtilityWindow: false }, preload: "views://mainview/preload.js", rpc: myRpcHandler, // Typed RPC sandbox: false, // true disables RPC, events only (for untrusted content) renderer: "native" | "cef", // Renderer engine (requires CEF bundled for "cef") navigationRules: null, // Navigation rules string or null }); // Methods win.setTitle("New Title"); win.close(); win.focus(); win.minimize(); win.unminimize(); win.isMinimized(); win.maximize(); win.unmaximize(); win.isMaximized(); win.setFullScreen(true); win.isFullScreen(); win.setAlwaysOnTop(true); win.isAlwaysOnTop(); win.setPosition(x, y); win.setSize(width, height); win.setFrame(x, y, width, height); win.getFrame(); // { x, y, width, height } win.getPosition(); // { x, y } win.getSize(); // { width, height } win.setVisibleOnAllWorkspaces(true); win.isVisibleOnAllWorkspaces(); // macOS only win.setPageZoom(1.5); win.getPageZoom(); // WebKit only (macOS), returns 1.0 on other platforms win.show(); // Events (per-window close handlers fire before global handlers) win.on("close", (e) => { /* e.data.id */ }); win.on("resize", (e) => { /* e.data: { id, x, y, width, height } */ }); win.on("move", (e) => { /* e.data: { id, x, y } */ }); win.on("focus", (e) => { /* e.data.id */ }); win.on("blur", (e) => { /* e.data.id */ }); // Access default webview win.webview.loadURL("https://example.com"); ``` -------------------------------- ### Manage Multiple Windows in Electrobun App Source: https://blackboard.sh/electrobun/llms.txt Implement multi-window functionality by creating and managing BrowserWindow instances using a Map to store active windows. Handles window close events to remove them from the map. ```typescript import { BrowserWindow } from "electrobun/bun"; const windows = new Map(); function createWindow() { const win = new BrowserWindow({ url: "views://main/index.html" }); windows.set(win.id, win); win.on("close", (e) => { windows.delete(e.data.id); }); return win; } ``` -------------------------------- ### Electrobun Utility Functions Source: https://blackboard.sh/electrobun/llms.txt Provides utilities for file system operations like moving to trash or revealing in folder, opening external resources, showing notifications, and interacting with file dialogs and message boxes. Also includes functions for managing dock icon visibility on macOS and initiating a graceful quit. ```typescript import { Utils } from "electrobun/bun"; // File system utilities Utils.moveToTrash(absolutePath); // Move to trash/recycle bin Utils.showItemInFolder(absolutePath); // Reveal in Finder/Explorer Utils.openExternal("https://example.com"); // Open URL in default browser (returns boolean) Utils.openPath("/path/to/file.pdf"); // Open file with default app (returns boolean) // Notifications Utils.showNotification({ title: "Reminder", subtitle: "Calendar Event", // Optional body: "Meeting in 15 min", // Optional silent: false, // Optional }); // File dialog const chosenPaths = await Utils.openFileDialog({ startingFolder: "/Users/me/Desktop", allowedFileTypes: "*", // or "png,jpg" canChooseFiles: true, canChooseDirectory: false, allowsMultipleSelection: true, }); // Message box const { response } = await Utils.showMessageBox({ type: "question", // "info" | "warning" | "error" | "question" title: "Confirm Delete", message: "Are you sure?", detail: "This cannot be undone.", buttons: ["Delete", "Cancel"], defaultId: 1, // Focus "Cancel" cancelId: 1, // Escape returns 1 }); // Dock icon visibility (macOS only) Utils.setDockIconVisible(false); // Hide from dock (menu bar / tray-only app) Utils.setDockIconVisible(true); // Show in dock Utils.isDockIconVisible(); // Returns boolean // Graceful quit (fires before-quit event, cancelable) Utils.quit(); ``` -------------------------------- ### GlobalShortcut Source: https://blackboard.sh/electrobun/llms.txt Register global keyboard shortcuts that work even when your app doesn't have focus. ```APIDOC ## GlobalShortcut ### Description Register global keyboard shortcuts that work even when your app doesn't have focus. ### Methods - `register(accelerator: string, callback: Function): boolean` - `unregister(accelerator: string): void` - `unregisterAll(): void` - `isRegistered(accelerator: string): boolean` ### Accelerator Syntax Modifiers: `Command`/`Cmd`, `Control`/`Ctrl`, `CommandOrControl`/`CmdOrCtrl`, `Alt`/`Option`, `Shift`, `Super`/`Meta`/`Win`. Keys: `A`-`Z`, `0`-`9`, `F1`-`F12`, `Space`, `Enter`, `Tab`, `Escape`, `Backspace`, `Delete`, `Up`, `Down`, `Left`, `Right`, `Home`, `End`, `PageUp`, `PageDown`, and symbols. ``` -------------------------------- ### Utils Source: https://blackboard.sh/electrobun/llms.txt Provides various utility functions for interacting with the operating system, such as file system operations, notifications, and dialogs. ```APIDOC ## Utils.moveToTrash ### Description Moves a file or folder to the system's trash or recycle bin. ### Parameters - `absolutePath` (string): The absolute path to the file or folder to move. ### Endpoint `Utils.moveToTrash(absolutePath)` ``` ```APIDOC ## Utils.showItemInFolder ### Description Reveals a file or folder in the system's file browser (Finder on macOS, Explorer on Windows). ### Parameters - `absolutePath` (string): The absolute path to the file or folder to reveal. ### Endpoint `Utils.showItemInFolder(absolutePath)` ``` ```APIDOC ## Utils.openExternal ### Description Opens a URL in the default web browser. ### Parameters - `url` (string): The URL to open. ### Returns - `boolean`: `true` if the URL was opened successfully, `false` otherwise. ### Endpoint `Utils.openExternal(url)` ``` ```APIDOC ## Utils.openPath ### Description Opens a file or directory using the default application associated with its type. ### Parameters - `path` (string): The absolute path to the file or directory to open. ### Returns - `boolean`: `true` if the path was opened successfully, `false` otherwise. ### Endpoint `Utils.openPath(path)` ``` ```APIDOC ## Utils.showNotification ### Description Displays a system notification to the user. ### Parameters - `options` (object): Configuration for the notification. - `title` (string): The main title of the notification. - `subtitle` (string, optional): An optional subtitle for the notification. - `body` (string, optional): The main content of the notification. - `silent` (boolean, optional): If true, the notification will not play a sound. ### Endpoint `Utils.showNotification(options)` ``` ```APIDOC ## Utils.openFileDialog ### Description Opens a file selection dialog, allowing the user to choose files or directories. ### Parameters - `options` (object, optional): Configuration for the file dialog. - `startingFolder` (string, optional): The directory the dialog should open in initially. - `allowedFileTypes` (string, optional): A comma-separated string of file extensions (e.g., "png,jpg") or "*" for all types. - `canChooseFiles` (boolean, optional): Whether the user can select files. - `canChooseDirectory` (boolean, optional): Whether the user can select directories. - `allowsMultipleSelection` (boolean, optional): Whether multiple files/directories can be selected. ### Returns - `Promise`: A promise that resolves with an array of absolute paths to the selected items, or an empty array if canceled. ### Endpoint `await Utils.openFileDialog(options)` ``` ```APIDOC ## Utils.showMessageBox ### Description Displays a modal message box to the user with customizable buttons and options. ### Parameters - `options` (object): Configuration for the message box. - `type` (string): The type of message box ("info", "warning", "error", "question"). - `title` (string): The title of the message box window. - `message` (string): The main message content. - `detail` (string, optional): Additional details to display. - `buttons` (Array): An array of button labels. - `defaultId` (number, optional): The index of the button that should be focused by default. - `cancelId` (number, optional): The index of the button that should be triggered when the user presses Escape. ### Returns - `Promise<{ response: number }>`: A promise that resolves with an object containing the index of the button clicked by the user. ### Endpoint `await Utils.showMessageBox(options)` ``` ```APIDOC ## Utils.setDockIconVisible ### Description Controls the visibility of the application's icon in the macOS Dock. This is macOS-specific. ### Parameters - `visible` (boolean): `true` to show the dock icon, `false` to hide it. ### Endpoint `Utils.setDockIconVisible(visible)` ``` ```APIDOC ## Utils.isDockIconVisible ### Description Checks whether the application's icon is currently visible in the macOS Dock. This is macOS-specific. ### Returns - `boolean`: `true` if the dock icon is visible, `false` otherwise. ### Endpoint `Utils.isDockIconVisible()` ``` ```APIDOC ## Utils.quit ### Description Initiates a graceful application quit process. This triggers the `before-quit` event and can be canceled. ### Endpoint `Utils.quit()` ``` -------------------------------- ### Cross-Compile Electrobun Applications Source: https://blackboard.sh/electrobun/llms.txt Perform cross-compilation for multiple platforms by specifying target architectures with the '--targets' flag. ```bash # Cross-compilation bunx electrobun build --targets macos-arm64,win-x64,linux-x64 ``` -------------------------------- ### Browser-side RPC Implementation Source: https://blackboard.sh/electrobun/llms.txt Implements the RPC handlers on the browser side and demonstrates how to call Bun functions. This enables bidirectional communication. ```typescript // src/views/main/index.ts - Browser side import { Electroview } from "electrobun/view"; import type { MyRPCType } from "../../shared/types"; const rpc = Electroview.defineRPC({ handlers: { requests: { getDocumentTitle: () => document.title, }, messages: { showNotification: ({ text }) => alert(text), }, }, }); const electroview = new Electroview({ rpc }); // Call Bun function const sum = await electroview.rpc.request.addNumbers({ a: 5, b: 3 }); electroview.rpc.send.logToBun({ msg: "Hello from browser" }); ``` -------------------------------- ### Utils.paths Source: https://blackboard.sh/electrobun/llms.txt Provides cross-platform access to common operating system directories and application-specific scoped directories. ```APIDOC ## Utils.paths ### Description An object providing access to various standard OS directories and app-scoped directories. ### OS Directories - `Utils.paths.home`: User's home directory. - `Utils.paths.appData`: Application data directory. - `Utils.paths.config`: Configuration directory. - `Utils.paths.cache`: Cache directory. - `Utils.paths.temp`: Temporary directory. - `Utils.paths.logs`: Log directory. - `Utils.paths.documents`: Documents directory. - `Utils.paths.downloads`: Downloads directory. - `Utils.paths.desktop`: Desktop directory. - `Utils.paths.pictures`: Pictures directory. - `Utils.paths.music`: Music directory. - `Utils.paths.videos`: Videos directory. ### App-Scoped Directories These directories are scoped to the application's identifier and channel. - `Utils.paths.userData`: User data directory specific to the app. - `Utils.paths.userCache`: User cache directory specific to the app. - `Utils.paths.userLogs`: User logs directory specific to the app. Example: `~/Library/Application Support/com.mycompany.myapp/canary` ``` -------------------------------- ### Electrobun Build Configuration Source: https://blackboard.sh/electrobun/llms.txt Configure application settings, runtime behavior, build options, and lifecycle hooks for your Electrobun project. This includes defining entry points, asset copying, ASAR packaging, and platform-specific settings. ```typescript // electrobun.config.ts import type { ElectrobunConfig } from "electrobun"; export default { app: { name: "My App", identifier: "com.mycompany.myapp", version: "1.0.0", urlSchemes: ["myapp"], // Deep linking (macOS only) }, runtime: { exitOnLastWindowClosed: true, myCustomSetting: "hello", // Custom runtime values accessible via BuildConfig }, build: { // Bun process entry point (accepts all Bun.build() options as pass-through) bun: { entrypoint: "src/bun/index.ts", plugins: [], external: [], sourcemap: "none", minify: false, }, // View entry points views: { mainview: { entrypoint: "src/mainview/index.ts", }, }, // Copy static files (destination maps to views:// scheme) copy: { "src/mainview/index.html": "views/mainview/index.html", "src/mainview/index.css": "views/mainview/index.css", }, // ASAR packaging useAsar: false, asarUnpack: ["*.node", "*.dll", "*.dylib", "*.so"], // Watch mode (electrobun dev --watch) watch: ["scripts", "vendor/my-lib"], // Additional paths to watch watchIgnore: ["**/*.generated.*", "data/**"], // Patterns to ignore // Custom Bun version override bunVersion: "1.4.2", // Platform-specific settings mac: { codesign: true, notarize: true, bundleCEF: false, defaultRenderer: "native", // "native" | "cef" icons: "icon.iconset", entitlements: { "com.apple.security.device.camera": "Camera access description", }, chromiumFlags: { "user-agent": "MyApp/1.0", // String value: --user-agent=MyApp/1.0 "show-paint-rects": true, // Boolean true: --show-paint-rects "use-mock-keychain": false, // Boolean false: skip this default flag }, }, linux: { bundleCEF: true, // Strongly recommended for Linux defaultRenderer: "cef", }, win: { bundleCEF: false, defaultRenderer: "native", }, }, // Build lifecycle hooks scripts: { preBuild: "./scripts/pre-build.ts", postBuild: "./scripts/post-build.ts", postWrap: "./scripts/post-wrap.ts", // After self-extracting bundle, before signing postPackage: "./scripts/post-package.ts", }, // Distribution release: { baseUrl: "https://your-bucket.com/updates", // NOTE: was "bucketUrl" before v1 }, } satisfies ElectrobunConfig; ``` -------------------------------- ### Cross-Compile Electrobun Application Source: https://blackboard.sh/electrobun/llms.txt Cross-compile your Electrobun application for various targets using 'bunx electrobun build --targets'. Supported targets include macOS (arm64, x64), Windows (x64), and Linux (x64, arm64). ```bash bunx electrobun build --targets macos-arm64,macos-x64,win-x64,linux-x64,linux-arm64 ``` -------------------------------- ### Manage Application Updates Source: https://blackboard.sh/electrobun/llms.txt Utilize the built-in update system for application updates, supporting binary diffs for smaller updates. Check for updates, download them, and apply them. Applying an update will quit the current application and relaunch the updated version. ```typescript import { Updater } from "electrobun/bun"; // Get local version info const localInfo = await Updater.getLocalInfo(); // { version, hash, baseUrl, channel, name, identifier } // Check for updates const updateInfo = await Updater.checkForUpdate(); // { version, hash, updateAvailable, updateReady, error } if (updateInfo.updateAvailable) { await Updater.downloadUpdate(); } if (Updater.updateInfo()?.updateReady) { await Updater.applyUpdate(); // Quits, replaces, relaunches } ``` -------------------------------- ### BrowserView Events Source: https://blackboard.sh/electrobun/llms.txt Handles various events emitted by the BrowserView, such as navigation, DOM readiness, and download progress. ```APIDOC ## BrowserView Events ### Description Listen for and respond to events triggered by the BrowserView. ### Events - `will-navigate`: Fired before navigation occurs. `e.data` contains `{ url, allowed }`. - `did-navigate`: Fired after navigation completes. `e.data.detail` contains the `url`. - `did-navigate-in-page`: Fired when navigation within the same page occurs. - `did-commit-navigation`: Fired when a navigation is committed. - `dom-ready`: Fired when the DOM of the page is ready. - `new-window-open`: Fired when a new window is requested. `e.detail` contains window information. - `download-started`: Fired when a download begins. `e.detail` contains `{ filename, path }`. - `download-progress`: Fired during download. `e.detail` contains `{ progress }` (0-100). - `download-completed`: Fired when a download finishes. `e.detail` contains `{ filename, path }`. - `download-failed`: Fired if a download fails. `e.detail` contains `{ filename, path, error }`. ### Example ```typescript win.webview.on('will-navigate', (e) => { console.log('Navigating to:', e.data.url); }); win.webview.on('download-progress', (e) => { console.log('Download progress:', e.detail.progress); }); ``` ``` -------------------------------- ### Tray API Source: https://blackboard.sh/electrobun/llms.txt Manages the system tray icon and its associated menu, allowing users to interact with the application from the system tray. ```APIDOC ## Tray API Manages system tray icon and menu. ```typescript import { Tray } from "electrobun/bun"; const tray = new Tray({ title: "My App", image: "views://assets/icon-template.png", template: true, // macOS template image (adapts to light/dark mode) width: 22, height: 22, }); // Set tray title tray.setTitle("Updated Title"); // Set context menu tray.setMenu([ { type: "normal", label: "Open", action: "open" }, { type: "divider" }, { type: "normal", label: "Settings", action: "settings", submenu: [ { type: "normal", label: "Preferences", action: "prefs" }, ]}, { type: "normal", label: "Quit", action: "quit" }, ]); // Set tray icon image tray.setImage("views://assets/new-icon.png"); // Control visibility tray.setVisible(false); // Hide tray icon tray.setVisible(true); // Show tray icon // Get tray bounds tray.getBounds(); // Returns { x, y, width, height } // Remove tray icon tray.remove(); // Permanently remove // Event listener for tray clicks tray.on("tray-clicked", (e) => { // action is "" for icon click, or the menu item action name console.log("Tray clicked:", e.data.action); if (e.data.action === "quit") Utils.quit(); }); ``` ``` -------------------------------- ### Electroview Class (Browser API) Source: https://blackboard.sh/electrobun/llms.txt The `Electroview` class provides a mechanism for defining and managing Remote Procedure Calls (RPC) between the browser environment and the Bun process, enabling communication with backend functions. ```APIDOC ## Electroview Class (Browser API) ```typescript import { Electroview } from "electrobun/view"; const rpc = Electroview.defineRPC({ handlers: { requests: { /* browser-side request handlers */ }, messages: { /* browser-side message handlers */ }, }, }); const electroview = new Electroview({ rpc }); // Call Bun functions from browser const result = await electroview.rpc.request.someBunFunction({ param: "value" }); electroview.rpc.send.messageToBun({ data: "hello" }); ``` **Note:** No browser-to-browser RPC by design. For cross-view communication, relay messages through the Bun process. ``` -------------------------------- ### Electrobun Utils.paths for Directory Access Source: https://blackboard.sh/electrobun/llms.txt Provides cross-platform access to common operating system directories and application-scoped directories, identified by an application identifier and channel. ```typescript import { Utils } from "electrobun/bun"; // OS Directories Utils.paths.home // ~ or %USERPROFILE% Utils.paths.appData // ~/Library/Application Support, %LOCALAPPDATA%, ~/.local/share Utils.paths.config // ~/Library/Application Support, %APPDATA%, ~/.config Utils.paths.cache // ~/Library/Caches, %LOCALAPPDATA%, ~/.cache Utils.paths.temp // $TMPDIR, %TEMP%, /tmp Utils.paths.logs // ~/Library/Logs, %LOCALAPPDATA%, ~/.local/state Utils.paths.documents // ~/Documents Utils.paths.downloads // ~/Downloads Utils.paths.desktop // ~/Desktop Utils.paths.pictures // ~/Pictures Utils.paths.music // ~/Music Utils.paths.videos // ~/Movies (macOS), ~/Videos (other) // App-scoped directories (scoped by identifier + channel) Utils.paths.userData // {appData}/{identifier}/{channel} Utils.paths.userCache // {cache}/{identifier}/{channel} Utils.paths.userLogs // {logs}/{identifier}/{channel} // Example: ~/Library/Application Support/com.mycompany.myapp/canary ``` -------------------------------- ### Screen Source: https://blackboard.sh/electrobun/llms.txt Information about connected displays and cursor position. ```APIDOC ## Screen ### Description Provides information about connected displays and the cursor's current position. ### Methods - `getPrimaryDisplay(): Display` - `getAllDisplays(): Display[]` - `getCursorScreenPoint(): { x: number, y: number }` ### Display Object Structure `{ id, bounds: { x, y, width, height }, workArea: { x, y, width, height }, scaleFactor, isPrimary }` ```