Chat about this codebase

AI-powered code exploration

Online

Project Overview

This section describes My Electron App v2.0, its core features, and how Electron’s main and renderer processes map to the project’s file layout.

Application Purpose

My Electron App v2.0 delivers a cross-platform desktop experience using web technologies. It demonstrates:

  • Window creation and management
  • Application lifecycle handling (startup, activation, shutdown)
  • Renderer-to-main communication via IPC

Main Features

  • Multi-platform support: Runs on Windows, macOS, and Linux
  • Window & lifecycle management: Custom window size, behavior on close/activate
  • Interactive UI: Buttons in the renderer trigger functions in the frontend and backend
  • Packaging scripts: Ready-to-use npm scripts for building installers

Architecture & Process Mapping

Electron splits responsibilities between two processes:

  1. Main Process

    • Entrypoint: main.js
    • Manages application lifecycle and native GUI (menus, dialogs, windows)
    • Listens to events like app.on('ready'), window-all-closed, activate
    • Uses BrowserWindow to load index.html
    // main.js
    const { app, BrowserWindow } = require('electron');
    
    function createWindow() {
      const win = new BrowserWindow({
        width: 800, height: 600,
        webPreferences: { nodeIntegration: true }
      });
      win.loadFile('index.html');
    }
    
    app.whenReady().then(createWindow);
    
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') app.quit();
    });
    
  2. Renderer Process

    • Files: index.html, linked CSS/JS
    • Handles UI rendering, user interactions, DOM manipulation
    • Can communicate with main via IPC (ipcRenderer) for native operations
    <!-- index.html -->
    <!DOCTYPE html>
    <html>
    <head>
      <link rel="stylesheet" href="style.css">
      <script src="renderer.js"></script>
    </head>
    <body>
      <button id="greet">Say Hello</button>
      <script>
        document.getElementById('greet').addEventListener('click', () => {
          alert('Hello from Renderer!');
        });
      </script>
    </body>
    </html>
    

File Layout

├─ package.json
├─ main.js ← Main process setup
├─ index.html ← Renderer entrypoint
├─ renderer.js ← Frontend logic (optional separate file)
├─ style.css ← Renderer styling
├─ README.md ← Project overview & setup instructions
└─ /assets ← Static assets (images, icons)

Extending the Project

  • Modify UI: Edit index.html and style.css
  • Add Renderer Logic: Create or update renderer.js for complex interactions
  • Main Process Hooks: Extend main.js to handle new IPC channels or native APIs
  • Packaging: Customize package.json scripts (electron-packager or electron-builder) for release builds

With this structure, you can quickly navigate between UI code in the renderer and native capabilities in the main process.

Quick Start & Running

Get the app up and running in under a minute.

Prerequisites

  • Node.js >= 14.x
  • npm >= 6.x (or Yarn)

1. Clone the Repository

git clone https://github.com/sandunMadhushan/my-electron-app.git
cd my-electron-app

2. Install Dependencies

npm install
# or with Yarn
# yarn install

This installs both Electron and project-specific packages defined in package.json.

3. Launch in Development Mode

npm start

This runs the start script (electron .) which:

  • Loads main.js
  • Creates the BrowserWindow and points it at index.html
  • Hooks into app lifecycle events for cross-platform behavior

The app window appears; open DevTools with Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (macOS).

4. Live Reload (Optional)

To auto-reload on changes, install electron-reload:

npm install --save-dev electron-reload

Then add at the top of main.js:

require('electron-reload')(__dirname, {
  electron: require('electron')
});

Now edits to your HTML, JS or CSS instantly reload the window.

5. Build for Distribution

After experimenting, package your app:

npm run build

– Uses electron-builder (configured in package.json)
– Outputs installers/binaries to dist/

Locate your platform’s installer (.exe, .dmg, .AppImage) in the dist/ folder and distribute it.

Packaging & Release

This section covers creating production-ready Windows installers with electron-builder and automating GitHub Releases via GitHub Actions when you push a version tag.

Configuring electron-builder in package.json

Define packaging metadata and output settings under the build key in package.json:

"build": {
  "appId": "com.sandunMadhushan.my-electron-app",
  "productName": "My Electron App",
  "directories": {
    "output": "dist"
  },
  "files": [
    "**/*",
    "!node_modules",
    "!dist",
    "!release-builds"
  ],
  "win": {
    "target": "nsis",
    "icon": "icon.ico"
  }
}

Key fields:

  • appId: reverse-DNS identifier for OS metadata and installer.
  • productName: display name in menus, folders and installer.
  • directories.output: folder for build artifacts (e.g. dist/).
  • files: include/exclude globs to bundle only production files.
  • win.target: nsis produces a Windows installer.
  • win.icon: path to your .ico file for installer and app.

Practical steps:

  1. Install electron-builder
    npm install --save-dev electron-builder
    
  2. Trigger a build
    npm run build
    
  3. Customize other platforms:
    • macOS:
      "mac": {
        "target": ["dmg","zip"],
        "icon": "icon.icns"
      }
      
    • Linux:
      "linux": {
        "target": ["AppImage","deb"]
      }
      
  4. Exclude development files: refine files globs to omit tests, docs or config.
  5. Code-sign builds: supply certificates via environment variables or an external electron-builder.yml to enable auto-updates.

After npm run build, you’ll find Setup My Electron App.exe (and other artifacts) in dist/.

Automating GitHub Releases for Electron Apps

Use actions/create-release and actions/upload-release-asset to publish your installer whenever you push a vX.Y.Z tag.

1. Prerequisites

  • A build script (npm run build) that outputs dist/My Electron App Setup.exe.
  • GITHUB_TOKEN available in repository secrets (auto-provided by GitHub Actions).

2. Create Release

- name: Create Release
  id: create_release
  uses: actions/create-release@v1
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  with:
    tag_name: ${{ github.ref_name }}        # e.g. v1.2.3
    release_name: ${{ github.ref_name }}
    body: |
      Auto-generated release for ${{ github.ref_name }}.
    draft: false                            # publish immediately
    prerelease: false                       # set true for beta/RC
  • id: create_release exposes outputs.upload_url for the upload step.
  • tag_name must match your push trigger (on.push.tags: ['v*']).

3. Upload Release Asset

- name: Upload Release Asset
  uses: actions/upload-release-asset@v1
  with:
    upload_url: ${{ steps.create_release.outputs.upload_url }}
    asset_path: ./dist/My Electron App Setup.exe
    asset_name: MyElectronApp-Setup-v${{ github.ref_name }}.exe
    asset_content_type: application/octet-stream
  • asset_path must exactly match your build output.
  • Include the version in asset_name for clarity.

4. Full Workflow Snippet

name: Publish Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 16

      - name: Install dependencies
        run: npm install

      - name: Build the Electron App
        run: npm run build

      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.ref_name }}
          release_name: ${{ github.ref_name }}
          body: Auto-generated release for ${{ github.ref_name }}.
          draft: false
          prerelease: false

      - name: Upload Release Asset
        uses: actions/upload-release-asset@v1
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: ./dist/My Electron App Setup.exe
          asset_name: MyElectronApp-Setup-v${{ github.ref_name }}.exe
          asset_content_type: application/octet-stream

With this workflow, pushing a tag like v1.0.0 builds your Electron app and publishes the Windows installer as a GitHub Release asset automatically.

Development & Contribution Guide

This guide covers coding conventions, file/folder responsibilities, UI customization tips, and the pull-request workflow for My Electron App v2.0.

File & Folder Responsibilities

  • /README.md
    Project overview, setup, running, packaging, and contribution instructions.
  • /index.html
    Defines the app’s UI structure. Place buttons, input fields, and container elements here.
  • /script.js
    Implements UI behavior. Export or attach functions to event handlers in HTML or via JavaScript.
  • /style.css
    Holds global and component styles. Use class selectors for new UI elements.
  • /package.json
    Specifies metadata, dependencies, and scripts (npm start, npm run package).
  • /assets/ (optional)
    Store icons, images, and other static resources.

Coding Conventions

  • Indentation: 2 spaces
  • Naming: camelCase for functions/variables; PascalCase for classes or constructors
  • Semicolons: always include
  • Functions: keep single-purpose; extract complex logic into modules
  • Commit messages:
    <type>(scope): short description
    • type: feat, fix, docs, chore, refactor
    • scope: ui, build, script
    • Example: feat(ui): add dark-mode toggle

Example: Refactoring an inline handler

Before (inline in index.html):

<button onclick="showMessage()">Click Me</button>

After (JS module):

<button id="msgBtn">Click Me</button>
// script.js
function showMessage() {
  alert('Hello from My Electron App!');
}

document
  .getElementById('msgBtn')
  .addEventListener('click', showMessage);

UI Customization

Adding New Buttons

  1. HTML: Add within <body> in index.html
    <!-- index.html -->
    <button id="awesomeBtn">Awesome Feature</button>
    
  2. JavaScript: Register handler in script.js
    // script.js
    function awesomeFeature() {
      alert('This feature is truly awesome!');
    }
    
    document
      .getElementById('awesomeBtn')
      .addEventListener('click', awesomeFeature);
    
  3. Styling: Define or extend in style.css
    /* style.css */
    #awesomeBtn {
      background-color: #4caf50;
      color: white;
      border: none;
      cursor: pointer;
    }
    

Modifying Layout

  • Wrap new UI sections in semantic containers (<section>, <div class="sidebar">).
  • Use Flexbox or Grid in style.css:
    .toolbar {
      display: flex;
      justify-content: space-between;
      margin-bottom: 1rem;
    }
    

Submitting a Pull Request

  1. Fork & Clone
    git clone https://github.com/your-user/my-electron-app.git
    cd my-electron-app
    
  2. Create a Branch
    git checkout -b feat/your-feature
    
  3. Implement & Test
    • Run npm install
    • Start with npm start
    • Verify UI and behavior across supported platforms.
  4. Commit Changes
    git add .
    git commit -m "feat(ui): add awesome feature button"
    
  5. Push & Open PR
    git push origin feat/your-feature
    
    • Base branch: main
    • Title: concise summary
    • Description:
      • What and why
      • Screenshots or GIFs (if UI changes)
      • Linked issue (if any)
  6. Address Feedback
    • Respond to review comments
    • Push fixes to the same branch
    • Ensure CI checks (linting, packaging) pass

Following these guidelines ensures a consistent codebase and smooth collaboration. We welcome your contributions!

\n \n \n \n \n \n \n ```\n\n### File Layout\n\n├─ package.json \n├─ main.js ← Main process setup \n├─ index.html ← Renderer entrypoint \n├─ renderer.js ← Frontend logic (optional separate file) \n├─ style.css ← Renderer styling \n├─ README.md ← Project overview & setup instructions \n└─ /assets ← Static assets (images, icons)\n\n### Extending the Project\n\n- **Modify UI**: Edit `index.html` and `style.css` \n- **Add Renderer Logic**: Create or update `renderer.js` for complex interactions \n- **Main Process Hooks**: Extend `main.js` to handle new IPC channels or native APIs \n- **Packaging**: Customize `package.json` scripts (`electron-packager` or `electron-builder`) for release builds\n\nWith this structure, you can quickly navigate between UI code in the renderer and native capabilities in the main process.\n## Quick Start & Running\n\nGet the app up and running in under a minute.\n\n### Prerequisites\n\n- Node.js >= 14.x \n- npm >= 6.x (or Yarn)\n\n### 1. Clone the Repository\n\n```bash\ngit clone https://github.com/sandunMadhushan/my-electron-app.git\ncd my-electron-app\n```\n\n### 2. Install Dependencies\n\n```bash\nnpm install\n# or with Yarn\n# yarn install\n```\n\nThis installs both Electron and project-specific packages defined in `package.json`.\n\n### 3. Launch in Development Mode\n\n```bash\nnpm start\n```\n\nThis runs the `start` script (`electron .`) which:\n\n- Loads `main.js`\n- Creates the BrowserWindow and points it at `index.html`\n- Hooks into app lifecycle events for cross-platform behavior\n\nThe app window appears; open DevTools with `Ctrl+Shift+I` (Windows/Linux) or `Cmd+Option+I` (macOS).\n\n### 4. Live Reload (Optional)\n\nTo auto-reload on changes, install `electron-reload`:\n\n```bash\nnpm install --save-dev electron-reload\n```\n\nThen add at the top of `main.js`:\n\n```js\nrequire('electron-reload')(__dirname, {\n electron: require('electron')\n});\n```\n\nNow edits to your HTML, JS or CSS instantly reload the window.\n\n### 5. Build for Distribution\n\nAfter experimenting, package your app:\n\n```bash\nnpm run build\n```\n\n– Uses `electron-builder` (configured in `package.json`) \n– Outputs installers/binaries to `dist/`\n\nLocate your platform’s installer (`.exe`, `.dmg`, `.AppImage`) in the `dist/` folder and distribute it.\n## Packaging & Release\n\nThis section covers creating production-ready Windows installers with electron-builder and automating GitHub Releases via GitHub Actions when you push a version tag.\n\n### Configuring electron-builder in package.json\n\nDefine packaging metadata and output settings under the `build` key in package.json:\n\n```json\n\"build\": {\n \"appId\": \"com.sandunMadhushan.my-electron-app\",\n \"productName\": \"My Electron App\",\n \"directories\": {\n \"output\": \"dist\"\n },\n \"files\": [\n \"**/*\",\n \"!node_modules\",\n \"!dist\",\n \"!release-builds\"\n ],\n \"win\": {\n \"target\": \"nsis\",\n \"icon\": \"icon.ico\"\n }\n}\n```\n\nKey fields:\n- **appId**: reverse-DNS identifier for OS metadata and installer.\n- **productName**: display name in menus, folders and installer.\n- **directories.output**: folder for build artifacts (e.g. `dist/`).\n- **files**: include/exclude globs to bundle only production files.\n- **win.target**: `nsis` produces a Windows installer.\n- **win.icon**: path to your `.ico` file for installer and app.\n\nPractical steps:\n1. Install electron-builder \n ```bash\n npm install --save-dev electron-builder\n ```\n2. Trigger a build \n ```bash\n npm run build\n ```\n3. Customize other platforms:\n - macOS: \n ```json\n \"mac\": {\n \"target\": [\"dmg\",\"zip\"],\n \"icon\": \"icon.icns\"\n }\n ```\n - Linux: \n ```json\n \"linux\": {\n \"target\": [\"AppImage\",\"deb\"]\n }\n ```\n4. Exclude development files: refine `files` globs to omit tests, docs or config.\n5. Code-sign builds: supply certificates via environment variables or an external `electron-builder.yml` to enable auto-updates.\n\nAfter `npm run build`, you’ll find `Setup My Electron App.exe` (and other artifacts) in `dist/`.\n\n### Automating GitHub Releases for Electron Apps\n\nUse `actions/create-release` and `actions/upload-release-asset` to publish your installer whenever you push a `vX.Y.Z` tag.\n\n#### 1. Prerequisites\n- A build script (`npm run build`) that outputs `dist/My Electron App Setup.exe`.\n- `GITHUB_TOKEN` available in repository secrets (auto-provided by GitHub Actions).\n\n#### 2. Create Release\n\n```yaml\n- name: Create Release\n id: create_release\n uses: actions/create-release@v1\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n with:\n tag_name: ${{ github.ref_name }} # e.g. v1.2.3\n release_name: ${{ github.ref_name }}\n body: |\n Auto-generated release for ${{ github.ref_name }}.\n draft: false # publish immediately\n prerelease: false # set true for beta/RC\n```\n\n- `id: create_release` exposes `outputs.upload_url` for the upload step.\n- `tag_name` must match your push trigger (`on.push.tags: ['v*']`).\n\n#### 3. Upload Release Asset\n\n```yaml\n- name: Upload Release Asset\n uses: actions/upload-release-asset@v1\n with:\n upload_url: ${{ steps.create_release.outputs.upload_url }}\n asset_path: ./dist/My Electron App Setup.exe\n asset_name: MyElectronApp-Setup-v${{ github.ref_name }}.exe\n asset_content_type: application/octet-stream\n```\n\n- `asset_path` must exactly match your build output.\n- Include the version in `asset_name` for clarity.\n\n#### 4. Full Workflow Snippet\n\n```yaml\nname: Publish Release\n\non:\n push:\n tags:\n - 'v*'\n\njobs:\n release:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout code\n uses: actions/checkout@v3\n\n - name: Set up Node.js\n uses: actions/setup-node@v3\n with:\n node-version: 16\n\n - name: Install dependencies\n run: npm install\n\n - name: Build the Electron App\n run: npm run build\n\n - name: Create Release\n id: create_release\n uses: actions/create-release@v1\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n with:\n tag_name: ${{ github.ref_name }}\n release_name: ${{ github.ref_name }}\n body: Auto-generated release for ${{ github.ref_name }}.\n draft: false\n prerelease: false\n\n - name: Upload Release Asset\n uses: actions/upload-release-asset@v1\n with:\n upload_url: ${{ steps.create_release.outputs.upload_url }}\n asset_path: ./dist/My Electron App Setup.exe\n asset_name: MyElectronApp-Setup-v${{ github.ref_name }}.exe\n asset_content_type: application/octet-stream\n```\n\nWith this workflow, pushing a tag like `v1.0.0` builds your Electron app and publishes the Windows installer as a GitHub Release asset automatically.\n## Development & Contribution Guide\n\nThis guide covers coding conventions, file/folder responsibilities, UI customization tips, and the pull-request workflow for My Electron App v2.0.\n\n### File & Folder Responsibilities\n\n- `/README.md` \n Project overview, setup, running, packaging, and contribution instructions. \n- `/index.html` \n Defines the app’s UI structure. Place buttons, input fields, and container elements here. \n- `/script.js` \n Implements UI behavior. Export or attach functions to event handlers in HTML or via JavaScript. \n- `/style.css` \n Holds global and component styles. Use class selectors for new UI elements. \n- `/package.json` \n Specifies metadata, dependencies, and scripts (`npm start`, `npm run package`). \n- `/assets/` (optional) \n Store icons, images, and other static resources.\n\n### Coding Conventions\n\n- Indentation: 2 spaces \n- Naming: camelCase for functions/variables; PascalCase for classes or constructors \n- Semicolons: always include \n- Functions: keep single-purpose; extract complex logic into modules \n- Commit messages: \n `(scope): short description` \n • type: feat, fix, docs, chore, refactor \n • scope: `ui`, `build`, `script` \n • Example: `feat(ui): add dark-mode toggle`\n\n#### Example: Refactoring an inline handler\n\nBefore (inline in `index.html`):\n```html\n\n```\nAfter (JS module):\n```html\n\n```\n```javascript\n// script.js\nfunction showMessage() {\n alert('Hello from My Electron App!');\n}\n\ndocument\n .getElementById('msgBtn')\n .addEventListener('click', showMessage);\n```\n\n### UI Customization\n\n#### Adding New Buttons\n\n1. **HTML**: Add within `` in `index.html`\n ```html\n \n \n ```\n2. **JavaScript**: Register handler in `script.js`\n ```javascript\n // script.js\n function awesomeFeature() {\n alert('This feature is truly awesome!');\n }\n\n document\n .getElementById('awesomeBtn')\n .addEventListener('click', awesomeFeature);\n ```\n3. **Styling**: Define or extend in `style.css`\n ```css\n /* style.css */\n #awesomeBtn {\n background-color: #4caf50;\n color: white;\n border: none;\n cursor: pointer;\n }\n ```\n\n#### Modifying Layout\n\n- Wrap new UI sections in semantic containers (`
`, `
`).\n- Use Flexbox or Grid in `style.css`:\n ```css\n .toolbar {\n display: flex;\n justify-content: space-between;\n margin-bottom: 1rem;\n }\n ```\n\n### Submitting a Pull Request\n\n1. **Fork & Clone** \n ```bash\n git clone https://github.com/your-user/my-electron-app.git\n cd my-electron-app\n ```\n2. **Create a Branch** \n ```bash\n git checkout -b feat/your-feature\n ```\n3. **Implement & Test** \n - Run `npm install` \n - Start with `npm start` \n - Verify UI and behavior across supported platforms.\n4. **Commit Changes** \n ```bash\n git add .\n git commit -m \"feat(ui): add awesome feature button\"\n ```\n5. **Push & Open PR** \n ```bash\n git push origin feat/your-feature\n ```\n - Base branch: `main` \n - Title: concise summary \n - Description: \n - What and why \n - Screenshots or GIFs (if UI changes) \n - Linked issue (if any)\n6. **Address Feedback** \n - Respond to review comments \n - Push fixes to the same branch \n - Ensure CI checks (linting, packaging) pass\n\nFollowing these guidelines ensures a consistent codebase and smooth collaboration. We welcome your contributions!"; document.addEventListener('DOMContentLoaded', function() { const contentDiv = AppUtils.dom.query('#documentation-content'); const tocNav = AppUtils.dom.query('#toc-nav'); const tocNavMobile = AppUtils.dom.query('#toc-nav-mobile'); // Initialize mobile menu functionality MobileMenu.init(); // Apply content styling and initialize TOC if (contentDiv) { ContentStyling.applyProseStyles(contentDiv); TableOfContents.init(contentDiv, tocNav, tocNavMobile); } // Setup quick actions QuickActions.init(tocNav, contentDiv); });