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
+5522 -164

No files matched your search

+1
View File
@@ -0,0 +1 @@
frontend_build/
+40 -72
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')
// --- IPC Handlers for window controls ---
ipcMain.on('window-minimize', () => mainWindow?.minimize());
ipcMain.on('window-maximize', () => {
if (mainWindow?.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow?.maximize();
}
// Start the Express server
backendExpressProcess = spawn('node', ['backend/server.js'], { env: { PARENT_PROCESS: JSON.stringify(parrentProcess) } });
});
ipcMain.on('window-close', () => mainWindow?.close());
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
}
// --- 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'),
});
backendExpressProcess.stderr.on('data', (data) => {
console.error(`Express stderr: ${data}`);
});
// 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
+26 -24
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"
}
}
}
+9 -3
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),
},
});