From 3390e91406365b9459af6bd222390669a32b9ded Mon Sep 17 00:00:00 2001 From: hunter-dev Date: Wed, 26 Aug 2026 15:05:09 +0800 Subject: [PATCH] =?UTF-8?q?feat(M2):=20FR-S1/S4/S6=20=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E6=9C=BA=E5=88=B6=E5=AE=8C=E5=96=84=E2=80=94=E2=80=94setBody?= =?UTF-8?q?=20=E9=98=B2=E6=8A=96=E8=AF=BB=20settings.autoSaveInterval(S1);?= =?UTF-8?q?=20beforeunload=20=E5=86=B2=E5=88=B7+saveNow(S4);=20ReadDocResu?= =?UTF-8?q?lt=20=E5=8A=A0=20mtime+reloadDoc=20=E6=A3=80=E6=B5=8B=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E6=94=B9=E5=8A=A8(R6);=20store=20=E6=9A=B4=E9=9C=B2?= =?UTF-8?q?=20=5F=5FSTORE=5F=5F;=20save-mechanism=20E2E=203=20=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../desktop/src/main/services/file-service.ts | 3 +- apps/desktop/src/renderer/App.tsx | 6 + apps/desktop/src/renderer/store.ts | 30 ++++- apps/desktop/tests/e2e/save-mechanism.spec.ts | 108 ++++++++++++++++++ packages/shared/src/types/doc.ts | 1 + 5 files changed, 142 insertions(+), 6 deletions(-) create mode 100644 apps/desktop/tests/e2e/save-mechanism.spec.ts diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.ts index 6b5a2b3..4ea5e10 100644 --- a/apps/desktop/src/main/services/file-service.ts +++ b/apps/desktop/src/main/services/file-service.ts @@ -140,8 +140,9 @@ export class FileService { async readDoc(path: string): Promise { 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 { diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx index b9223eb..e04be68 100644 --- a/apps/desktop/src/renderer/App.tsx +++ b/apps/desktop/src/renderer/App.tsx @@ -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-编辑器设置真实生效) diff --git a/apps/desktop/src/renderer/store.ts b/apps/desktop/src/renderer/store.ts index 4e4a28b..df0a18f 100644 --- a/apps/desktop/src/renderer/store.ts +++ b/apps/desktop/src/renderer/store.ts @@ -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; @@ -28,6 +29,7 @@ interface EditorState { addLink: (link: string) => void; removeLink: (link: string) => void; saveNow: () => Promise; + reloadDoc: () => Promise; // FR-S6:重新加载——检测 mtime 变化,有未保存改动时返回 false 需确认 resetEditor: () => void; // FR-V6: 切库时重置编辑区 syncCurrentPath: (oldPath: string, newPath: string) => void; // FR-T7: 重命名/移动后同步当前文档路径 } @@ -45,6 +47,7 @@ export const useStore = create((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((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((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((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((set, get) => ({ if (currentPath === oldPath) { set({ currentPath: newPath }); return; } if (oldPath && currentPath.startsWith(oldPath + '/')) set({ currentPath: newPath + currentPath.slice(oldPath.length) }); }, -})); \ No newline at end of file +})); + +// FR-S6:暴露 store 供 E2E 验证 +if (typeof window !== 'undefined') (window as any).__STORE__ = useStore; \ No newline at end of file diff --git a/apps/desktop/tests/e2e/save-mechanism.spec.ts b/apps/desktop/tests/e2e/save-mechanism.spec.ts new file mode 100644 index 0000000..b913367 --- /dev/null +++ b/apps/desktop/tests/e2e/save-mechanism.spec.ts @@ -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(); +}); diff --git a/packages/shared/src/types/doc.ts b/packages/shared/src/types/doc.ts index 072fbbc..d4313a1 100644 --- a/packages/shared/src/types/doc.ts +++ b/packages/shared/src/types/doc.ts @@ -9,6 +9,7 @@ export interface DocMeta { export interface ReadDocResult { meta: DocMeta; body: string; + mtime: number; // FR-S6:文件修改时间戳,用于检测外部改动 } export interface WriteDocPayload {