fix(frontend): 修复可视化编辑器文件切换时序

This commit is contained in:
2026-08-30 10:24:47 +08:00
parent 9bbe4d3c86
commit 693c86c24d
4 changed files with 519 additions and 6 deletions
@@ -0,0 +1,44 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { nextTick } from 'vue'
import EditorPane from './EditorPane.vue'
import { useEditorStore } from '@/stores/editor'
let wrapper: VueWrapper | null = null
async function waitForText(text: string) {
for (let attempt = 0; attempt < 100; attempt++) {
if (wrapper?.text().includes(text)) return
await new Promise((resolve) => setTimeout(resolve, 10))
}
throw new Error(`Editor did not render ${text}`)
}
beforeEach(() => {
localStorage.clear()
setActivePinia(createPinia())
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
document.body.innerHTML = ''
})
describe('EditorPane file switching', () => {
it('recreates the visual editor with the newly loaded file content', async () => {
const store = useEditorStore()
await store.loadFile('/欢迎使用知笔知己.md')
wrapper = mount(EditorPane, { attachTo: document.body })
await waitForText('欢迎使用知笔知己')
await store.loadFile('/数据结构/红黑树.md')
await nextTick()
await waitForText('红黑树')
expect(store.currentFilePath).toBe('/数据结构/红黑树.md')
expect(wrapper.text()).not.toContain('祝你写作愉快')
})
})
+7 -6
View File
@@ -83,18 +83,19 @@ export const useEditorStore = defineStore('editor', () => {
throw new Error('当前文件保存失败,已阻止切换以避免内容丢失。')
}
const version = ++loadVersion
currentFilePath.value = filePath
const previousStatus = saveStatus.value
saveStatus.value = 'saving'
try {
const loadedContent = await workspaceService.readFileContent(filePath)
if (version !== loadVersion || currentFilePath.value !== filePath) return
if (version !== loadVersion) return
currentFilePath.value = filePath
content.value = loadedContent
saveStatus.value = 'saved'
lastSavedAt.value = new Date().toISOString()
} catch {
if (version !== loadVersion || currentFilePath.value !== filePath) return
content.value = ''
saveStatus.value = 'idle'
} catch (error) {
if (version !== loadVersion) return
saveStatus.value = previousStatus
throw error
}
highlightBlockId.value = null
}