simplify: pure JS tray launcher, spawn npm run start
This commit is contained in:
1 parent
1ad9a59f76
commit
a1edf16c58
4 files changed
+45
-148
No files matched your search
@@ -2,14 +2,13 @@
|
|||||||
"name": "scanner-record-desktop",
|
"name": "scanner-record-desktop",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "src/main.ts",
|
"main": "src/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "electron -r tsx src/main.ts",
|
"dev": "electron .",
|
||||||
"build": "electron-builder --win portable"
|
"build": "electron-builder --win portable"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"electron": "^34.0.0",
|
"electron": "^34.0.0",
|
||||||
"electron-builder": "^25.0.0",
|
"electron-builder": "^25.0.0"
|
||||||
"tsx": "^4.19.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
const { app, Tray, Menu, nativeImage } = require('electron')
|
||||||
|
const { spawn } = require('child_process')
|
||||||
|
const path = require('path')
|
||||||
|
|
||||||
|
const PROJECT_DIR = path.resolve(__dirname, '../../project')
|
||||||
|
let backend = null
|
||||||
|
let tray = null
|
||||||
|
|
||||||
|
const ICON = nativeImage.createFromBuffer(Buffer.from(
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII=',
|
||||||
|
'base64'
|
||||||
|
))
|
||||||
|
|
||||||
|
function startBackend() {
|
||||||
|
backend = spawn('npm.cmd', ['run', 'start'], {
|
||||||
|
cwd: PROJECT_DIR,
|
||||||
|
stdio: 'ignore',
|
||||||
|
env: { ...process.env },
|
||||||
|
shell: true,
|
||||||
|
windowsHide: true,
|
||||||
|
})
|
||||||
|
backend.on('exit', () => { backend = null })
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopBackend() {
|
||||||
|
if (backend) { backend.kill('SIGTERM'); backend = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
app.whenReady().then(() => {
|
||||||
|
tray = new Tray(ICON.resize({ width: 32, height: 32 }))
|
||||||
|
tray.setToolTip('质量追溯系统')
|
||||||
|
tray.setContextMenu(Menu.buildFromTemplate([
|
||||||
|
{ label: '打开页面', click: () => require('child_process').exec('start http://localhost:3000') },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '退出', click: () => { stopBackend(); app.quit() } },
|
||||||
|
]))
|
||||||
|
|
||||||
|
startBackend()
|
||||||
|
})
|
||||||
|
|
||||||
|
app.on('window-all-closed', () => {})
|
||||||
|
app.on('before-quit', () => stopBackend())
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain } from 'electron'
|
|
||||||
import fs from 'fs'
|
|
||||||
import path from 'path'
|
|
||||||
|
|
||||||
/* ===== Paths ===== */
|
|
||||||
const PROJECT_DIR = path.resolve(process.cwd(), '../project')
|
|
||||||
const LOG_DIR = path.join(PROJECT_DIR, 'logs')
|
|
||||||
let isQuitting = false
|
|
||||||
|
|
||||||
/* ===== Icon ===== */
|
|
||||||
const ICON_B64 = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII='
|
|
||||||
function createIcon(size = 32): Electron.NativeImage {
|
|
||||||
return nativeImage.createFromBuffer(Buffer.from(ICON_B64, 'base64')).resize({ width: size, height: size })
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== Log window ===== */
|
|
||||||
let logWindow: BrowserWindow | null = null
|
|
||||||
let logBuffer: string[] = []
|
|
||||||
const MAX_LOG = 2000
|
|
||||||
|
|
||||||
function broadcastLog(line: string): void {
|
|
||||||
logBuffer.push(line)
|
|
||||||
if (logBuffer.length > MAX_LOG) logBuffer.shift()
|
|
||||||
logWindow?.webContents.send('log', line)
|
|
||||||
}
|
|
||||||
|
|
||||||
function createLogWindow(): void {
|
|
||||||
logWindow = new BrowserWindow({
|
|
||||||
width: 850, height: 500, show: false,
|
|
||||||
resizable: true, frame: true,
|
|
||||||
title: '质量追溯系统 - 日志',
|
|
||||||
icon: createIcon(),
|
|
||||||
webPreferences: {
|
|
||||||
preload: path.join(process.cwd(), 'src', 'preload.js'),
|
|
||||||
contextIsolation: true, nodeIntegration: false,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
logWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(LOG_HTML)}`)
|
|
||||||
logWindow.on('close', (e) => {
|
|
||||||
if (!isQuitting) { e.preventDefault(); logWindow?.hide() }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleWindow(): void {
|
|
||||||
logWindow?.isVisible() ? logWindow?.hide() : (logWindow?.show(), logWindow?.focus())
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== Intercept backend logs ===== */
|
|
||||||
function hookConsole(): void {
|
|
||||||
const origLog = console.log
|
|
||||||
const origError = console.error
|
|
||||||
const origWarn = console.warn
|
|
||||||
|
|
||||||
console.log = (...args: any[]) => {
|
|
||||||
origLog(...args)
|
|
||||||
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
|
|
||||||
broadcastLog(line)
|
|
||||||
}
|
|
||||||
console.error = (...args: any[]) => {
|
|
||||||
origError(...args)
|
|
||||||
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
|
|
||||||
broadcastLog(`[E] ${line}`)
|
|
||||||
}
|
|
||||||
console.warn = (...args: any[]) => {
|
|
||||||
origWarn(...args)
|
|
||||||
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
|
|
||||||
broadcastLog(`[W] ${line}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== Start backend in-process ===== */
|
|
||||||
async function startBackend(): Promise<void> {
|
|
||||||
broadcastLog('[后端] 正在加载...')
|
|
||||||
await import(path.join(PROJECT_DIR, 'src/index.ts'))
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== 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 'Consolas','Cascadia Code',monospace;padding:8px}
|
|
||||||
#log{white-space:pre-wrap;word-break:break-all;height:100vh;overflow-y:auto}
|
|
||||||
.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)=>{
|
|
||||||
var m=line.match(/^.{21}(\[.\])\[/);
|
|
||||||
var c=m?{D:'d',I:'i',W:'w',E:'e'}[m[1]]:'i';
|
|
||||||
el.innerHTML+='<span class="'+c+'">'+line.replace(/&/g,'&').replace(/</g,'<')+'</span>\\n';
|
|
||||||
el.scrollTop=el.scrollHeight;
|
|
||||||
});
|
|
||||||
window.electronAPI.getLogBuffer().then(buf=>{for(var l of buf){
|
|
||||||
var m=l.match(/^.{21}(\[.\])\[/),c=m?{D:'d',I:'i',W:'w',E:'e'}[m[1]]:'i';
|
|
||||||
el.innerHTML+='<span class="'+c+'">'+l.replace(/&/g,'&').replace(/</g,'<')+'</span>\\n';
|
|
||||||
}});
|
|
||||||
</script></body></html>`
|
|
||||||
|
|
||||||
/* ===== Tray ===== */
|
|
||||||
let tray: Tray | null = null
|
|
||||||
|
|
||||||
function createTray(): void {
|
|
||||||
tray = new Tray(createIcon(32))
|
|
||||||
tray.setToolTip('质量追溯系统')
|
|
||||||
tray.setContextMenu(Menu.buildFromTemplate([
|
|
||||||
{ label: '打开页面', click: () => { try { require('child_process').exec('start http://localhost:3000') } catch {} } },
|
|
||||||
{ label: '显示/隐藏 日志', click: toggleWindow },
|
|
||||||
{ type: 'separator' },
|
|
||||||
{ label: '退出', click: () => { isQuitting = true; app.quit() } },
|
|
||||||
]))
|
|
||||||
tray.on('double-click', toggleWindow)
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== App lifecycle ===== */
|
|
||||||
app.whenReady().then(() => {
|
|
||||||
;['data', 'logs'].forEach(d => {
|
|
||||||
const p = path.join(PROJECT_DIR, d)
|
|
||||||
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true })
|
|
||||||
})
|
|
||||||
|
|
||||||
hookConsole() // intercept console.log before backend loads
|
|
||||||
createTray()
|
|
||||||
createLogWindow()
|
|
||||||
startBackend()
|
|
||||||
|
|
||||||
setTimeout(() => logWindow?.show(), 1500)
|
|
||||||
})
|
|
||||||
|
|
||||||
app.on('window-all-closed', () => { /* keep running in tray */ })
|
|
||||||
app.on('before-quit', () => {
|
|
||||||
isQuitting = true
|
|
||||||
process.emit('SIGINT') // trigger backend's cleanup (scanner.stop, server close)
|
|
||||||
})
|
|
||||||
|
|
||||||
ipcMain.handle('get-log-buffer', () => logBuffer)
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
const { contextBridge, ipcRenderer } = require('electron')
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('electronAPI', {
|
|
||||||
onLog: (callback) => {
|
|
||||||
ipcRenderer.on('log', (_event, line) => callback(line))
|
|
||||||
},
|
|
||||||
getLogBuffer: () => ipcRenderer.invoke('get-log-buffer'),
|
|
||||||
})
|
|
||||||
Reference in new issue
Block a user