feat: migrate to react-markdown for robust markdown rendering

- Replace custom markdown parser with react-markdown + remark-gfm
- Fix document link navigation (./ and ../ references)
- Simplify doc viewing flow (direct markdown content instead of parsed structure)
- Update electron main process to only use api folder for docs
- Add blueprint loading from docs/blueprint.md dynamically
- Fix sidebar file selection path matching
- Update preload scripts for new API structure
This commit is contained in:
2026-03-18 18:50:26 +08:00
parent 4898ee5434
commit d66f5b09e6
16 changed files with 2003 additions and 451 deletions

View File

@@ -1,139 +1,123 @@
import { app, BrowserWindow, ipcMain, dialog } from 'electron';
import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import http from 'http';
import fs from 'fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let mainWindow = null;
let docsPath = '';
let port = 3001;
const LOG_FILE = path.join(__dirname, '..', 'electron.log');
const DEFAULT_PORT = 3001;
function log(...args) {
const msg = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
const ts = new Date().toISOString();
const line = `[${ts}] [main] ${msg}\n`;
fs.appendFileSync(LOG_FILE, line);
console.log(line.trim());
}
function parseArgs() {
const args = { port: DEFAULT_PORT, docs: null, headless: false };
const portIndex = process.argv.indexOf('--port');
if (portIndex !== -1 && process.argv[portIndex + 1]) {
args.port = parseInt(process.argv[portIndex + 1], 10);
}
const args = { docs: null, headless: false };
const docsIndex = process.argv.indexOf('--docs');
if (docsIndex !== -1 && process.argv[docsIndex + 1]) {
args.docs = process.argv[docsIndex + 1];
}
if (process.argv.includes('--headless')) {
args.headless = true;
}
return args;
}
const args = parseArgs();
port = args.port;
docsPath = args.docs || path.join(process.cwd(), 'src', 'docs');
function getDistPath() {
function getIndexPath() {
if (app.isPackaged) {
return path.join(__dirname, '..', 'dist');
return path.join(__dirname, '..', 'dist', 'index.html');
}
return path.join(__dirname, '..', 'dist');
}
function loadDistServer() {
const distPath = getDistPath();
const server = http.createServer((req, res) => {
let filePath = path.join(distPath, req.url === '/' ? 'index.html' : req.url);
if (!filePath.startsWith(distPath)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
const ext = path.extname(filePath);
const contentTypes = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.md': 'text/markdown',
};
if (fs.existsSync(filePath)) {
const contentType = contentTypes[ext] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': contentType });
res.end(fs.readFileSync(filePath));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(port, () => {
console.log(`XCSDD Server running on http://localhost:${port}`);
console.log(`Docs path: ${docsPath}`);
if (args.headless) {
console.log(`Headless mode: enabled`);
}
});
return server;
return path.join(__dirname, '..', 'dist', 'index.html');
}
function createWindow() {
if (args.headless) {
loadDistServer();
return;
}
loadDistServer();
const indexPath = getIndexPath();
log('Creating window, indexPath:', indexPath);
log('__dirname:', __dirname);
log('dist exists:', fs.existsSync(path.join(__dirname, '..', 'dist')));
log('index.html exists:', fs.existsSync(indexPath));
mainWindow = new BrowserWindow({
show: !args.headless,
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.mjs'),
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
devTools: true,
},
});
mainWindow.loadURL(`http://localhost:${port}`);
mainWindow.loadFile(indexPath);
mainWindow.webContents.on('did-fail-load', (_event, errorCode, errorDesc) => {
log('FAIL LOAD:', errorCode, errorDesc);
});
mainWindow.webContents.on('did-finish-load', () => {
log('Page finished loading');
});
if (!args.headless) {
mainWindow.webContents.openDevTools();
}
mainWindow.on('closed', () => {
mainWindow = null;
});
}
ipcMain.handle('select-folder', async () => {
if (!mainWindow) return null;
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory'],
});
if (result.canceled || result.filePaths.length === 0) {
return null;
ipcMain.handle('list-docs-files', (_event, basePath) => {
const docsPath = path.join(basePath, 'api');
if (!fs.existsSync(docsPath)) {
return [];
}
docsPath = result.filePaths[0];
mainWindow.webContents.send('docs-path-changed', docsPath);
return docsPath;
const result = [];
function walkDir(dir, baseDir) {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkDir(fullPath, baseDir);
} else if (entry.name.endsWith('.md')) {
const relativePath = path.relative(baseDir, fullPath);
result.push({
name: entry.name.replace('.md', ''),
path: fullPath,
relativePath: relativePath.replace(/\\/g, '/')
});
}
}
}
walkDir(docsPath, docsPath);
return result;
});
ipcMain.handle('get-docs-path', () => {
return docsPath;
ipcMain.handle('read-doc-file', (_event, filePath) => {
if (!fs.existsSync(filePath)) {
return null;
}
return fs.readFileSync(filePath, 'utf-8');
});
ipcMain.on('renderer-log', (_event, level, ...args) => {
log(`[renderer][${level}]`, ...args);
});
app.whenReady().then(() => {
log('App ready, creating window');
createWindow();
app.on('activate', () => {
@@ -141,6 +125,9 @@ app.whenReady().then(() => {
createWindow();
}
});
}).catch(err => {
log('FATAL ERROR:', err);
process.exit(1);
});
app.on('window-all-closed', () => {
@@ -148,3 +135,11 @@ app.on('window-all-closed', () => {
app.quit();
}
});
process.on('uncaughtException', (err) => {
log('Uncaught exception:', err);
});
process.on('unhandledRejection', (reason) => {
log('Unhandled rejection:', reason);
});

7
electron/preload.cjs Normal file
View File

@@ -0,0 +1,7 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
listDocsFiles: (basePath) => ipcRenderer.invoke('list-docs-files', basePath),
readDocFile: (filePath) => ipcRenderer.invoke('read-doc-file', filePath),
log: (level, ...args) => ipcRenderer.send('renderer-log', level, ...args),
});

View File

@@ -1,9 +1,7 @@
import { contextBridge, ipcRenderer } from 'electron';
contextBridge.exposeInMainWorld('electronAPI', {
selectFolder: () => ipcRenderer.invoke('select-folder'),
getDocsPath: () => ipcRenderer.invoke('get-docs-path'),
onDocsPathChanged: (callback: (path: string) => void) => {
ipcRenderer.on('docs-path-changed', (_event, path) => callback(path));
},
listDocsFiles: (basePath) => ipcRenderer.invoke('list-docs-files', basePath),
readDocFile: (filePath) => ipcRenderer.invoke('read-doc-file', filePath),
log: (level, ...args) => ipcRenderer.send('renderer-log', level, ...args),
});