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

+60
View File
@@ -0,0 +1,60 @@
/* Windows 原生文件剪贴板:通过 Win32 CF_HDROP 把文件对象放进系统剪贴板,
效果等同于在资源管理器里选中文件按 Ctrl+C(可以在别处 Ctrl+V 粘出文件副本)。
Electron 45 的 clipboard API 没有 writeBuffer,只能走 Win32。 */
let api = null;
function makeHdrop(paths) {
const header = Buffer.alloc(20);
header.writeUInt32LE(20, 0); // pFiles:文件列表相对结构头的偏移
// pt(8 字节) 与 fNC(4 字节) 留 0
header.writeUInt32LE(1, 16); // fWide = TRUE(UTF-16LE 路径)
const parts = paths.map((p) => Buffer.from(String(p) + '\0', 'utf16le'));
return Buffer.concat([header, ...parts, Buffer.from([0, 0])]); // 双 \0 结束
}
function getApi() {
if (api) return api;
const koffi = require('koffi');
const user32 = koffi.load('user32.dll');
const kernel32 = koffi.load('kernel32.dll');
const OpenClipboard = user32.func('bool OpenClipboard(void* hWnd)');
const EmptyClipboard = user32.func('bool EmptyClipboard()');
const SetClipboardData = user32.func('void* SetClipboardData(unsigned int uFormat, void* hMem)');
const CloseClipboard = user32.func('bool CloseClipboard()');
const IsClipboardFormatAvailable = user32.func('bool IsClipboardFormatAvailable(unsigned int format)');
const GlobalAlloc = kernel32.func('void* GlobalAlloc(unsigned int uFlags, size_t dwBytes)');
const GlobalLock = kernel32.func('void* GlobalLock(void* hMem)');
const GlobalUnlock = kernel32.func('bool GlobalUnlock(void* hMem)');
const RtlMoveMemory = kernel32.func('void RtlMoveMemory(void* dst, void* src, size_t len)');
function setFiles(paths) {
const data = makeHdrop(paths);
const h = GlobalAlloc(0x0002, data.length); // GMEM_MOVEABLE
if (!h) throw new Error('内存分配失败');
const p = GlobalLock(h);
RtlMoveMemory(p, koffi.as(data, 'void*'), data.length);
GlobalUnlock(h);
if (!OpenClipboard(null)) throw new Error('无法打开剪贴板');
try {
EmptyClipboard();
if (!SetClipboardData(15, h)) throw new Error('写入剪贴板失败'); // CF_HDROP
} finally {
CloseClipboard();
}
return true;
}
function hasFiles() {
return !!IsClipboardFormatAvailable(15);
}
api = { setFiles, hasFiles };
return api;
}
module.exports = {
setFiles: (paths) => getApi().setFiles(paths),
hasFiles: () => getApi().hasFiles()
};
+594
View File
@@ -0,0 +1,594 @@
/*
* 小银 Markdown 编辑器 —— 主进程
* 负责:多窗口管理、菜单与快捷键、文件读写、系统对话框、剪贴板、资源管理器联动
*
* 两种打开方式:
* tabs —— 一个窗口内用标签页打开多个文档
* windows —— 每个文档开一个独立窗口
* 偏好保存在 userData/prefs.json,切换后广播给所有窗口。
*/
const { app, BrowserWindow, ipcMain, dialog, Menu, shell, clipboard } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const windows = new Map(); // webContents.id -> state { win, path, dirty, pendingClose, closing }
const pendingAdopt = new Map(); // webContents.id -> 待装载的文档(窗口拆分时用)
let openMode = 'tabs';
const prefsFile = () => path.join(app.getPath('userData'), 'prefs.json');
function loadPrefs() {
try {
const p = JSON.parse(fs.readFileSync(prefsFile(), 'utf8'));
if (p.openMode === 'tabs' || p.openMode === 'windows') openMode = p.openMode;
} catch (_) { /* 首次运行,用默认 */ }
}
function savePrefs() {
try {
fs.mkdirSync(path.dirname(prefsFile()), { recursive: true });
fs.writeFileSync(prefsFile(), JSON.stringify({ openMode }), 'utf8');
} catch (_) { /* 忽略 */ }
}
function stateOf(sender) {
return sender && sender.id != null ? windows.get(sender.id) : null;
}
function focusedState() {
const win = BrowserWindow.getFocusedWindow();
if (win && windows.has(win.webContents.id)) return windows.get(win.webContents.id);
const first = windows.values().next();
return first.done ? null : first.value;
}
function sendTo(state, channel, ...args) {
if (state && state.win && !state.win.isDestroyed()) state.win.webContents.send(channel, ...args);
}
function primaryState() {
const first = windows.values().next();
return first.done ? null : first.value;
}
/* ------------------------------ 窗口 ------------------------------ */
/* 窗口图标(标题栏左上角 / 任务栏):打包版取安装目录 resources 下的 app-win.ico,开发环境取源码树 */
const appIconPath = app.isPackaged
? path.join(process.resourcesPath, 'app-win.ico')
: path.join(__dirname, 'resources', 'app.ico');
function createWindow(filePath) {
const win = new BrowserWindow({
width: 1380,
height: 880,
minWidth: 860,
minHeight: 520,
show: false,
backgroundColor: '#ffffff',
autoHideMenuBar: true,
icon: appIconPath, // 标题栏左上角 / 任务栏图标(保留)
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
spellcheck: false,
sandbox: false
}
});
const wcId = win.webContents.id;
const state = { win, path: filePath || null, dirty: false, pendingClose: false, closing: false };
windows.set(wcId, state);
win.loadFile(path.join(__dirname, 'renderer', 'index.html'));
win.once('ready-to-show', () => win.show());
win.webContents.on('did-finish-load', () => {
updateTitle(state);
sendTo(state, 'cmd', 'open-mode', openMode);
if (pendingAdopt.has(win.webContents.id)) {
// 标签拆成独立窗口:装载该窗口分到的那一份文档
sendTo(state, 'cmd', 'adopt-doc', pendingAdopt.get(win.webContents.id));
pendingAdopt.delete(win.webContents.id);
} else if (filePath) {
const r = readPathQuiet(filePath);
if (r.ok) sendTo(state, 'cmd', 'file-opened', r);
}
});
win.webContents.on('will-navigate', (e) => e.preventDefault());
win.webContents.setWindowOpenHandler(({ url }) => {
if (/^(https?|mailto):/i.test(url)) shell.openExternal(url);
return { action: 'deny' };
});
win.on('close', (e) => {
if (state.closing || !state.dirty) return;
e.preventDefault();
const choice = dialog.showMessageBoxSync(win, {
type: 'warning',
buttons: ['保存并退出', '不保存直接退出', '取消'],
defaultId: 0,
cancelId: 2,
noLink: true,
title: '未保存的修改',
message: '「' + (state.path ? path.basename(state.path) : '未命名') + '」还有未保存的修改',
detail: '是否先保存再退出?'
});
if (choice === 2) return;
if (choice === 1) { state.closing = true; win.close(); return; }
state.pendingClose = true;
sendTo(state, 'cmd', 'save');
});
// closed 触发时 webContents 已销毁,不能再读 win.webContents.id
win.on('closed', () => {
windows.delete(wcId);
pendingAdopt.delete(wcId);
});
return win;
}
function readPathQuiet(p) {
try {
const { text, eol } = readFileSmart(p);
return { ok: true, path: p, name: path.basename(p), text, eol };
} catch (err) {
return { ok: false, error: String(err.message || err) };
}
}
/* ------------------------------ 菜单 ------------------------------ */
function buildMenu() {
const template = [
{
label: '文件',
submenu: [
{ label: '新建', accelerator: 'CmdOrCtrl+N', click: () => sendTo(focusedState(), 'cmd', 'new') },
{ label: '打开…', accelerator: 'CmdOrCtrl+O', click: () => sendTo(focusedState(), 'cmd', 'open') },
{ label: '在新窗口打开', accelerator: 'CmdOrCtrl+Shift+N', click: () => sendTo(focusedState(), 'cmd', 'newWindow') },
{ type: 'separator' },
{ label: '保存', accelerator: 'CmdOrCtrl+S', click: () => sendTo(focusedState(), 'cmd', 'save') },
{ label: '另存为…', accelerator: 'CmdOrCtrl+Shift+S', click: () => sendTo(focusedState(), 'cmd', 'saveAs') },
{ type: 'separator' },
{ label: '打开文件夹…', accelerator: 'CmdOrCtrl+Shift+K', click: () => sendTo(focusedState(), 'cmd', 'openFolder') },
{ label: '在资源管理器中显示当前文件', accelerator: 'CmdOrCtrl+Shift+O', click: () => sendTo(focusedState(), 'cmd', 'openDir') },
{ label: '复制全文', accelerator: 'CmdOrCtrl+Shift+C', click: () => sendTo(focusedState(), 'cmd', 'copyAll') },
{ type: 'separator' },
{ label: '退出', accelerator: 'Alt+F4', role: 'quit' }
]
},
{
label: '编辑',
submenu: [
{ label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
{ label: '重做', accelerator: 'CmdOrCtrl+Y', role: 'redo' },
{ type: 'separator' },
{ label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
{ label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
{ label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
{ label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectAll' },
{ type: 'separator' },
{ label: '查找', accelerator: 'CmdOrCtrl+F', click: () => sendTo(focusedState(), 'cmd', 'find') }
]
},
{
label: '视图',
submenu: [
{ label: '编辑模式', accelerator: 'CmdOrCtrl+1', click: () => sendTo(focusedState(), 'cmd', 'mode', 'edit') },
{ label: '分栏模式', accelerator: 'CmdOrCtrl+2', click: () => sendTo(focusedState(), 'cmd', 'mode', 'split') },
{ label: '阅读模式', accelerator: 'CmdOrCtrl+3', click: () => sendTo(focusedState(), 'cmd', 'mode', 'read') },
{ type: 'separator' },
{
label: '文档打开方式',
submenu: [
{
label: '标签页(多窗口)', type: 'radio', checked: openMode === 'tabs',
click: () => setOpenMode('tabs')
},
{
label: '独立窗口', type: 'radio', checked: openMode === 'windows',
click: () => setOpenMode('windows')
}
]
},
{ type: 'separator' },
{ label: '显示 / 隐藏文件目录', accelerator: 'CmdOrCtrl+Shift+B', click: () => sendTo(focusedState(), 'cmd', 'tree') },
{ label: '显示 / 隐藏章节大纲', accelerator: 'CmdOrCtrl+Shift+T', click: () => sendTo(focusedState(), 'cmd', 'outline') },
{ label: '切换深色/浅色', accelerator: 'CmdOrCtrl+Shift+L', click: () => sendTo(focusedState(), 'cmd', 'theme') },
{ label: '放大', accelerator: 'CmdOrCtrl+Shift+=', click: () => sendTo(focusedState(), 'cmd', 'zoom', 1) },
{ label: '缩小', accelerator: 'CmdOrCtrl+Shift+-', click: () => sendTo(focusedState(), 'cmd', 'zoom', -1) },
{ label: '实际大小', accelerator: 'CmdOrCtrl+0', click: () => sendTo(focusedState(), 'cmd', 'zoom', 0) },
{ type: 'separator' },
{ label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
{ label: '全屏', accelerator: 'F11', role: 'togglefullscreen' }
]
}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
/* 让某个窗口把它的所有标签文档交出来(带未保存内容) */
function collectDocsFrom(state) {
return new Promise((resolve) => {
let done = false;
const timer = setTimeout(() => finish([]), 2500);
function finish(docs) {
if (done) return;
done = true;
clearTimeout(timer);
ipcMain.removeListener('docs:exported', handler);
resolve(docs);
}
function handler(e, payload) {
if (!state || e.sender.id !== state.win.webContents.id) return;
finish(Array.isArray(payload && payload.docs) ? payload.docs : []);
}
ipcMain.on('docs:exported', handler);
sendTo(state, 'cmd', 'export-docs');
});
}
function dedupeDocs(docs) {
const seen = new Set();
const out = [];
for (const d of docs) {
if (d.path && seen.has(d.path)) continue;
if (d.path) seen.add(d.path);
out.push(d);
}
return out;
}
function closeForMigration(state) {
if (!state || state.win.isDestroyed()) return;
state.closing = true; // 内容已收集,跳过未保存确认
state.win.close();
}
/* 切换模式时做双向迁移:
windows → tabs:把各窗口的文档并到一个窗口的多标签
tabs → windows:把标签拆成多个独立窗口 */
async function setOpenMode(mode) {
if (mode !== 'tabs' && mode !== 'windows') return;
if (mode === openMode) { buildMenu(); return; }
const states = [...windows.values()].filter((s) => s.win && !s.win.isDestroyed());
const allDocs = [];
for (const st of states) {
const docs = await collectDocsFrom(st);
allDocs.push(...docs);
}
let docs = dedupeDocs(allDocs);
if (!docs.length) docs.push({ path: null, name: null, text: '', eol: '\n', dirty: false, lastSaved: '' });
openMode = mode;
savePrefs();
buildMenu();
if (mode === 'tabs') {
const primary = states[0] || null;
for (const st of states.slice(1)) closeForMigration(st);
if (!primary) { createWindow(); return; }
sendTo(primary, 'cmd', 'open-mode', 'tabs');
sendTo(primary, 'cmd', 'adopt-tabs', docs);
} else {
for (const d of docs) {
const win = createWindow();
pendingAdopt.set(win.webContents.id, d);
}
for (const st of states) closeForMigration(st);
for (const st of windows.values()) sendTo(st, 'cmd', 'open-mode', 'windows');
}
}
/* ------------------------------ IPC ------------------------------ */
function readFileSmart(p) {
const buf = fs.readFileSync(p);
let text = buf.toString('utf8');
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // BOM
const eol = /\r\n/.test(text) ? '\r\n' : '\n';
text = text.replace(/\r\n?/g, '\n');
return { text, eol };
}
function openPathInternal(p, state) {
try {
const { text, eol } = readFileSmart(p);
if (state) { state.path = p; state.dirty = false; updateTitle(state); }
return { ok: true, path: p, name: path.basename(p), text, eol };
} catch (err) {
const st = state || focusedState();
dialog.showMessageBoxSync(st ? st.win : null, {
type: 'error', title: '打开失败', message: '无法读取该文件', detail: String(err.message || err), buttons: ['好']
});
return { ok: false, error: String(err.message || err) };
}
}
ipcMain.handle('file:open', async (e) => {
const state = stateOf(e.sender) || focusedState();
const r = await dialog.showOpenDialog(state ? state.win : null, {
title: '打开 Markdown 文件',
properties: ['openFile'],
filters: [
{ name: 'Markdown', extensions: ['md', 'markdown', 'mdown', 'mkd', 'mdwn', 'txt'] },
{ name: '所有文件', extensions: ['*'] }
]
});
if (r.canceled || !r.filePaths.length) return { ok: false, canceled: true };
return openPathInternal(r.filePaths[0], state);
});
ipcMain.handle('file:openPath', async (e, p) => openPathInternal(p, stateOf(e.sender) || focusedState()));
/* 新窗口打开(右键菜单 / 菜单命令都走这里) */
ipcMain.handle('window:openPath', async (_e, p) => {
if (!p) return { ok: false };
try {
if (!fs.statSync(p).isFile()) return { ok: false };
} catch (_) { return { ok: false }; }
createWindow(p);
return { ok: true };
});
ipcMain.handle('window:new', async () => {
createWindow();
return { ok: true };
});
ipcMain.handle('app:getOpenMode', async () => openMode);
ipcMain.handle('app:setOpenMode', async (_e, mode) => {
await setOpenMode(mode);
return { ok: true, mode: openMode };
});
/* ---------------------- 文件夹浏览 ---------------------- */
const MD_EXT = /\.(md|markdown|mdown|mkd|mdwn|txt)$/i;
const SKIP_DIRS = new Set(['node_modules', '$RECYCLE.BIN', 'System Volume Information']);
function listDir(dir) {
const entries = [];
let items;
try { items = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return entries; }
for (const d of items) {
if (d.name.startsWith('.')) continue;
if (SKIP_DIRS.has(d.name)) continue;
const full = path.join(dir, d.name);
let isDir = d.isDirectory();
if (!isDir && !d.isFile()) {
try { isDir = fs.statSync(full).isDirectory(); } catch (_) { continue; }
}
if (!isDir && !MD_EXT.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;
}
function dirInfo(p) {
return { ok: true, path: p, name: path.basename(p) || p, entries: listDir(p) };
}
ipcMain.handle('dir:open', async (e) => {
const state = stateOf(e.sender) || focusedState();
const r = await dialog.showOpenDialog(state ? state.win : null, {
title: '打开文件夹', properties: ['openDirectory']
});
if (r.canceled || !r.filePaths.length) return { ok: false, canceled: true };
return dirInfo(r.filePaths[0]);
});
ipcMain.handle('dir:read', async (_e, p) => {
try { if (!fs.statSync(p).isDirectory()) return { ok: false }; } catch (_) { return { ok: false }; }
return dirInfo(p);
});
ipcMain.handle('file:save', async (e, payload) => {
const state = stateOf(e.sender) || focusedState();
const { content, saveAs, eol } = payload;
let target = state && state.path;
if (!target || saveAs) {
const r = await dialog.showSaveDialog(state ? state.win : null, {
title: saveAs ? '另存为' : '保存',
defaultPath: target || path.join(app.getPath('documents'), '未命名.md'),
filters: [
{ name: 'Markdown', extensions: ['md'] },
{ name: '纯文本', extensions: ['txt'] },
{ name: '所有文件', extensions: ['*'] }
]
});
if (r.canceled || !r.filePath) return { ok: false, canceled: true };
target = r.filePath;
}
try {
let text = content;
if (eol === '\r\n') text = text.replace(/\r?\n/g, '\r\n');
await fs.promises.writeFile(target, text, 'utf8');
if (state) { state.path = target; state.dirty = false; updateTitle(state); }
return { ok: true, path: target, name: path.basename(target) };
} catch (err) {
dialog.showMessageBoxSync(state ? state.win : null, {
type: 'error', title: '保存失败', message: '写入文件时出错', detail: String(err.message || err), buttons: ['好']
});
return { ok: false, error: String(err.message || err) };
}
});
ipcMain.handle('file:reveal', async (e) => {
const state = stateOf(e.sender) || focusedState();
const target = state && state.path;
if (!target) {
dialog.showMessageBoxSync(state ? state.win : null, {
type: 'info', title: '提示', message: '当前文件还没有保存到磁盘',
detail: '请先保存文件,之后即可打开它所在的文件夹。', buttons: ['好']
});
return { ok: false };
}
if (!fs.existsSync(target)) {
dialog.showMessageBoxSync(state ? state.win : null, {
type: 'warning', title: '提示', message: '文件已不存在', detail: target, buttons: ['好']
});
return { ok: false };
}
shell.showItemInFolder(target);
return { ok: true };
});
ipcMain.handle('clip:read', () => clipboard.readText());
ipcMain.handle('clip:write', (_e, text) => { clipboard.writeText(String(text ?? '')); return true; });
const nativeClip = require('./clipboard-native');
ipcMain.handle('file:copyFile', async (_e, paths) => {
try {
const list = (Array.isArray(paths) ? paths : [paths]).filter((p) => p && fs.existsSync(p));
if (!list.length) return { ok: false, error: '文件不存在' };
nativeClip.setFiles(list);
return { ok: true, count: list.length };
} catch (err) {
return { ok: false, error: String(err.message || err) };
}
});
ipcMain.handle('file:readText', async (_e, p) => {
try { return { ok: true, text: readFileSmart(p).text }; } catch (_) { return { ok: false }; }
});
ipcMain.handle('file:revealPath', async (_e, p) => {
try {
if (!p || !fs.existsSync(p)) return { ok: false, error: '文件不存在' };
const err = await shell.openPath(path.dirname(p));
if (!err) return { ok: true };
shell.showItemInFolder(p);
return { ok: true, fallback: true };
} catch (err) {
try { shell.showItemInFolder(p); return { ok: true, fallback: true }; }
catch (_) { return { ok: false, error: String(err.message || err) }; }
}
});
ipcMain.handle('shell:openExternal', (_e, url) => {
const u = String(url || '');
if (/^(https?|mailto):/i.test(u)) shell.openExternal(u);
return true;
});
/* 拖放:作用于收到事件的那个窗口 */
ipcMain.on('file:drop', (e, p) => {
if (!p) return;
const state = stateOf(e.sender) || focusedState();
let isDir = false;
try { isDir = fs.statSync(p).isDirectory(); } catch (_) { return; }
if (isDir) {
sendTo(state, 'cmd', 'dir-opened', dirInfo(p));
return;
}
const r = openPathInternal(p, state);
if (r.ok) sendTo(state, 'cmd', 'file-opened', r);
});
ipcMain.on('file:droppedText', (e, payload) => {
sendTo(stateOf(e.sender) || focusedState(), 'cmd', 'dropped-text', {
name: payload && payload.name, text: (payload && payload.text) || ''
});
});
ipcMain.handle('ui:message', async (e, opts) => {
const state = stateOf(e.sender) || focusedState();
const r = await dialog.showMessageBox(state ? state.win : null, {
type: opts.type || 'info',
title: opts.title || '提示',
message: opts.message || '',
detail: opts.detail || '',
buttons: opts.buttons || ['好'],
noLink: true,
defaultId: 0,
cancelId: (opts.buttons || ['好']).length - 1
});
return r.response;
});
ipcMain.on('app:setDirty', (e, d) => {
const state = stateOf(e.sender) || focusedState();
if (state) { state.dirty = !!d; updateTitle(state); }
});
/* 切标签 / 迁移后,渲染进程把当前激活的文档路径同步给主进程,
这样窗口标题和「保存=覆盖原文件」才不会错位 */
ipcMain.on('doc:syncPath', (e, p) => {
const state = stateOf(e.sender);
if (!state) return;
state.path = p || null;
updateTitle(state);
});
ipcMain.on('win:setTitle', (e) => updateTitle(stateOf(e.sender) || focusedState()));
ipcMain.on('save:finished', (e, ok) => {
const state = stateOf(e.sender) || focusedState();
if (!state) return;
if (state.pendingClose && ok) {
state.pendingClose = false;
state.closing = true;
state.win.close();
} else if (!ok) {
state.pendingClose = false;
}
});
function updateTitle(state) {
if (!state || !state.win || state.win.isDestroyed()) return;
const name = state.path ? path.basename(state.path) : '未命名';
state.win.setTitle(`${state.dirty ? '● ' : ''}${name} — 小银 Markdown`);
state.win.setDocumentEdited(state.dirty);
}
/* ------------------------------ 生命周期 ------------------------------ */
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
app.on('second-instance', (_e, argv) => {
const arg = argv.find((a) => /\.(md|markdown|txt|mdown|mkd)$/i.test(a));
if (arg) {
if (openMode === 'windows') {
createWindow(arg);
} else {
const state = primaryState();
if (state) {
if (state.win.isMinimized()) state.win.restore();
state.win.focus();
sendTo(state, 'cmd', 'open-external', arg);
} else {
createWindow(arg);
}
}
return;
}
const state = primaryState();
if (state) {
if (state.win.isMinimized()) state.win.restore();
state.win.focus();
}
});
app.whenReady().then(() => {
loadPrefs();
buildMenu();
const arg = process.argv.find((a) => /\.(md|markdown|txt|mdown|mkd)$/i.test(a));
createWindow(arg || null);
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
});
app.on('window-all-closed', () => app.quit());
}
/* 供迁移测试直接驱动 */
module.exports = {
windows,
setOpenMode,
getOpenMode: () => openMode
};
+59
View File
@@ -0,0 +1,59 @@
const { contextBridge, ipcRenderer, webUtils } = require('electron');
contextBridge.exposeInMainWorld('api', {
open: () => ipcRenderer.invoke('file:open'),
openPath: (p) => ipcRenderer.invoke('file:openPath', p),
save: (payload) => ipcRenderer.invoke('file:save', payload),
reveal: () => ipcRenderer.invoke('file:reveal'),
revealPath: (p) => ipcRenderer.invoke('file:revealPath', p),
copyFile: (p) => ipcRenderer.invoke('file:copyFile', p),
readFileText: (p) => ipcRenderer.invoke('file:readText', p),
readClipboard: () => ipcRenderer.invoke('clip:read'),
writeClipboard: (t) => ipcRenderer.invoke('clip:write', t),
openExternal: (url) => ipcRenderer.invoke('shell:openExternal', url),
dirOpen: () => ipcRenderer.invoke('dir:open'),
dirRead: (p) => ipcRenderer.invoke('dir:read', p),
openNewWindow: (p) => ipcRenderer.invoke('window:openPath', p),
newWindow: () => ipcRenderer.invoke('window:new'),
getOpenMode: () => ipcRenderer.invoke('app:getOpenMode'),
setOpenMode: (mode) => ipcRenderer.invoke('app:setOpenMode', mode),
exportDocs: (payload) => ipcRenderer.send('docs:exported', payload),
syncDoc: (p) => ipcRenderer.send('doc:syncPath', p),
setDirty: (d) => ipcRenderer.send('app:setDirty', d),
message: (o) => ipcRenderer.invoke('ui:message', o),
saveFinished: (ok) => ipcRenderer.send('save:finished', ok),
onCommand: (cb) => ipcRenderer.on('cmd', (_e, name, payload) => cb(name, payload))
});
/* 拖放:在 preload 上下文里取真实路径(Electron 32+ 已移除 File.path) */
window.addEventListener('dragover', (e) => { e.preventDefault(); });
window.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
if (!dt) return;
e.preventDefault();
const files = dt.files ? Array.from(dt.files) : [];
if (!files.length) return;
// 逐个尝试取真实路径;取到第一个就送去开(文件或文件夹都行)
for (const file of files) {
let realPath = null;
try {
realPath = webUtils.getPathForFile(file);
} catch (_) { /* 拿不到就换兜底 */ }
if (realPath) {
ipcRenderer.send('file:drop', realPath);
return;
}
}
// 兜底:完全拿不到路径时,按普通文件读取内容(目录会失败,忽略)
const first = files[0];
if (typeof first.text === 'function') {
first.text()
.then((text) => ipcRenderer.send('file:droppedText', { name: first.name, text }))
.catch(() => { /* 目录或不可读文件,忽略 */ });
}
});
+1494
View File
File diff suppressed because it is too large. Load diff
+176
View File
@@ -0,0 +1,176 @@
<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: file: https: http:; font-src 'self' data:;">
<title>小银 Markdown</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="app">
<!-- 工具栏 -->
<header class="toolbar">
<div class="brand">
<span class="brand-name">小银 Markdown</span>
</div>
<div class="tb-sep"></div>
<div class="tb-group">
<button class="tb-btn" id="btn-new" title="新建 (Ctrl+N)">
<svg viewBox="0 0 16 16"><path d="M9 1H4a1 1 0 00-1 1v12a1 1 0 001 1h8a1 1 0 001-1V5L9 1zm0 1.5L11.5 5H9V2.5z"/></svg>
<span>新建</span>
</button>
<button class="tb-btn" id="btn-open" title="打开文件 (Ctrl+O)">
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3l1.5 2H14a1 1 0 011 1v7a1 1 0 01-1 1H2a1 1 0 01-1-1V3.5z"/></svg>
<span>打开</span>
</button>
<button class="tb-btn primary" id="btn-save" title="保存 (Ctrl+S)">
<svg viewBox="0 0 16 16"><path d="M2 2h9l3 3v9a1 1 0 01-1 1H3a1 1 0 01-1-1V2zm2 0v4h7V2H4zm1 7h6v5H5V9z"/></svg>
<span>保存</span>
</button>
<button class="tb-btn" id="btn-saveas" title="另存为 (Ctrl+Shift+S)">
<svg viewBox="0 0 16 16"><path d="M8 1v7m0 0L5.5 5.5M8 8l2.5-2.5M2 10v3a1 1 0 001 1h10a1 1 0 001-1v-3"/></svg>
<span>另存为</span>
</button>
</div>
<div class="tb-sep"></div>
<div class="tb-group">
<button class="tb-icon" id="btn-undo" title="撤销 (Ctrl+Z)">
<svg viewBox="0 0 16 16"><path d="M6 3.5L2 7l4 3.5V8h4a3 3 0 010 6H5v1.5h5a4.5 4.5 0 000-9H6V3.5z"/></svg>
</button>
<button class="tb-icon" id="btn-redo" title="重做 (Ctrl+Y)">
<svg viewBox="0 0 16 16"><path d="M10 3.5L14 7l-4 3.5V8H6a3 3 0 000 6h4v1.5H6a4.5 4.5 0 010-9h4V3.5z"/></svg>
</button>
<button class="tb-icon" id="btn-find" title="查找 (Ctrl+F)">
<svg viewBox="0 0 16 16"><path d="M6.5 1a5.5 5.5 0 014.2 9.05l4.1 4.1-1.05 1.05-4.1-4.1A5.5 5.5 0 116.5 1zm0 1.5a4 4 0 100 8 4 4 0 000-8z"/></svg>
</button>
<button class="tb-icon" id="btn-copyall" title="复制全文 (Ctrl+Shift+C)">
<svg viewBox="0 0 16 16"><path d="M5 1h7a1 1 0 011 1v9h-1.5V2.5H5V1zM3 3.5h7a1 1 0 011 1V14a1 1 0 01-1 1H3a1 1 0 01-1-1V4.5a1 1 0 011-1z"/></svg>
</button>
<button class="tb-icon" id="btn-dir" title="打开文件所在文件夹 (Ctrl+Shift+O)">
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3l1.5 2H14a1 1 0 011 1v7a1 1 0 01-1 1H2a1 1 0 01-1-1V3.5z"/></svg>
</button>
</div>
<div class="spacer"></div>
<button class="tb-btn toggle" id="btn-tree" title="显示 / 隐藏文件目录 (Ctrl+Shift+B)">
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3.2l1.4 1.8H14a1 1 0 011 1v1.2H1.5V3.5zM1.5 7.2H15v5.3a1 1 0 01-1 1H2.5a1 1 0 01-1-1V7.2z"/></svg>
<span>目录</span>
</button>
<div class="seg" id="mode-seg">
<button data-mode="edit" title="编辑模式 (Ctrl+1)">编辑</button>
<button data-mode="split" class="active" title="分栏模式 (Ctrl+2)">分栏</button>
<button data-mode="read" title="阅读模式 (Ctrl+3)">阅读</button>
</div>
<button class="tb-btn toggle" id="btn-outline" title="显示 / 隐藏章节大纲 (Ctrl+Shift+T)">
<svg viewBox="0 0 16 16"><path d="M2 3.2h1.8v1.3H2V3.2zm3.4 0H14v1.3H5.4V3.2zM2 7.35h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4V7.35zM2 11.5h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4v-1.3z"/></svg>
<span>大纲</span>
</button>
<button class="tb-btn" id="btn-openmode" title="文档打开方式:标签页 / 独立窗口(点击切换)">
<svg viewBox="0 0 16 16"><path d="M1.5 2.5h13v11h-13z" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M5 2.5v11M2.5 5h1.8M2.5 8h1.8M2.5 11h1.8" stroke="currentColor" stroke-width="1.2"/></svg>
<span id="openmode-label">标签</span>
</button>
<button class="tb-icon" id="btn-theme" title="切换深色/浅色 (Ctrl+Shift+L)">
<svg viewBox="0 0 16 16"><path d="M8 1a7 7 0 100 14A7 7 0 008 1zm0 1.5v11a5.5 5.5 0 010-11z"/></svg>
</button>
</header>
<!-- 标签栏(标签页模式下显示) -->
<div class="tabbar" id="tabbar"></div>
<!-- 查找条 -->
<div class="findbar" id="findbar" hidden>
<input type="text" id="find-input" placeholder="查找内容…" spellcheck="false">
<span class="find-count" id="find-count"></span>
<button id="find-prev" title="上一个 (Shift+Enter)">↑</button>
<button id="find-next" title="下一个 (Enter)">↓</button>
<button id="find-close" title="关闭 (Esc)">✕</button>
</div>
<!-- 工作区 -->
<main class="workspace" id="workspace" data-mode="split">
<aside class="sidebar" id="sidebar" hidden>
<div class="panel-head">
<svg class="panel-ico" viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3.2l1.4 1.8H14a1 1 0 011 1v1.2H1.5V3.5zM1.5 7.2H15v5.3a1 1 0 01-1 1H2.5a1 1 0 01-1-1V7.2z"/></svg>
<span class="panel-title" id="sb-title">目录</span>
<span class="panel-actions">
<button class="sb-btn" id="sb-pick" title="选择文件夹 (Ctrl+Shift+K)">
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3l1.5 2H14a1 1 0 011 1v7a1 1 0 01-1 1H2a1 1 0 01-1-1V3.5z"/></svg>
</button>
<button class="sb-btn" id="sb-close" title="隐藏文件目录 (Ctrl+Shift+B)">
<svg viewBox="0 0 16 16"><path d="M3.4 2.6L8 7.2l4.6-4.6 1.1 1.1L9.1 8.3l4.6 4.6-1.1 1.1L8 9.4l-4.6 4.6-1.1-1.1 4.6-4.6-4.6-4.6z"/></svg>
</button>
</span>
</div>
<div class="sb-body" id="sb-body"></div>
</aside>
<div class="vsplitter" id="sb-splitter" title="拖动调整目录宽度"></div>
<section class="pane editor-pane" id="editor-pane">
<div class="editor-wrap">
<div class="editor-hl" id="editor-hl" aria-hidden="true"></div>
<textarea id="editor" spellcheck="false" autocomplete="off"
placeholder="在这里写 Markdown…&#10;&#10;也可以把 .md 文件直接拖进窗口。"></textarea>
</div>
</section>
<div class="splitter" id="splitter" title="拖动调整宽度"></div>
<section class="pane preview-pane" id="preview-pane">
<article class="markdown-body" id="preview"></article>
</section>
<div class="vsplitter" id="ol-splitter" title="拖动调整大纲宽度"></div>
<aside class="outline" id="outline">
<div class="panel-head">
<svg class="panel-ico" viewBox="0 0 16 16"><path d="M2 3.2h1.8v1.3H2V3.2zm3.4 0H14v1.3H5.4V3.2zM2 7.35h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4V7.35zM2 11.5h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4v-1.3z"/></svg>
<span class="panel-title">章节大纲</span>
<span class="ol-count" id="ol-count">0</span>
<button class="sb-btn" id="ol-close" title="隐藏章节大纲 (Ctrl+Shift+T)">
<svg viewBox="0 0 16 16"><path d="M3.4 2.6L8 7.2l4.6-4.6 1.1 1.1L9.1 8.3l4.6 4.6-1.1 1.1L8 9.4l-4.6 4.6-1.1-1.1 4.6-4.6-4.6-4.6z"/></svg>
</button>
</div>
<div class="ol-body" id="ol-body"></div>
</aside>
</main>
<!-- 状态栏 -->
<footer class="statusbar">
<div class="st-left">
<span class="st-file" id="st-file">未命名</span>
<span class="st-dirty" id="st-dirty" hidden>未保存</span>
</div>
<div class="st-right">
<span id="st-words">0 字</span>
<span class="st-div">|</span>
<span id="st-chars">0 字符</span>
<span class="st-div">|</span>
<span id="st-cursor">第 1 行, 第 1 列</span>
<span class="st-div">|</span>
<span>UTF-8</span>
</div>
</footer>
<!-- 右键菜单 -->
<div class="ctx-menu" id="ctxmenu" hidden></div>
<div class="toast" id="toast" hidden></div>
<div class="drop-hint" id="drop-hint" hidden><div>松开鼠标:文件直接打开,文件夹列出目录</div></div>
</div>
<script src="markdown.js"></script>
<script src="tauri-bridge.js"></script>
<script src="app.js"></script>
</body>
</html>
+291
View File
@@ -0,0 +1,291 @@
/*
* 轻量 Markdown 渲染引擎(零依赖,纯本地)
* 支持:标题 / 粗体 / 斜体 / 删除线 / 行内代码 / 代码块 / 引用 / 有序无序列表 /
* 嵌套列表 / 任务列表 / 表格(含对齐)/ 分割线 / 链接 / 图片 / 自动链接
* 所有原始 HTML 均被转义,避免脚本注入。
*/
(function (global) {
'use strict';
const ESC_MAP = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
function safeUrl(u) {
const t = String(u).trim();
const flat = t.replace(/[\s\u0000-\u001f]/g, '');
if (/^(javascript|vbscript|data):/i.test(flat)) return '#';
return escapeHtml(t);
}
const PH = '\u0000';
/* ------------------------- 行内渲染 ------------------------- */
function renderInline(text) {
let s = escapeHtml(text);
const slots = [];
const put = (html) => { slots.push(html); return PH + (slots.length - 1) + PH; };
// 行内代码(先摘出来,避免内部语法被解析)
s = s.replace(/(`+)([\s\S]*?)\1/g, (_m, _t, code) => put('<code>' + code.replace(/^ | $/g, '') + '</code>'));
// 图片
s = s.replace(/!\[([^\]]*)\]\(\s*([^\s)]+)\s*\)/g,
(_m, alt, src) => put('<img src="' + safeUrl(src) + '" alt="' + alt + '" loading="lazy">'));
// 链接
s = s.replace(/\[([^\]]+)\]\(\s*([^\s)]+)\s*\)/g,
(_m, label, href) => put('<a href="' + safeUrl(href) + '" title="' + href + '">' + label + '</a>'));
// 裸链接
s = s.replace(/(^|[\s(])(https?:\/\/[^\s<)\]]+)/g,
(_m, pre, url) => pre + put('<a href="' + safeUrl(url) + '">' + url + '</a>'));
// 强调
s = s.replace(/\*\*\*([^*\n]+)\*\*\*/g, '<strong><em>$1</em></strong>');
s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
s = s.replace(/(^|[^\w_])__([^_\n]+)__/g, '$1<strong>$2</strong>');
s = s.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
s = s.replace(/(^|[^\w_])_([^_\n]+)_/g, '$1<em>$2</em>');
s = s.replace(/~~([^~\n]+)~~/g, '<del>$1</del>');
// 还原占位符
s = s.replace(/\u0000(\d+)\u0000/g, (_m, i) => slots[Number(i)]);
return s;
}
function inlineWithBreaks(text) {
return renderInline(text).replace(/\n/g, '<br>');
}
/* ------------------------- 块级解析 ------------------------- */
const RE_FENCE = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)\s*$/;
const RE_HEADING = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
const RE_HR = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;
const RE_QUOTE = /^\s{0,3}>\s?/;
const RE_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])(\s+)(.*)$/;
const RE_TASK = /^\[([ xX])\]\s+/;
function isTableSep(line) {
if (!line || !line.includes('|')) return false;
const cells = splitRow(line);
return cells.length > 0 && cells.every((c) => /^:?-{1,}:?$/.test(c.trim()));
}
function splitRow(line) {
let s = line.trim();
if (s.startsWith('|')) s = s.slice(1);
if (s.endsWith('|')) s = s.slice(0, -1);
return s.split('|').map((c) => c.trim());
}
function parseBlocks(lines, base) {
base = base || 0;
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
// 空行
if (/^\s*$/.test(line)) { i++; continue; }
// 代码块
let m = RE_FENCE.exec(line);
if (m) {
const fenceChar = m[2][0];
const fenceLen = m[2].length;
const lang = m[3] || '';
const closer = new RegExp('^\\s*' + (fenceChar === '`' ? '`' : '~') + '{' + fenceLen + ',}\\s*$');
const buf = [];
i++;
while (i < lines.length && !closer.test(lines[i])) { buf.push(lines[i]); i++; }
i++; // 跳过闭合行
out.push(
'<div class="code-wrap">' +
(lang ? '<span class="code-lang">' + escapeHtml(lang) + '</span>' : '') +
'<pre><code>' + escapeHtml(buf.join('\n')) + '</code></pre></div>'
);
continue;
}
// 分割线
if (RE_HR.test(line)) { out.push('<hr>'); i++; continue; }
// 标题(带原始行号,供大纲跳转用)
m = RE_HEADING.exec(line);
if (m) {
const lv = m[1].length;
out.push('<h' + lv + ' data-line="' + (base + i) + '">' + renderInline(m[2]) + '</h' + lv + '>');
i++;
continue;
}
// 引用
if (RE_QUOTE.test(line)) {
const buf = [];
const startAt = i;
while (i < lines.length && RE_QUOTE.test(lines[i])) {
buf.push(lines[i].replace(RE_QUOTE, ''));
i++;
}
out.push('<blockquote>' + parseBlocks(buf, base + startAt) + '</blockquote>');
continue;
}
// 表格
if (line.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1])) {
const head = splitRow(line);
const aligns = splitRow(lines[i + 1]).map((c) => {
const t = c.trim();
if (/^:-+:$/.test(t)) return 'center';
if (/^:-+$/.test(t)) return 'left';
if (/^-+:$/.test(t)) return 'right';
return '';
});
i += 2;
const rows = [];
while (i < lines.length && lines[i].includes('|') && !/^\s*$/.test(lines[i])) {
rows.push(splitRow(lines[i]));
i++;
}
const cell = (tag, txt, idx) => {
const al = aligns[idx] ? ' style="text-align:' + aligns[idx] + '"' : '';
return '<' + tag + al + '>' + renderInline(txt) + '</' + tag + '>';
};
let html = '<div class="table-wrap"><table><thead><tr>';
head.forEach((c, idx) => { html += cell('th', c, idx); });
html += '</tr></thead><tbody>';
rows.forEach((r) => {
html += '<tr>';
for (let k = 0; k < head.length; k++) html += cell('td', r[k] == null ? '' : r[k], k);
html += '</tr>';
});
html += '</tbody></table></div>';
out.push(html);
continue;
}
// 列表
if (RE_ITEM.test(line)) {
const r = parseList(lines, i, base);
out.push(r.html);
i = r.next;
continue;
}
// 段落
const buf = [];
while (i < lines.length && !/^\s*$/.test(lines[i])) {
const l = lines[i];
if (RE_FENCE.test(l) || RE_HEADING.test(l) || RE_HR.test(l) || RE_QUOTE.test(l) || RE_ITEM.test(l)) break;
if (l.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1])) break;
buf.push(l);
i++;
}
if (buf.length) out.push('<p>' + inlineWithBreaks(buf.join('\n')) + '</p>');
else i++; // 防死循环
}
return out.join('\n');
}
function parseList(lines, start, base) {
base = base || 0;
const m0 = RE_ITEM.exec(lines[start]);
const baseIndent = m0[1].length;
const ordered = /\d/.test(m0[2]);
const startNum = ordered ? parseInt(m0[2], 10) : 1;
const items = [];
let i = start;
while (i < lines.length) {
const m = RE_ITEM.exec(lines[i]);
if (!m || m[1].length !== baseIndent || (/\d/.test(m[2])) !== ordered) break;
const contentIndent = m[1].length + m[2].length + m[3].length;
const content = m[4];
i++;
// 收集该列表项的后续行(子内容)
const children = [];
let childStart = -1;
while (i < lines.length) {
const l = lines[i];
if (/^\s*$/.test(l)) {
let j = i;
while (j < lines.length && /^\s*$/.test(lines[j])) j++;
if (j < lines.length) {
const ind = lines[j].match(/^[ \t]*/)[0].length;
if (ind >= contentIndent || (RE_ITEM.test(lines[j]) && ind > baseIndent)) {
if (childStart < 0) childStart = i;
for (let k = i; k < j; k++) children.push('');
i = j;
continue;
}
}
break;
}
const ind = l.match(/^[ \t]*/)[0].length;
if (ind >= contentIndent) {
if (childStart < 0) childStart = i;
children.push(l.slice(Math.min(ind, contentIndent)));
i++;
continue;
}
if (ind > baseIndent) {
if (childStart < 0) childStart = i;
children.push(l.trim());
i++;
continue;
}
break;
}
items.push({ content, children, childStart });
}
let html = ordered
? '<ol' + (startNum !== 1 ? ' start="' + startNum + '"' : '') + '>'
: '<ul>';
for (const it of items) {
let inner;
let cls = '';
const task = RE_TASK.exec(it.content);
if (task) {
const checked = task[1].toLowerCase() === 'x';
inner = '<input type="checkbox" disabled' + (checked ? ' checked' : '') + '> ' +
renderInline(it.content.replace(RE_TASK, ''));
cls = ' class="task-item"';
} else {
inner = renderInline(it.content);
}
html += '<li' + cls + '>' + inner;
if (it.children.length) {
html += parseBlocks(it.children, base + (it.childStart >= 0 ? it.childStart : 0));
}
html += '</li>';
}
html += ordered ? '</ol>' : '</ul>';
return { html, next: i };
}
function render(md) {
const lines = String(md == null ? '' : md).replace(/\r\n?/g, '\n').split('\n');
return parseBlocks(lines);
}
/* ------------------------- 统计信息 ------------------------- */
function stats(md) {
const text = String(md || '');
const cjk = (text.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g) || []).length;
const words = (text.replace(/[\u4e00-\u9fa5\u3040-\u30ff]/g, ' ').match(/[A-Za-z0-9_'’-]+/g) || []).length;
const lines = text.split('\n').length;
const headings = (text.match(/^\s{0,3}#{1,6}\s+\S/gm) || []).length;
return { chars: text.length, words: cjk + words, lines, headings };
}
global.MD = { render, stats, escapeHtml };
})(window);
+795
View File
@@ -0,0 +1,795 @@
/* ============ 主题变量 ============ */
:root {
--bg: #ffffff;
--bg-soft: #f7f8fa;
--bg-toolbar: #fbfbfc;
--bg-hover: #eef1f5;
--bg-active: #e3e9f2;
--border: #e4e7ec;
--border-strong: #d3d8e0;
--text: #1f2329;
--text-dim: #6b7280;
--text-faint: #9aa1ac;
--accent: #2f6feb;
--accent-soft: #e8f0ff;
--accent-text: #ffffff;
--danger: #d14343;
--code-bg: #f2f4f7;
--code-block-bg: #f6f8fa;
--quote-bar: #d0d7e2;
--shadow: 0 8px 28px rgba(15, 23, 42, .14);
--shadow-sm: 0 1px 2px rgba(15, 23, 42, .06);
--font-ui: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
--font-mono: "Cascadia Code", "JetBrains Mono", Consolas, "Courier New", monospace;
}
html[data-theme="dark"] {
--bg: #1b1c1f;
--bg-soft: #202226;
--bg-toolbar: #1e2024;
--bg-hover: #2a2d33;
--bg-active: #32363d;
--border: #2e3238;
--border-strong: #3b4048;
--text: #e6e8ec;
--text-dim: #9aa3ae;
--text-faint: #6f7782;
--accent: #4f8ef7;
--accent-soft: #1e2c44;
--accent-text: #ffffff;
--danger: #ef6b6b;
--code-bg: #262a30;
--code-block-bg: #22252a;
--quote-bar: #3d434c;
--shadow: 0 8px 28px rgba(0, 0, 0, .5);
--shadow-sm: 0 1px 2px rgba(0, 0, 0, .3);
}
/* ============ 基础 ============ */
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
overflow: hidden;
}
body {
font-family: var(--font-ui);
font-size: 13px;
color: var(--text);
background: var(--bg);
-webkit-font-smoothing: antialiased;
user-select: none;
}
.app {
display: flex;
flex-direction: column;
height: 100vh;
}
button {
font-family: inherit;
font-size: inherit;
color: inherit;
border: none;
background: none;
cursor: pointer;
}
/* ============ 工具栏 ============ */
.toolbar {
display: flex;
align-items: center;
gap: 6px;
height: 50px;
flex: 0 0 50px;
padding: 0 10px;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border);
}
.brand {
display: flex;
align-items: center;
gap: 8px;
padding-right: 8px;
margin-right: 4px;
-webkit-app-region: drag;
}
.brand-name {
font-size: 12.5px;
font-weight: 600;
color: var(--text-dim);
white-space: nowrap;
}
.tb-group { display: flex; align-items: center; gap: 2px; }
.tb-btn {
display: inline-flex;
align-items: center;
gap: 5px;
height: 30px;
padding: 0 9px;
border-radius: 7px;
color: var(--text-dim);
white-space: nowrap;
transition: background .12s, color .12s;
}
.tb-btn svg { width: 15px; height: 15px; fill: currentColor; }
.tb-btn span { font-size: 12.5px; }
.tb-btn:hover { background: var(--bg-hover); color: var(--text); }
.tb-btn:active { background: var(--bg-active); }
.tb-btn.on { background: var(--accent-soft); color: var(--accent); }
.tb-btn.primary { color: var(--accent); }
.tb-btn.primary:hover { background: var(--accent-soft); }
.tb-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 30px; height: 30px;
border-radius: 7px;
color: var(--text-dim);
transition: background .12s, color .12s;
}
.tb-icon svg { width: 15px; height: 15px; fill: currentColor; }
.tb-icon:hover { background: var(--bg-hover); color: var(--text); }
.tb-icon:active { background: var(--bg-active); }
.tb-icon.disabled { opacity: .35; pointer-events: none; }
.tb-sep {
width: 1px;
height: 20px;
margin: 0 4px;
background: var(--border);
}
.spacer { flex: 1; }
/* 分段控件 */
.seg {
display: flex;
padding: 2px;
border-radius: 8px;
background: var(--bg-soft);
border: 1px solid var(--border);
}
.seg button {
height: 24px;
padding: 0 11px;
border-radius: 6px;
font-size: 12px;
color: var(--text-dim);
transition: background .12s, color .12s;
}
.seg button:hover { color: var(--text); }
.seg button.active {
background: var(--bg);
color: var(--accent);
font-weight: 600;
box-shadow: var(--shadow-sm);
}
html[data-theme="dark"] .seg button.active { background: var(--bg-active); }
/* ============ 标签栏 ============ */
.tabbar {
display: flex;
align-items: stretch;
flex: 0 0 32px;
height: 32px;
overflow-x: auto;
overflow-y: hidden;
background: var(--bg-soft);
border-bottom: 1px solid var(--border);
user-select: none;
}
.tabbar[hidden] { display: none; }
.tabbar::-webkit-scrollbar { height: 5px; }
.tabbar::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 3px; }
.tab {
display: flex;
align-items: center;
gap: 6px;
flex: 0 0 auto;
min-width: 118px;
max-width: 230px;
padding: 0 8px 0 12px;
border-right: 1px solid var(--border);
border-top: 2px solid transparent;
font-size: 12px;
color: var(--text-dim);
cursor: default;
}
.tab:hover { background: var(--bg-hover); }
.tab.active {
background: var(--bg);
color: var(--text);
border-top-color: var(--accent);
}
.tab .tab-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tab .tab-dot {
flex: 0 0 6px;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
opacity: 0;
}
.tab.dirty .tab-dot { opacity: 1; }
.tab .tab-close {
flex: 0 0 16px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border-radius: 4px;
color: var(--text-faint);
font-size: 11px;
line-height: 1;
}
.tab .tab-close:hover { background: var(--bg-active); color: var(--text); }
.tab .tab-close svg { width: 9px; height: 9px; fill: currentColor; }
/* ============ 查找条 ============ */
.findbar {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
background: var(--bg-soft);
border-bottom: 1px solid var(--border);
}
.findbar[hidden] { display: none; }
.findbar input {
flex: 1;
height: 28px;
padding: 0 10px;
border-radius: 6px;
border: 1px solid var(--border-strong);
background: var(--bg);
color: var(--text);
font-family: var(--font-ui);
font-size: 12.5px;
outline: none;
}
.findbar input:focus { border-color: var(--accent); }
.find-count { font-size: 11.5px; color: var(--text-faint); min-width: 62px; }
.findbar button {
width: 26px; height: 26px;
border-radius: 6px;
color: var(--text-dim);
font-size: 12px;
}
.findbar button:hover { background: var(--bg-hover); color: var(--text); }
/* ============ 工作区 ============ */
.workspace {
flex: 1;
display: flex;
min-height: 0;
overflow: hidden;
background: var(--bg);
}
.pane {
display: flex;
min-width: 0;
overflow: hidden;
}
/* ============ 文件树侧栏 ============ */
.sidebar {
flex: 0 0 232px;
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
background: var(--bg-soft);
border-left: 1px solid var(--border);
border-right: 1px solid var(--border);
}
.sidebar[hidden] { display: none; }
/* 面板头部(文件目录 / 章节大纲 共用,保证视觉统一) */
.panel-head {
display: flex;
align-items: center;
gap: 7px;
flex: 0 0 34px;
padding: 0 6px 0 12px;
border-bottom: 1px solid var(--border);
}
.panel-ico {
flex: 0 0 13px;
width: 13px;
height: 13px;
fill: var(--text-faint);
}
.panel-title {
font-size: 12px;
font-weight: 600;
color: var(--text-dim);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.panel-actions { display: flex; gap: 2px; flex: 0 0 auto; margin-left: auto; }
.sb-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px; height: 24px;
border-radius: 5px;
color: var(--text-faint);
}
.sb-btn svg { width: 13px; height: 13px; fill: currentColor; }
.sb-btn:hover { background: var(--bg-hover); color: var(--text); }
.sb-body {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 6px 0 24px;
user-select: none;
}
.tree-row {
display: flex;
align-items: center;
gap: 5px;
height: 26px;
padding-right: 8px;
font-size: 12.5px;
color: var(--text);
white-space: nowrap;
cursor: default;
}
.tree-row:hover { background: var(--bg-hover); }
.tree-row:focus { outline: none; background: var(--bg-active); }
.tree-row:focus.active { background: var(--accent-soft); }
.tree-row.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.tree-row .twisty {
flex: 0 0 12px;
text-align: center;
font-size: 9px;
line-height: 1;
color: var(--text-faint);
}
.tree-row.is-dir .tree-name { font-weight: 500; }
.tree-row .tree-name { overflow: hidden; text-overflow: ellipsis; }
.tree-empty { padding: 5px 12px 5px 30px; font-size: 11.5px; color: var(--text-faint); }
.sb-tip {
padding: 26px 16px;
font-size: 12px;
line-height: 1.7;
color: var(--text-faint);
text-align: center;
}
.sb-tip-sub { margin-top: 6px; font-size: 11.5px; color: var(--text-faint); opacity: .85; }.sb-pick-btn {
margin-top: 14px;
height: 28px;
padding: 0 16px;
border-radius: 7px;
background: var(--accent);
color: var(--accent-text);
font-size: 12px;
font-weight: 500;
}
.sb-pick-btn:hover { filter: brightness(1.06); }
.sb-pick-btn:active { filter: brightness(.94); }
/* ============ 章节大纲 ============ */
.outline {
flex: 0 0 210px;
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
background: var(--bg-soft);
border-left: 1px solid var(--border);
border-right: 1px solid var(--border);
}
.outline[hidden] { display: none; }
.ol-count {
margin-left: auto;
padding: 1px 7px;
border-radius: 9px;
background: var(--bg-hover);
font-size: 10.5px;
color: var(--text-faint);
}
.ol-body {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 6px 0 24px;
user-select: none;
}
.ol-item {
padding: 4px 10px;
font-size: 12.5px;
line-height: 1.45;
color: var(--text-dim);
border-left: 2px solid transparent;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: default;
}
.ol-item:hover { background: var(--bg-hover); color: var(--text); }
.ol-item.active {
color: var(--accent);
border-left-color: var(--accent);
background: var(--accent-soft);
}
.ol-item[data-level="1"] { color: var(--text); font-weight: 600; }
.ol-item[data-level="1"].active { color: var(--accent); }
.ol-empty {
padding: 22px 14px;
font-size: 12px;
line-height: 1.7;
color: var(--text-faint);
text-align: center;
}
.editor-pane { flex: 1; position: relative; }
/* 编辑器查找高亮叠加层:文字透明只显示 mark 背景,随编辑器滚动 */
.editor-wrap {
position: relative;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.editor-hl {
position: absolute;
inset: 0;
padding: 18px 22px;
color: transparent;
font-family: var(--font-mono);
font-size: 13.5px;
line-height: 1.7;
tab-size: 4;
white-space: pre-wrap;
word-wrap: break-word;
overflow: hidden;
pointer-events: none;
}
.editor-hl mark {
background: rgba(255, 193, 7, .32);
color: transparent;
border-radius: 3px;
}
.editor-hl mark.find-hit-active {
background: rgba(255, 159, 10, .55);
}
#editor {
flex: 1;
width: 100%;
height: 100%;
padding: 18px 22px;
border: none;
outline: none;
resize: none;
background: transparent;
color: var(--text);
font-family: var(--font-mono);
font-size: 13.5px;
line-height: 1.7;
tab-size: 4;
overflow-y: auto;
user-select: text;
caret-color: var(--accent);
}
#editor::placeholder { color: var(--text-faint); }
.splitter {
flex: 0 0 1px;
background: var(--border);
cursor: col-resize;
position: relative;
transition: background .15s;
}
.splitter::after {
content: '';
position: absolute;
top: 0; bottom: 0;
left: -3px; right: -3px;
}
.splitter:hover, .splitter.dragging { background: var(--accent); }
/* 侧栏 / 大纲的可拖拽分隔条 */
.vsplitter {
flex: 0 0 1px;
background: var(--border);
cursor: col-resize;
position: relative;
transition: background .15s;
}
.vsplitter::after {
content: '';
position: absolute;
top: 0; bottom: 0;
left: -3px; right: -3px;
}
.vsplitter:hover, .vsplitter.dragging { background: var(--accent); }
.vsplitter[hidden] { display: none; }
.preview-pane {
flex: 1;
overflow: hidden;
background: var(--bg);
}
/* 模式切换 */
.workspace[data-mode="edit"] .preview-pane,
.workspace[data-mode="edit"] .splitter { display: none; }
.workspace[data-mode="read"] .editor-pane,
.workspace[data-mode="read"] .splitter { display: none; }
/* ============ 预览排版 ============ */
/* 查找:正文关键字背景标记 */
#preview mark.find-hit {
background: rgba(255, 193, 7, .45);
color: inherit;
padding: 0 1px;
border-radius: 3px;
}
#preview mark.find-hit.find-hit-active {
background: #ff9f0a;
color: #fff;
}
.markdown-body {
height: 100%;
overflow-y: auto;
padding: 34px 46px 120px;
max-width: 900px;
margin: 0 auto;
font-size: 14.5px;
line-height: 1.78;
color: var(--text);
user-select: text;
overflow-wrap: break-word;
}
.markdown-body > *:first-child { margin-top: 0; }
.markdown-body h1, .markdown-body h2, .markdown-body h3,
.markdown-body h4, .markdown-body h5, .markdown-body h6 {
margin: 1.6em 0 .6em;
font-weight: 650;
line-height: 1.35;
scroll-margin-top: 20px;
}
.markdown-body h1 { font-size: 1.9em; padding-bottom: .3em; border-bottom: 1px solid var(--border); }
.markdown-body h2 { font-size: 1.5em; padding-bottom: .25em; border-bottom: 1px solid var(--border); }
.markdown-body h3 { font-size: 1.24em; }
.markdown-body h4 { font-size: 1.08em; }
.markdown-body h5 { font-size: 1em; }
.markdown-body h6 { font-size: .94em; color: var(--text-dim); }
.markdown-body p { margin: .85em 0; }
.markdown-body a {
color: var(--accent);
text-decoration: none;
border-bottom: 1px solid transparent;
}
.markdown-body a:hover { border-bottom-color: currentColor; }
.markdown-body strong { font-weight: 650; }
.markdown-body em { font-style: italic; }
.markdown-body del { color: var(--text-faint); }
.markdown-body code {
padding: .16em .4em;
border-radius: 5px;
background: var(--code-bg);
font-family: var(--font-mono);
font-size: .88em;
color: #b5446e;
}
html[data-theme="dark"] .markdown-body code { color: #f0a1c0; }
.code-wrap {
position: relative;
margin: 1em 0;
border-radius: 9px;
background: var(--code-block-bg);
border: 1px solid var(--border);
overflow: hidden;
}
.code-wrap pre {
margin: 0;
padding: 14px 16px;
overflow-x: auto;
font-family: var(--font-mono);
font-size: 12.8px;
line-height: 1.65;
}
.code-wrap pre code {
padding: 0;
background: none;
color: var(--text);
font-size: inherit;
white-space: pre;
}
.code-lang {
position: absolute;
top: 6px; right: 10px;
font-size: 10.5px;
letter-spacing: .04em;
text-transform: uppercase;
color: var(--text-faint);
font-family: var(--font-ui);
pointer-events: none;
}
.markdown-body blockquote {
margin: 1em 0;
padding: .2em 1em;
border-left: 3px solid var(--quote-bar);
color: var(--text-dim);
}
.markdown-body blockquote > *:first-child { margin-top: .4em; }
.markdown-body blockquote > *:last-child { margin-bottom: .4em; }
.markdown-body ul, .markdown-body ol { margin: .7em 0; padding-left: 1.7em; }
.markdown-body li { margin: .3em 0; }
.markdown-body li > ul, .markdown-body li > ol { margin: .3em 0; }
.markdown-body li.task-item { list-style: none; margin-left: -1.35em; }
.markdown-body li.task-item input { margin-right: .45em; vertical-align: 1px; accent-color: var(--accent); }
.markdown-body hr {
height: 1px;
margin: 1.8em 0;
border: none;
background: var(--border);
}
.table-wrap { overflow-x: auto; margin: 1.1em 0; }
.markdown-body table {
border-collapse: collapse;
width: 100%;
font-size: .95em;
}
.markdown-body th, .markdown-body td {
padding: 7px 13px;
border: 1px solid var(--border);
text-align: left;
}
.markdown-body th {
background: var(--bg-soft);
font-weight: 600;
}
.markdown-body tbody tr:nth-child(2n) { background: color-mix(in srgb, var(--bg-soft) 60%, transparent); }
.markdown-body img {
max-width: 100%;
border-radius: 8px;
margin: .4em 0;
}
/* ============ 状态栏 ============ */
.statusbar {
display: flex;
align-items: center;
justify-content: space-between;
flex: 0 0 26px;
height: 26px;
padding: 0 12px;
background: var(--bg-toolbar);
border-top: 1px solid var(--border);
font-size: 11.5px;
color: var(--text-faint);
}
.st-left, .st-right { display: flex; align-items: center; gap: 8px; }
.st-file { color: var(--text-dim); max-width: 46vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.st-dirty {
padding: 1px 6px;
border-radius: 4px;
background: var(--accent-soft);
color: var(--accent);
font-size: 10.5px;
}
.st-div { color: var(--border-strong); }
/* ============ 右键菜单 ============ */
.ctx-menu {
position: fixed;
z-index: 900;
min-width: 200px;
padding: 5px;
border-radius: 9px;
background: var(--bg);
border: 1px solid var(--border);
box-shadow: var(--shadow);
font-size: 12.5px;
}
.ctx-menu[hidden] { display: none; }
.ctx-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
height: 30px;
padding: 0 10px;
border-radius: 6px;
color: var(--text);
cursor: default;
}
.ctx-item:hover { background: var(--accent); color: var(--accent-text); }
.ctx-item .kbd { font-size: 11px; color: var(--text-faint); }
.ctx-item:hover .kbd { color: rgba(255, 255, 255, .8); }
.ctx-item.disabled { color: var(--text-faint); pointer-events: none; }
.ctx-sep { height: 1px; margin: 4px 6px; background: var(--border); }
/* ============ 提示 ============ */
.toast {
position: fixed;
left: 50%;
bottom: 46px;
transform: translateX(-50%) translateY(8px);
padding: 8px 16px;
border-radius: 8px;
background: rgba(28, 32, 38, .92);
color: #fff;
font-size: 12.5px;
opacity: 0;
transition: opacity .18s, transform .18s;
pointer-events: none;
z-index: 950;
}
.toast[hidden] { display: none; }
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
.drop-hint {
position: fixed;
inset: 0;
z-index: 990;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--accent) 12%, transparent);
border: 2px dashed var(--accent);
backdrop-filter: blur(1px);
}
.drop-hint[hidden] { display: none; }
.drop-hint div {
padding: 10px 22px;
border-radius: 10px;
background: var(--bg);
box-shadow: var(--shadow);
color: var(--accent);
font-weight: 600;
}
/* 滚动条 */
::-webkit-scrollbar { width: 11px; height: 11px; }
::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--text-faint) 42%, transparent);
border: 3px solid transparent;
background-clip: content-box;
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover { background: color-mix(in srgb, var(--text-faint) 70%, transparent); background-clip: content-box; }
::-webkit-scrollbar-track { background: transparent; }
/* 拖动分栏时禁止选中 */
body.resizing { cursor: col-resize; }
body.resizing #editor, body.resizing .markdown-body { pointer-events: none; }
+178
View File
@@ -0,0 +1,178 @@
/* Tauri 桥接层:替代 Electron preload,向 app.js 提供同形状的 window.api */
(function () {
'use strict';
const T = window.__TAURI__;
if (!T) { console.error('Tauri API 未注入'); return; }
const invoke = T.core.invoke;
const listen = T.event.listen;
const cur = T.window.getCurrentWindow();
/* ---------- 标题状态(等价原主进程窗口状态) ---------- */
const titleState = { path: null, dirty: false };
function baseName(p) {
if (!p) return null;
return String(p).replace(/[\\/]+$/, '').split(/[\\/]/).pop() || null;
}
function updateTitle() {
const t = (titleState.dirty ? '● ' : '') + (baseName(titleState.path) || '未命名') + ' — 小银 Markdown';
cur.setTitle(t).catch(() => {});
}
/* ---------- 模态对话框(支持任意按钮数组,返回按钮索引) ---------- */
function modalDialog(o) {
const buttons = Array.isArray(o.buttons) && o.buttons.length ? o.buttons : ['好'];
return new Promise((resolve) => {
const overlay = document.createElement('div');
overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:99999;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif;';
const box = document.createElement('div');
box.style.cssText = 'background:#fff;color:#222;border-radius:12px;padding:22px 24px 18px;max-width:440px;box-shadow:0 18px 60px rgba(0,0,0,.3);font-size:13.5px;';
const msg = document.createElement('div');
msg.style.cssText = 'font-weight:700;font-size:15px;margin-bottom:6px;';
msg.textContent = o.message || '';
box.appendChild(msg);
if (o.detail) {
const d = document.createElement('div');
d.style.cssText = 'opacity:.7;margin-bottom:14px;line-height:1.5;';
d.textContent = o.detail;
box.appendChild(d);
}
const row = document.createElement('div');
row.style.cssText = 'display:flex;gap:8px;justify-content:flex-end;';
buttons.forEach((label, i) => {
const b = document.createElement('button');
b.textContent = label;
const primary = i === buttons.length - 1;
b.style.cssText = 'padding:7px 16px;border-radius:8px;border:1px solid #c9cdd4;cursor:pointer;font-size:13px;background:' +
(primary ? '#3b7bf6;color:#fff;border-color:#3b7bf6;' : 'transparent;color:inherit;');
b.addEventListener('click', () => { overlay.remove(); resolve(i); });
row.appendChild(b);
});
box.appendChild(row);
overlay.appendChild(box);
document.body.appendChild(overlay);
});
}
/* ---------- 命令 / 关闭 / 导出 处理器注册表 ---------- */
const cmdHandlers = [];
const closeHandlers = [];
let exportHandler = null;
function fire(name, payload) {
cmdHandlers.forEach((cb) => { try { cb(name, payload); } catch (err) { console.error(err); } });
}
/* ---------- 迁移:广播收集所有窗口的文档 ---------- */
function collectAllDocs() {
return new Promise((resolve) => {
const replies = [];
let un = null;
listen('mig:docs', (e) => {
if (e.payload && Array.isArray(e.payload.docs)) replies.push(e.payload.docs);
}).then((u) => { un = u; });
T.event.emit('mig:request', { from: cur.label });
const start = Date.now();
const tick = () => {
if (Date.now() - start >= 2200 || un) {
if (un) un();
const seen = new Set();
const out = [];
for (const docs of replies) {
for (const d of docs) {
if (d.path && seen.has(d.path)) continue;
if (d.path) seen.add(d.path);
out.push(d);
}
}
if (!out.length) out.push({ path: null, name: null, text: '', eol: '\n', dirty: false, lastSaved: '' });
resolve(out);
return;
}
setTimeout(tick, 120);
};
setTimeout(tick, 600);
});
}
/* ---------- 对外 API(与 Electron preload 同形状) ---------- */
window.api = {
open: () => invoke('open_file_dialog'),
openPath: (p) => invoke('read_text_file', { path: p }),
save: async (payload) => {
const r = await invoke('save_file', {
content: payload.content,
saveAs: !!payload.saveAs,
eol: payload.eol || '\n',
currentPath: titleState.path
});
if (r && r.ok && r.path) {
titleState.path = r.path;
titleState.dirty = false;
updateTitle();
}
return r;
},
reveal: () => (titleState.path ? invoke('reveal_in_explorer', { path: titleState.path }) : Promise.resolve({ ok: false })),
revealPath: (p) => invoke('reveal_in_explorer', { path: p }),
copyFile: (p) => invoke('copy_file_to_clipboard', { path: p }),
readFileText: (p) => invoke('read_text_file', { path: p }),
readClipboard: () => invoke('read_clipboard_text'),
writeClipboard: (t) => invoke('write_clipboard_text', { text: t }),
openExternal: (url) => invoke('open_external', { url }),
dirOpen: () => invoke('open_dir_dialog'),
dirRead: (p) => invoke('read_dir', { path: p }),
openNewWindow: (p) => invoke('open_new_window', { path: p }),
newWindow: () => invoke('open_new_window', { path: null }),
closeWindow: () => invoke('force_close'),
getOpenMode: async () => ({ mode: localStorage.getItem('md-editor-open-mode') || 'tabs' }),
setOpenMode: async (mode) => {
const docs = await collectAllDocs();
await invoke('migrate_apply', { mode, docs, keepLabel: cur.label });
return { ok: true, mode };
},
setDirty: (d) => { titleState.dirty = !!d; updateTitle(); },
syncDoc: (p) => {
titleState.path = p || null;
updateTitle();
},
message: (o) => modalDialog(o),
saveFinished: () => {},
exportDocs: () => {},
onCommand: (cb) => cmdHandlers.push(cb),
onCloseConfirm: (cb) => closeHandlers.push(cb),
onExport: (cb) => { exportHandler = cb; }
};
/* ---------- 事件接线 ---------- */
listen('mig:adopt-tabs', (e) => fire('adopt-tabs', e.payload && e.payload.docs));
listen('mig:adopt-doc', (e) => fire('adopt-doc', e.payload));
listen('open-external', (e) => fire('open-external', e.payload));
listen('init-file', (e) => fire('file-opened', e.payload));
listen('close-confirm', () => closeHandlers.forEach((cb) => { try { cb(cur.label); } catch (err) { console.error(err); } }));
listen('mig:request', () => {
if (exportHandler) {
try {
const docs = exportHandler();
T.event.emit('mig:docs', { from: cur.label, docs });
} catch (err) { console.error(err); }
}
});
/* ---------- 拖放(Tauri 系统级,拿得到真实路径) ---------- */
cur.onDragDropEvent((e) => {
const p = e.payload;
if (p.type === 'drop' && Array.isArray(p.paths) && p.paths.length) {
fire('dropped-path', p.paths[0]);
}
});
/* ---------- 文本拖放兜底(HTML5) ---------- */
window.addEventListener('dragover', (e) => { e.preventDefault(); });
window.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
if (!dt) return;
e.preventDefault();
const text = dt.getData && dt.getData('text/plain');
if (text) fire('dropped-text', { name: null, text });
});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB