feat: add Electron desktop app with tray + log window

This commit is contained in:
zlm committed 2026-06-10 11:18:10 +08:00
1 parent aebca40edf
commit f49f6dcd3e
4 files changed
+257

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
{
"name": "scanner-record-desktop",
"version": "1.0.0",
"private": true,
"main": "dist/main.js",
"scripts": {
"dev": "tsc && electron dist/main.js",
"build": "tsc",
"start": "electron dist/main.js"
},
"devDependencies": {
"electron": "^34.0.0",
"tsx": "^4.19.0",
"typescript": "^5.7.0"
}
}
+217
View File
@@ -0,0 +1,217 @@
import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain, Notification } from 'electron'
import { spawn, ChildProcess } from 'child_process'
import fs from 'fs'
import path from 'path'
/* ===== Paths ===== */
const PROJECT_DIR = path.resolve(__dirname, '../../project')
const LOG_DIR = path.resolve(PROJECT_DIR, 'logs')
const isDev = !app.isPackaged
/* ===== Tray icon ===== */
const ICON_B64 = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII='
function createIcon(): Electron.NativeImage {
return nativeImage.createFromBuffer(Buffer.from(ICON_B64, 'base64'))
}
/* ===== Backend process ===== */
let backend: ChildProcess | null = null
let backendExited = false
function startBackend(): void {
const cmd = isDev ? 'npx' : 'node'
const args = isDev ? ['tsx', 'src/index.ts'] : ['dist/index.js']
const env: NodeJS.ProcessEnv = {
...process.env,
SKIP_PLC: '1',
PORT: '3000',
}
backend = spawn(cmd, args, {
cwd: PROJECT_DIR,
stdio: ['ignore', 'pipe', 'pipe'],
env,
windowsHide: true, // No console window on Windows
})
backend.stdout?.on('data', (d: Buffer) => {
const lines = d.toString().split('\n').filter(Boolean)
for (const line of lines) {
broadcastLog(line)
}
})
backend.stderr?.on('data', (d: Buffer) => {
const lines = d.toString().split('\n').filter(Boolean)
for (const line of lines) {
broadcastLog(`[E] ${line}`)
}
})
backend.on('exit', (code) => {
backendExited = true
broadcastLog(`[后端] 进程退出 (code=${code})`)
if (!app.isQuitting) {
setTimeout(startBackend, 3000) // auto-restart
}
})
}
function stopBackend(): void {
if (backend && !backendExited) {
backend.kill('SIGTERM')
}
}
/* ===== Log window ===== */
let logWindow: BrowserWindow | null = null
let logBuffer: string[] = []
let logWatcher: fs.FSWatcher | null = null
function broadcastLog(line: string): void {
logBuffer.push(line)
if (logBuffer.length > 1000) logBuffer.shift()
logWindow?.webContents.send('log', line)
}
function getTodayLogPath(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return path.join(LOG_DIR, `${y}-${m}-${dd}.log`)
}
function watchLogFile(): void {
const logPath = getTodayLogPath()
if (!fs.existsSync(logPath)) return
let fileSize = fs.statSync(logPath).size
logWatcher = fs.watch(logPath, () => {
try {
const stats = fs.statSync(logPath)
if (stats.size > fileSize) {
const fd = fs.openSync(logPath, 'r')
const buf = Buffer.alloc(stats.size - fileSize)
fs.readSync(fd, buf, 0, buf.length, fileSize)
fs.closeSync(fd)
fileSize = stats.size
const lines = buf.toString().split('\n').filter(Boolean)
for (const line of lines) {
broadcastLog(line)
}
}
} catch { /* ignore */ }
})
}
function createLogWindow(): void {
logWindow = new BrowserWindow({
width: 850,
height: 500,
show: false,
resizable: true,
frame: true,
title: '质量追溯系统 - 日志',
icon: createIcon(),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
})
logWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(LOG_HTML)}`)
logWindow.on('close', (e) => {
if (!app.isQuitting) {
e.preventDefault()
logWindow?.hide()
}
})
}
/* ===== Log window HTML ===== */
const LOG_HTML = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #1e1e2e; color: #cdd6f4; font: 13px/1.5 'Cascadia Code', 'Consolas', monospace; padding: 8px; }
#log { white-space: pre-wrap; word-break: break-all; }
.d { color: #6c7086; } .i { color: #cdd6f4; } .w { color: #f9e2af; } .e { color: #f38ba8; }
</style>
</head>
<body><div id="log"></div>
<script>
const el = document.getElementById('log');
window.electronAPI.onLog((line) => {
const prefix = line.match(/^.{21}(\[.\])\[/);
const level = prefix ? prefix[1] : '[I]';
const cls = { '[D]': 'd', '[I]': 'i', '[W]': 'w', '[E]': 'e' }[level] || 'i';
el.innerHTML += '<span class="' + cls + '">' + escapeHtml(line) + '</span>\\n';
el.scrollTop = el.scrollHeight;
});
function escapeHtml(s) {
return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
</script>
</body>
</html>`
/* ===== Tray ===== */
let tray: Tray | null = null
function createTray(): void {
tray = new Tray(createIcon())
tray.setToolTip('质量追溯系统')
const ctx = Menu.buildFromTemplate([
{
label: '显示/隐藏 日志',
click: () => { logWindow?.isVisible() ? logWindow?.hide() : logWindow?.show() },
},
{ type: 'separator' },
{
label: '重启后端',
click: () => { stopBackend(); setTimeout(startBackend, 1000) },
},
{ type: 'separator' },
{
label: '退出',
click: () => { app.isQuitting = true; stopBackend(); app.quit() },
},
])
tray.setContextMenu(ctx)
tray.on('double-click', () => {
logWindow?.isVisible() ? logWindow?.hide() : logWindow?.show()
})
}
/* ===== App lifecycle ===== */
app.whenReady().then(() => {
createTray()
createLogWindow()
startBackend()
watchLogFile()
// Show log window on first launch
setTimeout(() => logWindow?.show(), 1500)
})
app.on('window-all-closed', () => {
// Don't quit - keep running in tray
})
app.on('before-quit', () => {
app.isQuitting = true
stopBackend()
if (logWatcher) logWatcher.close()
})
ipcMain.handle('get-log-buffer', () => logBuffer)
+8
View File
@@ -0,0 +1,8 @@
import { contextBridge, ipcRenderer } from 'electron'
contextBridge.exposeInMainWorld('electronAPI', {
onLog: (callback: (line: string) => void) => {
ipcRenderer.on('log', (_event, line: string) => callback(line))
},
getLogBuffer: () => ipcRenderer.invoke('get-log-buffer'),
})
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}