Files
apes-sidebar/src/client/editor-dirty.ts
T
unsc9 ebc5d0b6b7 refactor: 精简 dev 相对 main 新增代码里的重复与白干(行为不变)
dev 分支的新增代码过了一轮「代码精简」审查(复用 / 简化 / 效率 / 修在哪一层四个角度,
分宿主侧、客户端外壳、客户端功能面板三片,另加测试与脚本),这里只落地行为完全不变的那批:

- `runGitRaw` 是 `runGit` 的纯转发别名(三个角度都点到):导出 `runGit`、删掉别名,
  `active-worktree.ts` 与它的 `vi.mock` 键同步改名。
- `open-external.ts` 的 `messageOf` 与 `fs-tree.ts` 的导出逐字相同:删本地实现改 import。
- `fs-operations.ts` 的单段名校验抄了三遍(注释却自称 shared rule):提成
  `assertSingleSegmentName`,rename / mkdir / 新建文件三处共用。
- `fs-tree.ts` 两个探测函数各抄一遍有界并发池:提成 `forEachRow`。
- `index.ts` 自己复刻了一遍 `request/header` 的 provider/model 读取:改调
  `collectModelRoutes(events, 1)[0]`;`lowestReasoningEffortOf` 的三态循环收成
  best/bestRank;`formatModelRoute` 零调用点,删掉(连带自测)。
- `state.ts`:`markUnread` / `clearUnread` 的当前会话路径改走已有的 `reduce`
  (「归约器返回同引用即 no-op」本来就在 reduce 里),删掉私有的 `replaceCurrent`;
  非当前会话那条仍只写内存不落盘,行为未动。
- `editor-dirty.ts`:`DirtyEntry.sessionId` 只服务一个没有生产调用者的
  `dirtyCountForSession`,会话隔离已由 `sessionId::tabId` 这个键承载,两个一起删,
  用例改断 `isEditorDirty(tabId, sessionId)`。
- `FileTree.tsx`:同一批行原先 `renderLevel` 与 `visibleRows` 各排一次,收进按
  `(data, sort)` 记忆的 `entriesFor`(照 `chainFor` 的形状)。
- `dock-fallback.tsx`:500ms 重测出的坐标没变就不换 state 对象(省掉一次无意义重渲染)。
- 其余同形收口:`DiffPane` 的死分支、`terminal-client` 的 `bottomTerminalKey`
  (与 `bottomTerminalContentId` 同值,调用点复用同一个 id)、`SideChatView` 的
  O(线程×目录) 排序扫描降为 Map、`conversation-draft` 的末段路径复用 `paths.baseName`、
  `TreePanel` 的目录命中集按 results 记忆。

验证:`tsc --noEmit` 只剩改动前那 3 条缺 `@xterm/*` 的既有报错;eslint 干净;
全套 vitest 与改动前的失败集合逐条一致(13 条,均为环境原因:缺 xterm 的构建/转换类
3 条、Windows 符号链接权限 3 条、语言字典串味 4 条、真起 git 的冒烟 1 条、文件级 1 条)。
2026-10-09 16:04:24 +08:00

131 lines
5.0 KiB
TypeScript

/**
* Unsaved-edit registry: which editor tabs currently hold a draft that
* differs from disk. The editor host registers its tab's dirty state here
* (the toolbar report already carries it), so the flows that would silently
* drop the draft can ask first:
*
* - the sidebar's tab close (the X button, the middle click, the tab context
* menu, and the tree's close-on-rename/delete path all land there),
* - the browser unload (refresh / close tab / navigate away) through a
* `beforeunload` guard.
*
* Module-level and keyed by `sessionId::tabId`: a tab id is unique only WITHIN
* one session — the native right column counts its own `tab1`…, and the bottom
* workbench reuses `editor:<path>` for the same file in every session. Keyed by
* the bare tab id, session B's editor mounting over the same id DELETED session
* A's record (its mount reports `dirty === false`), so A's still-live draft
* outlived its guard and a refresh dropped it without a word. The native
* surface accounts the same way (`viewKey`, native/tab-adapter.tsx).
* An entry is written while a tab is dirty and deleted the moment it goes
* clean (save) or its host unmounts (tab closed, in-place path switch), so a
* stale entry can never keep a guard armed.
*/
/** One registered draft: the id it was recorded under and the file. */
interface DirtyEntry {
tabId: string
path: string
}
const dirtyTabs = new Map<string, DirtyEntry>()
const listeners = new Set<() => void>()
/** Monotonic change counter: a stable `useSyncExternalStore` snapshot. */
let revision = 0
/** The map key of one tab: ids only identify a tab inside their session. */
function keyOf(sessionId: string, tabId: string): string {
return `${sessionId}::${tabId}`
}
/** Notify every subscriber (the `beforeunload` guard). */
function notify(): void {
revision += 1
for (const listener of [...listeners]) listener()
}
/**
* Publish one tab's dirty state: `true` registers the draft (session + path
* ride along for scoped queries), `false` / `undefined` clears it.
*/
export function setEditorDirty(tabId: string, dirty: boolean, sessionId: string, path: string): void {
const key = keyOf(sessionId, tabId)
if (!dirty) {
if (dirtyTabs.delete(key)) notify()
return
}
const previous = dirtyTabs.get(key)
if (previous !== undefined && previous.path === path) return
dirtyTabs.set(key, { tabId, path })
notify()
}
/**
* Drop a tab's entry (its editor host unmounted). Idempotent.
* @param sessionId - the owning session; omitted drops the id in EVERY session
* (the shape tests use for cleanup — a caller that knows its session should
* always name it, or it would clear a same-numbered tab elsewhere).
*/
export function clearEditorDirty(tabId: string, sessionId?: string): void {
if (sessionId !== undefined) {
if (dirtyTabs.delete(keyOf(sessionId, tabId))) notify()
return
}
let removed = false
for (const [key, entry] of dirtyTabs) {
if (entry.tabId !== tabId) continue
dirtyTabs.delete(key)
removed = true
}
if (removed) notify()
}
/**
* Whether one tab holds an unsaved draft.
* @param sessionId - the owning session; omitted matches the id in any session
* (the conservative read: a caller that cannot name the session should still
* warn rather than pass a live draft through).
*/
export function isEditorDirty(tabId: string, sessionId?: string): boolean {
if (sessionId !== undefined) return dirtyTabs.has(keyOf(sessionId, tabId))
for (const entry of dirtyTabs.values()) {
if (entry.tabId === tabId) return true
}
return false
}
/** How many tabs hold unsaved drafts across every session (the unload guard). */
export function dirtyCount(): number {
return dirtyTabs.size
}
/** Subscribe to dirty-set changes; returns the disposer. */
export function subscribeEditorDirty(listener: () => void): () => void {
listeners.add(listener)
return () => { listeners.delete(listener) }
}
/** The change counter (a stable `useSyncExternalStore` snapshot). */
export function editorDirtyRevision(): number {
return revision
}
/**
* Ask before dropping `tabId`'s unsaved draft. Returns true when the caller
* may proceed (the tab is clean, the user confirmed, or no `confirm` is
* available — letting a tab become unclosable would be worse than skipping one
* prompt). On confirm the entry is cleared immediately, so a follow-up close in
* the same tick does not double-prompt; the editor host's own cleanup would do
* it one commit later anyway.
*
* Shared by the sidebar's tab close and the file tree's close-on-delete so
* both paths warn exactly once, with the same copy.
* @param sessionId - the owning session (see {@link isEditorDirty} for the
* omitted case).
*/
export function confirmDiscardDraft(tabId: string, message: string, sessionId?: string): boolean {
if (!isEditorDirty(tabId, sessionId)) return true
const confirmed = typeof window.confirm === 'function' ? window.confirm(message) : true
if (confirmed) clearEditorDirty(tabId, sessionId)
return confirmed
}