feat(M2): FR-S1/S4/S6 保存机制完善——setBody 防抖读 settings.autoSaveInterval(S1); beforeunload 冲刷+saveNow(S4); ReadDocResult 加 mtime+reloadDoc 检测外部改动(R6); store 暴露 __STORE__; save-mechanism E2E 3 项

This commit is contained in:
hunter-dev
2026-08-26 15:05:09 +08:00
parent 01ea477d18
commit 3390e91406
5 changed files with 142 additions and 6 deletions
@@ -140,8 +140,9 @@ export class FileService {
async readDoc(path: string): Promise<ReadDocResult> {
const abs = this.abs(path);
const raw = await fs.readFile(abs, 'utf8');
const stat = await fs.stat(abs);
const { meta, body } = splitFrontmatter(raw);
return { meta, body };
return { meta, body, mtime: stat.mtimeMs };
}
async writeDoc(payload: WriteDocPayload): Promise<void> {
+6
View File
@@ -38,6 +38,12 @@ export function App() {
useEffect(() => { loadVault(); loadTree(); restore(); appearance.load(); useKeymap.getState().load(); useSettings.getState().loadGpu(); }, []);
useEffect(() => { if (activeId && tabs.length > 0) { const t = tabs.find(x => x.id === activeId); if (t) openDoc(t.path).catch(() => {}); } }, []);
// FR-S4:关窗前冲刷未保存内容
useEffect(() => {
const onBeforeUnload = () => { try { useStore.getState().saveNow(); } catch {} };
window.addEventListener('beforeunload', onBeforeUnload);
return () => window.removeEventListener('beforeunload', onBeforeUnload);
}, []);
useGlobalHotkeys({ onNewDoc: () => {}, onSave: () => useStore.getState().saveNow(), onFocusSearch: () => { const el = document.querySelector('input[placeholder*="搜索"]') as HTMLInputElement; el?.focus(); }, onToggleOutline: () => layout.toggleOutline(), onCheat: () => setShowCheat(true), onSettings: () => setShowSettings(true), onFind: () => { window.dispatchEvent(new CustomEvent('dsh-toggle-find')); } });
// 编辑器样式随设置生效(FR-编辑器设置真实生效)
+25 -5
View File
@@ -15,6 +15,7 @@ interface EditorState {
body: string;
meta: DocMeta;
saveState: SaveState;
docMtime: number; // FR-S6:已加载文档的 mtime,用于检测外部改动
tagFilter: string[]; // FR-R7:选中标签列表,FileTree 据此 AND 过滤
// actions
loadVault: () => Promise<void>;
@@ -28,6 +29,7 @@ interface EditorState {
addLink: (link: string) => void;
removeLink: (link: string) => void;
saveNow: () => Promise<void>;
reloadDoc: () => Promise<boolean>; // FR-S6:重新加载——检测 mtime 变化,有未保存改动时返回 false 需确认
resetEditor: () => void; // FR-V6: 切库时重置编辑区
syncCurrentPath: (oldPath: string, newPath: string) => void; // FR-T7: 重命名/移动后同步当前文档路径
}
@@ -45,6 +47,7 @@ export const useStore = create<EditorState>((set, get) => ({
meta: {},
saveState: 'saved',
tagFilter: [],
docMtime: 0,
loadVault: async () => {
const vault = await invoke(IPC.vaultList, undefined as never);
@@ -66,7 +69,7 @@ export const useStore = create<EditorState>((set, get) => ({
// 切换前冲刷当前文档
await get().saveNow();
const doc: ReadDocResult = await invoke(IPC.docRead, { path });
set({ currentPath: path, body: doc.body, meta: doc.meta, title: doc.meta.title ?? path.split('/').pop()!.replace(/\.md$/, ''), saveState: 'saved' });
set({ currentPath: path, body: doc.body, meta: doc.meta, title: doc.meta.title ?? path.split('/').pop()!.replace(/\.md$/, ''), saveState: 'saved', docMtime: doc.mtime });
// 同步到标签页(如已存在则激活,否则新建)
useTabs.getState().openTab(path);
},
@@ -98,9 +101,10 @@ export const useStore = create<EditorState>((set, get) => ({
},
setBody: (body: string) => {
set({ body, saveState: 'saving' });
// 防抖自动保存(M1:固定 600ms,M9 接设置间隔)
// FR-S1:防抖自动保存——间隔读 settings.autoSaveInterval(秒→毫秒)
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => { get().saveNow(); }, 600);
const interval = (() => { try { const s = JSON.parse(localStorage.getItem('dsh-settings') ?? '{}'); return (s.autoSaveInterval ?? 1) * 1000; } catch { return 1000; } })();
saveTimer = setTimeout(() => { get().saveNow(); }, interval);
},
saveNow: async () => {
@@ -116,7 +120,20 @@ export const useStore = create<EditorState>((set, get) => ({
}
},
resetEditor: () => { set({ currentPath: null, title: '', body: '', meta: {}, saveState: 'saved' }); },
// FR-S6:重新加载文档——检测 mtime 变化,有未保存改动时返回 false 需确认
reloadDoc: async () => {
const { currentPath, docMtime, saveState } = get();
if (!currentPath) return false;
try {
const doc: ReadDocResult = await invoke(IPC.docRead, { path: currentPath });
if (doc.mtime === docMtime) return true; // 未变
if (saveState !== 'saved') return false; // 有未保存改动,需确认
set({ body: doc.body, meta: doc.meta, docMtime: doc.mtime, saveState: 'saved' });
return true;
} catch { return false; }
},
resetEditor: () => { set({ currentPath: null, title: '', body: '', meta: {}, saveState: 'saved', docMtime: 0 }); },
syncCurrentPath: (oldPath, newPath) => {
const { currentPath } = get();
@@ -124,4 +141,7 @@ export const useStore = create<EditorState>((set, get) => ({
if (currentPath === oldPath) { set({ currentPath: newPath }); return; }
if (oldPath && currentPath.startsWith(oldPath + '/')) set({ currentPath: newPath + currentPath.slice(oldPath.length) });
},
}));
}));
// FR-S6:暴露 store 供 E2E 验证
if (typeof window !== 'undefined') (window as any).__STORE__ = useStore;
@@ -0,0 +1,108 @@
import { test, expect } from '@playwright/test';
import { _electron as electron } from 'playwright';
import { promises as fs } from 'node:fs';
import nodePath from 'node:path';
import os from 'node:os';
const MAIN_JS = nodePath.join(process.cwd(), 'dist-electron/main/index.js');
async function launch(userData: string) {
const app = await electron.launch({ args: ['--user-data-dir=' + userData, MAIN_JS] });
const page = await app.firstWindow();
await page.waitForLoadState('domcontentloaded');
const invoke = (ch: string, args: any) => page.evaluate(({ ch, args }) => (globalThis as any).dsh.invoke(ch, args), { ch, args });
return { app, page, invoke };
}
async function newDoc(a: { page: any; invoke: any }, title: string) {
await a.page.getByRole('button', { name: /新建文档/ }).click();
await a.page.getByPlaceholder(/输入文档标题/).fill(title);
await a.page.getByPlaceholder(/输入文档标题/).press('Enter');
await expect(a.page.getByTestId('tabbar').getByText(title, { exact: true })).toBeVisible({ timeout: 10000 });
}
// FR-S1:自动保存——停止输入后内容写入文件
test('FR-S1:自动保存防抖写入', async () => {
const tmp = await fs.mkdtemp(nodePath.join(os.tmpdir(), 'hn-s1-'));
const userData = nodePath.join(tmp, 'userdata');
const vault = nodePath.join(tmp, 'vault');
await fs.mkdir(userData, { recursive: true });
await fs.mkdir(vault, { recursive: true });
const a = await launch(userData);
await a.invoke('vault:switch', { root: vault });
await newDoc(a, '自动保存测试');
// 输入内容
await a.page.locator('.ProseMirror').click();
await a.page.keyboard.type('autosave content');
// 等待自动保存(默认 1 秒间隔 + 防抖)
await expect.poll(async () => {
try { const f = await fs.readFile(nodePath.join(vault, '自动保存测试.md'), 'utf8'); return f.includes('autosave content'); }
catch { return false; }
}, { timeout: 10000 }).toBe(true);
await a.app.close();
});
// FR-S4:关闭窗口前冲刷未保存内容
test('FR-S4:关窗冲刷未保存内容', async () => {
const tmp = await fs.mkdtemp(nodePath.join(os.tmpdir(), 'hn-s4-'));
const userData = nodePath.join(tmp, 'userdata');
const vault = nodePath.join(tmp, 'vault');
await fs.mkdir(userData, { recursive: true });
await fs.mkdir(vault, { recursive: true });
const a = await launch(userData);
await a.invoke('vault:switch', { root: vault });
await newDoc(a, '关窗测试');
await a.page.locator('.ProseMirror').click();
await a.page.keyboard.type('before-close-flush');
// 等一下让内容进入 store
await a.page.waitForTimeout(200);
// 手动触发 saveNow(模拟 beforeunload 冲刷)
await a.page.evaluate(() => (window as any).__STORE__?.getState?.().saveNow?.());
await a.page.waitForTimeout(500);
await a.app.close();
// 文件应包含内容(关窗前冲刷)
const fileContent = await fs.readFile(nodePath.join(vault, '关窗测试.md'), 'utf8');
expect(fileContent).toContain('before-close-flush');
});
// FR-S6:reloadDoc 检测 mtime 变化
test('FR-S6:reloadDoc 检测外部改动', async () => {
const tmp = await fs.mkdtemp(nodePath.join(os.tmpdir(), 'hn-s6-'));
const userData = nodePath.join(tmp, 'userdata');
const vault = nodePath.join(tmp, 'vault');
await fs.mkdir(userData, { recursive: true });
await fs.mkdir(vault, { recursive: true });
const a = await launch(userData);
await a.invoke('vault:switch', { root: vault });
await newDoc(a, '重载测试');
await a.page.locator('.ProseMirror').click();
await a.page.keyboard.type('original');
await a.page.waitForTimeout(2000); // 等待自动保存
// 外部修改文件
const filePath = nodePath.join(vault, '重载测试.md');
await fs.writeFile(filePath, '---\ntitle: 重载测试\n---\nexternal-change');
// reloadDoc 应检测到 mtime 变化并重载(无未保存改动时)
const result = await a.page.evaluate(async () => {
const store = (window as any).__STORE__;
if (!store) return { error: 'no store' };
return await store.getState().reloadDoc();
});
console.log('RELOAD_RESULT', JSON.stringify(result));
expect(result).toBe(true);
// 验证 store 的 body 已更新为外部修改的内容
const storeBody = await a.page.evaluate(() => (window as any).__STORE__?.getState?.().body ?? '');
expect(storeBody).toContain('external-change');
await a.app.close();
});
+1
View File
@@ -9,6 +9,7 @@ export interface DocMeta {
export interface ReadDocResult {
meta: DocMeta;
body: string;
mtime: number; // FR-S6:文件修改时间戳,用于检测外部改动
}
export interface WriteDocPayload {