feat: 小银 Markdown 编辑器 v2.6.1 源码

纯本地 Windows Markdown 编辑器(Electron + Tauri 双栈):

- 实时预览、多标签 / 多窗口两种打开方式
- 查找高亮、大纲、侧栏面板
- 右键复制全文 / 打开目录、常用快捷键
- 不联网、不登录、不收集任何数据

仓库化时做的处理:
- 路径脱敏:README 与 tools/mklink.js 里写死的 C:\Users\<用户名> 改为 %USERPROFILE% /
  process.env.USERPROFILE,换机器即可用(原文件含个人目录名)
- 补 .gitignore(node_modules / dist / src-tauri/target / Tauri 自动生成的 gen/schemas)
- 补 MIT LICENSE(与 package.json 的 license 字段一致)
This commit is contained in:
Jidekin committed 2026-11-19 19:09:45 +08:00
commit 66bad58593
37 files changed
+11319

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
/* 验证关闭窗口时主进程不抛异常 */
process.on('uncaughtException', (e) => {
console.log('UNCAUGHT:', e.message);
process.exit(2);
});
const { app, BrowserWindow } = require('electron');
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
require('../src/main.js');
// 阻止 window-all-closed 自动退出,便于关闭后继续检查
app.removeAllListeners('window-all-closed');
let errors = [];
process.on('uncaughtException', (e) => errors.push(e.message));
app.whenReady().then(async () => {
await wait(1400);
const wins = BrowserWindow.getAllWindows();
console.log('打开窗口数:', wins.length);
// 连续开关多个窗口,覆盖正常关闭和迁移式关闭
const w2 = new BrowserWindow({ show: false, webPreferences: { offscreen: true } });
w2.close();
await wait(300);
for (const w of wins) w.close();
await wait(1000);
if (errors.length) {
console.log('FAIL 主进程异常:', errors.join(' | '));
process.exit(1);
}
console.log('PASS 关闭窗口无主进程异常');
process.exit(0);
});
+171
View File
@@ -0,0 +1,171 @@
/* 验证:文件树右键复制(文件名/路径/内容)+ 聚焦后 Ctrl+C + 按钮位置 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const nativeClip = require('../src/clipboard-native');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'copytest-'));
const mdFile = path.join(tmp, '交易日历业务交接文档.md');
const mdText = '# 交易日历业务交接文档\n\n## 业务概览\n\n正文内容。\n';
fs.writeFileSync(mdFile, mdText, 'utf8');
fs.mkdirSync(path.join(tmp, '子目录'));
fs.writeFileSync(path.join(tmp, '另一个.md'), '# 另一个\n', 'utf8');
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }))
.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
let clipboard = '';
let lastRevealed = '';
let lastCopiedFile = '';
ipcMain.handle('clip:read', () => clipboard);
ipcMain.handle('clip:write', (_e, text) => { clipboard = String(text ?? ''); return true; });
ipcMain.handle('file:readText', async (_e, p) => {
try { return { ok: true, text: fs.readFileSync(p, 'utf8') }; } catch (_) { return { ok: false }; }
});
ipcMain.handle('file:copyFile', async (_e, p) => {
const list = (Array.isArray(p) ? p : [p]).filter((x) => x && fs.existsSync(x));
nativeClip.setFiles(list);
lastCopiedFile = p || '';
return { ok: true, count: list.length };
});
ipcMain.handle('file:revealPath', async (_e, p) => { lastRevealed = p || ''; return { ok: true }; });
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('file:reveal', async () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.on('app:setDirty', () => {});
ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {});
const win = new BrowserWindow({
width: 1400, height: 880, show: true,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
const js = (c) => win.webContents.executeJavaScript(c);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
await js(`localStorage.clear()`);
await win.webContents.reload();
await wait(1200);
/* 1. 按钮位置 */
const pos = await js(`(() => {
const btns = [...document.querySelectorAll('.toolbar button')];
const tree = document.getElementById('btn-tree');
const outline = document.getElementById('btn-outline');
const segBtn = document.querySelector('#mode-seg button');
return {
beforeSeg: btns.indexOf(tree) < btns.indexOf(segBtn),
adjacent: btns.indexOf(segBtn) - btns.indexOf(tree) === 1,
sameClass: tree.className === outline.className,
treeText: tree.textContent.trim(), outlineText: outline.textContent.trim()
};
})()`);
check('「目录」按钮紧挨在编辑/分栏/阅读之前', pos.beforeSeg === true && pos.adjacent === true, JSON.stringify(pos));
check('两个开关样式类名一致', pos.sameClass === true, pos.treeClass || '');
check('按钮文字为 目录 / 大纲', pos.treeText === '目录' && pos.outlineText === '大纲', pos.treeText + ' / ' + pos.outlineText);
/* 2. 打开文件夹,准备文件树 */
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmp, name: path.basename(tmp), entries: list() });
await wait(400);
const rightClick = async (pathSuffix, menuText) => js(`(() => {
const rows = [...document.querySelectorAll('#sb-body .tree-row')];
const row = rows.find(r => r.dataset.path.endsWith(${JSON.stringify(pathSuffix)}));
if (!row) return { error: 'row not found' };
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
const menu = document.getElementById('ctxmenu');
const items = [...menu.querySelectorAll('.ctx-item')].map(i => i.textContent);
const target = [...menu.querySelectorAll('.ctx-item')].find(i => {
const lab = i.querySelector('span');
return lab && lab.textContent === ${JSON.stringify(menuText)};
});
if (!target) return { error: 'menu item not found', items };
target.click();
return { items };
})()`);
/* 3. 右键复制文件名 */
await rightClick('交易日历业务交接文档.md', '复制文件名');
await wait(200);
check('右键复制文件名', clipboard === '交易日历业务交接文档.md', clipboard);
/* 4. 右键复制完整路径 */
await rightClick('交易日历业务交接文档.md', '复制完整路径');
await wait(200);
check('右键复制完整路径', clipboard === mdFile, clipboard);
/* 5. 右键复制文件内容 */
await rightClick('交易日历业务交接文档.md', '复制文件内容');
await wait(250);
check('右键复制文件内容', clipboard === mdText, JSON.stringify(clipboard).slice(0, 60));
/* 6. 右键复制文件本身(Windows 文件对象) */
await rightClick('交易日历业务交接文档.md', '复制文件');
await wait(250);
check('右键复制文件本身', lastCopiedFile === mdFile, lastCopiedFile);
check('系统剪贴板含文件列表 CF_HDROP', nativeClip.hasFiles() === true);
/* 7. 右键在资源管理器中显示:路径必须真的传过去 */
await rightClick('交易日历业务交接文档.md', '在资源管理器中显示');
await wait(200);
check('资源管理器显示:路径参数正确传递', lastRevealed === mdFile, lastRevealed);
/* 8. 右键菜单内容齐全、目录项禁用复制内容 */
const menuInfo = await js(`(() => {
const row = [...document.querySelectorAll('#sb-body .tree-row.is-dir')][0];
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
return {
labels: items.map(lab),
contentDisabled: items.find(i => lab(i) === '复制文件内容').classList.contains('disabled')
};
})()`);
check('右键菜单五项齐全', ['复制文件', '复制文件内容', '复制文件名', '复制完整路径', '在资源管理器中显示'].every(x => menuInfo.labels.includes(x)), JSON.stringify(menuInfo.labels));
check('目录项禁用复制文件内容', menuInfo.contentDisabled === true);
/* 9. 聚焦 + Ctrl+C 复制文件 */
const kbd = await js(`(() => {
document.getElementById('ctxmenu').hidden = true;
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('另一个.md'));
row.focus();
const focused = document.activeElement === row;
row.dispatchEvent(new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }));
return { focused };
})()`);
await wait(250);
check('文件树条目可聚焦', kbd.focused === true);
check('Ctrl+C 复制文件本身', lastCopiedFile === path.join(tmp, '另一个.md'), lastCopiedFile);
check('Ctrl+C 后剪贴板仍是文件列表', nativeClip.hasFiles() === true);
/* 8. 普通编辑区 Ctrl+C 不受影响 */
await js(`(() => {
const ed = document.getElementById('editor');
ed.value = 'EDITOR TEXT';
ed.focus();
ed.setSelectionRange(0, 5);
ed.dispatchEvent(new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }));
})()`);
await wait(250);
check('编辑区 Ctrl+C 不误触文件树复制', clipboard !== 'EDITOR TEXT', clipboard);
console.log('\n==== 文件树复制测试:通过 ' + pass + ',失败 ' + fail + ' ====');
const img = await win.webContents.capturePage();
fs.writeFileSync(path.join(__dirname, '..', 'shot-copy.png'), img.toPNG());
console.log('screenshot saved');
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(fail ? 1 : 0);
});
+110
View File
@@ -0,0 +1,110 @@
/* 用 CDP 模拟真实系统拖放,验证 preload 能否取到路径并打开 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const log = (...a) => console.log(...a);
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'dragtest-'));
const file = path.join(tmp, '拖进来的文件.md');
const dir = path.join(tmp, '文档库');
fs.writeFileSync(file, '# 拖进来的\n\n内容是 **拖放** 打开的。\n', 'utf8');
fs.mkdirSync(dir);
fs.writeFileSync(path.join(dir, '第一篇.md'), '# 第一篇\n', 'utf8');
fs.writeFileSync(path.join(dir, '第二篇.md'), '# 第二篇\n', 'utf8');
// 真实主进程逻辑(复刻 main.js 的两条通路)
ipcMain.handle('file:openPath', async (_e, p) => {
return { ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' };
});
ipcMain.handle('dir:read', async (_e, p) => {
const entries = fs.readdirSync(p, { withFileTypes: true })
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map((d) => ({ name: d.name, path: path.join(p, d.name), isDir: d.isDirectory() }));
return { ok: true, path: p, name: path.basename(p), entries };
});
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('clip:read', () => '');
ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.on('app:setDirty', () => {});
ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {});
// 复刻 main.js 里 file:drop 的分支(文件 → 打开;目录 → 文件树)
ipcMain.on('file:drop', (_e, p) => {
const win = BrowserWindow.getAllWindows()[0];
let isDir = false;
try { isDir = fs.statSync(p).isDirectory(); } catch (_) { return; }
if (isDir) {
const entries = fs.readdirSync(p, { withFileTypes: true })
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map((d) => ({ name: d.name, path: path.join(p, d.name), isDir: d.isDirectory() }));
win.webContents.send('cmd', 'dir-opened', { ok: true, path: p, name: path.basename(p), entries });
} else {
win.webContents.send('cmd', 'file-opened', {
ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n'
});
}
});
const win = new BrowserWindow({
width: 1280, height: 820, show: true,
webPreferences: {
preload: path.join(__dirname, '..', 'src', 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
win.focus();
await new Promise((r) => setTimeout(r, 800));
const dbg = win.webContents.debugger;
dbg.attach('1.3');
const dragDrop = async (absolutePath, x, y) => {
const data = { items: [], files: [absolutePath], dragOperationsMask: 1 };
await dbg.sendCommand('Input.dispatchDragEvent', { type: 'dragEnter', x, y, data });
await dbg.sendCommand('Input.dispatchDragEvent', { type: 'dragOver', x, y, data });
await dbg.sendCommand('Input.dispatchDragEvent', { type: 'drop', x, y, data });
};
const js = (code) => win.webContents.executeJavaScript(code);
let pass = 0;
let fail = 0;
const check = (name, ok, extra) => {
if (ok) { pass++; log('PASS ' + name); } else { fail++; log('FAIL ' + name + (extra ? ' → ' + extra : '')); }
};
// ---- 拖入单个 .md 文件 ----
try {
await dragDrop(file, 400, 380);
await new Promise((r) => setTimeout(r, 900));
const s = await js(`({ v: editor.value, name: document.getElementById('st-file').textContent, sb: !document.getElementById('sidebar').hidden, rows: [...document.querySelectorAll('#sb-body .tree-row')].map(r=>r.querySelector('.tree-name').textContent) })`);
check('拖入文件:取到真实路径并打开', s.v.indexOf('拖放') >= 0, s.name);
check('拖入文件:状态栏文件名正确', s.name === '拖进来的文件.md', s.name);
check('拖入文件:自动列出所在目录', s.sb === true && s.rows.includes('文档库'), JSON.stringify(s.rows));
} catch (e) {
check('拖入文件(CDP 未支持 files 参数)', false, e.message);
}
// ---- 拖入文件夹 ----
try {
await dragDrop(dir, 400, 380);
await new Promise((r) => setTimeout(r, 900));
const s = await js(`({ title: document.getElementById('sb-title').textContent, rows: [...document.querySelectorAll('#sb-body .tree-row')].map(r=>r.querySelector('.tree-name').textContent) })`);
check('拖入文件夹:侧栏标题为该文件夹', s.title === '文档库', s.title);
check('拖入文件夹:列出里面的 md', s.rows.includes('第一篇.md') && s.rows.includes('第二篇.md'), JSON.stringify(s.rows));
} catch (e) {
check('拖入文件夹(CDP 未支持 files 参数)', false, e.message);
}
log('\n==== 拖放测试:通过 ' + pass + ',失败 ' + fail + ' ====');
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(fail ? 1 : 0);
});
+130
View File
@@ -0,0 +1,130 @@
/* 验证:查找时预览正文的关键字背景标记与当前命中高亮 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
app.whenReady().then(async () => {
ipcMain.handle('clip:read', () => '');
ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.handle('app:getOpenMode', async () => ({ mode: 'tabs' }));
ipcMain.handle('app:setOpenMode', async () => ({ ok: true }));
ipcMain.on('app:setDirty', () => {}); ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {}); ipcMain.on('docs:exported', () => {});
ipcMain.on('doc:syncPath', () => {});
const win = new BrowserWindow({
width: 1400, height: 900, show: true,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
const js = (c) => win.webContents.executeJavaScript(c);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
await js(`localStorage.clear()`);
await win.webContents.reload();
await wait(1800);
/* 1. 输入关键字,预览出现标记 */
const r1 = await js(`(async () => {
editor.value = '# 标题\\n\\n银色是银色的银,银币也很银。\\n\\n- 银在列表里\\n\\n**银** 在加粗里。';
editor.dispatchEvent(new Event('input', { bubbles: true }));
await new Promise(r => setTimeout(r, 250));
document.getElementById('btn-find').click();
await new Promise(r => setTimeout(r, 150));
const inp = document.getElementById('find-input');
inp.value = '银';
inp.dispatchEvent(new Event('input', { bubbles: true }));
await new Promise(r => setTimeout(r, 200));
return {
total: document.querySelectorAll('#preview mark.find-hit').length,
active: document.querySelectorAll('#preview mark.find-hit.find-hit-active').length,
count: document.getElementById('find-count').textContent
};
})()`);
check('预览正文出现 7 处关键字标记', r1.total === 7, JSON.stringify(r1));
check('当前命中有一个且仅一个', r1.active === 1, JSON.stringify(r1));
check('计数显示正常', r1.count.indexOf('7') >= 0, r1.count);
/* 1b. 编辑器叠加层同步高亮 */
const r1b = await js(`(() => ({
marks: document.querySelectorAll('#editor-hl mark').length,
active: document.querySelectorAll('#editor-hl mark.find-hit-active').length
}))()`);
check('编辑器叠加层出现 7 处标记', r1b.marks === 7, JSON.stringify(r1b));
check('编辑器层当前命中唯一', r1b.active === 1, JSON.stringify(r1b));
/* 1c. 编辑模式(无预览)下叠加层仍然高亮 */
const r1c = await js(`(async () => {
document.querySelector('.seg button[data-mode="edit"]').click();
await new Promise(r => setTimeout(r, 150));
const inEdit = document.getElementById('workspace').dataset.mode;
const marks = document.querySelectorAll('#editor-hl mark').length;
document.querySelector('.seg button[data-mode="split"]').click();
await new Promise(r => setTimeout(r, 150));
return { inEdit, marks };
})()`);
check('编辑模式下叠加层保持标记', r1c.inEdit === 'edit' && r1c.marks === 7, JSON.stringify(r1c));
/* 2. 下一处:active 移动 */
const r2 = await js(`(() => {
document.getElementById('find-next').click();
return {
actives: [...document.querySelectorAll('#preview mark.find-hit-active')].map(m => m.textContent),
idx: document.getElementById('find-count').textContent
};
})()`);
check('下一处后当前命中唯一', r2.actives.length === 1, JSON.stringify(r2));
check('计数推进到 2 / 7', r2.idx.indexOf('2 /') >= 0, r2.idx);
/* 3. 编辑内容后(renderNow 重建 DOM)标记恢复 */
const r3 = await js(`(async () => {
editor.focus();
editor.setSelectionRange(editor.value.length, editor.value.length);
document.execCommand('insertText', false, '\\n新增一行也带银字。');
await new Promise(r => setTimeout(r, 350));
return { total: document.querySelectorAll('#preview mark.find-hit').length };
})()`);
check('编辑重渲染后标记自动恢复', r3.total === 8, JSON.stringify(r3));
/* 4. 关闭查找,标记清除 */
const r4 = await js(`(() => {
document.getElementById('find-close').click();
return {
preview: document.querySelectorAll('#preview mark.find-hit').length,
editor: document.querySelectorAll('#editor-hl mark').length
};
})()`);
check('关闭查找后标记全部清除', r4.preview === 0, JSON.stringify(r4));
check('编辑器叠加层同时清空', r4.editor === 0, JSON.stringify(r4));
/* 5. 再次查找(新关键字),标记正常 */
const r5 = await js(`(async () => {
document.getElementById('btn-find').click();
const inp = document.getElementById('find-input');
inp.value = '标题';
inp.dispatchEvent(new Event('input', { bubbles: true }));
await new Promise(r => setTimeout(r, 200));
return {
total: document.querySelectorAll('#preview mark.find-hit').length,
text: [...document.querySelectorAll('#preview mark.find-hit')].map(m => m.textContent)
};
})()`);
check('新关键字标记正常', r5.total === 1 && r5.text[0] === '标题', JSON.stringify(r5));
/* 6. 换回完整文本输入框内容,普通正文无残留 mark */
const r6 = await js(`(() => {
document.getElementById('find-close').click();
return { marks: document.querySelectorAll('#preview mark').length };
})()`);
check('正文中无任何 mark 残留', r6.marks === 0, JSON.stringify(r6));
console.log('\n==== 预览查找高亮测试:通过 ' + pass + ',失败 ' + fail + ' ====');
app.exit(fail ? 1 : 0);
});
+73
View File
@@ -0,0 +1,73 @@
/* 生成应用图标:渲染 SVG 风格图形 → PNG 多尺寸 → 打包为 .ico */
const { app, BrowserWindow, nativeImage } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const HTML = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>
html,body{margin:0;width:512px;height:512px;background:transparent;overflow:hidden}
.wrap{width:512px;height:512px;display:flex;align-items:center;justify-content:center}
.box{width:452px;height:452px;border-radius:106px;position:relative;overflow:hidden;
background:linear-gradient(145deg,#5B8CFF 0%,#6A5AF9 46%,#9B4DF7 100%);
box-shadow:inset 0 -18px 44px rgba(10,10,60,.22), inset 0 16px 34px rgba(255,255,255,.24);
display:flex;align-items:center;justify-content:center}
.box::before{content:'';position:absolute;inset:0;
background:radial-gradient(130% 95% at 16% 6%, rgba(255,255,255,.30), transparent 55%)}
/* 四个字母排成紧凑 2×2:列宽取同列较宽者,字母在各自格子内居中 → 上下左右全部对齐 */
.mark{display:grid;grid-template-columns:repeat(2, auto);column-gap:22px;row-gap:0;
align-items:center;justify-items:center;position:relative;z-index:2;color:#fff;
font-family:"Segoe UI","Microsoft YaHei",sans-serif;
text-shadow:0 8px 26px rgba(18,18,72,.32)}
.mark i{font-style:normal;font-weight:750;font-size:148px;line-height:1;display:block}
</style></head><body><div class="wrap"><div class="box">
<div class="mark"><i>X</i><i>Y</i><i>M</i><i>D</i></div>
</div></div></body></html>`;
function buildIco(pngs) {
const count = pngs.length;
const header = Buffer.alloc(6);
header.writeUInt16LE(0, 0);
header.writeUInt16LE(1, 2);
header.writeUInt16LE(count, 4);
let offset = 6 + count * 16;
const entries = [];
const datas = [];
for (const p of pngs) {
const e = Buffer.alloc(16);
e[0] = p.size >= 256 ? 0 : p.size;
e[1] = p.size >= 256 ? 0 : p.size;
e[2] = 0;
e[3] = 0;
e.writeUInt16LE(1, 4);
e.writeUInt16LE(32, 6);
e.writeUInt32LE(p.buf.length, 8);
e.writeUInt32LE(offset, 12);
offset += p.buf.length;
entries.push(e);
datas.push(p.buf);
}
return Buffer.concat([header, ...entries, ...datas]);
}
app.whenReady().then(async () => {
const win = new BrowserWindow({
width: 512, height: 512, show: false, frame: false, transparent: true,
backgroundColor: '#00000000',
webPreferences: { offscreen: false }
});
await win.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(HTML));
await new Promise((r) => setTimeout(r, 900));
const img = await win.webContents.capturePage();
const sizes = [16, 24, 32, 48, 64, 128, 256];
const pngs = sizes.map((size) => ({
size,
buf: img.resize({ width: size, height: size, quality: 'best' }).toPNG()
}));
const outDir = path.join(__dirname, '..', 'build');
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, 'icon.ico'), buildIco(pngs));
fs.writeFileSync(path.join(outDir, 'icon.png'), img.resize({ width: 512, height: 512, quality: 'best' }).toPNG());
console.log('icon written:', path.join(outDir, 'icon.ico'), fs.statSync(path.join(outDir, 'icon.ico')).size, 'bytes');
app.exit(0);
});
+111
View File
@@ -0,0 +1,111 @@
/* 直接驱动真实 main.js:验证标签↔独立窗口双向迁移 */
const { app, BrowserWindow } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const main = require('../src/main.js');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-'));
const docs = ['A.md', 'B.md', 'C.md'].map((n) => {
const p = path.join(tmp, n);
fs.writeFileSync(p, '# ' + n + '\n\n内容 ' + n + '\n', 'utf8');
return { path: p, name: n, text: '# ' + n + '\n\n内容 ' + n + '\n', eol: '\n' };
});
await wait(1200);
let wins = BrowserWindow.getAllWindows();
await wins[0].webContents.executeJavaScript(`localStorage.clear()`);
await wins[0].webContents.reload();
await wait(1200);
check('启动后 1 个窗口', wins.length === 1, String(wins.length));
// 在标签模式下打开 3 个文档
for (const d of docs) {
wins[0].webContents.send('cmd', 'file-opened', Object.assign({ ok: true }, d));
await wait(300);
}
const tabCount = await wins[0].webContents.executeJavaScript(`document.querySelectorAll('#tabbar .tab').length`);
check('标签模式有 3 个标签(欢迎 + A + B)', tabCount >= 3, String(tabCount));
check('标题显示最后打开的文件', wins[0].getTitle().indexOf('C.md') >= 0, wins[0].getTitle());
// 切到 A 标签,标题应跟着变(同步给主进程)
await wins[0].webContents.executeJavaScript(`document.querySelectorAll('#tabbar .tab')[1].click()`);
await wait(500);
check('切换标签后标题变成 A.md', wins[0].getTitle().indexOf('A.md') >= 0, wins[0].getTitle());
/* ---- 标签 → 独立窗口:应拆成多个窗口 ---- */
await main.setOpenMode('windows');
await wait(3200);
wins = BrowserWindow.getAllWindows();
check('切成独立窗口模式后拆成多个窗口', wins.length >= 3, String(wins.length));
let allHidden = true;
let foundDoc = false;
for (const w of wins) {
try {
const info = await w.webContents.executeJavaScript(`({
hidden: document.getElementById('tabbar').hidden,
val: editor.value.slice(0, 30)
})`);
if (!info.hidden) allHidden = false;
if (info.val.indexOf('内容') >= 0) foundDoc = true;
} catch (_) { /* 已关闭 */ }
}
check('拆分后各窗口标签栏隐藏', allHidden === true);
check('拆分后文档内容被带过去', foundDoc === true);
check('主进程模式为 windows', main.getOpenMode() === 'windows');
/* ---- 独立窗口 → 标签:应合并成一个窗口 ---- */
await main.setOpenMode('tabs');
await wait(3500);
wins = BrowserWindow.getAllWindows();
check('切成标签模式后合并为 1 个窗口', wins.length === 1, String(wins.length));
if (wins.length === 1) {
const merged = await wins[0].webContents.executeJavaScript(`(() => ({
hidden: document.getElementById('tabbar').hidden,
n: document.querySelectorAll('#tabbar .tab').length,
names: [...document.querySelectorAll('#tabbar .tab-name')].map(e => e.textContent)
}))()`);
check('合并后标签栏可见', merged.hidden === false);
check('合并后保留全部 4 个标签(含空白欢迎页)', merged.n === 4, JSON.stringify(merged.names));
check('合并后标签名正确', ['A.md', 'B.md', 'C.md'].every((n) => merged.names.includes(n)), JSON.stringify(merged.names));
}
check('主进程模式为 tabs', main.getOpenMode() === 'tabs');
/* ---- 保存必须直接覆盖原文件,而不是弹另存为 ---- */
if (wins.length === 1) {
const before = fs.readFileSync(docs[0].path, 'utf8');
await wins[0].webContents.executeJavaScript(`(() => {
// 确保激活的是 A.md 标签
const idx = [...document.querySelectorAll('#tabbar .tab-name')].findIndex(e => e.textContent === 'A.md');
if (idx >= 0) document.querySelectorAll('#tabbar .tab')[idx].click();
})()`);
await wait(500);
await wins[0].webContents.executeJavaScript(`(() => {
editor.focus();
editor.setSelectionRange(editor.value.length, editor.value.length);
document.execCommand('insertText', false, '\\n保存覆盖验证标记');
})()`);
await wait(250);
wins[0].webContents.send('cmd', 'save');
await wait(900);
const after = fs.readFileSync(docs[0].path, 'utf8');
check('保存直接覆盖原文件(A.md 内容已更新)', after.indexOf('保存覆盖验证标记') >= 0, after.slice(-60));
check('覆盖前原内容仍保留', before.indexOf('内容 A.md') >= 0);
const title = wins[0].getTitle();
check('保存后标题仍是 A.md', title.indexOf('A.md') >= 0, title);
}
console.log('\n==== 模式迁移测试:通过 ' + pass + ',失败 ' + fail + ' ====');
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(fail ? 1 : 0);
});
+23
View File
@@ -0,0 +1,23 @@
const ws = require('windows-shortcuts');
const path = require('path');
// 用 USERPROFILE 而不是写死某个人的目录 —— 换机器/换用户名都能直接用。
const home = process.env.USERPROFILE || process.env.HOME;
const appDir = path.join(home, 'Apps', 'XiaoyinMarkdown');
const target = path.join(appDir, 'XiaoyinMarkdown.exe');
const workingDir = appDir;
const lnk = path.join(home, 'Desktop', '小银Markdown.lnk');
ws.create(
lnk,
{ target, workingDir, icon: target, iconIndex: 0, desc: '小银 Markdown 编辑器', runStyle: 1 },
(err) => {
if (err) {
console.log('ERR', err.message);
process.exit(1);
}
ws.query(lnk, (e, d) => {
console.log(e ? 'QUERY ERR ' + e.message : JSON.stringify(d, null, 2));
});
}
);
+113
View File
@@ -0,0 +1,113 @@
/* 生成 Windows .lnk 快捷方式(纯字节拼装,不依赖 COM) */
const fs = require('node:fs');
const path = require('node:path');
function buildLnk({ target, workdir, icon, desc, args }) {
const isUnicode = true;
// ---- StringData ----
const strings = [];
const pushStr = (s) => {
if (s == null) return 0;
const chars = isUnicode ? 2 : 1;
const buf = Buffer.alloc(2 + s.length * chars);
buf.writeUInt16LE(s.length, 0);
if (isUnicode) buf.write(s, 2, 'utf16le');
else buf.write(s, 2, 'latin1');
strings.push(buf);
return 1;
};
let flags = 0x00000002 /* HasLinkInfo */ | 0x00000004 /* HasName */;
const parts = [];
parts.push(pushStr(desc ? desc : null)); // NAME_STRING
if (target) { flags |= 0x00000008; parts.push(pushStr(null)); } // RELATIVE_PATH 占位(用 target)
if (workdir) { flags |= 0x00000010; parts.push(pushStr(workdir)); }
if (args) { flags |= 0x00000020; parts.push(pushStr(args)); }
if (icon) { flags |= 0x00000040; parts.push(pushStr(icon)); }
if (isUnicode) flags |= 0x00000080;
// 重新按顺序构建(NAME, RELATIVE_PATH, WORKING_DIR, ARGUMENTS, ICON)
strings.length = 0;
const seq = [];
const add = (s) => {
const buf = Buffer.alloc(2 + String(s).length * 2);
buf.writeUInt16LE(String(s).length, 0);
buf.write(String(s), 2, 'utf16le');
seq.push(buf);
};
if (desc) add(desc);
if (target) add(target); // RELATIVE_PATH
if (workdir) add(workdir);
if (args) add(args);
if (icon) add(icon);
const stringData = Buffer.concat(seq);
// ---- LinkInfo ----
const volumeLabel = Buffer.from([0x00]); // 空卷标
const volumeIdHeader = Buffer.alloc(16);
volumeIdHeader.writeUInt32LE(16 + volumeLabel.length, 0); // VolumeIDSize
volumeIdHeader.writeUInt32LE(3, 4); // DRIVE_FIXED
volumeIdHeader.writeUInt32LE(0x12345678, 8); // DriveSerialNumber
volumeIdHeader.writeUInt32LE(0x10, 12); // VolumeLabelOffset
const volumeId = Buffer.concat([volumeIdHeader, volumeLabel]);
const localBaseAnsi = Buffer.from(target + '\0', 'latin1');
const suffixAnsi = Buffer.from([0x00]);
const localBaseUni = Buffer.from(target + '\0', 'utf16le');
const suffixUni = Buffer.from([0x00, 0x00]);
const headerSize = 0x24;
const volumeIdOffset = headerSize;
const localBaseOffset = volumeIdOffset + volumeId.length;
const suffixOffset = localBaseOffset + localBaseAnsi.length;
const localBaseUniOffset = suffixOffset + suffixAnsi.length;
const suffixUniOffset = localBaseUniOffset + localBaseUni.length;
const linkInfoSize = suffixUniOffset + suffixUni.length;
const li = Buffer.alloc(headerSize);
li.writeUInt32LE(linkInfoSize, 0);
li.writeUInt32LE(headerSize, 4);
li.writeUInt32LE(0x00000001, 8); // VolumeIDAndLocalBasePath
li.writeUInt32LE(volumeIdOffset, 12);
li.writeUInt32LE(localBaseOffset, 16);
li.writeUInt32LE(0, 20); // CommonNetworkRelativeLinkOffset
li.writeUInt32LE(suffixOffset, 24);
li.writeUInt32LE(localBaseUniOffset, 28);
li.writeUInt32LE(suffixUniOffset, 32);
const linkInfo = Buffer.concat([li, volumeId, localBaseAnsi, suffixAnsi, localBaseUni, suffixUni]);
// ---- Header (76 bytes) ----
const h = Buffer.alloc(76);
h.writeUInt32LE(0x4c, 0);
// LinkCLSID {00021401-0000-0000-C000-000000000046}
Buffer.from('0114020000000000c000000000000046', 'hex').copy(h, 4);
h.writeUInt32LE(flags, 20);
h.writeUInt32LE(0x20, 24); // FILE_ATTRIBUTE_ARCHIVE
// 28 CreationTime / 36 AccessTime / 44 WriteTime 均留 0
h.writeUInt32LE(0, 52); // FileSize
h.writeUInt32LE(0, 56); // IconIndex
h.writeUInt32LE(1, 60); // ShowCommand = SW_SHOWNORMAL
h.writeUInt16LE(0, 64); // HotKey
h.writeUInt16LE(0, 66); // Reserved1
h.writeUInt32LE(0, 68); // Reserved2
h.writeUInt32LE(0, 72); // Reserved3
return Buffer.concat([h, linkInfo, stringData, Buffer.alloc(4)]); // 末尾 TerminalBlock
}
const target = (process.argv[2] || '').replace(/\//g, '\\');
const out = process.argv[3];
if (!target || !out) {
console.error('usage: node tools/mklnk.js <target.exe> <out.lnk>');
process.exit(1);
}
const buf = buildLnk({
target,
workdir: path.dirname(target),
icon: target + ',0',
desc: '小银 Markdown 编辑器'
});
fs.writeFileSync(out, buf);
console.log('written', out, buf.length, 'bytes');
+222
View File
@@ -0,0 +1,222 @@
/* 验证:标签页、独立窗口偏好、右键打开方式、状态保留 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'multitest-'));
const a = path.join(tmp, 'A文档.md');
const b = path.join(tmp, 'B文档.md');
fs.writeFileSync(a, '# A 文档\n\n这是 A。\n', 'utf8');
fs.writeFileSync(b, '# B 文档\n\n这是 B。\n', 'utf8');
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }));
let forcedMode = 'tabs';
let lastNewWindow = '';
let lastNewBlank = 0;
let lastSetMode = '';
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('file:readText', async (_e, p) => ({ ok: true, text: fs.readFileSync(p, 'utf8') }));
ipcMain.handle('file:copyFile', async () => ({ ok: true }));
ipcMain.handle('file:revealPath', async () => ({ ok: true }));
ipcMain.handle('clip:read', () => '');
ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.handle('app:getOpenMode', async () => ({ mode: forcedMode }));
ipcMain.handle('app:setOpenMode', async (_e, m) => { lastSetMode = m; forcedMode = m; return { ok: true }; });
ipcMain.handle('window:openPath', async (_e, p) => { lastNewWindow = p || ''; return { ok: true }; });
ipcMain.handle('window:new', async () => { lastNewBlank++; return { ok: true }; });
ipcMain.on('app:setDirty', () => {});
ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {});
ipcMain.on('file:drop', () => {});
ipcMain.on('file:droppedText', () => {});
const win = new BrowserWindow({
width: 1400, height: 880, show: true,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
const js = (c) => win.webContents.executeJavaScript(c);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
await js(`localStorage.clear()`);
await win.webContents.reload();
await wait(1300);
/* 1. 初始标签 */
const init = await js(`(() => ({
visible: !document.getElementById('tabbar').hidden,
n: document.querySelectorAll('#tabbar .tab').length,
label: document.getElementById('openmode-label').textContent
}))()`);
check('默认标签栏可见且有 1 个标签', init.visible === true && init.n === 1, JSON.stringify(init));
check('按钮显示「标签」', init.label === '标签', init.label);
/* 2. 打开两个文件 → 两个新标签 */
win.webContents.send('cmd', 'file-opened', { ok: true, path: a, name: 'A文档.md', text: fs.readFileSync(a, 'utf8'), eol: '\n' });
await wait(300);
win.webContents.send('cmd', 'file-opened', { ok: true, path: b, name: 'B文档.md', text: fs.readFileSync(b, 'utf8'), eol: '\n' });
await wait(400);
const two = await js(`(() => ({
n: document.querySelectorAll('#tabbar .tab').length,
active: document.querySelector('#tabbar .tab.active .tab-name').textContent,
val: editor.value.slice(0, 6),
names: [...document.querySelectorAll('#tabbar .tab-name')].map(e => e.textContent)
}))()`);
check('打开两个文件得到 3 个标签', two.n === 3, JSON.stringify(two.names));
check('当前标签是最后打开的文件', two.active === 'B文档.md', two.active);
check('编辑区显示当前标签内容', two.val.indexOf('B 文档') >= 0, two.val);
/* 3. 切换标签,各自状态保留 */
await js(`(() => {
editor.focus();
editor.setSelectionRange(editor.value.length, editor.value.length);
document.execCommand('insertText', false, '\\nB 的修改');
})()`);
await wait(250);
await js(`document.querySelectorAll('#tabbar .tab')[1].click()`);
await wait(350);
const switched = await js(`(() => ({
active: document.querySelector('#tabbar .tab.active .tab-name').textContent,
val: editor.value.slice(0, 6)
}))()`);
check('点标签切到 A 文档', switched.active === 'A文档.md' && switched.val.indexOf('A 文档') >= 0, JSON.stringify(switched));
await js(`document.querySelectorAll('#tabbar .tab')[2].click()`);
await wait(350);
const back = await js(`editor.value.includes('B 的修改')`);
check('切回后 B 的修改还在', back === true);
/* 4. 重复打开同一文件不新增标签 */
win.webContents.send('cmd', 'file-opened', { ok: true, path: a, name: 'A文档.md', text: fs.readFileSync(a, 'utf8'), eol: '\n' });
await wait(350);
const dup = await js(`document.querySelectorAll('#tabbar .tab').length`);
check('重复打开同一文件不新建标签', dup === 3, String(dup));
/* 5. 关闭标签 */
await js(`document.querySelectorAll('#tabbar .tab-close')[2].click()`);
await wait(400);
const closed = await js(`(() => ({ n: document.querySelectorAll('#tabbar .tab').length, active: document.querySelector('#tabbar .tab.active .tab-name').textContent }))()`);
check('关闭标签后数量减 1', closed.n === 2, JSON.stringify(closed));
check('关闭后切到相邻标签', ['A文档.md', '未命名'].includes(closed.active), closed.active);
/* 6. 切换到独立窗口模式 */
const modeInfo = await js(`(async () => {
document.getElementById('btn-openmode').click();
await new Promise(r => setTimeout(r, 350));
return {
hidden: document.getElementById('tabbar').hidden,
label: document.getElementById('openmode-label').textContent,
ls: localStorage.getItem('md-editor-open-mode')
};
})()`);
check('切到窗口模式后标签栏隐藏', modeInfo.hidden === true, JSON.stringify(modeInfo));
check('按钮文字变为「窗口」', modeInfo.label === '窗口', modeInfo.label);
check('模式写入本地存储', modeInfo.ls === 'windows', modeInfo.ls);
check('模式同步到主进程', lastSetMode === 'windows', lastSetMode);
/* 7. 窗口模式下右键显示「在新窗口打开」,且真的走新窗口 */
const ctxWin = await js(`(() => {
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('A文档.md'));
if (!row) return { err: 'no row' };
const p = row.dataset.path;
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
const first = items[0] ? lab(items[0]) : '';
const target = items.find(i => lab(i) === '在新窗口打开');
if (target) target.click();
return { first, exists: !!target, path: p };
})()`).catch(async () => {
// executeJavaScript 里不能引用 win,重来一次
return js(`(() => {
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('A文档.md'));
if (!row) return { err: 'no row' };
const p = row.dataset.path;
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
const first = items[0] ? lab(items[0]) : '';
const target = items.find(i => lab(i) === '在新窗口打开');
if (target) target.click();
return { first, exists: !!target, path: p };
})()`);
});
await wait(350);
check('窗口模式右键首项是「在新窗口打开」', ctxWin.first === '在新窗口打开', JSON.stringify(ctxWin));
check('右键触发了独立窗口打开', lastNewWindow === a, lastNewWindow);
/* 8. 切回标签模式,右键变「在新标签打开」 */
await js(`document.getElementById('btn-openmode').click()`);
await wait(350);
const ctxTab = await js(`(() => {
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('B文档.md'));
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
const first = items[0] ? lab(items[0]) : '';
const target = items.find(i => lab(i) === '在新标签打开');
if (target) target.click();
return { first, exists: !!target };
})()`);
await wait(450);
check('标签模式右键首项是「在新标签打开」', ctxTab.first === '在新标签打开', JSON.stringify(ctxTab));
const afterCtx = await js(`(() => ({ n: document.querySelectorAll('#tabbar .tab').length, val: editor.value.slice(0,6) }))()`);
check('右键在新标签打开生效', afterCtx.val.indexOf('B 文档') >= 0, JSON.stringify(afterCtx));
/* 9. 重启后保持模式 */
await win.webContents.reload();
await wait(1300);
const kept = await js(`(() => ({
hidden: document.getElementById('tabbar').hidden,
label: document.getElementById('openmode-label').textContent,
tabs: document.querySelectorAll('#tabbar .tab').length
}))()`);
check('重启后保持标签模式', kept.hidden === false && kept.label === '标签', JSON.stringify(kept));
check('重启后有欢迎标签', kept.tabs === 1, String(kept.tabs));
/* 9.5 关闭欢迎页后,下次启动不再显示 */
const hadWelcome = await js(`editor.value.indexOf('欢迎使用') >= 0`);
await js(`document.querySelectorAll('#tabbar .tab-close')[0].click()`);
await wait(450);
const flag = await js(`localStorage.getItem('md-editor-welcome-closed')`);
check('初始打开的是欢迎页', hadWelcome === true);
check('关闭欢迎页后写入标记', flag === '1', flag);
await win.webContents.reload();
await wait(1300);
const afterClose = await js(`(() => ({
tabs: document.querySelectorAll('#tabbar .tab').length,
name: (document.querySelector('#tabbar .tab-name') || {}).textContent || '',
val: editor.value
}))()`);
check('重启后不再显示欢迎页', afterClose.val.indexOf('欢迎使用') < 0, JSON.stringify(afterClose.val.slice(0, 20)));
check('重启后是空白未命名标签', afterClose.tabs === 1 && afterClose.name === '未命名' && afterClose.val === '', JSON.stringify({ name: afterClose.name, len: afterClose.val.length }));
/* 10. 主进程偏好为 windows 时启动即窗口模式 */
forcedMode = 'windows';
await win.webContents.reload();
await wait(1300);
const fromMain = await js(`(() => ({
hidden: document.getElementById('tabbar').hidden,
label: document.getElementById('openmode-label').textContent
}))()`);
check('主进程偏好为窗口时启动即窗口模式', fromMain.hidden === true && fromMain.label === '窗口', JSON.stringify(fromMain));
console.log('\n==== 多窗口/标签测试:通过 ' + pass + ',失败 ' + fail + ' ====');
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(fail ? 1 : 0);
});
+141
View File
@@ -0,0 +1,141 @@
/* 验证章节目录:生成、开关、跳转、随编辑更新、状态记忆 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
app.whenReady().then(async () => {
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
ipcMain.handle('dir:read', async () => ({ ok: false }));
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('clip:read', () => '');
ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.on('app:setDirty', () => {});
ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {});
const win = new BrowserWindow({
width: 1360, height: 860, show: true,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
await win.webContents.executeJavaScript(`localStorage.clear()`);
await win.webContents.reload();
await new Promise((r) => setTimeout(r, 1800));
const js = (c) => win.webContents.executeJavaScript(c);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
// 清掉上次遗留的偏好,保证从"全新用户"状态开始
await js(`localStorage.clear()`);
await win.webContents.reload();
await wait(1200);
/* 1. 默认显示且能生成大纲 */
const init = await js(`(() => {
const rows = [...document.querySelectorAll('.ol-item')];
const heads = [...preview.querySelectorAll('h1,h2,h3,h4,h5,h6')];
return {
visible: !document.getElementById('outline').hidden,
count: rows.length,
heads: heads.length,
label: document.getElementById('ol-count').textContent,
btnOn: document.getElementById('btn-outline').classList.contains('on'),
first: rows[0] ? rows[0].textContent : '',
levels: rows.slice(0, 4).map(r => r.dataset.level)
};
})()`);
check('默认显示章节目录', init.visible === true);
check('大纲条数等于标题数', init.count > 0 && init.count === init.heads, init.count + ' vs ' + init.heads);
check('计数徽标同步', init.label === String(init.count), init.label);
check('右上角按钮为开启态', init.btnOn === true);
check('首条是欢迎标题', init.first.indexOf('欢迎使用') >= 0, init.first);
check('层级信息正确', init.levels[0] === '1', JSON.stringify(init.levels));
/* 2. 关闭按钮 */
const closed = await js(`(() => {
document.getElementById('ol-close').click();
return { hidden: document.getElementById('outline').hidden, on: document.getElementById('btn-outline').classList.contains('on'), ls: localStorage.getItem('md-editor-outline') };
})()`);
check('点关闭后大纲隐藏', closed.hidden === true);
check('关闭后按钮取消高亮', closed.on === false);
check('关闭状态被记住', closed.ls === '0', closed.ls);
/* 3. 用右上角按钮再打开 */
const reopened = await js(`(() => {
document.getElementById('btn-outline').click();
return { hidden: document.getElementById('outline').hidden, on: document.getElementById('btn-outline').classList.contains('on'), rows: document.querySelectorAll('.ol-item').length };
})()`);
check('右上角按钮可重新打开', reopened.hidden === false && reopened.on === true);
check('重新打开后条目仍在', reopened.rows === init.count, String(reopened.rows));
/* 4. 快捷键 / 菜单命令切换 */
win.webContents.send('cmd', 'outline');
await wait(200);
const byCmd = await js(`document.getElementById('outline').hidden`);
check('菜单命令可切换大纲', byCmd === true);
win.webContents.send('cmd', 'outline');
await wait(200);
const byCmd2 = await js(`document.getElementById('outline').hidden`);
check('再切一次恢复显示', byCmd2 === false);
/* 5. 点击大纲跳转 */
const jump = await js(`(() => {
const rows = [...document.querySelectorAll('.ol-item')];
const heads = [...preview.querySelectorAll('h1,h2,h3,h4,h5,h6')];
const target = rows[2];
const expectLine = Number(heads[2].dataset.line);
target.click();
return { expectLine, activeIdx: rows.indexOf(document.querySelector('.ol-item.active')) };
})()`);
await wait(700);
const jumped = await js(`(() => {
const pos = editor.selectionStart;
const line = editor.value.slice(0, pos).split('\\n').length - 1;
return { line, active: [...document.querySelectorAll('.ol-item')].findIndex(r => r.classList.contains('active')), pTop: preview.scrollTop };
})()`);
check('点击大纲定位到源码对应行', jumped.line === jump.expectLine, jumped.line + ' vs ' + jump.expectLine);
check('点击后大纲高亮该项', jumped.active === 2, String(jumped.active));
check('阅读区同步滚动', jumped.pTop > 0 || jump.expectLine === 0, String(jumped.pTop));
/* 6. 编辑内容后大纲实时更新 */
const updated = await js(`(async () => {
editor.focus();
editor.setSelectionRange(editor.value.length, editor.value.length);
document.execCommand('insertText', false, '\\n\\n## 新增的一个章节\\n\\n正文\\n\\n### 三级小节\\n');
await new Promise(r => setTimeout(r, 350));
const rows = [...document.querySelectorAll('.ol-item')];
return { count: rows.length, last: rows[rows.length - 1].textContent, hasNew: rows.some(r => r.textContent === '新增的一个章节') };
})()`);
check('新增标题后大纲自动更新', updated.hasNew === true && updated.count === init.count + 2, JSON.stringify(updated));
check('三级标题也被收录', updated.last === '三级小节', updated.last);
/* 7. 无标题文档显示空提示 */
const empty = await js(`(async () => {
editor.value = '只有正文,没有任何标题。\\n';
editor.dispatchEvent(new Event('input'));
await new Promise(r => setTimeout(r, 350));
return { rows: document.querySelectorAll('.ol-item').length, tip: document.querySelector('.ol-empty') ? document.querySelector('.ol-empty').textContent : '', label: document.getElementById('ol-count').textContent };
})()`);
check('无标题时给出空提示', empty.rows === 0 && empty.tip.length > 0, empty.tip);
check('无标题时计数为 0', empty.label === '0');
/* 8. 重启后保持隐藏状态 */
await js(`document.getElementById('ol-close').click()`);
await wait(200);
await win.webContents.reload();
await wait(1100);
const kept = await js(`({ hidden: document.getElementById('outline').hidden, rows: document.querySelectorAll('.ol-item').length })`);
check('重启后保持上次的显示状态', kept.hidden === true, String(kept.hidden));
check('重启后大纲仍能生成', kept.rows > 0, String(kept.rows));
console.log('\n==== 章节目录测试:通过 ' + pass + ',失败 ' + fail + ' ====');
app.exit(fail ? 1 : 0);
});
+154
View File
@@ -0,0 +1,154 @@
/* 验证:目录/大纲宽度可拖拽、写入本地存储、重启恢复、分隔条跟随面板显隐 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'paneltest-'));
fs.writeFileSync(path.join(tmp, '文档.md'), '# 文档\n\n正文。\n', 'utf8');
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }));
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('file:readText', async (_e, p) => ({ ok: true, text: fs.readFileSync(p, 'utf8') }));
ipcMain.handle('file:copyFile', async () => ({ ok: true }));
ipcMain.handle('file:revealPath', async () => ({ ok: true }));
ipcMain.handle('clip:read', () => ''); ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true })); ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.handle('app:getOpenMode', async () => ({ mode: 'tabs' }));
ipcMain.handle('app:setOpenMode', async () => ({ ok: true }));
ipcMain.on('app:setDirty', () => {}); ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {}); ipcMain.on('docs:exported', () => {});
const win = new BrowserWindow({
width: 1440, height: 900, show: true,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
const js = (c) => win.webContents.executeJavaScript(c);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
await js(`localStorage.clear(); localStorage.setItem('md-editor-dir', ${JSON.stringify(tmp)});`);
await win.webContents.reload();
await wait(1400);
/* 1. 初始宽度与分隔条存在 */
const init = await js(`(() => ({
sb: document.getElementById('sidebar').getBoundingClientRect().width,
ol: document.getElementById('outline').getBoundingClientRect().width,
sbSp: !document.getElementById('sb-splitter').hidden,
olSp: !document.getElementById('ol-splitter').hidden
}))()`);
check('分隔条存在且可见', init.sbSp === true && init.olSp === true, JSON.stringify(init));
check('目录初始宽度约 232', Math.abs(init.sb - 232) < 4, String(init.sb));
check('大纲初始宽度约 210', Math.abs(init.ol - 210) < 4, String(init.ol));
/* 2. 拖拽目录变宽 */
const sbDrag = await js(`(() => {
const before = document.getElementById('sidebar').getBoundingClientRect().width;
const sp = document.getElementById('sb-splitter');
sp.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: before + 6 }));
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: before + 146 }));
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
const after = document.getElementById('sidebar').getBoundingClientRect().width;
return { before, after, saved: localStorage.getItem('md-editor-sb-w') };
})()`);
check('拖拽后目录变宽约 150px', Math.abs(sbDrag.after - sbDrag.before - 140) < 25, JSON.stringify(sbDrag));
check('目录宽度写入本地存储', !!sbDrag.saved && Math.abs(Number(sbDrag.saved) - sbDrag.after) < 3, sbDrag.saved);
/* 3. 拖拽大纲变宽(分隔条在大纲左边缘,向左拖 = 变宽) */
const olDrag = await js(`(() => {
const ol = document.getElementById('outline');
const before = ol.getBoundingClientRect().width;
const left = ol.getBoundingClientRect().left;
const sp = document.getElementById('ol-splitter');
sp.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: left + 2 }));
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: left - 98 }));
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
const after = ol.getBoundingClientRect().width;
return { before, after, saved: localStorage.getItem('md-editor-ol-w') };
})()`);
check('拖拽后大纲变宽约 100px', Math.abs(olDrag.after - olDrag.before - 98) < 20, JSON.stringify(olDrag));
check('大纲宽度写入本地存储', !!olDrag.saved && Math.abs(Number(olDrag.saved) - olDrag.after) < 3, olDrag.saved);
/* 4. 重启后宽度恢复 */
await win.webContents.reload();
await wait(1400);
const kept = await js(`(() => ({
sb: document.getElementById('sidebar').getBoundingClientRect().width,
ol: document.getElementById('outline').getBoundingClientRect().width
}))()`);
check('重启后目录宽度恢复', Math.abs(kept.sb - sbDrag.after) < 4, JSON.stringify(kept));
check('重启后大纲宽度恢复', Math.abs(kept.ol - olDrag.after) < 4, JSON.stringify(kept));
/* 5. 最小宽度限制(放在恢复验证之后,避免覆盖已保存的宽度) */
const minTest = await js(`(() => {
document.getElementById('sb-splitter').dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: 300 }));
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 2 }));
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
return document.getElementById('sidebar').getBoundingClientRect().width;
})()`);
check('目录宽度不会被拖到小于 180', minTest >= 180 && minTest < 220, String(minTest));
/* 6. 关闭面板时分隔条跟随隐藏 */
await js(`document.getElementById('sb-close').click()`);
await wait(200);
const sbHidden = await js(`document.getElementById('sb-splitter').hidden`);
check('目录隐藏时分隔条跟随隐藏', sbHidden === true);
await js(`document.getElementById('ol-close').click()`);
await wait(200);
const olHidden = await js(`document.getElementById('ol-splitter').hidden`);
check('大纲隐藏时分隔条跟随隐藏', olHidden === true);
/* 7. 重新打开时分隔条恢复,宽度仍是记住的值 */
await js(`(() => {
localStorage.setItem('md-editor-sb', '0');
document.getElementById('btn-tree').click();
})()`);
await wait(250);
await js(`document.getElementById('btn-outline').click()`);
await wait(250);
const reopened = await js(`(() => ({
sbSp: !document.getElementById('sb-splitter').hidden,
olSp: !document.getElementById('ol-splitter').hidden,
sb: document.getElementById('sidebar').getBoundingClientRect().width,
ol: document.getElementById('outline').getBoundingClientRect().width
}))()`);
check('重新打开后分隔条恢复', reopened.sbSp === true && reopened.olSp === true, JSON.stringify(reopened));
const savedNow = await js(`({ sb: localStorage.getItem('md-editor-sb-w'), ol: localStorage.getItem('md-editor-ol-w') })`);
check('重新打开后宽度与保存值一致',
Math.abs(reopened.sb - Number(savedNow.sb)) < 4 && Math.abs(reopened.ol - Number(savedNow.ol)) < 4,
JSON.stringify({ reopened, savedNow }));
/* 8. 编辑/预览分栏比例记忆 */
const splitDrag = await js(`(() => {
const ws = document.getElementById('workspace');
const rect = ws.getBoundingClientRect();
const sp = document.getElementById('splitter');
const before = document.getElementById('editor-pane').getBoundingClientRect().width;
sp.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: rect.left + before }));
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: rect.left + rect.width * 0.62 }));
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
const after = document.getElementById('editor-pane').getBoundingClientRect().width;
return { before, after, pct: localStorage.getItem('md-editor-split-pct') };
})()`);
check('拖拽分栏后比例写入存储', !!splitDrag.pct && Math.abs(Number(splitDrag.pct) - 0.62) < 0.05, JSON.stringify(splitDrag));
await win.webContents.reload();
await wait(1400);
const splitKept = await js(`document.getElementById('editor-pane').getBoundingClientRect().width / document.getElementById('workspace').getBoundingClientRect().width`);
check('重启后分栏比例恢复', Math.abs(splitKept - 0.62) < 0.03, String(splitKept));
console.log('\n==== 面板宽度测试:通过 ' + pass + ',失败 ' + fail + ' ====');
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(fail ? 1 : 0);
});
+44
View File
@@ -0,0 +1,44 @@
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const theme = process.env.SHOT_THEME || 'light';
const out = process.env.SHOT_OUT || path.join(__dirname, '..', 'shot.png');
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'shotdir-'));
const mk = (n, c) => fs.writeFileSync(path.join(tmp, n), c, 'utf8');
mk('产品需求说明.md', '# 产品需求说明\n\n## 目标\n\n做一个**纯本地**的 Markdown 编辑器。\n\n- 实时预览\n- 右键复制全文\n- 拖进来就打开\n\n> 不联网,不登录。\n');
mk('API 设计.md', '# API\n');
mk('更新日志.md', '# 更新日志\n');
mk('readme.txt', 'txt\n');
fs.mkdirSync(path.join(tmp, '草稿'));
fs.writeFileSync(path.join(tmp, '草稿', '想法.md'), '# 想法\n', 'utf8');
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
.filter(d => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map(d => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }))
.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
ipcMain.handle('dir:open', async () => ({ ok: false }));
ipcMain.handle('clip:read', () => ''); ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true })); ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.on('app:setDirty', () => {}); ipcMain.on('win:setTitle', () => {}); ipcMain.on('save:finished', () => {});
const win = new BrowserWindow({ width: 1380, height: 880, show: true, backgroundColor: '#fff',
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false } });
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
await win.webContents.executeJavaScript(`localStorage.setItem('md-editor-theme', ${JSON.stringify(theme)}); document.documentElement.dataset.theme = ${JSON.stringify(theme)};`);
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmp, name: path.basename(tmp), entries: list() });
await new Promise(r => setTimeout(r, 500));
win.webContents.send('cmd', 'file-opened', { ok: true, path: path.join(tmp, '产品需求说明.md'), name: '产品需求说明.md', text: fs.readFileSync(path.join(tmp, '产品需求说明.md'), 'utf8'), eol: '\n' });
await new Promise(r => setTimeout(r, 1400));
const img = await win.webContents.capturePage();
fs.writeFileSync(out, img.toPNG());
console.log('saved', out);
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(0);
});
+97
View File
@@ -0,0 +1,97 @@
/* 验证:启动即显示侧栏、空态引导、记住上次文件夹 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
let pass = 0, fail = 0;
const check = (n, ok, extra) => {
if (ok) { pass++; console.log('PASS ' + n); }
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
};
app.whenReady().then(async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sidetest-'));
fs.writeFileSync(path.join(tmp, '一篇.md'), '# 一篇\n', 'utf8');
fs.writeFileSync(path.join(tmp, '二篇.md'), '# 二篇\n', 'utf8');
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }));
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
ipcMain.handle('dir:read', async (_e, p) => {
if (!fs.existsSync(p)) return { ok: false };
return { ok: true, path: p, name: path.basename(p), entries: list() };
});
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('clip:read', () => '');
ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
ipcMain.on('app:setDirty', () => {});
ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {});
const win = new BrowserWindow({
width: 1280, height: 820, show: false,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
const js = (c) => win.webContents.executeJavaScript(c);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
await wait(700);
// 1. 清空记忆后重新加载 = 首次启动
await js(`localStorage.clear()`);
await win.webContents.reload();
await wait(1100);
const first = await js(`({
visible: !document.getElementById('sidebar').hidden,
hasBtn: !!document.querySelector('.sb-pick-btn'),
title: document.getElementById('sb-title').textContent,
hasTree: document.querySelectorAll('#sb-body .tree-row').length
})`);
check('首次启动显示左侧目录(空态引导)', first.visible === true, JSON.stringify(first));
check('空态有「选择文件夹」按钮', first.hasBtn === true);
check('无文件夹时不渲染空条目', first.hasTree === 0);
check('面板标题为「目录」', first.title === '目录', first.title);
// 2. 打开文件夹后记录到本地
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmp, name: path.basename(tmp), entries: list() });
await wait(400);
const after = await js(`({ saved: localStorage.getItem('md-editor-dir'), rows: document.querySelectorAll('#sb-body .tree-row').length, title: document.getElementById('sb-title').textContent })`);
check('打开文件夹后写入记忆', after.saved === tmp, after.saved);
check('文件树列出两个文件', after.rows === 2, String(after.rows));
check('侧栏标题为文件夹名', after.title === path.basename(tmp), after.title);
// 3. 重启后自动恢复上次文件夹
await win.webContents.reload();
await wait(1100);
const restored = await js(`({
visible: !document.getElementById('sidebar').hidden,
title: document.getElementById('sb-title').textContent,
rows: [...document.querySelectorAll('#sb-body .tree-row')].map(r => r.querySelector('.tree-name').textContent)
})`);
check('重启后自动恢复上次文件夹', restored.visible === true && restored.rows.length === 2, JSON.stringify(restored));
check('恢复后标题正确', restored.title === path.basename(tmp));
// 4. 收起后下次启动保持收起
await js(`document.getElementById('sb-close').click()`);
await wait(200);
await win.webContents.reload();
await wait(1100);
const kept = await js(`!document.getElementById('sidebar').hidden`);
check('用户收起后重启仍保持收起', kept === false, String(kept));
// 5. 工具栏按钮再次唤出
await js(`document.getElementById('btn-tree').click()`);
await wait(400);
const shown = await js(`({ hidden: document.getElementById('sidebar').hidden, rows: document.querySelectorAll('#sb-body .tree-row').length })`);
check('工具栏可重新唤出文件树', shown.hidden === false && shown.rows === 2, JSON.stringify(shown));
console.log('\n==== 侧栏测试:通过 ' + pass + ',失败 ' + fail + ' ====');
fs.rmSync(tmp, { recursive: true, force: true });
app.exit(fail ? 1 : 0);
});
+245
View File
@@ -0,0 +1,245 @@
/* 自测脚本:跑真实渲染进程逻辑,验证打开/编辑/保存/撤销/渲染/查找 */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const results = [];
function check(name, ok, extra) {
results.push({ name, ok: !!ok, extra });
console.log((ok ? 'PASS ' : 'FAIL ') + name + (extra ? ' → ' + extra : ''));
}
app.whenReady().then(async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mdtest-'));
const tmpFile = path.join(tmpDir, '测试文档.md');
const sample = '# 标题一\n\n**粗体** 正文\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n- [x] 完成\n';
fs.writeFileSync(tmpFile, sample, 'utf8');
fs.mkdirSync(path.join(tmpDir, 'sub'));
fs.writeFileSync(path.join(tmpDir, 'sub', 'c.md'), '# 子文件\n\n内容\n', 'utf8');
fs.writeFileSync(path.join(tmpDir, '其他.txt'), 'hello\n', 'utf8');
fs.writeFileSync(path.join(tmpDir, 'pic.png'), 'not markdown\n', 'utf8');
// 模拟主进程的保存 handler
ipcMain.handle('file:save', async (_e, p) => {
let target = p.__target || tmpFile;
await fs.promises.writeFile(target, p.content, 'utf8');
return { ok: true, path: target, name: path.basename(target) };
});
ipcMain.handle('file:openPath', async (_e, p) => {
const text = fs.readFileSync(p, 'utf8');
return { ok: true, path: p, name: path.basename(p), text, eol: '\n' };
});
ipcMain.handle('clip:read', () => 'PASTED');
ipcMain.handle('clip:write', () => true);
ipcMain.handle('file:reveal', () => ({ ok: true }));
ipcMain.handle('ui:message', () => 0);
ipcMain.handle('shell:openExternal', () => true);
// 目录读取(与 main.js 的 listDir 保持同样的过滤规则)
const MD_RE = /\.(md|markdown|mdown|mkd|mdwn|txt)$/i;
const listDir = (dir) => {
const entries = [];
for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
if (d.name.startsWith('.') || d.name === 'node_modules') continue;
const full = path.join(dir, d.name);
const isDir = d.isDirectory();
if (!isDir && !MD_RE.test(d.name)) continue;
entries.push({ name: d.name, path: full, isDir });
}
entries.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
return entries;
};
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: listDir(p) }));
ipcMain.on('app:setDirty', () => {});
ipcMain.on('win:setTitle', () => {});
ipcMain.on('save:finished', () => {});
const win = new BrowserWindow({
width: 1300, height: 860, show: false,
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
});
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
await win.webContents.executeJavaScript(`localStorage.clear()`);
await win.webContents.reload();
await new Promise((r) => setTimeout(r, 900));
const js = (code) => win.webContents.executeJavaScript(code);
/* 1. 初始状态 */
const init = await js(`({ val: editor.value.length, h1: !!preview.querySelector('h1'), table: !!preview.querySelector('table'), dirty: !document.getElementById('st-dirty').hidden })`);
check('初始渲染:有 h1 与表格', init.h1 && init.table, JSON.stringify(init));
check('初始不标记未保存', init.dirty === false);
/* 2. 打开文件(走真实 cmd 通道) */
win.webContents.send('cmd', 'file-opened', { ok: true, path: tmpFile, name: '测试文档.md', text: sample, eol: '\n' });
await new Promise((r) => setTimeout(r, 400));
const opened = await js(`({ v: editor.value === ${JSON.stringify(sample)}, name: document.getElementById('st-file').textContent, dirty: !document.getElementById('st-dirty').hidden })`);
check('打开文件后编辑区内容正确', opened.v);
check('状态栏文件名更新', opened.name === '测试文档.md', opened.name);
check('打开后为已保存状态', opened.dirty === false);
/* 3. 编辑 → dirty */
await js(`(() => {
editor.focus();
editor.setSelectionRange(editor.value.length, editor.value.length);
document.execCommand('insertText', false, '\\n\\n新增一行 **内容**');
})()`);
await new Promise((r) => setTimeout(r, 300));
const edited = await js(`({ dirty: !document.getElementById('st-dirty').hidden, hasNew: editor.value.includes('新增一行'), bold: !!preview.querySelector('strong') })`);
check('输入后标记未保存', edited.dirty === true);
check('插入文本成功', edited.hasNew === true);
check('预览同步出现粗体', edited.bold === true);
/* 4. 保存 */
await js(`document.getElementById('btn-save').click()`);
await new Promise((r) => setTimeout(r, 600));
const saved = fs.readFileSync(tmpFile, 'utf8');
const afterSave = await js(`!document.getElementById('st-dirty').hidden`);
check('保存后磁盘内容已更新', saved.includes('新增一行'), saved.length + ' bytes');
check('保存后清除未保存标记', afterSave === false);
/* 5. 撤销 / 重做 */
const undo = await js(`(() => {
const before = editor.value;
editor.focus();
const ok1 = document.execCommand('undo');
const afterUndo = editor.value;
const ok2 = document.execCommand('redo');
return { ok1, ok2, changed: afterUndo !== before, restored: editor.value === before };
})()`);
check('撤销生效(内容发生变化)', undo.changed === true, JSON.stringify(undo));
check('重做恢复内容', undo.restored === true);
/* 6. 粘贴(读剪贴板 → insertText) */
const paste = await js(`(async () => {
editor.focus();
editor.setSelectionRange(0, 0);
const t = await api.readClipboard();
document.execCommand('insertText', false, t);
return editor.value.startsWith('PASTED');
})()`);
check('粘贴插入到光标处', paste === true);
/* 7. 复制全文 */
const copyAll = await js(`(async () => {
await document.getElementById('btn-copyall').click();
await new Promise(r => setTimeout(r, 100));
return document.getElementById('toast').textContent;
})()`);
check('复制全文有提示反馈', /已复制全文/.test(copyAll), copyAll);
/* 8. 查找 */
const find = await js(`(async () => {
document.getElementById('btn-find').click();
const inp = document.getElementById('find-input');
inp.value = '标题';
inp.dispatchEvent(new Event('input'));
await new Promise(r => setTimeout(r, 100));
return { count: document.getElementById('find-count').textContent, sel: editor.selectionStart, selEnd: editor.selectionEnd };
})()`);
check('查找定位并显示计数', find.selEnd > find.sel, JSON.stringify(find));
/* 9. 模式切换 */
const modes = await js(`(() => {
const ws = document.getElementById('workspace');
document.querySelector('#mode-seg button[data-mode="read"]').click();
const a = ws.dataset.mode;
document.querySelector('#mode-seg button[data-mode="split"]').click();
return { a, b: ws.dataset.mode };
})()`);
check('模式切换正常', modes.a === 'read' && modes.b === 'split', JSON.stringify(modes));
/* 10. 文件夹树 */
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmpDir, name: path.basename(tmpDir), entries: listDir(tmpDir) });
await new Promise((r) => setTimeout(r, 400));
const tree = await js(`(() => {
const rows = [...document.querySelectorAll('#sb-body .tree-row')];
return {
visible: !document.getElementById('sidebar').hidden,
names: rows.map(r => r.querySelector('.tree-name').textContent),
dirs: rows.filter(r => r.classList.contains('is-dir')).length,
pngFiltered: !rows.some(r => r.querySelector('.tree-name').textContent.includes('pic.png'))
};
})()`);
check('拖入文件夹后侧栏显示', tree.visible === true);
check('文件树列出文件与子目录', tree.names.includes('测试文档.md') && tree.names.includes('sub') && tree.dirs === 1, JSON.stringify(tree.names));
check('非 Markdown 文件被过滤', tree.pngFiltered === true);
/* 11. 展开子目录 */
await js(`(() => {
const r = [...document.querySelectorAll('.tree-row.is-dir')].find(x => x.dataset.path.endsWith('sub'));
if (r) r.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
})()`);
await new Promise((r) => setTimeout(r, 500));
const sub = await js(`(() => {
const rows = [...document.querySelectorAll('#sb-body .tree-row')];
return { hasC: rows.some(r => r.dataset.path.endsWith('c.md')) };
})()`);
check('双击子目录可展开', sub.hasC === true, JSON.stringify(sub));
/* 12. 单击不切换,双击才打开文件 */
const beforeSingle = await js(`editor.value`);
const single = await js(`(() => {
const r = [...document.querySelectorAll('#sb-body .tree-row')].find(x => x.dataset.path.endsWith('c.md'));
if (!r) return false;
r.click();
return document.activeElement === r;
})()`);
await new Promise((r) => setTimeout(r, 350));
const afterSingle = await js(`editor.value`);
check('单击文件只选中不切换文档', single === true && afterSingle === beforeSingle, JSON.stringify(single));
await js(`(() => {
const r = [...document.querySelectorAll('#sb-body .tree-row')].find(x => x.dataset.path.endsWith('c.md'));
if (r) r.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
})()`);
await new Promise((r) => setTimeout(r, 700));
const byTree = await js(`(() => {
const act = document.querySelector('#sb-body .tree-row.active');
return { v: editor.value.indexOf('子文件') >= 0, name: document.getElementById('st-file').textContent, active: act ? act.dataset.path : '' };
})()`);
check('双击文件树打开文件', byTree.v === true, byTree.name);
check('树中高亮当前文件', String(byTree.active).endsWith('c.md'), byTree.active);
/* 13. 收起侧栏 */
const collapsed = await js(`(() => {
document.getElementById('sb-close').click();
const hidden1 = document.getElementById('sidebar').hidden;
document.getElementById('btn-tree').click();
return { hidden1, hidden2: document.getElementById('sidebar').hidden };
})()`);
check('侧栏可收起再展开', collapsed.hidden1 === true && collapsed.hidden2 === false, JSON.stringify(collapsed));
/* 10. 渲染引擎边界用例 */
const r = await js(`(() => {
const cases = {
code: MD.render('\\u0060\\u0060\\u0060py\\nprint(1)\\n\\u0060\\u0060\\u0060'),
nested: MD.render('- a\\n - b\\n - c'),
quote: MD.render('> 引用\\n> 第二行'),
hr: MD.render('---'),
xss: MD.render('<script>alert(1)</script>'),
tableAlign: MD.render('|a|b|\\n|:--|--:|\\n|1|2|'),
task: MD.render('- [x] done'),
escape: MD.render('a & b < c')
};
return {
code: cases.code.includes('print(1)') && cases.code.includes('<pre>'),
nested: (cases.nested.match(/<ul>/g) || []).length === 3 && cases.nested.includes('<li>c</li>'),
quote: cases.quote.includes('<blockquote>'),
hr: cases.hr.includes('<hr>'),
xss: !cases.xss.includes('<script>') && cases.xss.includes('&lt;script&gt;'),
tableAlign: cases.tableAlign.includes('text-align:left'),
task: cases.task.includes('type="checkbox"') && cases.task.includes('checked'),
escape: cases.escape.includes('a &amp; b &lt; c')
};
})()`);
Object.keys(r).forEach((k) => check('渲染用例 ' + k, r[k]));
const failed = results.filter((x) => !x.ok);
console.log('\n==== 共 ' + results.length + ' 项,失败 ' + failed.length + ' 项 ====');
if (failed.length) console.log(failed.map((f) => f.name).join(', '));
fs.rmSync(tmpDir, { recursive: true, force: true });
app.exit(failed.length ? 1 : 0);
});
+60
View File
@@ -0,0 +1,60 @@
/* 用远程调试端口驱动真实 app,验证主进程确实能开出多个独立窗口 */
const { spawn } = require('node:child_process');
const path = require('node:path');
const fs = require('node:fs');
const root = path.join(__dirname, '..');
const electron = path.join(root, 'node_modules', 'electron', 'dist', 'electron.exe');
const port = 9333;
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const target = path.join(root, 'README.md');
(async () => {
const env = { ...process.env };
delete env.ELECTRON_RUN_AS_NODE;
delete env.ELECTRON_NO_ATTACH_CONSOLE;
const child = spawn(electron, ['--remote-debugging-port=' + port, '.'], {
cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: false
});
let err = '';
child.stderr.on('data', (d) => { err += d.toString(); });
let ok = false;
try {
await wait(3500);
const before = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
const pagesBefore = before.filter((p) => p.type === 'page');
console.log('窗口数(启动后):', pagesBefore.length);
if (pagesBefore.length) {
const page = pagesBefore[0];
const ws = new WebSocket(page.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
ws.onopen = resolve;
ws.onerror = reject;
});
ws.send(JSON.stringify({
id: 1,
method: 'Runtime.evaluate',
params: { expression: `api.openNewWindow(${JSON.stringify(target)})`, awaitPromise: true }
}));
await wait(400);
ws.close();
}
await wait(2500);
const after = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
const pagesAfter = after.filter((p) => p.type === 'page');
console.log('窗口数(新窗口打开后):', pagesAfter.length);
console.log('新窗口标题:', pagesAfter.map((p) => p.title).join(' | '));
ok = pagesAfter.length > pagesBefore.length;
console.log(ok ? 'PASS 主进程成功创建独立窗口' : 'FAIL 没有创建新窗口');
} catch (e) {
console.log('ERR:', e.message);
if (err) console.log('APP STDERR:', err.slice(0, 500));
} finally {
try { child.kill(); } catch (_) {}
setTimeout(() => process.exit(ok ? 0 : 1), 300);
}
})();