全面优化:暗色主题、文件监听、未保存提醒、滚动同步、分屏记忆、文件大小显示、删除死代码

This commit is contained in:
thzxx
2026-05-18 13:09:31 +08:00
parent dbbf1efc78
commit cb29c67f94
5 changed files with 403 additions and 157 deletions
+81 -106
View File
@@ -1,13 +1,14 @@
const { app, BrowserWindow, dialog, ipcMain, Menu } = require('electron');
const { app, BrowserWindow, dialog, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
let mainWindow = null;
let currentFilePath = null;
let pendingFilePath = null; // For file association race condition
let pendingFilePath = null;
let fileWatcher = null;
let isModifiedExternally = false;
function createWindow() {
// Create the browser window
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
@@ -23,7 +24,6 @@ function createWindow() {
show: false
});
// Register did-finish-load BEFORE loadFile to avoid race condition
mainWindow.webContents.on('did-finish-load', () => {
if (pendingFilePath) {
openFile(pendingFilePath);
@@ -31,102 +31,48 @@ function createWindow() {
}
});
// Load the index.html
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
// Show window when ready
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
// Remove native menu bar
mainWindow.setMenu(null);
// Unsaved changes warning on close
mainWindow.on('close', (e) => {
mainWindow.webContents.send('window:closing');
e.preventDefault();
mainWindow.webContents.send('window:confirmClose');
});
mainWindow.on('closed', () => {
stopWatching();
mainWindow = null;
});
}
function buildMenu() {
const template = [
{
label: '文件',
submenu: [
{
label: '打开文件',
accelerator: 'CmdOrCtrl+O',
click: () => handleOpenFile()
},
{
label: '保存',
accelerator: 'CmdOrCtrl+S',
click: () => mainWindow.webContents.send('menu:save')
},
{
label: '另存为',
accelerator: 'CmdOrCtrl+Shift+S',
click: () => mainWindow.webContents.send('menu:saveAs')
},
{ type: 'separator' },
{
label: '退出',
accelerator: 'CmdOrCtrl+Q',
click: () => app.quit()
}
]
},
{
label: '视图',
submenu: [
{
label: '编辑 + 预览',
accelerator: 'CmdOrCtrl+1',
click: () => mainWindow.webContents.send('menu:viewMode', 'split')
},
{
label: '纯编辑',
accelerator: 'CmdOrCtrl+2',
click: () => mainWindow.webContents.send('menu:viewMode', 'editor')
},
{
label: '纯预览',
accelerator: 'CmdOrCtrl+3',
click: () => mainWindow.webContents.send('menu:viewMode', 'preview')
},
{ type: 'separator' },
{
label: '开发者工具',
accelerator: 'F12',
click: () => mainWindow.webContents.toggleDevTools()
},
{ type: 'separator' },
{
label: '重新加载',
accelerator: 'CmdOrCtrl+R',
click: () => mainWindow.webContents.reload()
}
]
},
{
label: '帮助',
submenu: [
{
label: '关于 MarkLite',
click: () => {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '关于 MarkLite',
message: 'MarkLite v1.0.0',
detail: '一款轻量级的 Markdown 阅读器。\n\n技术栈:Electron + marked.js + highlight.js'
});
}
}
]
}
];
// File watcher - detect external modifications
function startWatching(filePath) {
stopWatching();
try {
isModifiedExternally = false;
fileWatcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change' && mainWindow && !mainWindow.isDestroyed()) {
isModifiedExternally = true;
mainWindow.webContents.send('file:externallyModified', filePath);
}
});
} catch (err) {
// Silently ignore watch errors
}
}
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
function stopWatching() {
if (fileWatcher) {
fileWatcher.close();
fileWatcher = null;
}
}
async function showOpenDialog() {
@@ -143,17 +89,11 @@ async function showOpenDialog() {
return null;
}
async function handleOpenFile() {
const filePath = await showOpenDialog();
if (filePath) {
openFile(filePath);
}
}
function openFile(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf-8');
currentFilePath = filePath;
startWatching(filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
mainWindow.webContents.send('file:opened', { filePath, content });
} catch (err) {
@@ -163,14 +103,19 @@ function openFile(filePath) {
// IPC Handlers
ipcMain.handle('dialog:openFile', async () => {
const filePath = await showOpenDialog();
if (filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
currentFilePath = filePath;
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
return { filePath, content };
try {
const filePath = await showOpenDialog();
if (filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
currentFilePath = filePath;
startWatching(filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
return { filePath, content };
}
return null;
} catch (err) {
return { error: err.message };
}
return null;
});
ipcMain.handle('file:read', async (event, filePath) => {
@@ -185,12 +130,13 @@ ipcMain.handle('file:read', async (event, filePath) => {
ipcMain.handle('file:save', async (event, { filePath, content }) => {
try {
if (filePath) {
stopWatching();
fs.writeFileSync(filePath, content, 'utf-8');
currentFilePath = filePath;
startWatching(filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
return { success: true, filePath };
} else {
// No file path, do save as
const result = await dialog.showSaveDialog(mainWindow, {
filters: [
{ name: 'Markdown 文件', extensions: ['md'] },
@@ -198,8 +144,10 @@ ipcMain.handle('file:save', async (event, { filePath, content }) => {
]
});
if (!result.canceled) {
stopWatching();
fs.writeFileSync(result.filePath, content, 'utf-8');
currentFilePath = result.filePath;
startWatching(result.filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(result.filePath)}`);
return { success: true, filePath: result.filePath };
}
@@ -219,8 +167,10 @@ ipcMain.handle('file:saveAs', async (event, { content }) => {
]
});
if (!result.canceled) {
stopWatching();
fs.writeFileSync(result.filePath, content, 'utf-8');
currentFilePath = result.filePath;
startWatching(result.filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(result.filePath)}`);
return { success: true, filePath: result.filePath };
}
@@ -234,6 +184,36 @@ ipcMain.handle('file:getCurrentPath', () => {
return currentFilePath;
});
ipcMain.handle('file:stats', async (event, filePath) => {
try {
const stats = fs.statSync(filePath);
return {
success: true,
size: stats.size,
mtime: stats.mtime.toISOString()
};
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('file:reload', async () => {
if (!currentFilePath) return { success: false, error: '没有打开的文件' };
try {
const content = fs.readFileSync(currentFilePath, 'utf-8');
isModifiedExternally = false;
return { success: true, content, filePath: currentFilePath };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('window:forceClose', () => {
stopWatching();
mainWindow.removeAllListeners('close');
mainWindow.close();
});
// Handle file open from command line or file association
function getCommandLineFile() {
const args = process.argv.slice(1);
@@ -248,28 +228,23 @@ function getCommandLineFile() {
// App lifecycle
app.whenReady().then(() => {
// Register open-file handler BEFORE creating window (fixes race condition)
app.on('open-file', (event, filePath) => {
event.preventDefault();
if (mainWindow && mainWindow.webContents.isLoading()) {
// Window is still loading, queue the file
pendingFilePath = filePath;
} else if (mainWindow) {
openFile(filePath);
} else {
// Window not created yet, store for later
pendingFilePath = filePath;
}
});
createWindow();
// Check for file passed via command line
const fileToOpen = getCommandLineFile();
if (fileToOpen) {
pendingFilePath = fileToOpen;
}
// pendingFilePath will be opened by the did-finish-load handler in createWindow()
});
app.on('window-all-closed', () => {