merge review/1083-editor-draft: #1083 confirm before an in-place file switch drops an unsaved draft
This commit is contained in:
commit
2e691142da
25 files changed
+187
-13
No files matched your search
+20
-10
@@ -30,7 +30,7 @@ import type { Context } from '../context-types.ts'
|
||||
import { api, mediaUrl, type SessionScope } from './api.ts'
|
||||
import { BinaryDownload } from './binary-download.tsx'
|
||||
import { planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts'
|
||||
import { clearEditorDirty, setEditorDirty } from './editor-dirty.ts'
|
||||
import { clearEditorDirty, isEditorDirty, setEditorDirty } from './editor-dirty.ts'
|
||||
import { baseName } from './FileTree.tsx'
|
||||
import { createFrameBatcher } from './frame-batcher.ts'
|
||||
import { openClaimedNativeFile, openSidebarFile } from './sidebar-file.ts'
|
||||
@@ -113,6 +113,14 @@ function accepted(pending: Promise<unknown>): Promise<boolean> {
|
||||
)
|
||||
}
|
||||
|
||||
/** Ask before a reload/switch drops a draft. A host without confirm blocks
|
||||
* the action: refusing is recoverable, while silently discarding is not.
|
||||
* (The tab-close guard intentionally proceeds instead — an unclosable tab
|
||||
* is worse than one skipped prompt.) */
|
||||
function confirmDiscard(message: string): boolean {
|
||||
return typeof window.confirm === 'function' ? window.confirm(message) : false
|
||||
}
|
||||
|
||||
export function EditorHost(props: {
|
||||
ctx: Context
|
||||
store: SidebarStore
|
||||
@@ -162,12 +170,7 @@ export function EditorHost(props: {
|
||||
// Manual refresh (issue #167 + PR #228): a dirty draft is dropped by the
|
||||
// reload (the editor instance remounts), so confirm before discarding it.
|
||||
const refreshFile = (): void => {
|
||||
if (toolbar?.dirty === true) {
|
||||
const confirmed = typeof window.confirm === 'function'
|
||||
? window.confirm(t('refreshUnsavedConfirm'))
|
||||
: false
|
||||
if (!confirmed) return
|
||||
}
|
||||
if (toolbar?.dirty === true && !confirmDiscard(t('refreshUnsavedConfirm'))) return
|
||||
setReloadSeq(sequence => sequence + 1)
|
||||
}
|
||||
|
||||
@@ -231,9 +234,16 @@ export function EditorHost(props: {
|
||||
*/
|
||||
const openFile = (absolute: string): void => {
|
||||
if (inPlace) {
|
||||
if (!openClaimedNativeFile(ctx, scope.sessionId, scope.cwd, absolute)) {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId)
|
||||
}
|
||||
// A native tab type claims the file: it opens elsewhere and THIS editor
|
||||
// keeps its draft, so there is nothing to confirm.
|
||||
if (openClaimedNativeFile(ctx, scope.sessionId, scope.cwd, absolute)) return
|
||||
// An in-place switch remounts the viewer, and the draft lives only in
|
||||
// that instance — ask before dropping it, reading the same dirty
|
||||
// registry the tab close uses. Re-opening the current path is not a
|
||||
// switch.
|
||||
if (absolute !== path && isEditorDirty(tab.id, scope.sessionId)
|
||||
&& !confirmDiscard(t('switchUnsavedConfirm'))) return
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId)
|
||||
} else {
|
||||
openSidebarFile(ctx, scope.sessionId, absolute, { cwd: scope.cwd })
|
||||
}
|
||||
|
||||
@@ -159,6 +159,7 @@ export const ar: Record<string, string> = {
|
||||
showInFolder: 'إظهار في المجلد',
|
||||
refreshUnsavedConfirm: 'تغيّر الملف على القرص. سيؤدي التحديث إلى فقدان التعديلات غير المحفوظة. متابعة؟',
|
||||
closeUnsavedConfirm: 'يحتوي هذا الملف على تعديلات غير محفوظة. سيؤدي إغلاق علامة التبويب إلى تجاهلها. المتابعة؟',
|
||||
switchUnsavedConfirm: 'يحتوي هذا الملف على تعديلات غير محفوظة. سيؤدي تبديل الملف إلى تجاهلها. المتابعة؟',
|
||||
save: 'حفظ',
|
||||
saved: 'تم الحفظ',
|
||||
unsaved: 'غير محفوظ',
|
||||
|
||||
@@ -144,6 +144,7 @@ export const de: Record<string, string> = {
|
||||
showInFolder: 'Im Ordner anzeigen',
|
||||
refreshUnsavedConfirm: 'Die Datei wurde geändert. Beim Aktualisieren gehen ungespeicherte Änderungen verloren. Fortfahren?',
|
||||
closeUnsavedConfirm: 'Diese Datei hat ungespeicherte Änderungen. Beim Schließen des Tabs gehen sie verloren. Fortfahren?',
|
||||
switchUnsavedConfirm: 'Diese Datei hat ungespeicherte Änderungen. Beim Wechseln der Datei gehen sie verloren. Fortfahren?',
|
||||
save: 'Speichern',
|
||||
saved: 'Gespeichert',
|
||||
unsaved: 'Nicht gespeichert',
|
||||
|
||||
@@ -151,6 +151,7 @@ export const fr: Record<string, string> = {
|
||||
showInFolder: 'Afficher dans le dossier',
|
||||
refreshUnsavedConfirm: 'Le fichier a changé sur le disque. Actualiser supprimera les modifications non enregistrées. Continuer ?',
|
||||
closeUnsavedConfirm: 'Ce fichier contient des modifications non enregistrées. Fermer l\'onglet les perdra. Continuer ?',
|
||||
switchUnsavedConfirm: 'Ce fichier contient des modifications non enregistrées. Changer de fichier les perdra. Continuer ?',
|
||||
save: 'Enregistrer',
|
||||
saved: 'Enregistré',
|
||||
unsaved: 'Non enregistré',
|
||||
|
||||
@@ -158,6 +158,7 @@ export const hi: Record<string, string> = {
|
||||
showInFolder: 'फ़ोल्डर में दिखाएँ',
|
||||
refreshUnsavedConfirm: 'डिस्क पर फ़ाइल बदल गई है। रीफ़्रेश करने पर असहेज किए गए संपादन खो जाएँगे। जारी रखें?',
|
||||
closeUnsavedConfirm: 'इस फ़ाइल में सहेजे नहीं गए संपादन हैं। टैब बंद करने पर वे हट जाएँगे। जारी रखें?',
|
||||
switchUnsavedConfirm: 'इस फ़ाइल में सहेजे नहीं गए संपादन हैं। फ़ाइल बदलने पर वे हट जाएँगे। जारी रखें?',
|
||||
save: 'सहेजें',
|
||||
saved: 'सहेजा गया',
|
||||
unsaved: 'असहेजित',
|
||||
|
||||
@@ -156,6 +156,7 @@ export const id: Record<string, string> = {
|
||||
showInFolder: 'Tampilkan di folder',
|
||||
refreshUnsavedConfirm: 'File berubah di disk. Menyegarkan akan membuang edit yang belum disimpan. Lanjutkan?',
|
||||
closeUnsavedConfirm: 'File ini memiliki edit yang belum disimpan. Menutup tab akan membuangnya. Lanjutkan?',
|
||||
switchUnsavedConfirm: 'File ini memiliki edit yang belum disimpan. Mengganti file akan membuangnya. Lanjutkan?',
|
||||
save: 'Simpan',
|
||||
saved: 'Tersimpan',
|
||||
unsaved: 'Belum disimpan',
|
||||
|
||||
@@ -149,6 +149,7 @@ export const it: Record<string, string> = {
|
||||
showInFolder: 'Mostra nella cartella',
|
||||
refreshUnsavedConfirm: 'Il file è cambiato su disco. Aggiornare scarterà le modifiche non salvate. Continuare?',
|
||||
closeUnsavedConfirm: 'Questo file ha modifiche non salvate. Chiudere la scheda le perderà. Continuare?',
|
||||
switchUnsavedConfirm: 'Questo file ha modifiche non salvate. Cambiare file le perderà. Continuare?',
|
||||
save: 'Salva',
|
||||
saved: 'Salvato',
|
||||
unsaved: 'Non salvato',
|
||||
|
||||
@@ -158,6 +158,7 @@ export const ja: Record<string, string> = {
|
||||
showInFolder: 'フォルダーで表示',
|
||||
refreshUnsavedConfirm: 'ディスク上のファイルが変更されました。更新すると未保存の編集が失われます。続行しますか?',
|
||||
closeUnsavedConfirm: 'このファイルには未保存の編集があります。タブを閉じると破棄されます。続行しますか?',
|
||||
switchUnsavedConfirm: 'このファイルには未保存の編集があります。ファイルを切り替えると破棄されます。続行しますか?',
|
||||
save: '保存',
|
||||
saved: '保存済み',
|
||||
unsaved: '未保存',
|
||||
|
||||
@@ -150,6 +150,7 @@ export const ko: Record<string, string> = {
|
||||
showInFolder: '폴더에서 표시',
|
||||
refreshUnsavedConfirm: '디스크의 파일이 변경되었습니다. 새로고침하면 저장되지 않은 편집 내용이 손실됩니다. 계속하시겠습니까?',
|
||||
closeUnsavedConfirm: '이 파일에 저장되지 않은 편집이 있습니다. 탭을 닫으면 삭제됩니다. 계속하시겠습니까?',
|
||||
switchUnsavedConfirm: '이 파일에 저장되지 않은 편집이 있습니다. 파일을 전환하면 삭제됩니다. 계속하시겠습니까?',
|
||||
save: '저장',
|
||||
saved: '저장됨',
|
||||
unsaved: '저장 안 됨',
|
||||
|
||||
@@ -156,6 +156,7 @@ export const nl: Record<string, string> = {
|
||||
showInFolder: 'In map tonen',
|
||||
refreshUnsavedConfirm: 'Het bestand is op schijf gewijzigd. Vernieuwen gooit niet-opgeslagen wijzigingen weg. Doorgaan?',
|
||||
closeUnsavedConfirm: 'Dit bestand heeft niet-opgeslagen wijzigingen. Het sluiten van het tabblad gooit ze weg. Doorgaan?',
|
||||
switchUnsavedConfirm: 'Dit bestand heeft niet-opgeslagen wijzigingen. Het wisselen van bestand gooit ze weg. Doorgaan?',
|
||||
save: 'Opslaan',
|
||||
saved: 'Opgeslagen',
|
||||
unsaved: 'Niet opgeslagen',
|
||||
|
||||
@@ -160,6 +160,7 @@ export const pl: Record<string, string> = {
|
||||
showInFolder: 'Pokaż w folderze',
|
||||
refreshUnsavedConfirm: 'Plik zmienił się na dysku. Odświeżenie odrzuci niezapisane zmiany. Kontynuować?',
|
||||
closeUnsavedConfirm: 'Ten plik ma niezapisane zmiany. Zamknięcie karty je odrzuci. Kontynuować?',
|
||||
switchUnsavedConfirm: 'Ten plik ma niezapisane zmiany. Przełączenie pliku je odrzuci. Kontynuować?',
|
||||
save: 'Zapisz',
|
||||
saved: 'Zapisano',
|
||||
unsaved: 'Niezapisane',
|
||||
|
||||
@@ -141,6 +141,7 @@ export const pt: Record<string, string> = {
|
||||
showInFolder: 'Mostrar na pasta',
|
||||
refreshUnsavedConfirm: 'O arquivo mudou no disco. Atualizar descartará edições não salvas. Continuar?',
|
||||
closeUnsavedConfirm: 'Este arquivo tem edições não salvas. Fechar a aba irá descartá-las. Continuar?',
|
||||
switchUnsavedConfirm: 'Este arquivo tem edições não salvas. Trocar de arquivo irá descartá-las. Continuar?',
|
||||
save: 'Salvar',
|
||||
saved: 'Salvo',
|
||||
unsaved: 'Não salvo',
|
||||
|
||||
@@ -154,6 +154,7 @@ export const ru: Record<string, string> = {
|
||||
showInFolder: 'Показать в папке',
|
||||
refreshUnsavedConfirm: 'Файл изменился на диске. Обновление отбросит несохранённые изменения. Продолжить?',
|
||||
closeUnsavedConfirm: 'В файле есть несохранённые изменения. Закрытие вкладки их отменит. Продолжить?',
|
||||
switchUnsavedConfirm: 'В файле есть несохранённые изменения. При переключении на другой файл они будут отброшены. Продолжить?',
|
||||
save: 'Сохранить',
|
||||
saved: 'Сохранено',
|
||||
unsaved: 'Не сохранено',
|
||||
|
||||
@@ -141,6 +141,7 @@ export const sv: Record<string, string> = {
|
||||
showInFolder: 'Visa i mapp',
|
||||
refreshUnsavedConfirm: 'Filen ändrades på disken. Uppdatering kastar osparade ändringar. Fortsätta?',
|
||||
closeUnsavedConfirm: 'Filen har osparade ändringar. Att stänga fliken kastar dem. Fortsätta?',
|
||||
switchUnsavedConfirm: 'Filen har osparade ändringar. Att byta fil kastar dem. Fortsätta?',
|
||||
save: 'Spara',
|
||||
saved: 'Sparad',
|
||||
unsaved: 'Osparad',
|
||||
|
||||
@@ -158,6 +158,7 @@ export const th: Record<string, string> = {
|
||||
showInFolder: 'แสดงในโฟลเดอร์',
|
||||
refreshUnsavedConfirm: 'ไฟล์เปลี่ยนบนดิสก์ การรีเฟรชจะทิ้งการแก้ไขที่ยังไม่ได้บันทึก ดำเนินการต่อหรือไม่',
|
||||
closeUnsavedConfirm: 'ไฟล์นี้มีการแก้ไขที่ยังไม่ได้บันทึก การปิดแท็บจะทิ้งการแก้ไขนั้น ดำเนินการต่อหรือไม่',
|
||||
switchUnsavedConfirm: 'ไฟล์นี้มีการแก้ไขที่ยังไม่ได้บันทึก การสลับไฟล์จะทิ้งการแก้ไขนั้น ดำเนินการต่อหรือไม่',
|
||||
save: 'บันทึก',
|
||||
saved: 'บันทึกแล้ว',
|
||||
unsaved: 'ยังไม่ได้บันทึก',
|
||||
|
||||
@@ -158,6 +158,7 @@ export const tr: Record<string, string> = {
|
||||
showInFolder: 'Klasörde göster',
|
||||
refreshUnsavedConfirm: 'Dosya diskte değişti. Yenileme kaydedilmemiş düzenlemeleri atar. Devam edilsin mi?',
|
||||
closeUnsavedConfirm: 'Bu dosyada kaydedilmemiş değişiklikler var. Sekmeyi kapatmak bunları atacak. Devam edilsin mi?',
|
||||
switchUnsavedConfirm: 'Bu dosyada kaydedilmemiş değişiklikler var. Dosya değiştirmek bunları atacak. Devam edilsin mi?',
|
||||
save: 'Kaydet',
|
||||
saved: 'Kaydedildi',
|
||||
unsaved: 'Kaydedilmedi',
|
||||
|
||||
@@ -158,6 +158,7 @@ export const vi: Record<string, string> = {
|
||||
showInFolder: 'Hiển thị trong thư mục',
|
||||
refreshUnsavedConfirm: 'Tệp đã thay đổi trên đĩa. Làm mới sẽ loại bỏ các chỉnh sửa chưa lưu. Tiếp tục?',
|
||||
closeUnsavedConfirm: 'Tệp này có chỉnh sửa chưa lưu. Đóng tab sẽ loại bỏ chúng. Tiếp tục?',
|
||||
switchUnsavedConfirm: 'Tệp này có chỉnh sửa chưa lưu. Chuyển tệp sẽ loại bỏ chúng. Tiếp tục?',
|
||||
save: 'Lưu',
|
||||
saved: 'Đã lưu',
|
||||
unsaved: 'Chưa lưu',
|
||||
|
||||
@@ -173,6 +173,7 @@ export const zhHK: Record<string, string> = {
|
||||
showInFolder: '在文件夾中顯示',
|
||||
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
|
||||
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
|
||||
switchUnsavedConfirm: '此檔案有未儲存的編輯,切換檔案將丟棄這些內容。繼續嗎?',
|
||||
save: '儲存',
|
||||
saved: '已儲存',
|
||||
unsaved: '未儲存',
|
||||
|
||||
@@ -173,6 +173,7 @@ export const zhMO: Record<string, string> = {
|
||||
showInFolder: '在文件夾中顯示',
|
||||
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
|
||||
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
|
||||
switchUnsavedConfirm: '此檔案有未儲存的編輯,切換檔案將丟棄這些內容。繼續嗎?',
|
||||
save: '儲存',
|
||||
saved: '已儲存',
|
||||
unsaved: '未儲存',
|
||||
|
||||
@@ -173,6 +173,7 @@ export const zhTW: Record<string, string> = {
|
||||
showInFolder: '在資料夾中顯示',
|
||||
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
|
||||
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
|
||||
switchUnsavedConfirm: '此檔案有未儲存的編輯,切換檔案將丟棄這些內容。繼續嗎?',
|
||||
save: '儲存',
|
||||
saved: '已儲存',
|
||||
unsaved: '未儲存',
|
||||
|
||||
@@ -169,6 +169,7 @@ export const zh = {
|
||||
refresh: '刷新',
|
||||
refreshUnsavedConfirm: '文件已在磁盘更新,刷新将丢弃未保存编辑。继续吗?',
|
||||
closeUnsavedConfirm: '该文件有未保存的编辑,关闭后将丢弃。继续吗?',
|
||||
switchUnsavedConfirm: '该文件有未保存的编辑,切换文件将丢弃这些内容。继续吗?',
|
||||
save: '保存',
|
||||
saved: '已保存',
|
||||
unsaved: '未保存',
|
||||
@@ -813,6 +814,7 @@ export const en: Record<keyof typeof zh, string> = {
|
||||
refresh: 'Refresh',
|
||||
refreshUnsavedConfirm: 'The file changed on disk. Refreshing will discard unsaved edits. Continue?',
|
||||
closeUnsavedConfirm: 'This file has unsaved edits. Closing the tab will discard them. Continue?',
|
||||
switchUnsavedConfirm: 'This file has unsaved edits. Switching files will discard them. Continue?',
|
||||
save: 'Save',
|
||||
saved: 'Saved',
|
||||
unsaved: 'Unsaved',
|
||||
|
||||
@@ -268,12 +268,16 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
// `start()` launches `pack()` detached; give its open/spawn a beat to land
|
||||
// before dispose kills the child. Disposing first lets a late open create a
|
||||
// temp file AFTER the cleanup below has already walked the tree.
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
// Before the mocks go: `dispose()` kills through a fake whose `kill` is a
|
||||
// `vi.fn`, and those implementations do not survive a restore.
|
||||
for (const tasks of tables.splice(0)) tasks.dispose()
|
||||
// A killed child closes asynchronously; let the close land (and the packer
|
||||
// close its descriptor) before the directories underneath it disappear.
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
for (const [key, value] of Object.entries(savedTmp)) {
|
||||
if (value === undefined) delete process.env[key]
|
||||
else process.env[key] = value
|
||||
|
||||
@@ -36,7 +36,9 @@ curl() {
|
||||
}
|
||||
${script.slice(start)}
|
||||
`], {
|
||||
encoding: 'utf8', timeout: 5_000,
|
||||
// A ceiling, not a budget: the script is fast, but a loaded Windows
|
||||
// runner can take seconds just to start bash (status: null on timeout).
|
||||
encoding: 'utf8', timeout: 15_000,
|
||||
env: { ...process.env, ROOT: root, SCRATCH: scratch, TEST_LAUNCH_URL: launch },
|
||||
})
|
||||
expect(result.stderr).toBe('')
|
||||
|
||||
@@ -338,6 +338,25 @@ function typeAndCommit(input: HTMLInputElement, value: string): void {
|
||||
})
|
||||
}
|
||||
|
||||
/** Register a viewer that reports an unsaved draft on mount; its report
|
||||
* feeds the editor-dirty registry the switch/close guards read. */
|
||||
function registerDirtyViewer(service: ReturnType<typeof createBetterSidebarService>): void {
|
||||
const DirtyViewer = (viewerProps: FileViewerProps): ReactNode => {
|
||||
useEffect(() => {
|
||||
viewerProps.onToolbarState?.({ modes: true, mode: 'edit', dirty: true, editable: true, saveState: 'idle' })
|
||||
// Mount-only: this instance's draft is the report above.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
return null
|
||||
}
|
||||
service.registerFileViewer({
|
||||
id: 'test:dirty',
|
||||
exts: ['fake'],
|
||||
fetchStrategy: 'none',
|
||||
component: DirtyViewer,
|
||||
})
|
||||
}
|
||||
|
||||
describe('EditorHost (files window)', () => {
|
||||
it('a path-less tab renders the empty-state hint with the tree panel open', () => {
|
||||
const { store, ctx, homeTab } = setup()
|
||||
@@ -408,6 +427,121 @@ describe('EditorHost (files window)', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('in-place mode: switching files confirms before dropping an unsaved draft', () => {
|
||||
const { store, ctx } = setup()
|
||||
const service = ctx.betterSidebar
|
||||
registerDirtyViewer(service)
|
||||
const tabId = 'editor:/tmp/a.fake'
|
||||
service.openTab({ type: 'editor', title: 'a.fake', path: '/tmp/a.fake', id: tabId })
|
||||
const fileTab = (): SidebarTab =>
|
||||
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
||||
.find(tab => tab.id === tabId)!
|
||||
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
|
||||
const { container, unmount } = mountHost(ctx, store, fileTab)
|
||||
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
|
||||
try {
|
||||
const input = container.querySelector('input')!
|
||||
typeAndCommit(input, '/tmp/b.fake')
|
||||
// Cancelled: the tab keeps its file (and the mounted draft).
|
||||
expect(confirm).toHaveBeenCalledTimes(1)
|
||||
expect(fileTab().path).toBe('/tmp/a.fake')
|
||||
// Confirmed: the same gesture switches in place.
|
||||
confirm.mockReturnValue(true)
|
||||
typeAndCommit(input, '/tmp/b.fake')
|
||||
expect(confirm).toHaveBeenCalledTimes(2)
|
||||
expect(fileTab().path).toBe('/tmp/b.fake')
|
||||
expect(fileTab().title).toBe('b.fake')
|
||||
} finally {
|
||||
confirm.mockRestore()
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('in-place mode: re-opening the same path never asks to discard the draft', () => {
|
||||
const { store, ctx } = setup()
|
||||
registerDirtyViewer(ctx.betterSidebar)
|
||||
const tabId = 'editor:/tmp/a.fake'
|
||||
ctx.betterSidebar.openTab({ type: 'editor', title: 'a.fake', path: '/tmp/a.fake', id: tabId })
|
||||
const fileTab = (): SidebarTab =>
|
||||
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
||||
.find(tab => tab.id === tabId)!
|
||||
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
|
||||
const { container, unmount } = mountHost(ctx, store, fileTab)
|
||||
const confirm = vi.spyOn(window, 'confirm')
|
||||
try {
|
||||
typeAndCommit(container.querySelector('input')!, '/tmp/a.fake')
|
||||
// The same path is not a switch: no prompt, same tab, same file.
|
||||
expect(confirm).not.toHaveBeenCalled()
|
||||
expect(fileTab().id).toBe(tabId)
|
||||
expect(fileTab().path).toBe('/tmp/a.fake')
|
||||
} finally {
|
||||
confirm.mockRestore()
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('in-place mode: a file another native type claims never asks about the draft', () => {
|
||||
const { store, ctx } = setup()
|
||||
const service = ctx.betterSidebar
|
||||
registerDirtyViewer(service)
|
||||
const resources: string[] = []
|
||||
const claimedCtx = {
|
||||
betterSidebar: service,
|
||||
get: (name: string) => {
|
||||
if (name === 'betterSidebar') return service
|
||||
if (name === 'sidebarRightTabs') {
|
||||
return { candidates: (address: string) => address.endsWith('.drawio') ? [{ kind: 'drawio' }] : [{ kind: 'editor' }] }
|
||||
}
|
||||
if (name === 'sidebarRight') {
|
||||
return { openResource: (address: string) => { resources.push(address) } }
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
sessions: ctx.sessions,
|
||||
} as unknown as Context
|
||||
service.openTab({ type: 'editor', title: 'a.fake', path: '/tmp/a.fake', id: 'editor:/tmp/a.fake', meta: { treeOpen: false } })
|
||||
const fileTab = (): SidebarTab =>
|
||||
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
||||
.find(tab => tab.path === '/tmp/a.fake')!
|
||||
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
|
||||
const { container, unmount } = mountHost(claimedCtx, store, fileTab)
|
||||
const confirm = vi.spyOn(window, 'confirm')
|
||||
try {
|
||||
typeAndCommit(container.querySelector('input[placeholder^="File path"]')!, '/tmp/board.drawio')
|
||||
// The claiming type opens the file elsewhere; this tab keeps its draft,
|
||||
// so there is nothing to confirm.
|
||||
expect(confirm).not.toHaveBeenCalled()
|
||||
expect(resources).toHaveLength(1)
|
||||
expect(fileTab().path).toBe('/tmp/a.fake')
|
||||
} finally {
|
||||
confirm.mockRestore()
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('split mode: opening another file never asks about the source draft', () => {
|
||||
const { store, ctx } = setup()
|
||||
registerDirtyViewer(ctx.betterSidebar)
|
||||
ctx.betterSidebar.openTab({ type: 'editor', title: 'a.fake', path: '/tmp/a.fake', id: 'editor:/tmp/a.fake' })
|
||||
const fileTab = (): SidebarTab =>
|
||||
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
||||
.find(tab => tab.path === '/tmp/a.fake')!
|
||||
store.setPrefs({ ...store.getPrefs(), editorExplorer: false })
|
||||
const { container, unmount } = mountHost(ctx, store, fileTab)
|
||||
const confirm = vi.spyOn(window, 'confirm')
|
||||
try {
|
||||
typeAndCommit(container.querySelector('input[placeholder^="File path"]')!, '/tmp/b.fake')
|
||||
const tabs = allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
|
||||
// Split mode opens a per-path tab; the source tab and its draft stay put.
|
||||
expect(confirm).not.toHaveBeenCalled()
|
||||
expect(fileTab().path).toBe('/tmp/a.fake')
|
||||
expect(tabs.some(tab => tab.path === '/tmp/b.fake')).toBe(true)
|
||||
} finally {
|
||||
confirm.mockRestore()
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('in-place mode: a file another native type claims opens THAT type\'s tab, not the editor (#695)', () => {
|
||||
const { store, ctx } = setup()
|
||||
const service = ctx.betterSidebar
|
||||
|
||||
+4
-1
@@ -13,6 +13,9 @@
|
||||
*
|
||||
* `maxRetries` + `retryDelay` is Node's own remedy for exactly this, so every
|
||||
* risky cleanup goes through here instead of repeating the retry inline.
|
||||
* The same archive cleanup flaked again on 2026-10-28 under a loaded runner,
|
||||
* so the budget now covers a slower handle release than the original 10×50 ms;
|
||||
* the Windows lane still hit it once on 2026-10-29, hence the 6 s budget.
|
||||
* POSIX runs are unaffected: the first attempt succeeds and no retry happens.
|
||||
*/
|
||||
import { rmSync } from 'node:fs'
|
||||
@@ -23,5 +26,5 @@ import { rmSync } from 'node:fs'
|
||||
* @param path - file or directory to remove (missing paths are ignored).
|
||||
*/
|
||||
export function removeTree(path: string): void {
|
||||
rmSync(path, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
|
||||
rmSync(path, { recursive: true, force: true, maxRetries: 60, retryDelay: 100 })
|
||||
}
|
||||
Reference in new issue
Block a user