Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion scripts/windowStateRestore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import test from 'node:test';
const tabs = readFileSync('src/lib/stores/tabs.svelte.ts', 'utf8');
const viewer = readFileSync('src/lib/MarkdownViewer.svelte', 'utf8');
const session = readFileSync('src/lib/sessions/windowSession.svelte.ts', 'utf8');
const documentSession = readFileSync('src/lib/sessions/documentSession.svelte.ts', 'utf8');

// Session restore persists WINDOW state only: which files are open, the
// active tab, and per-tab UI (edit mode, split, scroll). Document content
Expand Down Expand Up @@ -52,7 +53,7 @@ test('startup restore reads content from disk, not from the snapshot', () => {
});

test('the discard choice reverts the tab to its last saved content', () => {
const fn = slice(viewer, 'async function canCloseTab', 'async function toggleEdit');
const fn = slice(documentSession, 'async function canCloseTab', 'return { loadMarkdown');
assert.match(fn, /tab\.rawContent = tab\.originalContent;/);
assert.match(fn, /tab\.isDirty = false;/);
});
Expand Down
61 changes: 10 additions & 51 deletions src/lib/MarkdownViewer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,15 @@ import { createDocumentSession, type LoadMarkdownOptions } from './sessions/docu
addToast(`${message}: ${String(error)}`, 'error');
},
selfWriteGraceMs: SELF_WRITE_GRACE_MS,
cancelPendingAutoSave,
askClose: (title) =>
askCustom(t('modal.youHaveUnsavedChanges', settings.language).replace('{title}', title), {
title: t('modal.unsavedChanges', settings.language),
kind: 'warning',
showSave: true,
}),
onCloseSaveNewerEdits: () => addToast(t('toast.savedNewerEdits', settings.language), 'info'),
onCloseAutoSaveFailed: () => addToast(t('toast.autoSaveFailed', settings.language), 'error'),
});

async function discardPersistedWindowState() {
Expand Down Expand Up @@ -1533,57 +1542,7 @@ import { createDocumentSession, type LoadMarkdownOptions } from './sessions/docu
}

async function canCloseTab(tabId: string): Promise<boolean> {
const tab = tabManager.tabs.find((t) => t.id === tabId);
if (!tab || (!tab.isDirty && tab.path !== '')) return true;

if (!tab.isDirty) return true;

// Silent save path: only when auto-save is on, the user did NOT ask
// for confirmation, and the tab has a real path. Untitled tabs always
// need a save dialog, which means the modal flow is the right place
// for them. We cancel the pending timer right before the manual save
// to avoid a duplicate write from a timer that fires concurrently.
if (settings.autoSave && !settings.confirmBeforeSave && tab.path !== '') {
cancelPendingAutoSave(tabId);
const success = await saveContent(tabId);
// Only allow the close if the tab is fully clean afterwards.
// `saveContent` resolves true even when post-save `isDirty=true`
// (the user typed during the await — TOCTOU) — closing here
// would silently drop those new keystrokes.
if (success && !tab.isDirty) return true;
if (success) {
// Save succeeded but the tab is dirty again — let the user
// decide via the modal whether to save again, discard, or cancel.
addToast(t('toast.savedNewerEdits', settings.language), 'info');
} else {
// Silent save failed — surface and fall through to the modal.
addToast(t('toast.autoSaveFailed', settings.language), 'error');
}
}

const response = await askCustom(t('modal.youHaveUnsavedChanges', settings.language).replace('{title}', tab.title), {
title: t('modal.unsavedChanges', settings.language),
kind: 'warning',
showSave: true,
});

// Important: do NOT cancel the pending auto-save timer before this
// modal. If the user clicks Cancel, the tab remains dirty and we
// want background auto-save to keep firing on the existing schedule.
if (response === 'cancel') return false;
if (response === 'save') {
cancelPendingAutoSave(tabId);
return await saveContent(tabId);
}

// Discard: drop pending save so we don't write what the user just
// threw away, and revert to the last saved content so the tab is
// clean — callers either close it (tab close) or keep it open for the
// window-state snapshot (window close with restore enabled).
cancelPendingAutoSave(tabId);
tab.rawContent = tab.originalContent;
tab.isDirty = false;
return true;
return documentSession.canCloseTab(tabId);
}

async function toggleEdit(silentSave = false) {
Expand Down
29 changes: 28 additions & 1 deletion src/lib/sessions/documentSession.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ type DocumentSessionOptions = {
renderRichContent: () => void;
onError: (message: string, error: unknown) => void;
selfWriteGraceMs: number;
cancelPendingAutoSave: (tabId: string) => void;
askClose: (title: string) => Promise<'save' | 'discard' | 'cancel'>;
onCloseSaveNewerEdits: () => void;
onCloseAutoSaveFailed: () => void;
};

export function createDocumentSession(options: DocumentSessionOptions) {
Expand Down Expand Up @@ -223,5 +227,28 @@ export function createDocumentSession(options: DocumentSessionOptions) {
return true;
}

return { loadMarkdown, saveContent, saveContentAs, toggleTaskCheckbox, shouldReloadExternalChange };
async function canCloseTab(tabId: string): Promise<boolean> {
const tab = tabManager.tabs.find((item) => item.id === tabId);
if (!tab || (!tab.isDirty && tab.path !== '')) return true;
if (!tab.isDirty) return true;
if (settings.autoSave && !settings.confirmBeforeSave && tab.path !== '') {
options.cancelPendingAutoSave(tabId);
const success = await saveContent(tabId);
if (success && !tab.isDirty) return true;
if (success) options.onCloseSaveNewerEdits();
else options.onCloseAutoSaveFailed();
}
const response = await options.askClose(tab.title);
if (response === 'cancel') return false;
if (response === 'save') {
options.cancelPendingAutoSave(tabId);
return saveContent(tabId);
}
options.cancelPendingAutoSave(tabId);
tab.rawContent = tab.originalContent;
tab.isDirty = false;
return true;
}

return { loadMarkdown, saveContent, saveContentAs, toggleTaskCheckbox, shouldReloadExternalChange, canCloseTab };
}
Loading