feat: M0-M2 骨架落地(服务端/前端/宿主/数据库/积分引擎)

- server: Go 单二进制骨架,embed 内嵌前端,配置/迁移/HTTP 路由
- store: system.db + event.db 两套迁移,业务表 + 种子数据
- domain: 积分引擎(并列三口径/计分通道/流水/排名/破纪录)+ 68 个测试
- web: Vite + Vue 三入口骨架 + shared 层(类型/API/WebSocket 客户端)
- console: Electron 宿主骨架(选屏/防熄屏/进程守护/托盘)
This commit is contained in:
AskaEth committed 2026-09-09 18:36:40 +08:00
1 parent a61d793d79
commit 7d5d94f815
76 files changed
+10131

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
# Scoreboard Console
赛事积分榜系统的桌面宿主(Electron)。它只做四件事:
1. 拉起并守护同目录(或配置指定)的 `scoreboard.exe`,把它的 stdout/stderr 接管到管理窗口与日志文件;
2. 用 `screen.getAllDisplays()` 枚举显示器,把大屏页面投到扩展屏;
3. `powerSaveBlocker.start('prevent-display-sleep')` 防熄屏;
4. 提供启动/停止/状态/日志的管理 GUI 和托盘菜单。
规范来源:`devdocs/06-大屏端设计.md` 第 6 节、`devdocs/10-部署与现场方案.md` 第 4 节。
## 目录结构
```
console/
├── package.json # main 指向 main/index.js;electron-builder 配置
├── config.json # 运行配置(端口 / exe 路径 / 选屏策略)
├── main/
│ ├── index.js # 应用入口:窗口 / 托盘 / IPC / 生命周期
│ ├── config.js # 配置加载与合并、exe 路径解析
│ ├── service.js # 服务端子进程守护:spawn / 日志转发 / 健康检查 / 自动重启
│ ├── displays.js # 大屏窗口管理:选屏、kiosk、排布、24h 重载
│ ├── log-bus.js # 日志环形缓冲 + 落文件 + 广播
│ └── tray-icon.js # 托盘图标(base64 内嵌,无外部资源文件)
└── renderer/
├── index.html # 管理窗口
├── styles.css
├── app.js
└── preload.js # contextBridge 白名单
```
## 运行方式
```bash
cd console
npm install # 首次需要下载 Electron
npm start # 等价于 electron .
```
开发时把 `scoreboard.exe` 放在以下任一位置都能被找到(`config.json` 里的相对路径会按顺序探测):
1. `console/`
2. 当前工作目录
3. 仓库根目录
4. `dist/`
现场(部署包)形态:
```
scoreboard-windows-amd64/
├── Scoreboard Console.exe
├── resources/app.asar # 内含 main/ renderer/ config.json
├── config.json # exe 旁边的可编辑配置
├── scoreboard.exe
├── config.yaml
├── rules/
├── data/
└── logs/console.log # 运行时生成
```
打包后 `config.json` 读取顺序:`SCOREBOARD_CONSOLE_CONFIG` 环境变量 → exe 同目录的 `config.json`。
## 行为说明
| 场景 | 行为 |
| --- | --- |
| 只有一块屏 | 窗口化(屏幕 80% 大小、居中),不做多屏编排,**不挂** `display-metrics-changed` 等监听(行为冻结);`F11` 手动切换全屏 |
| 多块屏 | 除主屏外每块屏一个 kiosk 窗口,按 `display.bounds`(DIP)定位,窗口 `setIgnoreMouseEvents(true)`,光标由页面 CSS 隐藏 |
| 选屏 | 运行时枚举,不写死坐标;`selection` 可选 `all-secondary`(默认)/ `all` / `specified` |
| 页面锁定 | 每块屏各锁一页,URL 形如 `http://127.0.0.1:8080/display?page=standings&lock=1&screen=<id>&instance=<host>-<id>`,页序按 `display.pages` 轮转 |
| 防熄屏 | Console 启动即生效,退出时释放;前台后台都算 |
| 服务端就绪 | 首次 `/api/health` 通过后开大屏窗口;等待超过 `display.waitForServerMs` 也先开,避免现场只见桌面 |
| 服务端崩溃 | 按 `restartDelayMs` 递增退避自动重启(`maxRestarts=0` 为无限);恢复健康后自动重载大屏 |
| 关管理窗口 | 只隐藏到托盘,服务端继续运行;退出必须走托盘「退出」 |
| 日志 | 内存环形缓冲(`log.maxLines`)+ 文件 `logs/console.log`(超 `maxFileBytes` 轮转一份 `.1`) |
## 配置项(`config.json`)
| 键 | 默认值 | 说明 |
| --- | --- | --- |
| `server.exe` | `scoreboard.exe` | 相对路径按上文顺序探测,也可写绝对路径 |
| `server.args` | `["-config","config.yaml"]` | 传给服务端的参数 |
| `server.host` / `server.port` | `127.0.0.1` / `8080` | 健康检查与管理面板地址(`0.0.0.0` 会自动换成回环地址探测) |
| `server.autoStart` | `true` | Console 启动后是否立刻拉起服务端 |
| `server.healthIntervalMs` | `5000` | 健康检查间隔 |
| `server.restartDelayMs` | `3000` | 重启基础退避,每次翻倍,最多 5 倍 |
| `server.maxRestarts` | `0` | 0 = 无限重启 |
| `display.selection` | `all-secondary` | `all-secondary` / `all` / `specified` |
| `display.displays` | `[]` | `specified` 时生效,填 display id 或 0 起序号 |
| `display.pages` | `["standings","medals","individual","results","records"]` | 按屏序轮转锁定 |
| `display.pageParam` | `page` | 页面 URL 参数名 |
| `display.kiosk` | `true` | 多屏时是否 kiosk(单屏恒窗口化) |
| `display.ignoreMouse` | `true` | 多屏窗口是否忽略鼠标 |
| `display.reloadEveryHours` | `24` | 定时重载兜底,0 = 关闭 |
| `display.waitForServerMs` | `20000` | 服务端未就绪时开大屏的兜底等待 |
| `display.backgroundColor` | `#0b0f1a` | 窗口底色,减少加载白闪 |
| `admin.width` / `admin.height` | `1040` / `760` | 管理窗口初始尺寸 |
| `log.maxLines` / `log.file` / `log.maxFileBytes` | `2000` / `logs/console.log` / `4194304` | 日志缓冲与文件 |
配置缺项自动用内置默认值,文件不存在或 JSON 语法错误时回落到全默认值,并在管理窗口顶部给出提示。
## 打包计划(electron-builder,尚未跑通)
`package.json` 里已写好 `build` 段:
```bash
cd console
npm install
npm run dist # electron-builder --win --x64 → ../dist/console/
npm run pack # 只出目录,不生成安装包,便于现场调试
```
- 产物:NSIS 安装包 + zip(`Scoreboard Console-0.1.0-x64.*`)。
- `extraFiles` 会把 `../dist/scoreboard.exe` 与 `../config.yaml` 拷到安装目录,最终形成第 4 节里的部署包形态。
- 图标资源目录 `build/` 尚未提供,暂用 Electron 默认图标;补上 `build/icon.ico` 后自动生效。
- **未在 Windows 构建机上实际执行过 `npm run dist`**(本机没有安装 Electron/electron-builder,也按要求未执行 npm install)。
## 尚未实机验证
以下内容只做了静态语法检查,需要在 Windows + 真实多显示器环境跑一遍:
- 多屏 kiosk 定位与 `display-metrics-changed` 重排(改分辨率 / 缩放 / 插拔 HDMI)。
- `powerSaveBlocker` 在长时间后台下的实际效果。
- 托盘图标在 Windows 任务栏的显示效果(16px 缩放)。
- `scoreboard.exe` 真实拉起、日志转发、健康检查与崩溃重启的端到端链路。
- electron-builder 打包与 NSIS 安装。
+32
View File
@@ -0,0 +1,32 @@
{
"server": {
"exe": "scoreboard.exe",
"args": ["-config", "config.yaml"],
"host": "127.0.0.1",
"port": 8080,
"autoStart": true,
"healthIntervalMs": 5000,
"restartDelayMs": 3000,
"maxRestarts": 0
},
"display": {
"selection": "all-secondary",
"displays": [],
"pages": ["standings", "medals", "individual", "results", "records"],
"pageParam": "page",
"kiosk": true,
"ignoreMouse": true,
"reloadEveryHours": 24,
"waitForServerMs": 20000,
"backgroundColor": "#0b0f1a"
},
"admin": {
"width": 1040,
"height": 760
},
"log": {
"maxLines": 2000,
"file": "logs/console.log",
"maxFileBytes": 4194304
}
}
+95
View File
@@ -0,0 +1,95 @@
'use strict'
const fs = require('fs')
const path = require('path')
// 默认值写死在代码里:config.json 只覆盖要改的项。
// 这样升级新增字段时老配置依然能用,现场也不容易配出半成品。
const DEFAULTS = {
server: {
exe: 'scoreboard.exe',
args: ['-config', 'config.yaml'],
host: '127.0.0.1',
port: 8080,
autoStart: true,
healthIntervalMs: 5000,
restartDelayMs: 3000,
// 0 表示无限重启;服务端是现场唯一进程,崩了必须拉起来
maxRestarts: 0
},
display: {
// all-secondary | all | specified
selection: 'all-secondary',
displays: [],
pages: ['standings', 'medals', 'individual', 'results', 'records'],
pageParam: 'page',
kiosk: true,
ignoreMouse: true,
reloadEveryHours: 24,
// 服务端迟迟没就绪时的兜底:超时后也把大屏开出来,避免现场一片黑
waitForServerMs: 20000,
backgroundColor: '#0b0f1a'
},
admin: {
width: 1040,
height: 760
},
log: {
maxLines: 2000,
file: 'logs/console.log',
maxFileBytes: 4 * 1024 * 1024
}
}
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
function merge(base, override) {
const out = isPlainObject(base) ? { ...base } : {}
if (!isPlainObject(override)) return out
for (const [key, value] of Object.entries(override)) {
if (value === undefined) continue
out[key] = isPlainObject(value) && isPlainObject(base[key]) ? merge(base[key], value) : value
}
return out
}
function readJson(file) {
try {
const raw = fs.readFileSync(file, 'utf8')
return { values: JSON.parse(raw), warning: null }
} catch (err) {
if (err.code === 'ENOENT') return { values: {}, warning: `配置文件不存在,使用内置默认值:${file}` }
return { values: {}, warning: `配置文件无法解析,使用内置默认值:${file}(${err.message})` }
}
}
function loadConfig(configPath) {
const { values, warning } = readJson(configPath)
return {
path: configPath,
values: merge(DEFAULTS, values),
warning
}
}
// 相对路径的 exe 需要按「部署包根目录」理解,而部署包根目录在不同形态下不同:
// 开发时是 console/ 的上级,打包后是 exe 所在目录。逐个候选位置探测,避免写死。
function resolveExecutable(exe, configPath) {
if (!exe) return { path: null, candidates: [] }
if (path.isAbsolute(exe)) return { path: exe, candidates: [exe] }
const configDir = path.dirname(configPath)
const candidates = [
configDir,
process.cwd(),
path.resolve(configDir, '..'),
path.resolve(configDir, '..', 'dist')
].map((dir) => path.resolve(dir, exe))
const found = candidates.find((candidate) => fs.existsSync(candidate))
return { path: found || candidates[0], candidates: [...new Set(candidates)] }
}
module.exports = { DEFAULTS, loadConfig, merge, resolveExecutable }
+276
View File
@@ -0,0 +1,276 @@
'use strict'
const os = require('os')
const { BrowserWindow, screen } = require('electron')
const SELECTION = {
ALL_SECONDARY: 'all-secondary',
ALL: 'all',
SPECIFIED: 'specified'
}
// 大屏窗口管理:按显示器枚举结果开窗,绝不写死坐标。
// 坐标一律用 DIP(display.bounds),页面内部再用 CSS 缩放适配,两边互不干扰。
class DisplayManager {
constructor({ values, server, log }) {
this.display = values.display
this.server = server
this.log = log
this.enabled = false
this.single = true
this.boundSingle = null
this.windows = new Map() // displayId -> { win, page, reloadTimer }
this.screenListeners = []
this.layoutTimer = null
}
enable() {
if (this.enabled) return
this.enabled = true
this.layout()
}
pageFor(index) {
const pages = Array.isArray(this.display.pages) && this.display.pages.length ? this.display.pages : ['standings']
// 单屏没有编排可言,固定锁第一页(默认总积分榜)
if (this.single) return pages[0]
return pages[index % pages.length]
}
pickDisplays() {
const all = screen.getAllDisplays()
const primary = screen.getPrimaryDisplay()
// 单屏机器上谈「扩展屏编排」没有意义,直接窗口化
if (all.length <= 1) return { single: true, displays: all.slice(0, 1) }
const selection = this.display.selection || SELECTION.ALL_SECONDARY
let picked
if (selection === SELECTION.ALL) {
picked = all.slice()
} else if (selection === SELECTION.SPECIFIED) {
picked = this.pickSpecified(all)
} else {
picked = all.filter((item) => item.id !== primary.id)
}
// 只有整机就一块屏时才是「单屏测试模式」;笔记本 + 一块扩展屏属于多屏场景,
// 扩展屏要正常 kiosk,不能退化成窗口化
if (!picked.length) return { single: true, displays: [primary] }
return { single: false, displays: picked }
}
// displays 配置里可以写 display.id,也可以写 0 起的序号
pickSpecified(all) {
const wanted = Array.isArray(this.display.displays) ? this.display.displays : []
const picked = []
for (const key of wanted) {
const match = typeof key === 'number' ? all.find((item) => item.id === key) || all[key] : all.find((item) => String(item.id) === String(key))
if (match && !picked.includes(match)) picked.push(match)
}
return picked
}
layout() {
if (!this.enabled) return
const { single, displays } = this.pickDisplays()
this.single = single
this.bindScreenListeners(single)
const wanted = new Set(displays.map((item) => item.id))
for (const [displayId, entry] of [...this.windows]) {
if (!wanted.has(displayId)) {
this.destroyEntry(displayId, entry)
}
}
displays.forEach((display, index) => {
const page = this.pageFor(index)
const existing = this.windows.get(display.id)
if (existing) {
this.applyGeometry(existing.win, display, single)
if (existing.page !== page) {
existing.page = page
this.loadPage(existing, display, page)
}
return
}
this.windows.set(display.id, this.createWindow(display, index, single, page))
})
this.log.push('console', `大屏排布完成:${single ? '单屏窗口化' : `多屏 kiosk × ${displays.length}`},显示器 ${displays.map((d) => d.id).join(', ')}`)
}
createWindow(display, index, single, page) {
const bounds = display.bounds
const win = new BrowserWindow({
...this.geometryFor(display, single),
show: false,
frame: single,
kiosk: !single && this.display.kiosk !== false,
autoHideMenuBar: true,
backgroundColor: this.display.backgroundColor || '#000000',
title: `大屏 · ${page}`,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
// 大屏常年在后台焦点之外,默认节流会冻结动画和定时器
backgroundThrottling: false
}
})
// 大屏页零交互控件;窗口层再兜一道,防止现场误触鼠标
if (!single && this.display.ignoreMouse !== false) {
win.setIgnoreMouseEvents(true)
}
// F11 只在单屏模式下有意义(现场调试用),多屏 kiosk 不允许切走
if (single) {
win.webContents.on('before-input-event', (event, input) => {
if (input.type === 'keyDown' && input.key === 'F11') {
event.preventDefault()
win.setFullScreen(!win.isFullScreen())
}
})
}
win.once('ready-to-show', () => {
if (!win.isDestroyed()) win.show()
})
win.webContents.on('render-process-gone', (_event, details) => {
this.log.push('console', `大屏渲染进程异常(display=${display.id},${details.reason}),将重载`)
if (!win.isDestroyed()) win.webContents.reload()
})
const entry = { win, page, reloadTimer: null }
// 无人值守跑 24h 以上,定时重载兜底内存与连接泄漏
const hours = Number(this.display.reloadEveryHours) || 0
if (hours > 0) {
entry.reloadTimer = setInterval(() => {
if (!win.isDestroyed()) win.webContents.reload()
}, hours * 3600 * 1000)
}
this.applyGeometry(win, display, single)
this.loadPage(entry, display, page)
this.log.push('console', `打开大屏窗口 display=${display.id} bounds=${bounds.width}x${bounds.height}@${bounds.x},${bounds.y} page=${page}`)
return entry
}
geometryFor(display, single) {
const bounds = display.bounds
if (!single) return { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
// 单屏窗口化:不铺满,留出边距方便看管理窗口和调试
const width = Math.round(bounds.width * 0.8)
const height = Math.round(bounds.height * 0.8)
return {
x: bounds.x + Math.round((bounds.width - width) / 2),
y: bounds.y + Math.round((bounds.height - height) / 2),
width,
height
}
}
applyGeometry(win, display, single) {
if (!win || win.isDestroyed()) return
if (single) {
if (win.isKiosk()) win.setKiosk(false)
if (win.isFullScreen()) win.setFullScreen(false)
} else if (this.display.kiosk !== false) {
win.setKiosk(true)
}
win.setBounds(this.geometryFor(display, single))
}
loadPage(entry, display, page) {
if (!entry || !entry.win || entry.win.isDestroyed()) return
const url = this.urlFor(display, page)
this.log.push('console', `大屏加载 ${url}`)
entry.win.loadURL(url).catch((err) => {
// 服务端还没起来时加载失败是正常的,健康检查通过后会重排重载
this.log.push('console', `大屏加载失败(display=${display.id}):${err.message}`)
})
}
urlFor(display, page) {
const params = new URLSearchParams()
params.set(this.display.pageParam || 'page', page)
// lock=1 告知页面锁死单页,不参与轮播
params.set('lock', '1')
params.set('screen', String(display.id))
params.set('instance', `${os.hostname()}-${display.id}`)
return `http://127.0.0.1:${this.server.port}/display?${params.toString()}`
}
// 单屏模式要「行为冻结」:不跟随屏幕变化重排,所以连监听都不挂
bindScreenListeners(single) {
if (this.screenListeners.length && this.boundSingle === single) return
this.unbindScreenListeners()
this.boundSingle = single
if (single) return
const schedule = () => {
if (this.layoutTimer) clearTimeout(this.layoutTimer)
// 分辨率/缩放变化会连续触发多次,防抖后再重排
this.layoutTimer = setTimeout(() => {
this.layoutTimer = null
this.layout()
}, 600)
}
screen.on('display-metrics-changed', schedule)
screen.on('display-added', schedule)
screen.on('display-removed', schedule)
this.screenListeners = [
['display-metrics-changed', schedule],
['display-added', schedule],
['display-removed', schedule]
]
}
unbindScreenListeners() {
for (const [event, handler] of this.screenListeners) {
screen.removeListener(event, handler)
}
this.screenListeners = []
}
destroyEntry(displayId, entry) {
if (entry.reloadTimer) clearInterval(entry.reloadTimer)
if (entry.win && !entry.win.isDestroyed()) entry.win.destroy()
this.windows.delete(displayId)
this.log.push('console', `关闭大屏窗口 display=${displayId}`)
}
relayout() {
if (!this.enabled) return
for (const [, entry] of this.windows) {
if (entry.win && !entry.win.isDestroyed()) entry.win.webContents.reload()
}
this.layout()
}
getInfo() {
return [...this.windows.entries()].map(([displayId, entry]) => ({
displayId,
page: entry.page,
url: entry.win && !entry.win.isDestroyed() ? entry.win.webContents.getURL() : '',
bounds: entry.win && !entry.win.isDestroyed() ? entry.win.getBounds() : null
}))
}
closeAll() {
if (this.layoutTimer) clearTimeout(this.layoutTimer)
this.unbindScreenListeners()
for (const [displayId, entry] of [...this.windows]) {
this.destroyEntry(displayId, entry)
}
this.enabled = false
}
}
module.exports = { DisplayManager, SELECTION }
+299
View File
@@ -0,0 +1,299 @@
'use strict'
const path = require('path')
const {
app,
BrowserWindow,
Menu,
Tray,
ipcMain,
powerSaveBlocker,
shell
} = require('electron')
const { loadConfig, resolveExecutable } = require('./config')
const { LogBus } = require('./log-bus')
const { ServiceSupervisor } = require('./service')
const { DisplayManager } = require('./displays')
const { createTrayIcon } = require('./tray-icon')
// 现场只允许一个实例:两个 Console 会互相抢同一个服务端端口和同一块大屏
if (!app.requestSingleInstanceLock()) {
app.quit()
} else {
main()
}
function main() {
let cfg = null
let log = null
let service = null
let displays = null
let adminWindow = null
let tray = null
let powerBlockerId = null
let displayFallbackTimer = null
let displaysEnabled = false
let quitting = false
let shutdownDone = false
function resolveConfigPath() {
if (process.env.SCOREBOARD_CONSOLE_CONFIG) {
return path.resolve(process.env.SCOREBOARD_CONSOLE_CONFIG)
}
// 打包后 config.json 放在 exe 旁边,方便现场直接改,不藏在 asar 里
if (app.isPackaged) {
return path.join(path.dirname(app.getPath('exe')), 'config.json')
}
return path.join(__dirname, '..', 'config.json')
}
function statusSnapshot() {
const status = service ? service.status : { state: 'stopped', stateLabel: '已停止' }
return {
...status,
configPath: cfg ? cfg.path : null,
configWarning: cfg ? cfg.warning : null,
displays: displays ? displays.getInfo() : [],
powerSaveBlocked: powerBlockerId !== null ? powerSaveBlocker.isStarted(powerBlockerId) : false,
appVersion: app.getVersion()
}
}
function sendToAdmin(channel, payload) {
if (adminWindow && !adminWindow.isDestroyed()) {
adminWindow.webContents.send(channel, payload)
}
}
function broadcastStatus() {
sendToAdmin('service:status', statusSnapshot())
}
function showAdmin() {
if (!adminWindow || adminWindow.isDestroyed()) {
createAdminWindow()
return
}
if (adminWindow.isMinimized()) adminWindow.restore()
adminWindow.show()
adminWindow.focus()
}
function createAdminWindow() {
const { width, height } = cfg.values.admin
adminWindow = new BrowserWindow({
width,
height,
minWidth: 860,
minHeight: 600,
title: 'Scoreboard Console · 启动管理',
backgroundColor: '#0f1420',
show: false,
webPreferences: {
preload: path.join(__dirname, '..', 'renderer', 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
})
adminWindow.loadFile(path.join(__dirname, '..', 'renderer', 'index.html'))
adminWindow.once('ready-to-show', () => adminWindow.show())
// 关窗只隐藏,服务端和守护逻辑要继续在托盘里跑
adminWindow.on('close', (event) => {
if (quitting) return
event.preventDefault()
adminWindow.hide()
log.push('console', '管理窗口已最小化到托盘(服务端继续运行)')
})
adminWindow.on('closed', () => {
adminWindow = null
})
}
function ensureDisplays() {
if (displaysEnabled || !displays) return
displaysEnabled = true
if (displayFallbackTimer) {
clearTimeout(displayFallbackTimer)
displayFallbackTimer = null
}
displays.enable()
}
function buildTrayMenu() {
const status = statusSnapshot()
const busy = status.state === 'starting' || status.state === 'running' || status.state === 'stopping'
return Menu.buildFromTemplate([
{
label: `服务端:${status.stateLabel}${status.healthy ? ' · 就绪' : ''}`,
enabled: false
},
{ type: 'separator' },
{ label: '启动服务', enabled: !busy, click: () => service.start() },
{ label: '停止服务', enabled: busy, click: () => service.stop() },
{ label: '重启服务', enabled: busy, click: () => service.restart() },
{ type: 'separator' },
{ label: '打开管理端', click: () => showAdmin() },
{
label: '打开服务端管理面板',
click: () => shell.openExternal(status.adminUrl || `http://127.0.0.1:${cfg.values.server.port}/admin`)
},
{ type: 'separator' },
{
label: '退出',
click: () => {
quitting = true
app.quit()
}
}
])
}
function refreshTray() {
if (!tray || tray.isDestroyed()) return
const status = statusSnapshot()
tray.setToolTip(`Scoreboard Console · ${status.stateLabel}${status.healthy ? ' · 就绪' : ''}`)
tray.setContextMenu(buildTrayMenu())
}
function createTray() {
tray = new Tray(createTrayIcon())
tray.setToolTip('Scoreboard Console')
tray.setContextMenu(buildTrayMenu())
tray.on('double-click', () => showAdmin())
}
function registerIpc() {
ipcMain.handle('service:get-status', () => statusSnapshot())
ipcMain.handle('service:start', () => {
service.start()
return statusSnapshot()
})
ipcMain.handle('service:stop', async () => {
await service.stop()
return statusSnapshot()
})
ipcMain.handle('service:restart', async () => {
await service.restart()
return statusSnapshot()
})
ipcMain.handle('log:tail', () => (log ? log.tail() : []))
ipcMain.handle('log:clear', () => {
if (log) log.clear()
return true
})
ipcMain.handle('display:relayout', () => {
if (displays && displaysEnabled) displays.relayout()
return statusSnapshot()
})
ipcMain.handle('app:open-external', (_event, url) => {
// 只放行 http/https,避免管理窗口被注入的链接拉去执行本地协议
if (typeof url === 'string' && /^https?:\/\//i.test(url)) {
shell.openExternal(url)
return true
}
return false
})
ipcMain.handle('app:open-admin-window', () => {
showAdmin()
return true
})
}
app.on('second-instance', () => showAdmin())
app.whenReady().then(() => {
cfg = loadConfig(resolveConfigPath())
log = new LogBus({
maxLines: cfg.values.log.maxLines,
file: path.resolve(path.dirname(cfg.path), cfg.values.log.file || 'logs/console.log'),
maxFileBytes: cfg.values.log.maxFileBytes
})
log.push('console', `Scoreboard Console v${app.getVersion()} 启动(配置:${cfg.path})`)
if (cfg.warning) log.push('console', cfg.warning)
const resolved = resolveExecutable(cfg.values.server.exe, cfg.path)
log.push('console', `服务端程序:${resolved.path}`)
service = new ServiceSupervisor({
values: cfg.values,
exePath: resolved.path,
log
})
displays = new DisplayManager({
values: cfg.values,
server: cfg.values.server,
log
})
log.onLine((line) => sendToAdmin('log:line', line))
service.on('status', (status) => {
broadcastStatus()
refreshTray()
if (!status.healthy) return
// 服务端恢复后必须让大屏重新加载,否则页面还停在断线兜底画面上
if (displaysEnabled) displays.relayout()
else ensureDisplays()
})
createAdminWindow()
createTray()
registerIpc()
// 防熄屏要在服务端起来之前就生效,否则开机后第一段时间屏幕仍会休眠
powerBlockerId = powerSaveBlocker.start('prevent-display-sleep')
log.push('console', `防熄屏已启用(powerSaveBlocker=${powerBlockerId},生效=${powerSaveBlocker.isStarted(powerBlockerId)})`)
if (cfg.values.server.autoStart) {
service.start()
} else {
log.push('console', '配置为不自动启动,等待手动启动服务端')
}
// 服务端迟迟不健康(例如首次迁移很慢)也要把大屏开出来,别让现场只看到桌面
const wait = Number(cfg.values.display.waitForServerMs) || 0
if (wait > 0) {
displayFallbackTimer = setTimeout(() => {
displayFallbackTimer = null
if (!displaysEnabled) {
log.push('console', `等待服务端就绪超过 ${Math.round(wait / 1000)} 秒,先打开大屏窗口`)
ensureDisplays()
}
}, wait)
}
})
// 常驻托盘:窗口全关也不退出,服务端要继续守着
app.on('window-all-closed', () => {})
app.on('before-quit', (event) => {
quitting = true
if (shutdownDone) return
event.preventDefault()
const finish = () => {
if (displays) displays.closeAll()
if (powerBlockerId !== null) powerSaveBlocker.stop(powerBlockerId)
if (log) log.close()
shutdownDone = true
app.quit()
}
if (service) {
service.stop().then(finish).catch(finish)
} else {
finish()
}
})
app.on('quit', () => {
if (service) service.dispose()
})
}
+79
View File
@@ -0,0 +1,79 @@
'use strict'
const fs = require('fs')
const path = require('path')
// 日志总线:内存环形缓冲供管理窗口实时查看,同时落一份文件供现场排障。
// 现场没有外网也没有终端,文件日志是事后定位问题的唯一线索。
class LogBus {
constructor(options = {}) {
const { maxLines = 2000, file = null, maxFileBytes = 4 * 1024 * 1024 } = options
this.maxLines = maxLines
this.maxFileBytes = maxFileBytes
this.lines = []
this.listeners = new Set()
// 子进程的输出是流式分片的,可能把一行拆到两次 data 事件里
this.pending = new Map()
this.stream = null
if (file) this.openFile(file)
}
openFile(file) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true })
if (fs.existsSync(file) && fs.statSync(file).size > this.maxFileBytes) {
fs.renameSync(file, `${file}.1`)
}
this.stream = fs.createWriteStream(file, { flags: 'a' })
} catch (err) {
this.stream = null
this.push('console', `日志文件不可写,仅保留内存日志:${err.message}`)
}
}
append(source, chunk) {
const text = `${this.pending.get(source) || ''}${String(chunk)}`
const parts = text.split(/\r?\n/)
// 最后一段是没有换行的残行,留到下一次拼接
this.pending.set(source, parts.pop() || '')
for (const part of parts) this.push(source, part)
}
push(source, message) {
const line = `[${new Date().toISOString()}] [${source}] ${message}`
this.lines.push(line)
if (this.lines.length > this.maxLines) {
this.lines.splice(0, this.lines.length - this.maxLines)
}
if (this.stream) this.stream.write(`${line}\n`)
for (const listener of this.listeners) {
try {
listener(line)
} catch {
// 单个订阅者出错不能拖垮日志链路
}
}
}
tail() {
return this.lines.slice()
}
clear() {
this.lines = []
}
onLine(listener) {
this.listeners.add(listener)
return () => this.listeners.delete(listener)
}
close() {
if (this.stream) {
this.stream.end()
this.stream = null
}
}
}
module.exports = { LogBus }
+264
View File
@@ -0,0 +1,264 @@
'use strict'
const fs = require('fs')
const http = require('http')
const path = require('path')
const { EventEmitter } = require('events')
const { spawn } = require('child_process')
const STATE_LABEL = {
stopped: '已停止',
starting: '启动中',
running: '运行中',
stopping: '停止中',
crashed: '异常退出'
}
// 服务端守护:拉起 scoreboard.exe、转发日志、健康探测、崩溃自动重启。
// 现场无人值守,所以「崩了自动拉起」比「暴露复杂控制」更重要。
class ServiceSupervisor extends EventEmitter {
constructor({ values, exePath, log }) {
super()
this.values = values
this.server = values.server
this.exePath = exePath
this.log = log
this.child = null
this.state = 'stopped'
this.healthy = false
this.pid = null
this.restarts = 0
this.startedAt = null
this.lastError = null
this.stopRequested = false
this.healthTimer = null
this.restartTimer = null
this.forceKillTimer = null
}
get status() {
const host = this.healthHost()
return {
state: this.state,
stateLabel: STATE_LABEL[this.state] || this.state,
healthy: this.healthy,
pid: this.pid,
restarts: this.restarts,
startedAt: this.startedAt,
lastError: this.lastError,
exePath: this.exePath,
url: `http://${host}:${this.server.port}`,
adminUrl: `http://${host}:${this.server.port}/admin`
}
}
// 服务端可能监听 0.0.0.0,本机探测要走回环地址
healthHost() {
const host = this.server.host || '127.0.0.1'
return host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host
}
emitStatus() {
this.emit('status', this.status)
}
setState(state, patch = {}) {
const changed = this.state !== state
this.state = state
Object.assign(this, patch)
if (changed) {
this.log.push('console', `服务状态:${STATE_LABEL[state] || state}${this.lastError ? `(${this.lastError})` : ''}`)
}
this.emitStatus()
}
start() {
if (this.child || this.state === 'starting' || this.state === 'running') return this.status
this.stopRequested = false
if (!this.exePath || !fs.existsSync(this.exePath)) {
this.setState('crashed', {
lastError: `未找到服务端程序:${this.exePath || this.server.exe}`
})
return this.status
}
const args = Array.isArray(this.server.args) ? this.server.args : []
// 工作目录取 exe 所在目录:部署包里 config.yaml / data/ 都跟 exe 平级
const cwd = path.dirname(this.exePath)
this.lastError = null
this.startedAt = new Date().toISOString()
this.setState('starting')
this.log.push('console', `启动服务端:${this.exePath} ${args.join(' ')}(cwd=${cwd})`)
let child
try {
child = spawn(this.exePath, args, {
cwd,
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe']
})
} catch (err) {
this.setState('crashed', { lastError: `启动失败:${err.message}` })
this.scheduleRestart()
return this.status
}
this.child = child
this.pid = child.pid
if (child.stdout) {
child.stdout.setEncoding('utf8')
child.stdout.on('data', (chunk) => this.log.append('server', chunk))
}
if (child.stderr) {
child.stderr.setEncoding('utf8')
child.stderr.on('data', (chunk) => this.log.append('server!', chunk))
}
child.on('error', (err) => {
this.log.push('console', `服务端进程错误:${err.message}`)
this.setState('crashed', { lastError: err.message })
})
child.on('exit', (code, signal) => this.handleExit(code, signal))
this.setState('running')
this.startHealthCheck()
return this.status
}
handleExit(code, signal) {
if (this.forceKillTimer) {
clearTimeout(this.forceKillTimer)
this.forceKillTimer = null
}
this.stopHealthCheck()
this.child = null
this.pid = null
this.healthy = false
const reason = signal ? `信号 ${signal}` : `退出码 ${code}`
if (this.stopRequested) {
this.log.push('console', `服务端已停止(${reason})`)
this.setState('stopped', { lastError: null })
return
}
this.setState('crashed', { lastError: `服务端意外退出(${reason})` })
this.scheduleRestart()
}
scheduleRestart() {
const max = Number(this.server.maxRestarts) || 0
if (max > 0 && this.restarts >= max) {
this.log.push('console', `已达到最大重启次数 ${max},不再自动拉起`)
return
}
const delay = (Number(this.server.restartDelayMs) || 3000) * Math.min(this.restarts + 1, 5)
this.restarts += 1
this.log.push('console', `${Math.round(delay / 1000)} 秒后自动重启服务端(第 ${this.restarts} 次)`)
this.emitStatus()
if (this.restartTimer) clearTimeout(this.restartTimer)
this.restartTimer = setTimeout(() => {
this.restartTimer = null
if (!this.stopRequested) this.start()
}, delay)
}
stop() {
return new Promise((resolve) => {
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
}
const child = this.child
if (!child) {
this.setState('stopped', { lastError: null })
resolve()
return
}
this.stopRequested = true
this.setState('stopping')
this.log.push('console', '正在停止服务端…')
child.once('exit', () => resolve())
try {
child.kill()
} catch (err) {
this.log.push('console', `发送停止信号失败:${err.message}`)
}
// Go 服务端有 10s 优雅关闭窗口,超过 5s 仍未退出就强杀,避免 Console 退不干净
this.forceKillTimer = setTimeout(() => {
if (this.child && this.pid) {
this.log.push('console', '服务端未在 5 秒内退出,强制结束')
try {
this.child.kill('SIGKILL')
} catch {
// 进程可能已经没了
}
}
}, 5000)
})
}
async restart() {
await this.stop()
this.restarts = 0
return this.start()
}
startHealthCheck() {
this.stopHealthCheck()
const interval = Number(this.server.healthIntervalMs) || 5000
const tick = () => this.probe()
setTimeout(tick, 800)
this.healthTimer = setInterval(tick, interval)
}
stopHealthCheck() {
if (this.healthTimer) {
clearInterval(this.healthTimer)
this.healthTimer = null
}
}
probe() {
if (!this.child) return
const request = http.get(
{
host: this.healthHost(),
port: this.server.port,
path: '/api/health',
timeout: 2500
},
(response) => {
response.resume()
const ok = response.statusCode === 200
this.setHealthy(ok)
}
)
request.on('timeout', () => request.destroy())
request.on('error', () => this.setHealthy(false))
}
setHealthy(ok) {
if (this.healthy === ok) return
this.healthy = ok
this.log.push('console', ok ? '服务端健康检查通过' : '服务端健康检查失败(等待重试)')
this.emitStatus()
}
dispose() {
if (this.restartTimer) clearTimeout(this.restartTimer)
if (this.forceKillTimer) clearTimeout(this.forceKillTimer)
this.stopHealthCheck()
this.removeAllListeners()
}
}
module.exports = { ServiceSupervisor, STATE_LABEL }
+16
View File
@@ -0,0 +1,16 @@
'use strict'
const { nativeImage } = require('electron')
// 托盘图标以 base64 内嵌:现场部署包只有 exe 和几个文件,
// 少一个需要跟着走的资源文件就少一处「文件丢了图标不显示」的故障点。
const ICON_PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABUklEQVR42u2XwUdEURTG5z9JSholJY2SklJSf0+0iKFFtIhoES0iWkSLiBaRDKNSKU2GjCRGEkkSSZsvb3GfnHPnzTm382Y1P36b9x33fKv37stkmiiYLf1AovnimatvhPjvxdMXX7AwaPnU6ScsVS2fLH4gDUXLJwrvSNO6BcaP3pCmicvHDl/RCGsWGD14QSP0Lh/Zf4aVFN8MKzC89wQrKb4ZVmBotworKb4ZVmBw5xFWUnwzrEBu+wFWUnwzrMDA1j00UqSZkxXo36xAI0WaOVmBvo07aKRIMycr0LtehkaKNHOyAj1rt9BIkWZO79uwe/UGUinSLLLmt6Br5Rp/pVhkkYlfxOzyJZwUi6zufaBz6RxOikUmuhV1LJ4hkuKeh2aqe2F7/oQdFD1zarOgmzE9qG2hGKvJgv8L6EGt84VYTWZWoGXuOFaTNX9qk/gFLmHiXP3t+GEAAAAASUVORK5CYII='
function createTrayIcon() {
const image = nativeImage.createFromDataURL(`data:image/png;base64,${ICON_PNG_BASE64}`)
// Windows 上托盘按 16px 显示,缩放交给系统会更模糊,这里直接给 16px
return image.resize({ width: 16, height: 16 })
}
module.exports = { createTrayIcon }
+62
View File
@@ -0,0 +1,62 @@
{
"name": "scoreboard-console",
"productName": "Scoreboard Console",
"version": "0.1.0",
"private": true,
"description": "赛事积分榜 · 桌面宿主:守护 Go 服务端并把大屏投到扩展屏",
"main": "main/index.js",
"scripts": {
"start": "electron .",
"check": "node -e \"const {execSync}=require('child_process');execSync('for f in $(find . -name \\\"*.js\\\" -not -path \\\"./node_modules/*\\\"); do node --check \\\"$f\\\"; done',{stdio:'inherit'})\"",
"dist": "electron-builder --win --x64",
"pack": "electron-builder --dir"
},
"devDependencies": {
"electron": "^38.0.0",
"electron-builder": "^26.0.12"
},
"build": {
"appId": "top.yeij.scoreboard.console",
"productName": "Scoreboard Console",
"directories": {
"output": "../dist/console",
"buildResources": "build"
},
"files": [
"main/**/*",
"renderer/**/*",
"config.json",
"package.json"
],
"extraFiles": [
{
"from": "../dist/scoreboard.exe",
"to": "scoreboard.exe",
"filter": ["**/*"]
},
{
"from": "../config.yaml",
"to": "config.yaml"
}
],
"win": {
"target": [
{
"target": "nsis",
"arch": ["x64"]
},
{
"target": "zip",
"arch": ["x64"]
}
],
"artifactName": "${productName}-${version}-${arch}.${ext}"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"shortcutName": "Scoreboard Console"
}
}
}
+130
View File
@@ -0,0 +1,130 @@
'use strict'
const el = {
version: document.getElementById('app-version'),
stateDot: document.getElementById('state-dot'),
stateLabel: document.getElementById('state-label'),
stateDetail: document.getElementById('state-detail'),
url: document.getElementById('k-url'),
pid: document.getElementById('k-pid'),
restarts: document.getElementById('k-restarts'),
power: document.getElementById('k-power'),
exe: document.getElementById('k-exe'),
config: document.getElementById('k-config'),
configWarning: document.getElementById('config-warning'),
displayList: document.getElementById('display-list'),
log: document.getElementById('log'),
autoscroll: document.getElementById('autoscroll'),
btnStart: document.getElementById('btn-start'),
btnStop: document.getElementById('btn-stop'),
btnRestart: document.getElementById('btn-restart'),
btnRelayout: document.getElementById('btn-relayout'),
btnOpenAdmin: document.getElementById('btn-open-admin'),
btnClearLog: document.getElementById('btn-clear-log')
}
const DOT_CLASS = {
running: 'ok',
starting: 'warn',
stopping: 'warn',
crashed: 'err',
stopped: ''
}
let lastStatus = null
function renderStatus(status) {
lastStatus = status
el.version.textContent = status.appVersion ? `v${status.appVersion}` : ''
el.stateDot.className = `dot ${status.healthy ? 'ok' : DOT_CLASS[status.state] || ''}`
el.stateLabel.textContent = status.stateLabel || status.state
el.stateDetail.textContent = status.healthy
? '健康检查通过'
: status.lastError || (status.state === 'stopped' ? '服务未运行' : '等待健康检查')
el.url.textContent = status.url || '—'
el.pid.textContent = status.pid || '—'
el.restarts.textContent = status.restarts ? `${status.restarts} 次` : '0 次'
el.power.textContent = status.powerSaveBlocked ? '已启用(阻止显示器休眠)' : '未启用'
el.exe.textContent = status.exePath || '—'
el.config.textContent = status.configPath || '—'
if (status.configWarning) {
el.configWarning.hidden = false
el.configWarning.textContent = status.configWarning
} else {
el.configWarning.hidden = true
}
const busy = ['starting', 'running', 'stopping'].includes(status.state)
el.btnStart.disabled = busy
el.btnStop.disabled = !busy
el.btnRestart.disabled = !busy
renderDisplays(status.displays || [])
}
function renderDisplays(displays) {
el.displayList.textContent = ''
if (!displays.length) {
const li = document.createElement('li')
li.className = 'muted'
li.textContent = '尚未打开大屏窗口'
el.displayList.append(li)
return
}
for (const item of displays) {
const li = document.createElement('li')
const page = document.createElement('span')
page.className = 'page'
page.textContent = `屏 ${item.displayId} · ${item.page}`
const url = document.createElement('span')
url.className = 'url'
url.textContent = item.url || '(加载中)'
li.append(page, url)
el.displayList.append(li)
}
}
function appendLog(line) {
const atBottom = el.log.scrollTop + el.log.clientHeight >= el.log.scrollHeight - 8
el.log.textContent += `${line}\n`
if (el.autoscroll.checked && atBottom) {
el.log.scrollTop = el.log.scrollHeight
}
}
function setLog(lines) {
el.log.textContent = lines.length ? `${lines.join('\n')}\n` : ''
el.log.scrollTop = el.log.scrollHeight
}
async function refresh() {
renderStatus(await window.consoleApi.getStatus())
}
function bindActions() {
el.btnStart.addEventListener('click', async () => renderStatus(await window.consoleApi.startService()))
el.btnStop.addEventListener('click', async () => renderStatus(await window.consoleApi.stopService()))
el.btnRestart.addEventListener('click', async () => renderStatus(await window.consoleApi.restartService()))
el.btnRelayout.addEventListener('click', async () => renderStatus(await window.consoleApi.relayoutDisplays()))
el.btnClearLog.addEventListener('click', async () => {
await window.consoleApi.clearLog()
setLog([])
})
el.btnOpenAdmin.addEventListener('click', () => {
const url = (lastStatus && lastStatus.adminUrl) || 'http://127.0.0.1:8080/admin'
window.consoleApi.openExternal(url)
})
}
async function boot() {
bindActions()
window.consoleApi.onStatus(renderStatus)
window.consoleApi.onLog(appendLog)
setLog(await window.consoleApi.getLog())
await refresh()
}
boot()
+103
View File
@@ -0,0 +1,103 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'none'"
/>
<title>Scoreboard Console · 启动管理</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="brand-mark"></span>
<div>
<h1>Scoreboard Console</h1>
<p class="brand-sub">赛事积分榜 · 桌面宿主</p>
</div>
</div>
<div class="topbar-right">
<span id="app-version" class="muted"></span>
</div>
</header>
<main>
<section class="card">
<div class="card-head">
<h2>服务端状态</h2>
<div class="actions">
<button id="btn-start" class="btn primary" type="button">启动服务</button>
<button id="btn-stop" class="btn" type="button">停止服务</button>
<button id="btn-restart" class="btn" type="button">重启服务</button>
</div>
</div>
<div class="status-row">
<span id="state-dot" class="dot"></span>
<strong id="state-label">已停止</strong>
<span id="state-detail" class="muted"></span>
</div>
<dl class="kv">
<div>
<dt>服务地址</dt>
<dd id="k-url">—</dd>
</div>
<div>
<dt>进程 PID</dt>
<dd id="k-pid">—</dd>
</div>
<div>
<dt>自动重启</dt>
<dd id="k-restarts">—</dd>
</div>
<div>
<dt>防熄屏</dt>
<dd id="k-power">—</dd>
</div>
<div class="wide">
<dt>服务端程序</dt>
<dd id="k-exe" class="mono">—</dd>
</div>
<div class="wide">
<dt>配置文件</dt>
<dd id="k-config" class="mono">—</dd>
</div>
</dl>
<p id="config-warning" class="warning" hidden></p>
</section>
<section class="card">
<div class="card-head">
<h2>大屏窗口</h2>
<div class="actions">
<button id="btn-relayout" class="btn" type="button">重新排布</button>
<button id="btn-open-admin" class="btn" type="button">打开服务端管理面板</button>
</div>
</div>
<p class="hint">
单屏时窗口化、按 F11 切换全屏;多屏时除主屏外每块屏一个 kiosk 窗口,各锁一页。
</p>
<ul id="display-list" class="display-list">
<li class="muted">尚未打开大屏窗口</li>
</ul>
</section>
<section class="card log-card">
<div class="card-head">
<h2>运行日志</h2>
<div class="actions">
<label class="check"><input id="autoscroll" type="checkbox" checked /> 自动滚动</label>
<button id="btn-clear-log" class="btn" type="button">清空</button>
</div>
</div>
<pre id="log" class="log"></pre>
</section>
</main>
<script src="app.js"></script>
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
'use strict'
const { contextBridge, ipcRenderer } = require('electron')
// 渲染层是纯静态页面,能力全部经这里白名单暴露,不开 nodeIntegration
const subscribe = (channel, callback) => {
const handler = (_event, payload) => callback(payload)
ipcRenderer.on(channel, handler)
return () => ipcRenderer.removeListener(channel, handler)
}
contextBridge.exposeInMainWorld('consoleApi', {
getStatus: () => ipcRenderer.invoke('service:get-status'),
startService: () => ipcRenderer.invoke('service:start'),
stopService: () => ipcRenderer.invoke('service:stop'),
restartService: () => ipcRenderer.invoke('service:restart'),
getLog: () => ipcRenderer.invoke('log:tail'),
clearLog: () => ipcRenderer.invoke('log:clear'),
relayoutDisplays: () => ipcRenderer.invoke('display:relayout'),
openExternal: (url) => ipcRenderer.invoke('app:open-external', url),
onLog: (callback) => subscribe('log:line', callback),
onStatus: (callback) => subscribe('service:status', callback)
})
+270
View File
@@ -0,0 +1,270 @@
:root {
--bg: #0f1420;
--panel: #161d2d;
--panel-2: #1d2637;
--border: #27314a;
--text: #e6ecf7;
--muted: #8b98b4;
--accent: #4fd8ff;
--ok: #3ddc97;
--warn: #ffb454;
--err: #ff6b6b;
}
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
background: var(--bg);
color: var(--text);
font: 14px/1.5 "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 20px;
border-bottom: 1px solid var(--border);
background: var(--panel);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
width: 10px;
height: 34px;
border-radius: 5px;
background: linear-gradient(180deg, var(--accent), #1b6bb8);
}
h1 {
margin: 0;
font-size: 16px;
font-weight: 600;
letter-spacing: 0.02em;
}
.brand-sub {
margin: 0;
font-size: 12px;
color: var(--muted);
}
main {
flex: 1;
min-height: 0;
padding: 16px 20px 20px;
display: grid;
gap: 14px;
grid-template-columns: 1fr 1fr;
grid-template-rows: auto auto minmax(160px, 1fr);
overflow: auto;
}
.card {
grid-column: span 2;
padding: 14px 16px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--panel);
}
.log-card {
display: flex;
flex-direction: column;
min-height: 0;
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
h2 {
margin: 0;
font-size: 13px;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.08em;
}
.actions {
display: flex;
gap: 8px;
align-items: center;
}
.btn {
padding: 6px 14px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--panel-2);
color: var(--text);
font-size: 13px;
cursor: pointer;
}
.btn:hover:not(:disabled) {
border-color: var(--accent);
}
.btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.btn.primary {
border-color: transparent;
background: var(--accent);
color: #06202b;
font-weight: 600;
}
.status-row {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
font-size: 15px;
}
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--muted);
}
.dot.ok {
background: var(--ok);
box-shadow: 0 0 0 4px rgba(61, 220, 151, 0.15);
}
.dot.warn {
background: var(--warn);
box-shadow: 0 0 0 4px rgba(255, 180, 84, 0.15);
}
.dot.err {
background: var(--err);
box-shadow: 0 0 0 4px rgba(255, 107, 107, 0.15);
}
.muted {
color: var(--muted);
}
.kv {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px 16px;
margin: 0;
}
.kv > div.wide {
grid-column: span 2;
}
.kv dt {
margin: 0;
font-size: 12px;
color: var(--muted);
}
.kv dd {
margin: 2px 0 0;
word-break: break-all;
}
.mono {
font-family: Consolas, "Cascadia Mono", monospace;
font-size: 12px;
}
.warning {
margin: 12px 0 0;
padding: 8px 10px;
border-radius: 6px;
background: rgba(255, 180, 84, 0.12);
color: var(--warn);
font-size: 12px;
}
.hint {
margin: 0 0 10px;
font-size: 12px;
color: var(--muted);
}
.display-list {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: 6px;
}
.display-list li {
display: flex;
gap: 10px;
padding: 8px 10px;
border-radius: 6px;
background: var(--panel-2);
font-size: 13px;
}
.display-list .page {
min-width: 96px;
color: var(--accent);
font-weight: 600;
}
.display-list .url {
color: var(--muted);
font-family: Consolas, "Cascadia Mono", monospace;
font-size: 12px;
word-break: break-all;
}
.check {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--muted);
cursor: pointer;
}
.log {
flex: 1;
min-height: 0;
margin: 0;
padding: 10px 12px;
overflow: auto;
border-radius: 8px;
background: #0a0e17;
color: #b9c6e0;
font-family: Consolas, "Cascadia Mono", monospace;
font-size: 12px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-all;
}