75 lines
2.6 KiB
TypeScript
75 lines
2.6 KiB
TypeScript
// src/electron/renderer.ts
|
||
const maxLogs = 200; // 设置最大日志数量
|
||
const logs: string[] = [];
|
||
|
||
|
||
|
||
// 格式化时间戳的函数
|
||
function formatDate(date: Date): string {
|
||
// const year = date.getFullYear();
|
||
// const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
|
||
// const day = String(date.getDate()).padStart(2, '0');
|
||
const hours = String(date.getHours()).padStart(2, '0');
|
||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||
const seconds = String(date.getSeconds()).padStart(2, '0');
|
||
|
||
// return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
|
||
return `${hours}:${minutes}:${seconds}`;
|
||
}
|
||
|
||
function updateLogDisplay() {
|
||
const logContainer = document.getElementById('log') as HTMLElement;
|
||
if (logContainer) {
|
||
logContainer.innerHTML = logs.join(''); // 使用 innerHTML 来渲染带有样式的日志
|
||
logContainer.scrollTop = 0; // 保持滚动位置在顶部
|
||
}
|
||
}
|
||
|
||
function addLog(message: string, color: string = 'green') {
|
||
const timestamp = formatDate(new Date()); // 使用当前时间生成时间戳
|
||
const logMessage = `<div style="color:${color};">[${timestamp}] ${message}</div>`; // 在日志消息前添加时间戳,并设置颜色
|
||
|
||
logs.unshift(logMessage); // 在数组开头插入新消息
|
||
|
||
// 如果日志超过200条,删除最旧的一条(数组末尾的元素)
|
||
if (logs.length > maxLogs) {
|
||
logs.pop();
|
||
}
|
||
|
||
updateLogDisplay();
|
||
}
|
||
|
||
// 设置默认端口值
|
||
const portInputElement = document.getElementById('port') as HTMLInputElement;
|
||
if (portInputElement) {
|
||
const defaultPort = window.electron.env.PORT; // 从预加载脚本中获取默认端口
|
||
portInputElement.value = defaultPort;
|
||
}
|
||
|
||
document.getElementById('startBtn')?.addEventListener('click', () => {
|
||
const portElement = document.getElementById('port') as HTMLInputElement;
|
||
const port = parseInt(portElement.value, 10);
|
||
window.electron.startWebSocket(port);
|
||
});
|
||
|
||
document.getElementById('stopBtn')?.addEventListener('click', () => {
|
||
window.electron.stopWebSocket();
|
||
});
|
||
|
||
document.getElementById('devToolsBtn')?.addEventListener('click', () => {
|
||
window.electron.openDevTools();
|
||
});
|
||
|
||
window.electron.onWebSocketStatus((message: string) => {
|
||
console.log(`WebSocket status: ${message}`);
|
||
const statusElement = document.getElementById('status');
|
||
if (statusElement) {
|
||
statusElement.innerText = `Status: ${message}`;
|
||
}
|
||
addLog(message); // 將 WebSocket 狀態消息添加到日誌顯示區
|
||
});
|
||
|
||
// 监听主进程发送的日志消息
|
||
window.electron.onLogMessage((message: string, color: string) => {
|
||
addLog(message, color); // 將日誌消息添加到顯示區
|
||
}); |