### Basic createElectronRouter Setup Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createElectronRouter.md Initializes the router with a port and an array of route IDs. This is a fundamental setup for basic routing configurations. ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ port: 4927, types: { ids: ['main', 'settings', 'about'], }, }) ``` -------------------------------- ### Create Router with Typed Configuration Example Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md An example of creating the router with a typed configuration, specifying strict mode, allowed IDs, and query keys. It also demonstrates how to infer valid query keys using the `Query.Keys` utility. ```typescript import { createElectronRouter, Query } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ types: { strict: true, ids: ['main', 'modal'] as const, queryKeys: ['userId', 'action'] as const, }, }) type ValidQueryKeys = Query.Keys // ValidQueryKeys: 'userId' | 'action' ``` -------------------------------- ### Full Usage Example with Query Utilities Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md Demonstrates creating an electron router with typed query keys and using Query.Keys and Query.Return for type-safe query parameter handling. ```typescript import { createElectronRouter, Query } from 'electron-router-dom' const { Router, registerRoute } = createElectronRouter({ types: { ids: ['main', 'settings'], queryKeys: ['userId', 'action', 'tab'] as const, }, }) // Type the valid query keys type QueryKeys = Query.Keys<{ types: { ids: ['main', 'settings'] queryKeys: ['userId', 'action', 'tab'] } }> // Result: 'userId' | 'action' | 'tab' // Use in a component import { useSearchParams } from 'react-router-dom' function UserPage() { const [params] = useSearchParams() const userId: Query.Return = params.get('userId') return
User: {userId}
} ``` -------------------------------- ### Basic Router Setup Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/api/renderer/router.mdx Defines the main layout and routes for the application. Use this to set up the primary navigation and content areas. ```tsx } errorElement={}> } /> } /> } /> ``` -------------------------------- ### Basic Router Setup Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/Router.md Define basic routes for different window IDs. Each window ID maps to a React Router Route element. ```typescript import { Router } from './electron-router-dom' import { Route } from 'react-router-dom' import MainPage from './pages/main' import SettingsPage from './pages/settings' export function AppRouter() { return ( } /> } settings={ } /> } /> ) } ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/configuration.md Demonstrates a comprehensive configuration including a custom dev server URL and strict type checking for both route IDs and query parameters. Accessing resolved settings is also shown. ```typescript export const { Router, registerRoute, settings } = createElectronRouter({ devServerUrl: 'http://localhost:5173', types: { strict: true, ids: ['main', 'preferences', 'about'], queryKeys: ['userId', 'action', 'theme', 'debug'], }, }) // Access resolved settings console.log(settings.port) // undefined (devServerUrl takes precedence) console.log(settings.devServerUrl) // 'http://localhost:5173' console.log(settings.types.strict) // true console.log(settings.types.ids) // ['main', 'preferences', 'about'] ``` -------------------------------- ### Initialize Electron Router DOM Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/hmr.mdx This snippet shows the basic setup for creating an Electron Router instance with specified types. It's used in your main router configuration file. ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ types: { ids: ['main'], }, }) ``` -------------------------------- ### Install React Router DOM (Peer Dependency) Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/README.md Install react-router-dom as a peer dependency if your package manager does not handle it automatically. ```bash npm i react-router-dom ``` -------------------------------- ### Direct Usage of createFileRoute in Production Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createFileRoute.md Demonstrates how to use createFileRoute to get the file path and options for `browserWindow.loadFile` in a production environment. Ensure `electron-router-dom` is imported and `path` module is available. ```typescript import { createFileRoute } from 'electron-router-dom' import path from 'node:path' const htmlPath = path.join(__dirname, '../renderer/index.html') const [filePath, options] = createFileRoute( htmlPath, 'main', { query: { userId: '123' } } ) // filePath: '/absolute/path/to/index.html' // options: { hash: '/?main?userId=123#/main' } browserWindow.loadFile(filePath, options) ``` -------------------------------- ### Usage of RouteDef for Router Configuration Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md Example demonstrating how to use the RouteDef type to define routes for multiple windows in an application. ```typescript import { RouteDef } from 'electron-router-dom' const routes: RouteDef = { main: } />, settings: } />, } ``` -------------------------------- ### Generated Hash Format Example Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createFileRoute.md Illustrates the format of the generated hash string for a given window ID and query parameters. ```typescript /?main?userId=123&action=edit#/main ``` -------------------------------- ### Install Electron Router DOM Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/README.md Install the electron-router-dom package in your terminal. Ensure you have the minimum required versions of electron, react, and react-router-dom. ```bash npm i electron-router-dom ``` -------------------------------- ### Basic Window Registration Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/registerRoute.md Registers a main window with a specified HTML file. Ensure to import necessary modules like `app`, `BrowserWindow`, `path`, and `registerRoute`. This example is typically called within `app.whenReady().then()`. ```typescript import { app, BrowserWindow } from 'electron' import path from 'node:path' import { registerRoute } from './electron-router-dom' app.whenReady().then(() => { const mainWindow = new BrowserWindow({ width: 1280, height: 720, webPreferences: { nodeIntegration: false, }, }) registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), }) }) ``` -------------------------------- ### Register Multiple Windows with Different Routes Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/registerRoute.md Demonstrates registering multiple windows, each with a unique ID and potentially different query parameters. This setup is common for applications with distinct sections like a main window and a settings window. ```typescript const windows = {} function createMainWindow() { windows.main = new BrowserWindow({ width: 1280, height: 720 }) registerRoute({ id: 'main', browserWindow: windows.main, htmlFile: path.join(__dirname, '../renderer/index.html'), }) } function createSettingsWindow() { windows.settings = new BrowserWindow({ width: 600, height: 500 }) registerRoute({ id: 'settings', browserWindow: windows.settings, htmlFile: path.join(__dirname, '../renderer/index.html'), query: { modal: 'settings' }, }) } app.whenReady().then(() => { createMainWindow() createSettingsWindow() }) ``` -------------------------------- ### createFileRoute Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/INDEX.md Internal utility for building production file URLs and Electron LoadFileOptions. It details hash format construction, query parameter serialization, and the structure of the return value (a tuple). Examples of generated hash formats are also provided. ```APIDOC ## createFileRoute ### Description Internal utility for building production file URLs and Electron LoadFileOptions. ### Signature ```typescript createFileRoute(route: string, query?: Record) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table - **route** (string) - Required - The base route path. - **query** (Record) - Optional - Query parameters to serialize. ### Return Type A tuple containing the file path and LoadFileOptions. ### Behavior - Constructs hash format. - Serializes query parameters. ### Examples - Generated hash examples ``` -------------------------------- ### createElectronRouter Signature and Usage Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createElectronRouter.md This snippet shows the signature of the createElectronRouter function and basic examples of its usage in both the main and renderer processes. ```APIDOC ## createElectronRouter ### Description Factory function that creates the core router instance for electron-router-dom. This function initializes the router with configuration and returns methods for managing window routing in the main process and a Router component for the renderer process. ### Signature ```typescript function createElectronRouter({ types, devServerUrl, port }: ElectronRouterOutput): { Router: (props: RouterProps) => JSX.Element, registerRoute: (props: RegisterRouteConfig) => void, settings: { port: number, devServerUrl: string | undefined, types: { strict: boolean, ids: string[], queryKeys: string[] } } } ``` ### Parameters #### Configuration Options - **port** (`number`): Optional. The port where the dev server is running. Defaults to `3000`. Only necessary if not using `devServerUrl` and not using the default port. - **devServerUrl** (`string`): Optional. The full URL of the dev server (e.g., `http://localhost:5173`). If not provided, defaults to `http://localhost:${port}`. - **types.strict** (`boolean`): Optional. Enable strict type checking for route IDs and query keys. Defaults to `true`. In strict mode, only predefined `ids` and `queryKeys` are allowed. - **types.ids** (`string[]`): Optional. Array of route IDs representing each BrowserWindow. Defaults to `[]`. Each ID acts as a route basename. - **types.queryKeys** (`string[]`): Optional. Array of allowed query parameter keys. Defaults to `[]`. Used to type-check query parameters passed to `registerRoute`. ### Return Type Returns an object with the following properties: - **Router**: A React component for the renderer process that sets up routing based on window ID. - **registerRoute**: A function to register a BrowserWindow to a route. Called in the main process. - **settings**: A configuration object containing resolved settings (port, devServerUrl, types). ### Behavior - **Development Mode**: When `isDev()` returns true, uses `devServerUrl` to load the app. - **Production Mode**: Uses `createFileRoute()` to load HTML files from disk. - **Type Safety**: When `strict: true`, TypeScript enforces that route IDs and query keys match the predefined arrays. - **Query Parameters**: Query parameters are serialized and passed through URL hash. ### Example: Basic Setup ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ port: 4927, types: { ids: ['main', 'settings', 'about'], }, }) ``` ### Example: With Query Keys and Dev Server URL ```typescript const { Router, registerRoute, settings } = createElectronRouter({ devServerUrl: 'http://localhost:5173', types: { strict: true, ids: ['main', 'modal'], queryKeys: ['userId', 'action', 'tab'], }, }) ``` ### Example: Main Process Usage ```typescript import { app, BrowserWindow } from 'electron' import path from 'node:path' import { registerRoute } from './electron-router-dom' async function createMainWindow() { const mainWindow = new BrowserWindow({ width: 1280, height: 720, }) registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), query: { userId: '123' }, }) } app.whenReady().then(createMainWindow) ``` ### Example: Renderer Process Usage ```typescript import { Router } from './electron-router-dom' import { Route } from 'react-router-dom' import MainScreen from './screens/main' import SettingsScreen from './screens/settings' export function Routes() { return ( } /> } settings={ } /> } /> ) } ``` ``` -------------------------------- ### Slash Normalization Example Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createURLRoute.md Demonstrates how createURLRoute normalizes URLs by removing extra double slashes, ensuring a clean and valid URL format. ```typescript // Input with extra slashes: http://localhost:5173///#/main // Output: http://localhost:5173/#/main ``` -------------------------------- ### Renderer Process Routing Setup Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createElectronRouter.md Sets up the Router component in the renderer process to handle different routes and their corresponding React components. This component is responsible for rendering the UI based on the current window ID. ```typescript import { Router } from './electron-router-dom' import { Route } from 'react-router-dom' import MainScreen from './screens/main' import SettingsScreen from './screens/settings' export function Routes() { return ( } /> } settings={ } /> } /> ) } ``` -------------------------------- ### createElectronRouter Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/INDEX.md Factory function to initialize the router. It returns the Router component, the registerRoute function, and the settings object. This function handles configuration parameters such as port, devServerUrl, and various type-related settings. It also details development vs. production behavior, query parameter handling, and provides usage examples for different scenarios. ```APIDOC ## createElectronRouter ### Description Factory function to initialize the router. Returns Router component, registerRoute function, and settings object. ### Signature ```typescript createElectronRouter(config?: ElectronRouterOutput) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Return Type An object containing the Router component, registerRoute function, and settings object. ### Behavior - Handles configuration parameters (port, devServerUrl, types.strict, types.ids, types.queryKeys). - Details development vs. production behavior. - Manages query parameter handling. ### Examples - Basic setup - With query keys - Main process usage - Renderer usage ``` -------------------------------- ### Recommended Import Pattern for Initialization (Main Process) Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/modules.md Demonstrates the recommended way to import and initialize electron-router-dom in the main process, including type definitions for query keys. ```typescript // Initialization (main process) import { createElectronRouter } from 'electron-router-dom' import type { Query } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ types: { ids: ['main'] as const, queryKeys: ['userId'] as const, }, }) ``` -------------------------------- ### Initialize Router with Main and Renderer Components Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/modules.md Use this factory function to initialize the router. It requires configuration for the port, types, and optionally a dev server URL. This is the main API entry point for setting up the router. ```typescript import { createElectronRouter, type RouterProps, type Query } from 'electron-router-dom' const { Router, registerRoute, settings } = createElectronRouter({ port: 3000, types: { ids: ['main'] }, }) ``` -------------------------------- ### Minimal Configuration Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/configuration.md Initializes the router with default settings. The resulting settings object will contain default values for all options. ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({}) ``` ```javascript { port: 3000, devServerUrl: undefined, types: { strict: true, ids: [], queryKeys: [], }, } ``` -------------------------------- ### toLowerCaseKeys Function Signature and Usage Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/toLowerCaseKeys.md This snippet details the TypeScript signature of the toLowerCaseKeys function, its parameters, return type, and provides examples of its usage for normalizing object keys to lowercase. ```APIDOC ## toLowerCaseKeys Function ### Description An internal utility function that converts all object keys to lowercase. It is used by the Router component to normalize route definitions for case-insensitive route ID matching. ### Signature ```typescript function toLowerCaseKeys>(target: T): T ``` ### Parameters #### Path Parameters This function does not have path parameters. #### Query Parameters This function does not have query parameters. #### Request Body This function does not have a request body. ### Parameters - **target** (`T extends Record`) - Required - Object whose keys should be converted to lowercase. ### Request Example ```javascript import { toLowerCaseKeys } from 'electron-router-dom' const routes = { Main: '
Main
', Settings: '
Settings
', About: '
About
', } const normalized = toLowerCaseKeys(routes) // Result: { // main: '
Main
', // settings: '
Settings
', // about: '
About
', // } ``` ### Response #### Success Response (200) - **T** (`T`) - A new object with the same type as the input, but all keys converted to lowercase. #### Response Example ```json { "main": "
Main
", "settings": "
Settings
", "about": "
About
" } ``` ### Behavior 1. **Key Transformation**: Iterates through all keys of the input object. 2. **Lowercase Conversion**: Converts each key to lowercase using `.toLowerCase()`. 3. **Value Preservation**: Maintains original values unchanged. 4. **Type Preservation**: Returns the same type as input (type-level). ``` -------------------------------- ### Initialize Electron Router Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Initialize the router in your main process. Define the port and types for window IDs. ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ port: 3000, types: { ids: ['main', 'settings'], }, }) ``` -------------------------------- ### Recommended Import Pattern for Usage (Renderer Process) Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/modules.md Shows the recommended import for using the Router in a renderer process, including type definitions for route definitions. ```typescript // Usage (renderer process) import { Router } from './lib/electron-router-dom' import type { RouteDef } from 'electron-router-dom' ``` -------------------------------- ### LiteralUnion Type Example Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md Demonstrates the usage of `LiteralUnion` for defining strict and non-strict ID types. In strict mode, only specified literals are allowed, while non-strict mode allows literals with fallback to any string. ```typescript // In strict mode: only 'main' or 'settings' type StrictIds = 'main' | 'settings' // In non-strict mode: autocomplete 'main'/'settings', but accepts any string type NonStrictIds = LiteralUnion<'main' | 'settings', string> ``` -------------------------------- ### Register Route with Custom Dev Server URL Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/registerRoute.md Overrides the default development server URL calculation by providing a custom `devServerUrl`. This is useful for specific HMR configurations or when using non-standard server setups. ```typescript registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), devServerUrl: 'http://localhost:5173', // Override port-based URL }) ``` -------------------------------- ### createFileRoute with Additional LoadFileOptions Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createFileRoute.md Shows how to pass additional Electron LoadFileOptions, such as `search`, alongside the generated hash when using `createFileRoute`. ```typescript const [filePath, options] = createFileRoute( htmlPath, 'settings', { query: { tab: 'profile' }, search: 'v=1', // Additional LoadFileOptions } ) // options includes both generated hash and search parameter ``` -------------------------------- ### Register Windows with Routes Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Register BrowserWindow instances with their corresponding route IDs and HTML files in the main process. ```typescript import { registerRoute } from './lib/electron-router-dom' import path from 'node:path' function createMainWindow() { const mainWindow = new BrowserWindow({ width: 1280, height: 720 }) registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), }) } app.whenReady().then(createMainWindow) ``` -------------------------------- ### Previous route creation in v1.0 Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/blog/en/introducing-v2.mdx Illustrates the older method of creating URL and file routes using createFileRoute and createURLRoute functions in version 1.0. ```ts const devServerURL = createURLRoute('http://localhost:3000', id) const fileRoute = createFileRoute( join(__dirname, '../renderer/index.html'), id ) process.env.NODE_ENV === 'development' ? window.loadURL(devServerURL) : window.loadFile(...fileRoute) ``` -------------------------------- ### Globally Type URLSearchParams with Specific Query Keys Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/typescript.mdx This snippet demonstrates how to globally type the `get` method of `URLSearchParams` to work with specific query keys defined in the router settings. It's useful for ensuring type safety when accessing query parameters. ```typescript import { createElectronRouter, type Query } from 'electron-router-dom' export const { Router, registerRoute, settings } = createElectronRouter({ port: 4927, types: { ids: ['main'], queryKeys: ['name', 'version'], }, }) declare global { interface URLSearchParams { get(name: Query.Keys): Query.Return } } ``` -------------------------------- ### Direct Usage with Query Parameters Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createURLRoute.md Use createURLRoute to generate a development URL with query parameters for a specific window ID. The resulting URL is suitable for browserWindow.loadURL(). ```typescript import { createURLRoute } from 'electron-router-dom' const url = createURLRoute('http://localhost:5173', 'main', { query: { userId: '123', action: 'edit' }, }) // Result: 'http://localhost:5173?userId=123&action=edit#/main?userId=123&action=edit' browserWindow.loadURL(url) ``` -------------------------------- ### Runtime Function Imports Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/modules.md Demonstrates importing runtime functions like Router and registerRoute directly from the createElectronRouter factory. ```typescript const { Router, registerRoute } = createElectronRouter({...}) // Or access directly via factory return export const { Router, registerRoute, settings } = createElectronRouter({...}) ``` -------------------------------- ### Router Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/INDEX.md React component for renderer process routing. It detects the window ID from the URL hash and renders the appropriate routes. The documentation includes details on window ID detection, route selection logic, hash router configuration, query parameter handling, and provides usage examples. ```APIDOC ## Router ### Description React component for renderer process routing. Extracts window ID from URL hash and renders appropriate routes. ### Signature ```typescript (props: RouterProps) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table - **props** (RouterProps) - Required - Props for the Router component. - **routes** (RouteDef[]) - Required - An array of route definitions. - **basename** (string) - Optional - Base path for the router. - **queryKeys** (string[]) - Optional - Keys to extract from query parameters. ### Return Type A React component that renders routes based on the URL hash. ### Behavior - Detects window ID and normalizes case from URL hash. - Implements route selection logic. - Configures hash router. - Handles query parameter extraction. ### Examples - Basic routes - With provider config - Nested routes - Accessing query parameters ``` -------------------------------- ### Update Main Process Imports Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/migration/migrating-from-v1-to-v2.mdx Replace the import of createFileRoute and createURLRoute with registerRoute from the newly created electron-router-dom.ts file. ```diff - import { createFileRoute, createURLRoute } from 'electron-router-dom' + import { registerRoute } from '../lib/electron-router-dom' ``` -------------------------------- ### Registering a Main Route Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/api/main/register-route.mdx Use this snippet to register the main window as a route. Ensure you have the mainWindow object and the correct path to your HTML file. ```typescript registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), }) ``` -------------------------------- ### createElectronRouter() Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Initializes the router for your Electron application. This is the main factory function to set up the routing system. ```APIDOC ## createElectronRouter() ### Description Initializes the router for your Electron application. This is the main factory function to set up the routing system. ### Type function ### Purpose Initialize router ``` -------------------------------- ### Create File Route for Production Loading Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/modules.md This function constructs file paths and Electron options for loading HTML files in production. It returns a tuple suitable for `browserWindow.loadFile()`. ```typescript createFileRoute(path, id, options?) ``` -------------------------------- ### Register Route with Query Parameters Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/registerRoute.md Creates and registers a user window, passing query parameters like `userId`, `action`, and `tab`. These parameters are accessible in the renderer process via the `useSearchParams()` hook. ```typescript function createUserWindow(userId: string, action: string) { const userWindow = new BrowserWindow({ width: 800, height: 600 }) registerRoute({ id: 'settings', browserWindow: userWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), query: { userId, action, tab: 'profile', }, }) return userWindow } ``` -------------------------------- ### Configuration Object Structure Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/configuration.md The entire configuration is passed as a single object to createElectronRouter(). This object includes optional properties for port, devServerUrl, and types. ```typescript createElectronRouter({ port?: number devServerUrl?: string types?: { strict?: boolean ids?: string[] queryKeys?: string[] } }) ``` -------------------------------- ### Create electron-router-dom.ts Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/migration/migrating-from-v1-to-v2.mdx Create a new file at src/lib/electron-router-dom.ts to expose registerRoute and Router. This file centralizes configuration for the library. ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute } = createElectronRouter({ port: 4927, // the port of your React server is running on (optional, default port is 3000) types: { /** * The ids of the windows of your application, think of these ids as the basenames of the routes * this new way will allow your editor's intelisense to help you know which ids are available to use * both in the main and renderer process */ ids: ['main'], }, }) ``` -------------------------------- ### New route creation with registerRoute in v2.0 Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/blog/en/introducing-v2.mdx Demonstrates the simplified approach in version 2.0 using the registerRoute method for handling development server URLs and application HTML files. ```ts registerRoute({ id: 'main', browserWindow: window, htmlFile: path.join(__dirname, '../renderer/index.html'), }) ``` -------------------------------- ### Custom Development Server Configuration Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Configure a custom development server URL. This is useful when the dev server runs on a non-default port or address. ```typescript createElectronRouter({ devServerUrl: process.env.DEV_SERVER_URL || 'http://localhost:5173', types: { ids: ['main'] }, }) ``` -------------------------------- ### Create URL Route for Development Loading Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/modules.md This function builds development server URLs for loading applications during development. It constructs a complete URL string for `browserWindow.loadURL()`. ```typescript createURLRoute(route, id, options?) ``` -------------------------------- ### Create Renderer Process Routes Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Define routes for different windows in your renderer process using the Router component. ```typescript import { Router } from './lib/electron-router-dom' import { Route } from 'react-router-dom' import MainPage from './pages/main' import SettingsPage from './pages/settings' export function Routes() { return ( } /> } settings={ } /> } /> ) } ``` -------------------------------- ### Type Factory Function with Router IDs and Query Keys Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/typescript.mdx This snippet shows how to type a factory function for creating Electron windows, ensuring that the `id` and `query` parameters are correctly typed according to the `createElectronRouter` configuration. This improves type safety when defining and registering routes. ```typescript import { registerRoute } from './lib/electron-router-dom' type Route = Parameters[0] interface WindowProps extends Electron.BrowserWindowConstructorOptions { id: Route['id'] query?: Route['query'] } export function createWindow({ id, query, ...options }: WindowProps) { const window = new BrowserWindow(options) registerRoute({ id, query, browserWindow: window, htmlFile: path.join(__dirname, '../renderer/index.html'), }) return window } ``` -------------------------------- ### Router with Multiple Window IDs Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/api/renderer/router.mdx Illustrates how to define routes for different window IDs when strict mode is enabled. Each property name corresponds to a window ID defined in the main process. ```tsx } /> } about={ } /> } /> ``` -------------------------------- ### Update Main Process with registerRoute Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/index.mdx Import and use the registerRoute method in your main process to register a window as an application route. This method handles loading the correct URL or HTML file, so manual use of loadURL and loadFile is not needed. ```typescript import { registerRoute } from '../lib/electron-router-dom' ``` ```typescript registerRoute({ id: 'main', browserWindow: window, htmlFile: path.join(__dirname, '../renderer/index.html'), }) ``` -------------------------------- ### Basic Usage of toLowerCaseKeys Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/toLowerCaseKeys.md Demonstrates a simple use case of converting keys in a route definition object from PascalCase to lowercase. ```typescript import { toLowerCaseKeys } from 'electron-router-dom' // Simple example const routes = { Main:
Main
, Settings:
Settings
, About:
About
, } const normalized = toLowerCaseKeys(routes) // Result: { // main:
Main
, // settings:
Settings
, // about:
About
, // } ``` -------------------------------- ### Create Electron Router Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/api/create-electron-router.mdx Initializes the electron router with a specific port and defines custom types for route identifiers and query keys. Ensure the port is available and matches between main and renderer processes. ```typescript import { createElectronRouter } from 'electron-router-dom' export const { Router, registerRoute } = createElectronRouter({ port: 4927, types: { ids: ['main', 'about'], queryKeys: ['id', 'name'], }, }) ``` -------------------------------- ### Dynamic Configuration with Environment Variables Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/configuration.md Configure electron-router-dom dynamically based on environment variables by using Node.js environment variables in your own code before passing them to createElectronRouter. ```typescript import { createElectronRouter } from 'electron-router-dom' const devServerUrl = process.env.DEV_SERVER_URL || 'http://localhost:5173' const port = parseInt(process.env.PORT || '3000', 10) export const { Router, registerRoute } = createElectronRouter({ port, devServerUrl, types: { ids: ['main', 'settings'], }, }) ``` -------------------------------- ### createElectronRouter Configuration Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/api/create-electron-router.mdx The createElectronRouter function accepts an options object to configure the router. Key properties include `port` for the development server port, `devServerUrl` for a custom development server URL, and `types` for defining custom route parameter types. ```APIDOC ## createElectronRouter ### Description Creates a router for your Electron application, enabling communication between main and renderer processes. ### Parameters #### Request Body - **port** (number) - Optional - The port where the React development server is running. Defaults to `3000`. - **devServerUrl** (string) - Optional - The URL of the React development server. If not set, the value of `http://localhost:${port}` will be used. This can be useful for HMR. - **types** (object) - Optional - Definitions of allowed types for routes. Used to enforce contracts and improve editor suggestions. - **strict** (boolean) - Optional - If true, enforces strict type checking. - **ids** (Array) - Optional - Allowed string identifiers for routes. - **queryKeys** (Array) - Optional - Allowed string keys for query parameters. ``` -------------------------------- ### Window-to-Window Communication with Query Parameters Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Facilitates communication between main and renderer processes using query parameters. The main process sends data via `query`, and the renderer process receives it using `useSearchParams`. ```typescript // Main process ipcMain.on('open-settings', (event, config) => { const settingsWindow = new BrowserWindow(...) registerRoute({ id: 'settings', browserWindow: settingsWindow, htmlFile: 'index.html', query: { initialConfig: JSON.stringify(config) }, }) }) // Renderer const [params] = useSearchParams() const config = JSON.parse(params.get('initialConfig') || '{}') ``` -------------------------------- ### Basic Type Imports Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md Shows how to import common type definitions from the 'electron-router-dom' library. ```typescript import type { RouteDef, RouterProps, Query } from 'electron-router-dom' ``` -------------------------------- ### Update Main Process Route Registration (v1) Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/migration/migrating-from-v1-to-v2.mdx This is the previous method for registering routes in the main process using v1 functions. ```ts const devServerURL = createURLRoute('http://localhost:3000', id) const fileRoute = createFileRoute( join(__dirname, '../renderer/index.html'), id ) process.env.NODE_ENV === 'development' ? window.loadURL(devServerURL) : window.loadFile(...fileRoute) ``` -------------------------------- ### createFileRoute Function Signature Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createFileRoute.md Defines the signature, parameters, and return type of the createFileRoute function. It takes a path, an ID, and optional load file options, returning a tuple containing the file path and the configured LoadFileOptions with a generated hash. ```APIDOC ## createFileRoute ### Description Internal utility function that builds a file path and Electron LoadFileOptions for production environments. Constructs the hash with window ID and query parameters for file-based loading. ### Signature ```typescript function createFileRoute( path: string, id: string, options?: Omit ): [string, LoadFileOptions] ``` ### Parameters #### Path Parameters - **path** (string) - Required - Absolute path to the HTML file to load. - **id** (string) - Required - Window route ID to use as the route basename. - **options** (Omit) - Optional - Electron LoadFileOptions. The `hash` field is automatically generated and cannot be overridden. - **options.query** (Record) - Optional - Query parameters to serialize into the hash. ### Return Type `[string, LoadFileOptions]` — Tuple containing: 1. The file path (first element) 2. Electron LoadFileOptions with generated hash (second element) ### Behavior 1. **URL Construction**: Builds a hash string in the format `/{id}?${query}#/${id}` 2. **Query Serialization**: Converts query object to URLSearchParams string 3. **LoadFileOptions**: Returns the options object with the generated hash appended 4. **Return Format**: Returns a tuple suitable for spreading into `browserWindow.loadFile(...)` ### Generated Hash Format For `id: 'main'` and `query: { userId: '123', action: 'edit' }`: ``` /?main?userId=123&action=edit#/main ``` ### Example: Direct Usage (Production Mode) ```typescript import { createFileRoute } from 'electron-router-dom' import path from 'node:path' const htmlPath = path.join(__dirname, '../renderer/index.html') const [filePath, options] = createFileRoute( htmlPath, 'main', { query: { userId: '123' } } ) // filePath: '/absolute/path/to/index.html' // options: { hash: '/?main?userId=123#/main' } browserWindow.loadFile(filePath, options) ``` ### Example: With Additional LoadFileOptions ```typescript const [filePath, options] = createFileRoute( htmlPath, 'settings', { query: { tab: 'profile' }, search: 'v=1', // Additional LoadFileOptions } ) // options includes both generated hash and search parameter ``` ### Query Parameter Handling Query parameters are serialized using `URLSearchParams`: ```typescript const query = { userId: '123', action: 'edit', tags: 'important' } const queryString = new URLSearchParams(query).toString() // Result: "userId=123&action=edit&tags=important" ``` ``` -------------------------------- ### Implementation of toLowerCaseKeys Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/toLowerCaseKeys.md Provides the JavaScript implementation using Object.keys and reduce to iterate, convert keys to lowercase, and build a new object. ```javascript Object.keys(target).reduce( (acc, key) => ({ ...acc, [key.toLowerCase()]: target[key], }), {} as T ) ``` -------------------------------- ### Query Parameter Serialization with URLSearchParams Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createFileRoute.md Demonstrates how query parameters are serialized into a URL query string using `URLSearchParams`. ```typescript const query = { userId: '123', action: 'edit', tags: 'important' } const queryString = new URLSearchParams(query).toString() // Result: "userId=123&action=edit&tags=important" ``` -------------------------------- ### createElectronRouter with Strict Types and Dev Server Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createElectronRouter.md Configures the router with strict type checking, custom route IDs, allowed query keys, and a specific development server URL. Use this for more controlled development environments. ```typescript const { Router, registerRoute, settings } = createElectronRouter({ devServerUrl: 'http://localhost:5173', types: { strict: true, ids: ['main', 'modal'], queryKeys: ['userId', 'action', 'tab'], }, }) ``` -------------------------------- ### Usage with Custom Development Server URL Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createURLRoute.md Create a development URL when your dev server is running on a custom IP address and port. Includes query parameters for debugging. ```typescript const url = createURLRoute('http://192.168.1.100:8080', 'main', { query: { debug: 'true' }, }) // Result: 'http://192.168.1.100:8080?debug=true#/main?debug=true' ``` -------------------------------- ### Update Main Process Route Registration (v2) Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/apps/content/docs/en/guides/migration/migrating-from-v1-to-v2.mdx Register routes in the main process using the simplified registerRoute function from v2. This handles loading the development server URL or the application HTML file automatically. ```ts registerRoute({ id: 'main', browserWindow: window, htmlFile: path.join(__dirname, '../renderer/index.html'), }) ``` -------------------------------- ### registerRoute Function Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/registerRoute.md Registers a BrowserWindow to a route. This function is called in the main process and determines whether to load from a development server or a production HTML file based on the app's packaging state. It accepts a configuration object with details about the route, window, and server settings. ```APIDOC ## registerRoute ### Description Registers a BrowserWindow to a route. This function is called in the main process and determines whether to load from a development server or a production HTML file based on the app's packaging state. It accepts a configuration object with details about the route, window, and server settings. ### Signature ```typescript function registerRoute(props: S): void ``` ### Parameters #### Request Body - **id** (string) - Required - The route ID for this window. Must match one of the IDs defined in `createElectronRouter`'s `types.ids` array (if in strict mode). Acts as the basename for this window's routes. - **browserWindow** (BrowserWindow) - Required - The Electron BrowserWindow instance to register. - **htmlFile** (string) - Required - Path to the HTML file to load in production. Should be an absolute path (typically using `path.join(__dirname, ...)`). - **query** (Record) - Optional - Query parameters to pass to the renderer as URLSearchParams. Accessible via `useSearchParams()` hook. - **port** (number) - Optional - Dev server port. Overrides the default port if provided. - **devServerUrl** (string) - Optional - Full dev server URL. Overrides port-based URL calculation. Recommended for HMR or custom server URLs. ### Return Type `void` ### Behavior - **Development Mode**: Uses `createURLRoute()` to build a development server URL and loads from `devServerUrl` or `http://localhost:${port}`. Calls `browserWindow.loadURL()`. - **Production Mode**: Uses `createFileRoute()` to build a file URL with hash and loads from the HTML file on disk. Calls `browserWindow.loadFile()` with Electron's options. - **Query Parameters**: Serialized as URLSearchParams and appended to both dev and production URLs. Available in renderer via `useSearchParams()`. - **Window ID**: Defaults to `'main'` if not provided and used as the route basename in the hash. ### Example: Basic Window Registration ```typescript import { app, BrowserWindow } from 'electron' import path from 'node:path' import { registerRoute } from './electron-router-dom' app.whenReady().then(() => { const mainWindow = new BrowserWindow({ width: 1280, height: 720, webPreferences: { nodeIntegration: false, }, }) registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), }) }) ``` ### Example: With Query Parameters ```typescript function createUserWindow(userId: string, action: string) { const userWindow = new BrowserWindow({ width: 800, height: 600 }) registerRoute({ id: 'settings', browserWindow: userWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), query: { userId, action, tab: 'profile', }, }) return userWindow } ``` ### Example: With Custom Dev Server URL ```typescript registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), devServerUrl: 'http://localhost:5173', // Override port-based URL }) ``` ### Example: Multiple Windows with Different Routes ```typescript const windows = {} function createMainWindow() { windows.main = new BrowserWindow({ width: 1280, height: 720 }) registerRoute({ id: 'main', browserWindow: windows.main, htmlFile: path.join(__dirname, '../renderer/index.html'), }) } function createSettingsWindow() { windows.settings = new BrowserWindow({ width: 600, height: 500 }) registerRoute({ id: 'settings', browserWindow: windows.settings, htmlFile: path.join(__dirname, '../renderer/index.html'), query: { modal: 'settings' }, }) } app.whenReady().then(() => { createMainWindow() createSettingsWindow() }) ``` ``` -------------------------------- ### Use Case in Router Component Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/toLowerCaseKeys.md Demonstrates how toLowerCaseKeys is integrated within the Router component to normalize route definitions before matching them against window IDs. ```typescript export function Router({ _providerProps, ...routes }: RouterProps): JSX.Element { const selectAllSlashes = /\/g const rawId = location.hash.split(selectAllSlashes)?.[1]?.toLowerCase() || 'main' const windowID = rawId.split('?')[0] || 'main' const transformedRoutes: RouteDef = toLowerCaseKeys(routes) // Normalize keys const Route = () => transformedRoutes[windowID] // ... rest of component } ``` -------------------------------- ### Registering a Route in the Main Process Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/api-reference/createElectronRouter.md Registers a BrowserWindow to a specific route ID in the main process. This function is essential for linking windows to routes and can include initial query parameters. ```typescript import { app, BrowserWindow } from 'electron' import path from 'node:path' import { registerRoute } from './electron-router-dom' async function createMainWindow() { const mainWindow = new BrowserWindow({ width: 1280, height: 720, }) registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: path.join(__dirname, '../renderer/index.html'), query: { userId: '123' }, }) } app.whenReady().then(createMainWindow) ``` -------------------------------- ### Usage of RouterProps with Provider Configuration Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md Shows how to use RouterProps to pass custom configuration to the underlying RouterProvider via the _providerProps property. ```typescript // Or pass provider configuration const props2: AppRouterProps = { _providerProps: { future: { v7_startTransition: true }, }, } ``` -------------------------------- ### Pass Query Parameters from Main to Renderer Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/README.md Pass query parameters from the main process to the renderer process via the URL when registering a route. ```typescript // Main process registerRoute({ id: 'main', browserWindow: mainWindow, htmlFile: 'index.html', query: { userId: '123', action: 'edit' }, }) // Renderer process function MainPage() { const [params] = useSearchParams() const userId = params.get('userId') // '123' } ``` -------------------------------- ### Internal Router Creation Source: https://github.com/daltonmenezes/electron-router-dom/blob/main/_autodocs/types.md This snippet shows the internal usage of `createElectronRouter` with a typed configuration, including strict mode settings for IDs and query keys. ```typescript const { Router, registerRoute } = createElectronRouter({ port: 3000, devServerUrl: 'http://localhost:5173', types: { strict: true, ids: ['main', 'settings'], queryKeys: ['userId'], }, }) ```