feat(electron/frontend) Electron Full Rework

- **Electron Full Rework**: Completely rewrote `electron/main.js` — removed child process spawn, backend now runs in-process via `require()`; frameless window with custom title bar; dual-mode support (dev loads Vite at `:4200`, production loads built files)
- **`electron/preload.js`**: Enhanced contextBridge to expose `windowControls` (minimize/maximize/close) and `isElectron` flag alongside existing `ipcRenderer` bridge
- **`electron/package.json`**: Updated scripts (`start`, `dev`, `build-front` → calls React build), removed duplicated backend dependencies (backend now required in-process), updated electron-builder config with proper `files` and `extraResources`
- **`TitleBar` component**: New `react_frontend/src/components/layout/TitleBar.tsx` — custom frameless window title bar with drag region, app branding, and IPC-powered minimize/maximize/close buttons
- **`AppLayout`**: Conditionally renders `<TitleBar>` when built for Electron (`VITE_ELECTRON=true`); wrapped content in an extra flex container to accommodate title bar height
- **`vite.config.ts`**: Added `VITE_ELECTRON` env detection — sets `base: './'` for correct asset resolution in `file://` context
- **`api.ts`**: Dynamic base URL — uses `http://localhost:4000/api/v1` in Electron mode, `/api/v1` (proxy-relative) otherwise
- **`router.tsx`**: Conditional router factory — uses `createHashRouter` in Electron mode (required for `file://` navigation) and `createBrowserRouter` for web
- **`electron.d.ts`**: Added TypeScript declarations for `window.electron` global (windowControls, ipcRenderer, isElectron)
- **`package.json`**: Added `build:electron` script with `cross-env VITE_ELECTRON=true`; added `cross-env` devDependency
- Updated `Electron.md`

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
Mohammed AbadandCopilot committed 2026-05-03 02:00:14 +01:00
1 parent 7b84f89b65
commit 4303b33677
14 files changed
+5486 -128

No files matched your search

+132 -28
View File
@@ -9,67 +9,171 @@ tags:
## Overview
Electron 34 wraps the Showy backend + frontend into a standalone desktop application for Windows.
Electron 34 wraps the Showy backend + React frontend into a standalone desktop application for Windows. The backend runs **in-process** (no child process spawn), and the app uses a custom frameless title bar with IPC-driven window controls.
## Architecture
```mermaid
graph TD
E[Electron Main Process] --> |child_process.spawn| B[Node.js Backend]
E --> |BrowserWindow.loadFile| FE[Frontend Build]
FE --> |HTTP requests| B
E --> |IPC: backend-ready| FE
E[Electron Main Process] --> |require in-process| B[Node.js Backend]
E --> |BrowserWindow| FE[React Frontend Build]
FE --> |HTTP localhost:4000| B
FE --> |IPC: windowControls| E
```
## Main Process — `electron/main.js`
1. Spawns backend as a **child process**: `node backend/server.js`
2. Sets `PARENT_PROCESS` env var pointing to Electron user data path
3. Backend auto-restarts if it crashes
4. Creates `BrowserWindow` (1200×720) loading `frontend_build/browser/index.html`
5. Sends `backend-ready` IPC event when backend starts listening
6. On window close → kills backend child process
1. Sets `process.env.PARENT_PROCESS` with Electron user data path
2. Starts backend **in-process** via `require('../backend/server.js')`
3. Creates frameless `BrowserWindow` (1280×800)
4. **Dev mode** (`!app.isPackaged` or `ELECTRON_DEV=true`): loads `http://localhost:4200` (Vite dev server) + opens DevTools
5. **Production mode**: loads `frontend_build/index.html` (hash-routed React app)
6. Registers IPC handlers for window controls
### Window Configuration
| Setting | Value |
|---|---|
| Width | 1200 |
| Height | 720 |
| ----------------- | ------------------------------ |
| Width | 1280 |
| Height | 800 |
| Min Width | 900 |
| Min Height | 600 |
| Frame | `false` (frameless) |
| Context Isolation | `true` |
| Sandbox | `true` |
| Node Integration | `true` |
| Node Integration | `false` |
| Sandbox | `false` (required for preload) |
## Preload Script — `electron/preload.js`
Exposes `electron.ipcRenderer` to the renderer process via `contextBridge.exposeInMainWorld`:
Exposes via `contextBridge.exposeInMainWorld('electron', ...)`:
- `send(channel, data)` — send to main
- `on(channel, callback)` — listen from main
| API | Methods |
| ---------------- | -------------------------------------------------- |
| `isElectron` | `true` (flag for frontend detection) |
| `windowControls` | `minimize()`, `maximize()`, `close()` |
| `ipcRenderer` | `send()`, `on()`, `once()`, `removeAllListeners()` |
## IPC Channels
| Channel | Direction | Purpose |
| ----------------- | --------------- | ----------------------- |
| `window-minimize` | Renderer → Main | Minimize window |
| `window-maximize` | Renderer → Main | Toggle maximize/restore |
| `window-close` | Renderer → Main | Close window |
## Custom Title Bar
The React frontend renders a `<TitleBar>` component when `VITE_ELECTRON=true`:
- Draggable region (`-webkit-app-region: drag`)
- App branding ("SHOWY")
- Min/Max/Close buttons (no-drag region, sends IPC)
See: `react_frontend/src/components/layout/TitleBar.tsx`
## Dev Mode Workflow
1. Start Vite dev server: `cd react_frontend && pnpm dev` (port 4200)
2. Run Electron in dev: `cd electron && pnpm dev`
3. Electron detects `ELECTRON_DEV=true` → loads from Vite HMR server
## Production Build Workflow
1. Build React for Electron: `cd react_frontend && pnpm build:electron`
- Sets `VITE_ELECTRON=true` → hash router, `base: './'`, API points to `localhost:4000`
- Outputs to `electron/frontend_build/`
2. Package with electron-builder: `cd electron && pnpm generate-exe`
- Bundles `frontend_build/`, backend code, and electron files
- Outputs to `dist/electron/`
## Build Configuration
| Field | Value |
|---|---|
| ------- | ---------------------------- |
| `appId` | `x4lo.showy` |
| Target | Windows x64 directory output |
| Icon | From Angular frontend assets |
| Output | `../dist/electron` |
## Frontend Adaptations for Electron
| Concern | Web Mode | Electron Mode |
| ------------ | ----------------------- | ------------------------------------------ |
| Router | `createBrowserRouter` | `createHashRouter` |
| API Base URL | `/api/v1` (Vite proxy) | `http://localhost:4000/api/v1` |
| Asset Paths | `/` base | `./` relative base |
| Title Bar | Hidden (native browser) | Custom `<TitleBar>` component |
| Detection | — | `import.meta.env.VITE_ELECTRON === 'true'` |
## Package Dependencies
- `electron` 34
- `electron-builder` 25
- All backend dependencies (bundled)
| Package | Purpose |
| ---------------------- | ------------------ |
| `electron` ^34 | Runtime |
| `electron-builder` ^25 | Packaging (devDep) |
Backend dependencies live in `backend/package.json` (required in-process at runtime).
## Important Files
| File | Role |
|---|---|
| `electron/main.js` | Main process entry |
| `electron/preload.js` | Context bridge for IPC |
| `electron/package.json` | Electron + backend deps |
| --------------------------------------------------- | ------------------------------------------------------- |
| `electron/main.js` | Main process — in-process backend, window creation, IPC |
| `electron/preload.js` | Context bridge (window controls + IPC) |
| `electron/package.json` | Scripts + builder config |
| `react_frontend/src/components/layout/TitleBar.tsx` | Custom frameless title bar |
| `react_frontend/src/electron.d.ts` | TypeScript types for `window.electron` |
## Folder Structure
### Running from source (`npm run start` in `electron/`)
Before running from source, you need:
1. `cd react_frontend && pnpm build:electron` → builds the React app into `electron/frontend_build/`
2. `cd backend && npm install` → install backend deps
3. `cd electron && npm install` → install electron dep
4. `cd electron && npm start`
Expected structure:
```
Showy/
├── backend/
│ ├── server.js
│ ├── package.json
│ └── node_modules/ ← npm install in backend/
├── electron/
│ ├── main.js
│ ├── preload.js
│ ├── package.json
│ ├── node_modules/ ← npm install in electron/
│ └── frontend_build/ ← created by pnpm build:electron
│ ├── index.html
│ └── assets/
```
### After packaging (`npm run generate-exe`)
```
dist/electron/win-unpacked/
├── Showy.exe
├── resources/
│ ├── app/
│ │ ├── main.js
│ │ ├── preload.js
│ │ └── frontend_build/
│ │ ├── index.html
│ │ └── assets/
│ └── backend/ ← copied via extraResources (no node_modules!)
│ ├── server.js
│ └── ...
└── (Electron runtime DLLs)
```
> **⚠️ Packaging caveat**: The current config excludes `backend/node_modules` from the package via `extraResources`. The packaged app will be missing backend dependencies (Express, Sequelize, etc.) and will crash at runtime. To fix this for distribution, either include `backend/node_modules` in `extraResources`, or move all backend dependencies into `electron/package.json`.
## See Also
- [[Architecture]] — System overview
- [[Frontend]] — React frontend details
- [[Backend]] — API and services
- [[Deployment]] — Docker alternative
+1
View File
@@ -0,0 +1 @@
frontend_build/
+38 -70
View File
@@ -1,31 +1,15 @@
const { spawn } = require('child_process');
const { app, BrowserWindow } = require('electron');
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const url = require('url');
const configService = require('./backend/services/configService');
let backendExpressProcess;
let mainWindow;
const _configService = configService;
const isDev = !app.isPackaged || process.env.ELECTRON_DEV === 'true';
app.on('ready', () => {
// ! Start the Express server loop
startExpressServer();
_configService.createMediaFolders();
// Start the Electron app
startBackend();
createWindow();
});
app.on('before-quit', () => {
if (backendExpressProcess) {
backendExpressProcess.kill();
console.log('Killing backend process.');
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
@@ -38,73 +22,57 @@ app.on('activate', () => {
}
});
// const { dialog, ipcMain } = require('electron');
// ipcMain.on('select-dirs', async (event, arg) => {
// const result = await dialog.showOpenDialog(mainWindow, {
// properties: ['openDirectory']
// })
// console.log('directories selected', result.filePaths)
// })
function startExpressServer() {
let parrentProcess = {
"electron_path": app.getPath('userData')
}
// Start the Express server
backendExpressProcess = spawn('node', ['backend/server.js'], { env: { PARENT_PROCESS: JSON.stringify(parrentProcess) } });
backendExpressProcess.stdout.on('data', (data) => {
console.log(`Express stdout: ${data}`);
if (data.toString().includes('Server started')) { // Adjust to match backend's startup message
mainWindow.webContents.send('backend-ready'); // Send event to frontend
// --- IPC Handlers for window controls ---
ipcMain.on('window-minimize', () => mainWindow?.minimize());
ipcMain.on('window-maximize', () => {
if (mainWindow?.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow?.maximize();
}
});
ipcMain.on('window-close', () => mainWindow?.close());
backendExpressProcess.stderr.on('data', (data) => {
console.error(`Express stderr: ${data}`);
// --- Backend (in-process) ---
function startBackend() {
// Set env before requiring backend so configService / server.js can read it
process.env.PARENT_PROCESS = JSON.stringify({
electron_path: app.getPath('userData'),
});
// Restart the server if it crashes
backendExpressProcess.on('exit', (code, signal) => {
console.log(`Express process exited with code ${code} and signal ${signal}. Restarting...`);
startExpressServer();
});
try {
require(path.join(__dirname, '..', 'backend', 'server.js'));
} catch (err) {
console.error('Failed to start backend:', err);
}
}
// --- Window ---
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 720,
width: 1280,
height: 800,
minWidth: 900,
minHeight: 600,
frame: false,
titleBarStyle: 'hidden',
backgroundColor: '#09090b',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
enableRemoteModule: false,
nodeIntegration: false,
contextIsolation: true,
sandbox: true
}
sandbox: false, // required for preload to access Node APIs
},
});
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, 'frontend_build', 'browser', 'index.html'),
protocol: 'file:',
slashes: true
})
);
if (isDev) {
mainWindow.loadURL('http://localhost:4200');
mainWindow.webContents.openDevTools({ mode: 'detach' });
} else {
mainWindow.loadFile(path.join(__dirname, 'frontend_build', 'index.html'));
}
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.webContents.on('will-navigate', (event, url) => {
event.preventDefault();;
mainWindow.loadURL(`file://${path.join(__dirname, 'dist/showy/index.html')}`);
});
mainWindow.webContents.on('did-fail-load', (event, url) => {
// event.preventDefault();
mainWindow.loadURL(`file://${path.join(__dirname, 'dist/showy/browser/index.html')}`);
});
}
+5183
View File
File diff suppressed because it is too large. Load diff
+25 -23
View File
@@ -1,13 +1,12 @@
{
"name": "showy_electron",
"version": "1.0.0",
"description": "",
"version": "2.0.0",
"description": "Showy Desktop App",
"main": "main.js",
"scripts": {
"electron": "electron .",
"build-front": "ng build --configuration=production --base-href ./",
"copy-front": "",
"copy-back": "copyfiles ../backend/**/* ./frontend_build/",
"start": "electron .",
"dev": "set ELECTRON_DEV=true && electron .",
"build-front": "cd ../react_frontend && pnpm build:electron",
"generate-exe": "electron-builder"
},
"portable": true,
@@ -15,17 +14,28 @@
"build": {
"appId": "x4lo.showy",
"productName": "Showy",
"files": [
"main.js",
"preload.js",
"frontend_build/**/*",
"../backend/**/*",
"!../backend/node_modules/**/*"
],
"extraResources": [
{
"from": "../backend",
"to": "backend",
"filter": ["**/*", "!node_modules/**"]
}
],
"win": {
"target": [
{
"target": "dir",
"arch": [
"x64",
"win32"
]
"arch": ["x64"]
}
],
"icon": "../frontend/src/assets/images/showy.ico"
"icon": "../react_frontend/public/showy.ico"
},
"directories": {
"output": "../dist/electron"
@@ -34,17 +44,9 @@
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.7.9",
"body-parser": "^1.20.3",
"copyfiles": "^2.4.1",
"dotenv": "^16.4.7",
"electron": "^34.0.1",
"electron-builder": "^25.1.8",
"express": "^4.21.2",
"multer": "1.4.5-lts.1",
"mysql2": "^3.12.0",
"sequelize": "^6.37.5",
"sharp": "^0.33.5",
"uuid": "^11.0.5"
"electron": "^34.0.1"
},
"devDependencies": {
"electron-builder": "^25.1.8"
}
}
+8 -2
View File
@@ -1,10 +1,16 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electron', {
isElectron: true,
windowControls: {
minimize: () => ipcRenderer.send('window-minimize'),
maximize: () => ipcRenderer.send('window-maximize'),
close: () => ipcRenderer.send('window-close'),
},
ipcRenderer: {
send: (channel, data) => ipcRenderer.send(channel, data),
on: (channel, listener) => ipcRenderer.on(channel, (event, ...args) => listener(...args)),
once: (channel, listener) => ipcRenderer.once(channel, (event, ...args) => listener(...args)),
removeAllListeners: (channel) => ipcRenderer.removeAllListeners(channel)
}
removeAllListeners: (channel) => ipcRenderer.removeAllListeners(channel),
},
});
+20
View File
@@ -37,6 +37,7 @@
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"cross-env": "^7.0.3",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
@@ -3181,6 +3182,25 @@
}
}
},
"node_modules/cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.1"
},
"bin": {
"cross-env": "src/bin/cross-env.js",
"cross-env-shell": "src/bin/cross-env-shell.js"
},
"engines": {
"node": ">=10.14",
"npm": ">=6",
"yarn": ">=1"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+2
View File
@@ -6,6 +6,7 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"build:electron": "cross-env VITE_ELECTRON=true vite build --outDir ../electron/frontend_build",
"lint": "eslint .",
"preview": "vite preview"
},
@@ -39,6 +40,7 @@
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"cross-env": "^7.0.3",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
@@ -9,6 +9,9 @@ import {
SheetTitle,
} from '@/components/ui/sheet';
import { Sidebar, MobileSidebarContent } from './Sidebar';
import { TitleBar } from './TitleBar';
const isElectron = import.meta.env.VITE_ELECTRON === 'true' || !!window.electron?.isElectron;
export function AppLayout() {
const [mobileOpen, setMobileOpen] = useState(false);
@@ -20,7 +23,10 @@ export function AppLayout() {
}, [pathname]);
return (
<div className="flex h-screen overflow-hidden">
<div className="flex h-screen flex-col overflow-hidden">
{isElectron && <TitleBar />}
<div className="flex flex-1 overflow-hidden">
{/* Desktop sidebar */}
<div className="hidden md:block">
<Sidebar />
@@ -50,5 +56,6 @@ export function AppLayout() {
</div>
</main>
</div>
</div>
);
}
@@ -0,0 +1,38 @@
import { Minus, Square, X } from 'lucide-react';
export function TitleBar() {
const minimize = () => window.electron?.windowControls.minimize();
const maximize = () => window.electron?.windowControls.maximize();
const close = () => window.electron?.windowControls.close();
return (
<div className="flex h-14 select-none items-center justify-between border-b border-border bg-background"
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
>
<div className="flex items-center gap-2 pl-3">
<span className="text-xs font-semibold tracking-wide text-foreground/80">SHOWY</span>
</div>
<div className="flex h-full" style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}>
<button
onClick={minimize}
className="flex h-full w-11 items-center justify-center transition-colors hover:bg-muted"
>
<Minus className="h-3.5 w-3.5" />
</button>
<button
onClick={maximize}
className="flex h-full w-11 items-center justify-center transition-colors hover:bg-muted"
>
<Square className="h-3 w-3" />
</button>
<button
onClick={close}
className="flex h-full w-11 items-center justify-center transition-colors hover:bg-red-500 hover:text-white"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
export {};
declare global {
interface Window {
electron?: {
isElectron: boolean;
windowControls: {
minimize: () => void;
maximize: () => void;
close: () => void;
};
ipcRenderer: {
send: (channel: string, data?: unknown) => void;
on: (channel: string, listener: (...args: unknown[]) => void) => void;
once: (channel: string, listener: (...args: unknown[]) => void) => void;
removeAllListeners: (channel: string) => void;
};
};
}
}
+3 -2
View File
@@ -1,7 +1,8 @@
import axios from 'axios';
// const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:4000/api/v1';
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://showyback.coolguy.space/api/v1';
const API_BASE_URL = import.meta.env.VITE_ELECTRON === 'true'
? 'http://localhost:4000/api/v1'
: (import.meta.env.VITE_API_URL || '/api/v1');
export const api = axios.create({
baseURL: API_BASE_URL,
+5 -2
View File
@@ -1,4 +1,4 @@
import { createBrowserRouter } from 'react-router-dom';
import { createBrowserRouter, createHashRouter } from 'react-router-dom';
import { lazy, Suspense, type ReactNode } from 'react';
import { AppLayout } from '@/components/layout/AppLayout';
import {
@@ -90,7 +90,10 @@ function SuspensePage({ children, fallback }: { children: ReactNode; fallback?:
return <Suspense fallback={fallback ?? <HomeSkeleton />}>{children}</Suspense>;
}
export const router = createBrowserRouter([
const isElectron = import.meta.env.VITE_ELECTRON === 'true';
const createRouter = isElectron ? createHashRouter : createBrowserRouter;
export const router = createRouter([
{
element: <AppLayout />,
children: [
+3
View File
@@ -3,8 +3,11 @@ import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'
const isElectron = process.env.VITE_ELECTRON === 'true';
// https://vite.dev/config/
export default defineConfig({
base: isElectron ? './' : '/',
plugins: [react(), tailwindcss()],
resolve: {
alias: {