贡献者 PR #600(feat/editor-draft-protection,head a14c1e8)以 --no-ff 落到 dev 基线(9b97e6f)。贡献者的提交原样保留,冲突解决体现为本次合并结果。 保留(PR 独有): - 草稿保护:src/client/editor-dirty.ts(脏稿登记表 + confirmDiscardDraft)、EditorHost 的登记/卸载清理、Sidebar 的 closeTab 门与 beforeunload、closePathTabs 的确认参数。 - 保存冲突门:fs.read 回报 mtimeMs、fs.write 的 expectedMtimeMs(409 fs-conflict,在写 临时文件之前判定)、TextEditor 的 mtimeRef + 冲突横幅 + onReload、wire 的 fs-conflict 码,以及 fs-write-route / text-editor-conflict 两个新 spec。 - 查找/替换入口:TextEditor 工具栏放大镜按钮(打开 #587 的面板;可编辑视图的面板自带 替换行),文案用 #587 的 searchFind。 删除(与 #587 /2e22b90重复的部分): - TextEditor 里重复的那份查找接线:本地 searchPhrases()、EditorState.phrases.of(...)、 search({ top: true })、编辑器 keymap 里的 ...searchKeymap,以及 search / searchKeymap 两个 import——#587 的 src/client/cm-search.ts 已提供同一套(面板、keymap、phrases 隔间、 令牌主题)。 - 20 份词典里被 #587 取代的 10 个键:find / replace / findNext / findPrevious / findAll / findMatchCase / findRegexp / findByWord / replaceOne / replaceAll(命名以先落的 #587 为准: searchFind / searchReplace / searchNext / searchPrevious / searchAll / searchMatchCase / searchWholeWord / searchRegexp / searchReplaceAll)。 - src/index.ts 里已被2e22b90覆盖的临时文件改名(.dsh-write-<uuid>):保留 dev 的 .dsh-sidebar-tmp-<uuid>,tests/fs-write-route.spec.ts 的残留断言改指 dev 命名。 - tests/text-editor-search.spec.tsx 中与 editor-find.spec.tsx 重复的三个用例(en/zh 文案、 Mod-f),只留「工具栏按钮开面板并切到编辑态」这一个独有用例。 - README / README_EN / 指南里未实现的 Ctrl/Cmd + H 声明(PR 从未绑定 Mod-h,且浏览器保留 该组合键),改为如实描述「Ctrl/Cmd + F 的面板含替换行」,并补上 #587 已支持的 Ctrl/Cmd + G / Shift + Ctrl/Cmd + G / Ctrl/Cmd + D。 其它解冲突取舍(dev 上下文已漂移,不复活 PR 基线代码): - 图标:IconSearchOutline16 在宿主图标整族改名后已不存在,换为 IconSearchOutlineRegular size={16}(显式尺寸;旧 16 后缀已删,不传会按新默认尺寸)。 - 采纳 dev 侧:fs.read 的 ensureWorkspacePath 两参调用、truncation 横幅不带 mode 条件、 fs.write 的编码探测与 invalidateDirectoryCache、Sidebar 的 closeTab 里 PR 基线的终端 pty 释放块(dev 已移走)与 summaryCwd/pushedBottomHeight/collapsed 块(dev 已删)。 - 测试 harness 跟随 dev:ctx.sidebarRight.mounted、bottomSplits、先打开底部工作台、 apply() 需要的 ctx.on、api 模块改为部分 mock(保留 sessionPhase / sessionCwd)。 - 取舍记录写入 docs/plans/2026-09-09-editor-draft-protection-design.md。 Refs #600
305 lines
13 KiB
TypeScript
305 lines
13 KiB
TypeScript
/**
|
|
* Unsaved-draft protection: the dirty registry itself plus the close guard it
|
|
* arms. The registry is fed by the editor host's toolbar report; the guard is
|
|
* the sidebar's tab close (the X button, middle click, tab context menu, and
|
|
* the tree's close-on-rename/delete all funnel through the same action).
|
|
*
|
|
* The close path is driven through the REAL Sidebar shell (same minimal fake
|
|
* context as sidebar-crash.spec.tsx) so the test pins the behavior a user
|
|
* actually gets, not a helper: cancel keeps the tab, confirm closes it.
|
|
*/
|
|
// @vitest-environment jsdom
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { createElement, useEffect } from 'react'
|
|
import { createRoot, type Root } from 'react-dom/client'
|
|
import { act } from 'react-dom/test-utils'
|
|
import { renderRoot, setupReactAct } from './test-utils.ts'
|
|
import type { Context } from '../src/context-types.ts'
|
|
import { EditorHost } from '../src/client/EditorHost.tsx'
|
|
import { Sidebar } from '../src/client/Sidebar.tsx'
|
|
import { createBetterSidebarService, type BetterSidebarService, type FileViewerProps } from '../src/client/service.ts'
|
|
import { allLeaves, createSidebarStore, toggleBottomPanel, type SidebarStore } from '../src/client/state.ts'
|
|
import {
|
|
clearEditorDirty, confirmDiscardDraft, dirtyCount, dirtyCountForSession, editorDirtyRevision,
|
|
isEditorDirty, setEditorDirty, subscribeEditorDirty,
|
|
} from '../src/client/editor-dirty.ts'
|
|
import { closePathTabs } from '../src/client/tree-mutations.ts'
|
|
|
|
setupReactAct()
|
|
|
|
const fsRead = vi.fn()
|
|
// Partial mock: only the reads this spec drives are stubbed. The sidebar shell
|
|
// also touches `sessionPhase` / `api.sessionCwd` / the tree panel on mount, and
|
|
// a wholesale replacement breaks them (`No "sessionPhase" export …`).
|
|
vi.mock('../src/client/api.ts', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
|
|
return {
|
|
...actual,
|
|
api: {
|
|
...actual.api,
|
|
fsRead: (...args: unknown[]) => fsRead(...args),
|
|
fsTree: () => Promise.resolve({ path: '', entries: [], truncated: false }),
|
|
},
|
|
}
|
|
})
|
|
|
|
/** jsdom has no WebSocket; the sidebar's agent-terminals effect builds one. */
|
|
class FakeWebSocket {
|
|
onmessage: ((event: { data: unknown }) => void) | null = null
|
|
onclose: (() => void) | null = null
|
|
onerror: (() => void) | null = null
|
|
close = (): void => {}
|
|
constructor(_url: string) {}
|
|
}
|
|
|
|
/** A viewer that reports a dirty toolbar and renders nothing else. */
|
|
function DirtyViewer({ onToolbarState }: FileViewerProps) {
|
|
useEffect(() => {
|
|
onToolbarState?.({ modes: false, mode: 'edit', dirty: true, editable: true, saveState: 'idle' })
|
|
}, [onToolbarState])
|
|
return createElement('div', null, 'dirty-viewer')
|
|
}
|
|
|
|
let sessionSeq = 0
|
|
|
|
interface Mounted {
|
|
container: HTMLDivElement
|
|
store: SidebarStore
|
|
service: BetterSidebarService
|
|
sessionId: string
|
|
unmount: () => void
|
|
}
|
|
|
|
/** Mount the real Sidebar shell with one open editor tab (dirty viewer). */
|
|
function mountSidebarWithEditor(): Mounted {
|
|
vi.stubGlobal('WebSocket', FakeWebSocket)
|
|
const container = document.createElement('div')
|
|
document.body.append(container)
|
|
const store = createSidebarStore()
|
|
const service = createBetterSidebarService(store)
|
|
service.registerTab({
|
|
id: 'editor',
|
|
title: 'Files',
|
|
dedupeKey: (tab) => tab.path,
|
|
component: ({ ctx, store: tabStore, scope, tab, expanded, revealed, onToggleDir, onReferenceFile }) =>
|
|
createElement(EditorHost, {
|
|
ctx, store: tabStore, scope, tab,
|
|
expanded: expanded ?? [], revealed: revealed ?? [],
|
|
onToggleDir: onToggleDir ?? (() => {}), onReferenceFile: onReferenceFile ?? (() => {}),
|
|
}),
|
|
})
|
|
service.registerFileViewer({
|
|
id: 'mock-text', exts: ['ts'], priority: 0, fetchStrategy: 'fsRead', component: DirtyViewer,
|
|
})
|
|
const sessionId = `dirty-${++sessionSeq}`
|
|
store.setSession(sessionId)
|
|
// The plugin's own workbench hosts its tabs; without the panel open the tab
|
|
// strip (and its close button) is not rendered at all.
|
|
store.reduce(toggleBottomPanel)
|
|
const localeSnapshot = { active: 'en' }
|
|
// The session-list snapshot never carried a current-session field: the shell
|
|
// binds its per-session state to the native surface's mounted seat.
|
|
const sessionsSnapshot = { byId: { [sessionId]: { cwd: '/tmp' } } }
|
|
const mounted = { getSnapshot: () => sessionId, subscribe: () => () => {} }
|
|
const ctx = {
|
|
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
|
|
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
|
|
betterSidebar: service,
|
|
get: (name: string) => name === 'betterSidebar'
|
|
? service
|
|
: name === 'sidebarRight' ? { mounted } : undefined,
|
|
} as unknown as Context
|
|
service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' })
|
|
const root: Root = createRoot(container)
|
|
act(() => { root.render(createElement(Sidebar, { ctx, store })) })
|
|
return {
|
|
container, store, service, sessionId,
|
|
unmount: () => {
|
|
act(() => { root.unmount() })
|
|
container.remove()
|
|
},
|
|
}
|
|
}
|
|
|
|
/** The a.ts tab's close button (the seeded Files home tab also has one). */
|
|
function closeButton(container: HTMLDivElement): HTMLButtonElement {
|
|
const tabNode = Array.from(container.querySelectorAll('[title="a.ts"]'))
|
|
.find(node => node.querySelector('button') !== null)
|
|
const button = tabNode?.querySelector('button[aria-label="Close"], button[aria-label="关闭"]')
|
|
if (button === undefined || button === null) throw new Error('close button not found')
|
|
return button as HTMLButtonElement
|
|
}
|
|
|
|
function click(button: HTMLElement): void {
|
|
act(() => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
|
}
|
|
|
|
function openTabIds(store: SidebarStore): string[] {
|
|
const state = store.getSnapshot().state
|
|
if (state === undefined) return []
|
|
// The plugin's tabs live in its own bottom workbench (the main column
|
|
// belongs to DSH's native right sidebar).
|
|
return allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs).map(tab => tab.id)
|
|
}
|
|
|
|
beforeEach(() => {
|
|
fsRead.mockReset()
|
|
fsRead.mockResolvedValue({ kind: 'text', content: 'hello', truncated: false })
|
|
// The registry is module-level: a previous test's draft must not leak in.
|
|
for (const id of ['editor:/tmp/a.ts', 't1', 't2']) clearEditorDirty(id)
|
|
})
|
|
|
|
afterEach(() => {
|
|
document.body.innerHTML = ''
|
|
localStorage.clear()
|
|
vi.unstubAllGlobals()
|
|
vi.restoreAllMocks()
|
|
})
|
|
|
|
describe('editor-dirty registry', () => {
|
|
it('registers a dirty tab and clears it again, bumping the revision each time', () => {
|
|
const before = editorDirtyRevision()
|
|
setEditorDirty('t1', true, 's1', '/tmp/a.ts')
|
|
expect(isEditorDirty('t1')).toBe(true)
|
|
expect(dirtyCount()).toBe(1)
|
|
expect(dirtyCountForSession('s1')).toBe(1)
|
|
expect(dirtyCountForSession('other')).toBe(0)
|
|
expect(editorDirtyRevision()).toBeGreaterThan(before)
|
|
|
|
const afterRegister = editorDirtyRevision()
|
|
setEditorDirty('t1', true, 's1', '/tmp/a.ts')
|
|
// Same entry twice is a no-op: no revision churn (the unload effect would
|
|
// otherwise re-subscribe on every render).
|
|
expect(editorDirtyRevision()).toBe(afterRegister)
|
|
|
|
clearEditorDirty('t1')
|
|
expect(isEditorDirty('t1')).toBe(false)
|
|
expect(dirtyCount()).toBe(0)
|
|
expect(editorDirtyRevision()).toBeGreaterThan(afterRegister)
|
|
})
|
|
|
|
it('re-points an entry when the tab switches file or session', () => {
|
|
setEditorDirty('t2', true, 's1', '/tmp/a.ts')
|
|
setEditorDirty('t2', true, 's2', '/tmp/b.ts')
|
|
expect(dirtyCountForSession('s1')).toBe(0)
|
|
expect(dirtyCountForSession('s2')).toBe(1)
|
|
})
|
|
|
|
it('notifies subscribers and stops after unsubscribe', () => {
|
|
const listener = vi.fn()
|
|
const unsubscribe = subscribeEditorDirty(listener)
|
|
setEditorDirty('t1', true, 's1', '/tmp/a.ts')
|
|
expect(listener).toHaveBeenCalledTimes(1)
|
|
clearEditorDirty('t1')
|
|
expect(listener).toHaveBeenCalledTimes(2)
|
|
unsubscribe()
|
|
setEditorDirty('t1', true, 's1', '/tmp/a.ts')
|
|
expect(listener).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('confirmDiscardDraft passes clean tabs through and prompts for dirty ones', () => {
|
|
const confirmSpy = vi.fn().mockReturnValue(false)
|
|
vi.stubGlobal('confirm', confirmSpy)
|
|
expect(confirmDiscardDraft('t1', 'sure?')).toBe(true)
|
|
expect(confirmSpy).not.toHaveBeenCalled()
|
|
|
|
setEditorDirty('t1', true, 's1', '/tmp/a.ts')
|
|
expect(confirmDiscardDraft('t1', 'sure?')).toBe(false)
|
|
expect(confirmSpy).toHaveBeenCalledWith('sure?')
|
|
// Declined: the draft survives.
|
|
expect(isEditorDirty('t1')).toBe(true)
|
|
|
|
confirmSpy.mockReturnValue(true)
|
|
expect(confirmDiscardDraft('t1', 'sure?')).toBe(true)
|
|
// Confirmed: the entry is cleared so a follow-up close cannot re-prompt.
|
|
expect(isEditorDirty('t1')).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('tree close-on-delete', () => {
|
|
it('keeps a dirty tab when the user declines, closes it on confirm', () => {
|
|
const confirmSpy = vi.fn().mockReturnValue(false)
|
|
vi.stubGlobal('confirm', confirmSpy)
|
|
const store = createSidebarStore()
|
|
const service = createBetterSidebarService(store)
|
|
service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null })
|
|
store.setSession('tree-close')
|
|
const ctx = { betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : undefined } as unknown as Context
|
|
service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' })
|
|
setEditorDirty('editor:/tmp/a.ts', true, 'tree-close', '/tmp/a.ts')
|
|
|
|
closePathTabs(ctx, store, '/tmp/a.ts', 'discard?')
|
|
expect(confirmSpy).toHaveBeenCalledWith('discard?')
|
|
expect(openTabIds(store)).toContain('editor:/tmp/a.ts')
|
|
|
|
confirmSpy.mockReturnValue(true)
|
|
closePathTabs(ctx, store, '/tmp/a.ts', 'discard?')
|
|
expect(openTabIds(store)).not.toContain('editor:/tmp/a.ts')
|
|
})
|
|
})
|
|
|
|
describe('EditorHost dirty registration', () => {
|
|
it('registers the open tab and clears it when the host unmounts', async () => {
|
|
const store = createSidebarStore()
|
|
const service = createBetterSidebarService(store)
|
|
service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null })
|
|
service.registerFileViewer({ id: 'mock-text', exts: ['ts'], fetchStrategy: 'fsRead', component: DirtyViewer })
|
|
store.setSession('editor-host-dirty')
|
|
const ctx = { betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : undefined } as unknown as Context
|
|
service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' })
|
|
const tab = allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
|
.find(candidate => candidate.path === '/tmp/a.ts')!
|
|
const mounted = renderRoot(createElement(EditorHost, {
|
|
ctx, store, scope: { sessionId: 'editor-host-dirty' }, tab,
|
|
expanded: [], revealed: [], onToggleDir: () => {}, onReferenceFile: () => {},
|
|
}))
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(isEditorDirty(tab.id)).toBe(true)
|
|
mounted.unmount()
|
|
expect(isEditorDirty(tab.id)).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('close guard', () => {
|
|
it('cancel keeps the tab open and confirm closes it', async () => {
|
|
const confirmSpy = vi.fn()
|
|
vi.stubGlobal('confirm', confirmSpy)
|
|
const mounted = mountSidebarWithEditor()
|
|
try {
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(openTabIds(mounted.store)).toContain('editor:/tmp/a.ts')
|
|
expect(isEditorDirty('editor:/tmp/a.ts')).toBe(true)
|
|
|
|
// Cancel: the tab survives and stays dirty.
|
|
confirmSpy.mockReturnValue(false)
|
|
click(closeButton(mounted.container))
|
|
expect(confirmSpy).toHaveBeenCalledTimes(1)
|
|
expect(openTabIds(mounted.store)).toContain('editor:/tmp/a.ts')
|
|
expect(isEditorDirty('editor:/tmp/a.ts')).toBe(true)
|
|
|
|
// Confirm: the tab closes.
|
|
confirmSpy.mockReturnValue(true)
|
|
click(closeButton(mounted.container))
|
|
expect(confirmSpy).toHaveBeenCalledTimes(2)
|
|
expect(openTabIds(mounted.store)).not.toContain('editor:/tmp/a.ts')
|
|
} finally {
|
|
mounted.unmount()
|
|
}
|
|
})
|
|
|
|
it('a clean tab closes without prompting', async () => {
|
|
const confirmSpy = vi.fn().mockReturnValue(false)
|
|
vi.stubGlobal('confirm', confirmSpy)
|
|
const mounted = mountSidebarWithEditor()
|
|
try {
|
|
await act(async () => { await Promise.resolve() })
|
|
clearEditorDirty('editor:/tmp/a.ts')
|
|
click(closeButton(mounted.container))
|
|
expect(confirmSpy).not.toHaveBeenCalled()
|
|
expect(openTabIds(mounted.store)).not.toContain('editor:/tmp/a.ts')
|
|
} finally {
|
|
mounted.unmount()
|
|
}
|
|
})
|
|
})
|