electron-window-manager

repository·master·Indexed 19 days ago

https://github.com/tamkeen-tms/electron-window-manager

A NodeJs module for Electron (version 1.1.3) that simplifies the creation, control, and management of multi-window applications. It provides a wrapper around Electron's BrowserWindow to enable named windows, setup templates, unified layouts, and cross-window communication via a bridge and shared data store.

Tokens
8.3K
Snippets
28
Records
29
Agent score
14%

What's inside electron-window-manager

  1. Use Layouts to wrap window content in themes

    master

    Layouts allow you to define a consistent UI/theme (HTML/CSS) for your application. When a window is created using a layout, the window's specific content (HTML) is embedded into the layout file at the {{content}} placeholder. The layout can also use {{appBase}} to reference the application's base path.

    Workflow:

    1. Create a layout HTML file with {{content}} and {{appBase}} placeholders.
    2. Register the layout using windowManager.layouts.add(name, path).
    3. Apply the layout to a window during creation or via win.useLayout(name).
    4. (Optional) Set a global default layout in windowManager.init({ 'defaultLayout': 'name' }).
    <!-- layout.html -->
    <body>
        {{content}} <!-- Window content is injected here -->
        <script src="{{appBase}}scripts/bootstrap.js"></script>
    </body>
    // Register a layout
    windowManager.layouts.add('default', '/layouts/default.html');
    
    // Apply layout when creating a window
    var win = windowManager.createNew('home', 'Welcome', '/pages/welcome.html', false, {'layout': 'default'});
    
    // Or apply to an existing window instance
    win.useLayout('default');
  2. Configure Window Setup and Layouts

    master

    The windowManager extends standard Electron BrowserWindow options with specialized features for layout and positioning.

    Module-Specific Setup Options

    • layout (string): The name of the layout (defined in init) to use for the window's content.
    • position (string|array): Sets the window position.
      • Names: top, right, bottom, left, topRight, topLeft, bottomRight, bottomLeft. (Default is center).
      • Coordinates: An array of [x, y] coordinates.
    • onLoadFailure (function): A window-specific callback for loading errors.
    • showDevTools (boolean): Controls DevTools visibility.
    // Using position name
    var win = windowManager.open(false, false, false, false, {'position': 'bottomRight'});
    
    // Using coordinate array
    var win = windowManager.open(false, false, false, false, {'position': [300, 200]});
  3. How electron-window-manager works

    master

    The module acts as a wrapper for Electron's native BrowserWindow module. It manages BrowserWindow instances by storing them in a Window class, where each instance is associated with a unique name. This allows you to access and control any window from anywhere in your application by its name.

    Key concepts:

    • Named Windows: Every window is assigned a unique name, enabling cross-window access.
    • Setup Templates: If multiple windows share similar configurations (width, height, title, etc.), you can define a Setup Template and apply it by name to new windows.
    • Development Mode: Enabled by default. It allows you to reload any window with Ctrl + R and toggle Chrome DevTools with Ctrl + F12 without manual configuration.
    • DevTools Control: You can enable DevTools by default in a window's setup using showDevTools: true or by calling the .showDevTools() method on the window object.
  4. The Window class and WindowManager relationship

    master

    The Window class represents an individual window instance. However, Window is not available directly in your application scope. Instead, you must use the windowManager instance to create or open windows. Calling windowManager.createNew(...) or windowManager.open(...) returns a Window instance.

    Key properties of a Window instance:

    • name: The unique name of the window.
    • setup: The configuration object used for the window.
    • object: The underlying Electron BrowserWindow instance. You can use this to access all native Electron methods (e.g., win.object.setFullScreen(false)).
    // Do NOT use: var window = new Window(...);
    
    // DO use windowManager to get a Window instance:
    var win = windowManager.createNew(name, title, url, setupTemplate, setup, showDevTools);
  5. Use Setup Templates to manage window configurations

    master

    Setup Templates allow you to create named presets for window properties (like width, height, resizable, title, etc.) to avoid repeating configuration code. You can define a template using windowManager.templates.set(name, setup) and then apply it when opening or creating a window by passing the template name.

    To set a global default template for all windows, use the defaultSetupTemplate key in the windowManager.init configuration.

    Overriding templates:

    • To bypass the default template for a specific window, pass FALSE as the setupTemplate argument in open() or createNew().
    • To explicitly provide a custom setup object instead of a template, pass null as the setupTemplate argument and provide your setup object in the subsequent parameter.
    // Define a template
    windowManager.templates.set('small', {
        'width': 600,
        'height': 350,
        'resizable': true,
        'title': 'App name, for small windows!'
    });
    
    // Set a global default
    windowManager.init({
        'defaultSetupTemplate': 'small'
    });
    
    // Use the template
    windowManager.open(false, false, 'welcome.html', 'small');
    
    // Override default template with FALSE
    windowManager.open('home', 'Welcome', '/pages/welcome.html', FALSE);
    
    // Use null to provide a custom setup object instead of a template
    windowManager.open('home', 'Welcome', '/pages/welcome.html', null, { 'width': 800 });
  6. Share data and communicate between windows

    master

    The library provides two mechanisms for inter-window communication: Shared Data (state management) and a Bridge (event-based messaging).

    Shared Data

    Use this for synchronizing state (variables) across different windows. It uses Watch.js to allow windows to react to changes.

    • windowManager.sharedData.set(key, value): Store a value.
    • windowManager.sharedData.fetch(key, altValue): Retrieve a value.
    • windowManager.sharedData.watch(prop, callback): Trigger a callback when a specific property changes.
    • windowManager.sharedData.unwatch(prop, callback): Stop watching a property.

    The Bridge (Event Emitter)

    Use this to fire events from one window to another (or to a specific target window).

    • windowManager.bridge.emit(event, data, target): Emits an event. target is the name of the window intended to receive it.
    • windowManager.bridge.on(event, callback): Listens for an event. The callback receives (data, target, emittedBy).
    • windowManager.bridge.once(event, callback): Listens for an event exactly once.
    • windowManager.bridge.removeListener(event, handler): Removes a listener.
    // --- Shared Data Example ---
    windowManager.sharedData.set('theme', 'dark');
    
    windowManager.sharedData.watch('theme', (newValue) => {
      console.log('Theme changed to:', newValue);
    });
    
    // --- Bridge Example ---
    // Window A (Listener)
    windowManager.bridge.on('user-login', (data, target, emittedBy) => {
      console.log(`User ${data.user} logged in from ${emittedBy}`);
    });
    
    // Window B (Emitter)
    windowManager.bridge.emit('user-login', { user: 'Alice' }, 'WindowA');
  7. How templates and layouts work

    master

    The electron-window-manager uses Templates and Layouts to standardize window configurations and UI structures.

    Setup Templates

    Templates are reusable groups of BrowserWindow configuration options. You define them once and apply them to multiple windows.

    • windowManager.templates.set(name, setup): Register a template.
    • windowManager.templates.modify(name, setup): Update an existing template.
    • Use win.applySetupTemplate(name) to apply it to a window.

    Layouts

    Layouts are HTML files used to wrap window content. When a layout is used, the manager reads the layout file, replaces {{appBase}} with the application path and {{content}} with the window's actual content, then loads the resulting HTML.

    • windowManager.layouts.add(name, path): Register a layout file.
    • Use win.useLayout(name) to apply it.
    • When loading a URL with a layout, the manager performs a file-system read to merge the layout and the content.
    // 1. Define a template
    windowManager.templates.set('popup', {
      width: 300,
      height: 200,
      resizable: false
    });
    
    // 2. Define a layout
    windowManager.layouts.add('main-layout', '/layouts/main.html');
    
    // 3. Create a window using both
    const win = windowManager.createNew('popup-win', 'Popup', 'index.html', 'popup');
    win.useLayout('main-layout');
    win.open();
  8. Bulk Window Creation via JSON

    master

    You can define multiple windows in a JSON file and import them all at once using importList(file). This is useful for complex application structures.

    JSON Format Example

    {
        "home": { "title": "Home", "url": "http://...", "setup": { "width": 800 } },
        "about": { "title": "About", "url": "/about.html" }
    }

    Usage

    windowManager.importList('windows.json');
    windowManager.get('home').open();
    // windows.json
    {
        "home": { "title": "Home", "url": "http:// ...", "setup": { ... } },
        "about": { "title": "About", ... }
    }
    
    // Import the window list
    windowManager.importList('windows.json');
    
    // Open a window, by name
    windowManager.get('home').open();
  9. Use electron-window-manager in the Main process

    master

    In the Electron Main process, you can initialize the manager and open windows. You must call windowManager.init() before attempting to open windows.

    const electron = require('electron');
    const app = electron.app;
    const windowManager = require('electron-window-manager');
    
    // When the application is ready
    app.on('ready', function(){
        windowManager.init();
        // Open a window named 'home'
        windowManager.open('home', 'Welcome ...', '/home.html');
    });
  10. Use electron-window-manager in the Renderer process

    master

    You can also use the module within a Renderer process (inside a created window) to spawn new windows. This requires using Electron's remote module to require the electron-window-manager package.

    <script>
        var remote = require('remote');
        var windowManager = remote.require('electron-window-manager');
    
        // Create a new window named 'win2'
        var win2 = windowManager.createNew('win2', 'Windows #2');
        win2.setURL('/win2.html');
        win2.onReady(function() {
            // Handle window ready state
        });
        win2.open();
    </script>
  11. Create and Open Windows

    master

    You can create windows using createNew or open.

    • createNew(...): Creates a new Window instance but does not automatically open it. Returns the instance.
    • open(...): Creates and immediately opens the window. Returns the instance.

    Arguments

    All arguments are optional:

    1. name (string): Unique identifier. If omitted, a serialized name like window_1 is used.
    2. title (string): The window title.
    3. url (string): The target URL. If it starts with /, it is prefixed with appBase. You can also use the {appBase} placeholder.
    4. setupTemplate (string): The name of a preset setup template.
    5. setup (object|string): The window configuration. Supports standard BrowserWindow options plus module-specific ones (see below). You can use a shorthand string like "300x200" for dimensions.
    6. showDevTools (boolean): Whether to show Chrome DevTools. Defaults to false.
    // Create a window with specific setup
    var homeWindow = windowManager.createNew('home', 'Welcome', '/pages/home.html', false, {
        'width': 600,
        'height': 450,
        'position': 'topLeft',
        'layout': 'simple',
        'showDevTools': true,
        'resizable': true
    });
    
    homeWindow.open();