From b08c3277775e416ac1d232c11d5c9d0d96a1749b Mon Sep 17 00:00:00 2001 From: Hoang Pham Date: Wed, 4 Nov 2026 14:57:26 +0700 Subject: [PATCH] fix(comparison): compare the file as the closing editor saved it Opening a comparison from the viewer closes the editor, which saves unsaved changes on its way out. The comparison loaded the file at the same time, so it could show the file without those changes. It now waits for that save, up to 15 seconds, and shows its error when the save fails, is refused (a conflict or lost write access) or takes longer; loading again then compares the file as the server has it. Plain-text files, compared side by side in their source view, wait and fail the same way; an older version shown there does not wait, and every file shows as text, also one the browser could read as JSON. Files are served without caching rules, so the browser could also reuse an older copy of a file saved meanwhile. The comparison now asks with Cache-Control: no-cache, gives up after two minutes instead of waiting forever, and loads again when the viewer shows a newer state of the file, as after a restore. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Hoang Pham --- playwright/e2e/versions.spec.ts | 19 ++ src/comparison/sharedComparison.ts | 41 +++- src/components/CollaborativeEditor.vue | 23 ++- src/components/SourceView.vue | 23 ++- src/helpers/closingSaves.ts | 69 +++++++ src/tests/comparison/sharedComparison.spec.ts | 175 ++++++++++++++++++ .../CollaborativeEditor.saveWhenDirty.spec.ts | 36 ++++ src/tests/components/SourceView.spec.ts | 111 +++++++++++ .../components/TextViewerWrapper.spec.ts | 22 ++- .../ViewerVersionComparison.spec.ts | 24 ++- src/views/TextViewerWrapper.vue | 8 +- 11 files changed, 528 insertions(+), 23 deletions(-) create mode 100644 src/helpers/closingSaves.ts create mode 100644 src/tests/comparison/sharedComparison.spec.ts create mode 100644 src/tests/components/CollaborativeEditor.saveWhenDirty.spec.ts create mode 100644 src/tests/components/SourceView.spec.ts diff --git a/playwright/e2e/versions.spec.ts b/playwright/e2e/versions.spec.ts index 2f9d288bb29..a66f5ee27df 100644 --- a/playwright/e2e/versions.spec.ts +++ b/playwright/e2e/versions.spec.ts @@ -80,6 +80,25 @@ test.describe('Versions with distant timestamps', () => { await expect(change.locator('ins')).toHaveText('3') await expect(before).toHaveCount(0) }) + + test('Compare what was typed just before', async ({ editor, open, page, viewer }) => { + await open() + await editor.content.getByRole('heading', { name: 'V3' }).click() + await editor.press('End') + await editor.type(' draft') + // The save on closing lands only after the comparison started + await page.route('**/apps/text/session/*/save', async (route) => { + await new Promise((resolve) => setTimeout(resolve, 1500)) + await route.continue() + }) + const versions = await viewer.openSidebarTab('Versions') + await versions.getByRole('button').nth(2).click() + await page + .getByRole('menuitem', { name: 'Compare to current version' }) + .click() + + await expect(page.getByRole('article', { name: 'After' }).getByRole('heading', { name: 'V3 draft' })).toBeVisible() + }) }) /** diff --git a/src/comparison/sharedComparison.ts b/src/comparison/sharedComparison.ts index 9b80be71451..9824b907a7c 100644 --- a/src/comparison/sharedComparison.ts +++ b/src/comparison/sharedComparison.ts @@ -9,6 +9,7 @@ import type { ComparisonSession } from './session.ts' import axios from '@nextcloud/axios' import { onScopeDispose, ref, shallowRef } from 'vue' +import { closingSaveOf } from '../helpers/closingSaves.ts' import { logger } from '../helpers/logger.ts' import { createComparisonSession } from './session.ts' @@ -16,10 +17,19 @@ interface SharedComparison { users: number session: ShallowRef error: Ref + /** Etag of the newer file as loaded */ + etag?: string } const comparisons = new Map() +/** + * An etag without its quotes, as headers and file attributes write it differently. + * + * @param value The etag. + */ +const etagOf = (value: unknown) => typeof value === 'string' && value !== '' ? value.replace(/^W\//, '').replaceAll('"', '') : undefined + /** * The comparison of two files, loaded once for every element showing part of * it. The viewer shows a comparison as two elements side by side, or as one, @@ -31,7 +41,12 @@ const comparisons = new Map() */ export function useSharedComparison(base: IFile, file: IFile) { const key = `${base.source}\n${file.source}` + const etag = etagOf(file.attributes?.etag) let comparison = comparisons.get(key) + // A newer state of the file than the one loaded, as after a restore, is another comparison + if (etag !== undefined && comparison?.etag !== undefined && comparison.etag !== etag) { + comparison = undefined + } if (!comparison) { comparison = { users: 0, session: shallowRef(), error: ref(false) } comparisons.set(key, comparison) @@ -45,8 +60,10 @@ export function useSharedComparison(base: IFile, file: IFile) { // The element of the next view takes over before this one is gone, // unless the viewer closed setTimeout(() => { - if (shared.users === 0 && comparisons.get(key) === shared) { - comparisons.delete(key) + if (shared.users === 0) { + if (comparisons.get(key) === shared) { + comparisons.delete(key) + } shared.session.value?.destroy() } }) @@ -64,17 +81,29 @@ export function useSharedComparison(base: IFile, file: IFile) { * @param file The newer file. */ async function load(key: string, comparison: SharedComparison, base: IFile, file: IFile) { + // Nobody waits for it anymore + const stale = () => comparisons.get(key) !== comparison try { + // The editor this comparison replaces may still be saving the newer file + await closingSaveOf(file.fileid) + if (stale()) { + return + } + // Files are served without caching rules, so browsers may reuse an old copy + const options = { responseType: 'text', headers: { 'Cache-Control': 'no-cache' }, timeout: 120_000 } as const const [before, after] = await Promise.all([ - axios.get(base.encodedSource, { responseType: 'text' }), - axios.get(file.encodedSource, { responseType: 'text' }), + axios.get(base.encodedSource, options), + axios.get(file.encodedSource, options), ]) - // Nobody waits for it anymore - if (comparisons.get(key) !== comparison) { + if (stale()) { return } + comparison.etag = etagOf(after.headers.etag) comparison.session.value = createComparisonSession(before.data, after.data, { filePath: file.path }) } catch (exception) { + if (stale()) { + return + } logger.error('Failed to load versions for comparison', { exception }) comparison.error.value = true } diff --git a/src/components/CollaborativeEditor.vue b/src/components/CollaborativeEditor.vue index 7937d5cdff5..20c6db41bde 100644 --- a/src/components/CollaborativeEditor.vue +++ b/src/components/CollaborativeEditor.vue @@ -112,6 +112,7 @@ import { provideSyncService } from '../composables/useSyncService.ts' import { useSyntaxHighlighting } from '../composables/useSyntaxHighlighting.ts' import Autofocus from '../extensions/Autofocus.ts' import { CollaborationCaret } from '../extensions/index.js' +import { trackClosingSave } from '../helpers/closingSaves.ts' import { exposeForDebugging, removeFromDebugging } from '../helpers/debug.ts' import { logger } from '../helpers/logger.ts' import { setInitialYjsState } from '../helpers/setInitialYjsState.ts' @@ -548,8 +549,12 @@ export default defineComponent({ window.removeEventListener('afterprint', this.preparePrinting) } unsubscribe('text:keyboard:save', this.onKeyboardSave) - const timeout = new Promise((resolve) => setTimeout(resolve, 2000)) - await Promise.any([timeout, this.saveWhenDirty()]) + const save = this.saveWhenDirty() + // A comparison opened instead waits for the save itself, the editor closes after at most 2 seconds + if (this.context.type === 'file') { + trackClosingSave(this.context.id, save) + } + await Promise.any([new Promise((resolve) => setTimeout(resolve, 2000)), save]) await this.close() removeFromDebugging(this) }, @@ -812,10 +817,20 @@ export default defineComponent({ return await this.saveService.save() }, + /** + * Save unsaved changes. + * + * @return {Promise} Whether the file holds what the editor shows; rejects when the save request fails + */ async saveWhenDirty() { - if (this.dirty && !this.hasOutdatedDocument && !this.hasSyncCollision) { - await this.save() + if (!this.dirty) { + return true + } + if (this.hasOutdatedDocument || this.hasSyncCollision) { + return false } + // The save service resolves without `true` when the server refused or deferred the save + return (await this.save()) === true }, async disconnect() { diff --git a/src/components/SourceView.vue b/src/components/SourceView.vue index e26acc5c483..3213de76182 100644 --- a/src/components/SourceView.vue +++ b/src/components/SourceView.vue @@ -35,6 +35,8 @@ import NcButton from '@nextcloud/vue/components/NcButton' import PencilOutlineIcon from 'vue-material-design-icons/PencilOutline.vue' import MarkdownContentEditor from './Editor/MarkdownContentEditor.vue' import PlainTextReader from './PlainTextReader.vue' +import { closingSaveOf } from '../helpers/closingSaves.ts' +import { logger } from '../helpers/logger.ts' export default defineComponent({ name: 'SourceView', @@ -71,9 +73,15 @@ export default defineComponent({ type: Boolean, default: false, }, + + /** Shows the file without waiting for an editor this view replaces to save it */ + skipClosingSave: { + type: Boolean, + default: false, + }, }, - emits: ['edit', 'loaded'], + emits: ['edit', 'loaded', 'errored'], data() { return { @@ -109,7 +117,18 @@ export default defineComponent({ this.content = await this.fetchDecryptedContent() this.contentLoaded = true } else { - const response = await axios.get(this.source) + // The editor this view replaces may still be saving the file + try { + if (!this.skipClosingSave) { + await closingSaveOf(this.fileid) + } + } catch (error) { + logger.warn('The closing editor did not save', { error }) + this.$emit('errored', new Error(t('text', 'The latest edits could not be saved before comparing. Try again to compare the file as it is stored.'))) + return + } + // Files are served without caching rules, so browsers may reuse an old copy + const response = await axios.get(this.source, { responseType: 'text', headers: { 'Cache-Control': 'no-cache' } }) this.content = response.data this.contentLoaded = true } diff --git a/src/helpers/closingSaves.ts b/src/helpers/closingSaves.ts new file mode 100644 index 00000000000..b671dae2b80 --- /dev/null +++ b/src/helpers/closingSaves.ts @@ -0,0 +1,69 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +/** Saves of editors that are closing, by file id */ +const saves = new Map>() +/** How long a comparison waits for such a save before it shows its error */ +const SAVE_WAIT_MS = 15_000 + +/** + * Remember the save of a closing editor until it ends. A failed save is kept a + * while longer, so the comparison opened instead shows its error. + * + * @param fileId The file the editor saves. + * @param closing The save: whether the file holds what the editor showed. + */ +export function trackClosingSave(fileId: number, closing: Promise) { + const own = closing.then((saved) => { + if (!saved) { + throw new Error('The closing editor could not save the file') + } + }) + // Another editor on the file may still be saving too + const earlier = saves.get(fileId) + const save = earlier ? Promise.all([earlier, own]) : own + saves.set(fileId, save) + save.then(() => forget(fileId, save), () => setTimeout(() => forget(fileId, save), SAVE_WAIT_MS)) +} + +/** + * Forget a save, unless a newer one replaced it. + * + * @param fileId The file. + * @param save The save. + */ +function forget(fileId: number, save: Promise) { + if (saves.get(fileId) === save) { + saves.delete(fileId) + } +} + +/** + * Wait until an editor closing on the file has saved it. Opening a view can + * close the editor it replaces only after the view started, so the check + * waits for that first. Rejects when the save fails or takes too long. + * + * @param fileId The file. + */ +export async function closingSaveOf(fileId: number | undefined) { + await new Promise((resolve) => setTimeout(resolve)) + const save = fileId === undefined ? undefined : saves.get(fileId) + if (!save) { + return + } + let timer: ReturnType | undefined + const late = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('The closing editor did not save in time')), SAVE_WAIT_MS) + }) + try { + await Promise.race([save, late]) + } catch (error) { + // Shown once, by every view opened together: loading again compares the file as the server has it + setTimeout(() => forget(fileId!, save)) + throw error + } finally { + clearTimeout(timer) + } +} diff --git a/src/tests/comparison/sharedComparison.spec.ts b/src/tests/comparison/sharedComparison.spec.ts new file mode 100644 index 00000000000..7cd3fc7a591 --- /dev/null +++ b/src/tests/comparison/sharedComparison.spec.ts @@ -0,0 +1,175 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { IFile } from '@nextcloud/files' + +import axios from '@nextcloud/axios' +import { flushPromises } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { effectScope } from 'vue' +import { useSharedComparison } from '../../comparison/sharedComparison.ts' +import { trackClosingSave } from '../../helpers/closingSaves.ts' + +vi.mock('../../comparison/session.ts', () => ({ + createComparisonSession: vi.fn((before: string, after: string) => ({ before, after, destroy: vi.fn() })), +})) + +const base = { source: 'https://cloud.example/v/1', encodedSource: 'https://cloud.example/v/1', path: '/plan.md' } as unknown as IFile +const file = { source: 'https://cloud.example/f/plan.md', encodedSource: 'https://cloud.example/f/plan.md', path: '/plan.md' } as unknown as IFile + +// Let a load that just started fetch both files and compare them +async function settle() { + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() +} + +afterEach(() => { + vi.restoreAllMocks() + // Also when a test failed before undoing them + vi.useRealTimers() +}) + +describe('useSharedComparison', () => { + it('loads a file again once the viewer shows a newer state of it', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('text').buffer, headers: { etag: '"before-restore"' } }) + const current = (etag: string) => ({ ...file, fileid: 13, attributes: { etag } }) as unknown as IFile + const scope = effectScope() + scope.run(() => useSharedComparison(base, current('before-restore'))) + await settle() + // Restoring a version from the sidebar swaps in the file at its new etag + scope.run(() => useSharedComparison(base, current('after-restore'))) + await settle() + + expect(get).toHaveBeenCalledTimes(4) + scope.stop() + }) + + it('keeps what it loaded when the viewer shows the state of the file it loaded', async () => { + // The editor the comparison replaces saved the file, so the viewer shows it at its new etag + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('text').buffer, headers: { etag: '"after-save"' } }) + const current = (etag: string) => ({ ...file, source: 'https://cloud.example/f/saved.md', encodedSource: 'https://cloud.example/f/saved.md', fileid: 14, attributes: { etag } }) as unknown as IFile + const scope = effectScope() + scope.run(() => useSharedComparison(base, current('"before-save"'))) + await settle() + scope.run(() => useSharedComparison(base, current('"after-save"'))) + await settle() + + expect(get).toHaveBeenCalledTimes(2) + scope.stop() + }) + + it('gives a slow download time, as a long file on a slow link takes', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('text').buffer, headers: {} }) + const scope = effectScope() + scope.run(() => useSharedComparison(base, { ...file, source: 'https://cloud.example/f/slow.md', encodedSource: 'https://cloud.example/f/slow.md' } as unknown as IFile)) + await settle() + + expect(get).toHaveBeenCalledWith('https://cloud.example/f/slow.md', expect.objectContaining({ timeout: 120_000 })) + scope.stop() + }) + + it('loads the newer file once the editor it replaces has saved it', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'saved', headers: {} }) + const edited = { ...file, source: 'https://cloud.example/f/edited.md', encodedSource: 'https://cloud.example/f/edited.md', fileid: 7 } as unknown as IFile + let saved!: () => void + const scope = effectScope() + const comparison = scope.run(() => useSharedComparison(base, edited))! + // The viewer closes the editor after the comparison started + trackClosingSave(7, new Promise((resolve) => { + saved = () => resolve(true) + })) + await settle() + expect(get).not.toHaveBeenCalled() + + saved() + await flushPromises() + // Files come without caching rules: a stale copy would not show the save + expect(get).toHaveBeenCalledWith(edited.encodedSource, expect.objectContaining({ headers: { 'Cache-Control': 'no-cache' } })) + expect(comparison.session.value).toMatchObject({ after: 'saved' }) + scope.stop() + }) + + it('waits for every editor closing on the newer file', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: new TextEncoder().encode('saved').buffer, headers: {} }) + const edited = { ...file, source: 'https://cloud.example/f/twice.md', encodedSource: 'https://cloud.example/f/twice.md', fileid: 13 } as unknown as IFile + let saved!: () => void + const scope = effectScope() + scope.run(() => useSharedComparison(base, edited)) + // One editor still saves while another one on the same file closes without changes + trackClosingSave(13, new Promise((resolve) => { + saved = () => resolve(true) + })) + trackClosingSave(13, Promise.resolve(true)) + await settle() + expect(get).not.toHaveBeenCalled() + + saved() + await settle() + expect(get).toHaveBeenCalledWith(edited.encodedSource, expect.anything()) + scope.stop() + }) + + it('shows its error when the editor it replaces could not save', async () => { + const get = vi.spyOn(axios, 'get') + const edited = { ...file, source: 'https://cloud.example/f/failed.md', encodedSource: 'https://cloud.example/f/failed.md', fileid: 9 } as unknown as IFile + trackClosingSave(9, Promise.reject(new Error('Request failed with status code 500'))) + await flushPromises() + const scope = effectScope() + const comparison = scope.run(() => useSharedComparison(base, edited))! + await settle() + + expect(comparison.error.value).toBe(true) + expect(get).not.toHaveBeenCalled() + scope.stop() + }) + + it('shows its error when the save of the editor it replaces did not reach the file', async () => { + const get = vi.spyOn(axios, 'get') + const edited = { ...file, source: 'https://cloud.example/f/refused.md', encodedSource: 'https://cloud.example/f/refused.md', fileid: 10 } as unknown as IFile + // A save the server refused, as after a conflict or a lost write permission + trackClosingSave(10, Promise.resolve(false)) + const scope = effectScope() + const comparison = scope.run(() => useSharedComparison(base, edited))! + await settle() + + expect(comparison.error.value).toBe(true) + expect(get).not.toHaveBeenCalled() + scope.stop() + }) + + it('loads the file as the server has it once it showed that the closing save failed', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'server', headers: {} }) + const edited = { ...file, source: 'https://cloud.example/f/again.md', encodedSource: 'https://cloud.example/f/again.md', fileid: 11 } as unknown as IFile + trackClosingSave(11, Promise.resolve(false)) + const scope = effectScope() + const failed = scope.run(() => useSharedComparison(base, edited))! + await settle() + expect(failed.error.value).toBe(true) + + // Another comparison of the file, as when it is opened again + const other = { ...base, source: 'https://cloud.example/v/2', encodedSource: 'https://cloud.example/v/2' } as unknown as IFile + const again = scope.run(() => useSharedComparison(other, edited))! + await settle() + + expect(again.error.value).toBe(false) + expect(get).toHaveBeenCalledTimes(2) + scope.stop() + }) + + it('shows its error when the editor it replaces does not save in time', async () => { + vi.useFakeTimers() + const get = vi.spyOn(axios, 'get') + const edited = { ...file, source: 'https://cloud.example/f/stuck.md', encodedSource: 'https://cloud.example/f/stuck.md', fileid: 8 } as unknown as IFile + const scope = effectScope() + const comparison = scope.run(() => useSharedComparison(base, edited))! + trackClosingSave(8, new Promise(() => {})) + + await vi.advanceTimersByTimeAsync(15_000) + + expect(comparison.error.value).toBe(true) + expect(get).not.toHaveBeenCalled() + scope.stop() + }) +}) diff --git a/src/tests/components/CollaborativeEditor.saveWhenDirty.spec.ts b/src/tests/components/CollaborativeEditor.saveWhenDirty.spec.ts new file mode 100644 index 00000000000..5e1e5be2034 --- /dev/null +++ b/src/tests/components/CollaborativeEditor.saveWhenDirty.spec.ts @@ -0,0 +1,36 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { describe, expect, it } from 'vitest' +import CollaborativeEditor from '../../components/CollaborativeEditor.vue' + +const saveWhenDirty = (CollaborativeEditor as { methods: { saveWhenDirty: (this: object) => Promise } }).methods.saveWhenDirty + +function editor(dirty: boolean, saved: boolean | undefined, conflict = false) { + return { dirty, hasOutdatedDocument: false, hasSyncCollision: conflict, save: async () => saved } +} + +describe('CollaborativeEditor saveWhenDirty', () => { + it('says the file holds the content when there is nothing to save', async () => { + expect(await saveWhenDirty.call(editor(false, undefined))).toBe(true) + }) + + it('says the file holds the content once the save went through', async () => { + expect(await saveWhenDirty.call(editor(true, true))).toBe(true) + }) + + it('says the content did not reach the file when the server refused the save', async () => { + // SaveService resolves without a result after a 403 or a 409 + expect(await saveWhenDirty.call(editor(true, undefined))).toBe(false) + }) + + it('says the content did not reach the file when a conflict keeps it from saving', async () => { + expect(await saveWhenDirty.call(editor(true, true, true))).toBe(false) + }) + + it('says the content did not reach the file when the server deferred the save', async () => { + expect(await saveWhenDirty.call(editor(true, false))).toBe(false) + }) +}) diff --git a/src/tests/components/SourceView.spec.ts b/src/tests/components/SourceView.spec.ts new file mode 100644 index 00000000000..6bba7aeab51 --- /dev/null +++ b/src/tests/components/SourceView.spec.ts @@ -0,0 +1,111 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import SourceView from '../../components/SourceView.vue' +import { trackClosingSave } from '../../helpers/closingSaves.ts' + +const source = 'https://cloud.example/remote.php/dav/files/alice/notes.txt' + +function mountSource(fileid: number, props: Record = {}) { + return mount(SourceView, { + props: { filename: '/notes.txt', fileid, source, mime: 'text/plain', ...props }, + global: { provide: { isEmbedded: false }, stubs: { PlainTextReader: true, MarkdownContentEditor: true } }, + }) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('SourceView', () => { + it('shows a plain text file as the editor closing on it saved it', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'saved' }) + let saved!: (done: boolean) => void + const wrapper = mountSource(21) + // The viewer closes the editor after the view started + trackClosingSave(21, new Promise((resolve) => { + saved = resolve + })) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + expect(get).not.toHaveBeenCalled() + + saved(true) + await flushPromises() + + // Files come without caching rules: a cached copy would miss the save + expect(get).toHaveBeenCalledWith(source, expect.objectContaining({ headers: { 'Cache-Control': 'no-cache' } })) + wrapper.unmount() + }) + + it('shows a file at once where it need not wait for an editor saving it', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'old' }) + trackClosingSave(23, Promise.resolve(false)) + const version = mountSource(23, { skipClosingSave: true }) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + expect(get).toHaveBeenCalledOnce() + expect(version.emitted('loaded')).toEqual([[true]]) + version.unmount() + + // The failed save is still told to what shows the current file + const current = mountSource(23) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + expect(current.emitted('errored')).toEqual([[expect.any(Error)]]) + current.unmount() + }) + + it('shows a file as text, also one the browser could read as JSON', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: '{"a":1}' }) + const wrapper = mountSource(24, { mime: 'application/json' }) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + + expect(get).toHaveBeenCalledWith(source, expect.objectContaining({ responseType: 'text' })) + wrapper.unmount() + }) + + it('shows an error instead of the stored file when the closing save failed', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'server' }) + trackClosingSave(22, Promise.resolve(false)) + const failed = mountSource(22) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + + expect(get).not.toHaveBeenCalled() + expect(failed.emitted('loaded')).toBeUndefined() + expect(failed.emitted('errored')).toEqual([[expect.any(Error)]]) + failed.unmount() + + // Opened again, it shows the file as the server has it + const again = mountSource(22) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + expect(get).toHaveBeenCalledOnce() + expect(again.emitted('loaded')).toEqual([[true]]) + again.unmount() + }) + + it('shows a closing save that failed at once in both panes side by side', async () => { + const get = vi.spyOn(axios, 'get').mockResolvedValue({ data: 'server' }) + const before = mountSource(25) + const after = mountSource(25) + // The viewer closes the editor after the view started; it could not save at all + trackClosingSave(25, Promise.resolve(false)) + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() + + // A pane that loaded would clear the other's error in the viewer + expect(get).not.toHaveBeenCalled() + expect(before.emitted('errored')).toEqual([[expect.any(Error)]]) + expect(after.emitted('errored')).toEqual([[expect.any(Error)]]) + before.unmount() + after.unmount() + }) +}) diff --git a/src/tests/components/TextViewerWrapper.spec.ts b/src/tests/components/TextViewerWrapper.spec.ts index 1fba22b93fc..512da9f932a 100644 --- a/src/tests/components/TextViewerWrapper.spec.ts +++ b/src/tests/components/TextViewerWrapper.spec.ts @@ -15,7 +15,7 @@ const saveWhenDirty = vi.hoisted(() => vi.fn(async () => {})) vi.mock('../../components/ViewerComponent.vue', () => ({ default: defineComponent({ name: 'ViewerComponent', - props: ['filename', 'fileid', 'forceSource', 'mime', 'source', 'e2EeIsEncrypted', 'active', 'onLoadedHandler'], + props: ['filename', 'fileid', 'forceSource', 'mime', 'source', 'e2EeIsEncrypted', 'skipClosingSave', 'active', 'onLoadedHandler'], methods: { saveWhenDirty }, template: '
', }), @@ -72,6 +72,8 @@ describe('the text viewer wrapper', () => { expect(editor.props('forceSource')).toBe(true) expect(editor.props('fileid')).toBe(42) expect(editor.props('source')).toBe(version.encodedSource) + // Alone, it does not wait for an editor saving the file + expect(editor.props('skipClosingSave')).toBe(true) }) // A download from the viewer would otherwise get the last saved version @@ -133,6 +135,15 @@ describe('the text viewer wrapper', () => { expect(wrapper.emitted('loaded')).toHaveLength(1) }) + it('reports an error of the file it shows to the viewer', () => { + const wrapper = mount(TextViewerWrapper, { props: { file: makeFile(undefined, undefined, 'text/plain'), comparison: 'side-by-side' } }) + const error = new Error('The latest edits could not be saved') + + wrapper.findComponent({ name: 'ViewerComponent' }).vm.$emit('errored', error) + + expect(wrapper.emitted('errored')).toEqual([[error]]) + }) + it('shows plain text side by side, only read', () => { const version = makeVersion('text/plain') const file = makeFile(undefined, undefined, 'text/plain') @@ -144,4 +155,13 @@ describe('the text viewer wrapper', () => { expect(editor.props('fileid')).toBe(42) expect(editor.props('source')).toBe(currentSource) }) + + it('lets an older version side by side wait for the editor saving the file, as the other side does', () => { + const version = makeVersion('text/plain') + const file = makeFile(undefined, undefined, 'text/plain') + const editor = mount(TextViewerWrapper, { props: { file: version, files: [version, file], comparison: 'side-by-side' } }).findComponent({ name: 'ViewerComponent' }) + + // Both sides then show a failed save, which the viewer would otherwise clear once the other side loaded + expect(editor.props('skipClosingSave')).toBe(false) + }) }) diff --git a/src/tests/components/ViewerVersionComparison.spec.ts b/src/tests/components/ViewerVersionComparison.spec.ts index 2f8d1f2d708..9cf1457a0e5 100644 --- a/src/tests/components/ViewerVersionComparison.spec.ts +++ b/src/tests/components/ViewerVersionComparison.spec.ts @@ -40,13 +40,19 @@ function mountPart(part: 'before' | 'after' | 'changes') { return mount(ViewerVersionComparison, { props: { base, file, part }, attachTo: document.body }) } +// Mounted parts load both files after a moment, waiting for an editor the comparison replaces +async function loaded() { + await new Promise((resolve) => setTimeout(resolve)) + await flushPromises() +} + // The comparison editors are heavy to import; load them once so no test pays for it. beforeAll(() => import('../../comparison/session.ts'), 30_000) let get: MockInstance beforeEach(() => { - get = vi.spyOn(axios, 'get').mockImplementation(async (url: string) => ({ data: contents[url] })) + get = vi.spyOn(axios, 'get').mockImplementation(async (url: string) => ({ data: contents[url], headers: {} })) }) afterEach(async () => { @@ -59,7 +65,7 @@ describe('ViewerVersionComparison', () => { it('loads both files once for both documents side by side', async () => { const before = mountPart('before') const after = mountPart('after') - await flushPromises() + await loaded() expect(get.mock.calls.map(([url]) => url)).toEqual([baseSource, fileSource]) expect(before.find('.text-comparison__document--before').text()).toContain('Old title') @@ -74,7 +80,7 @@ describe('ViewerVersionComparison', () => { it('splits the header: the filter on the left, the navigation on the right', async () => { const before = mountPart('before') const after = mountPart('after') - await flushPromises() + await loaded() expect(before.find('.text-comparison__filter').exists()).toBe(true) expect(before.find('.text-comparison__navigation').exists()).toBe(false) @@ -87,7 +93,7 @@ describe('ViewerVersionComparison', () => { it('lists the changes with the filter, and makes a picked one current', async () => { const changes = mountPart('changes') - await flushPromises() + await loaded() expect(changes.find('.text-comparison__filter').exists()).toBe(true) const rows = changes.findAll('[data-comparison-select]') @@ -102,13 +108,13 @@ describe('ViewerVersionComparison', () => { it('keeps the current change when the view changes', async () => { const changes = mountPart('changes') - await flushPromises() + await loaded() await changes.findAll('[data-comparison-select]')[1]!.trigger('click') // The viewer mounts the next view before it lets go of the previous one const after = mountPart('after') changes.unmount() - await flushPromises() + await loaded() expect(get).toHaveBeenCalledTimes(2) expect(after.find('.text-comparison__navigation').text()).toContain('Change 2 of 2') @@ -118,11 +124,11 @@ describe('ViewerVersionComparison', () => { it('loads the files again once every part is gone', async () => { mountPart('changes').unmount() - await flushPromises() + await loaded() await new Promise((resolve) => setTimeout(resolve)) const again = mountPart('changes') - await flushPromises() + await loaded() expect(get).toHaveBeenCalledTimes(4) again.unmount() @@ -132,7 +138,7 @@ describe('ViewerVersionComparison', () => { const error = vi.spyOn(logger, 'error').mockImplementation(() => {}) get.mockRejectedValue(new Error('offline')) const before = mountPart('before') - await flushPromises() + await loaded() expect(error).toHaveBeenCalledWith('Failed to load versions for comparison', expect.anything()) expect(before.emitted('loaded')).toHaveLength(1) diff --git a/src/views/TextViewerWrapper.vue b/src/views/TextViewerWrapper.vue index 04f7daf7cd7..6d245eee9df 100644 --- a/src/views/TextViewerWrapper.vue +++ b/src/views/TextViewerWrapper.vue @@ -24,6 +24,7 @@ const props = defineProps<{ const emit = defineEmits<{ loaded: [] + errored: [error: Error] 'update:canSwipe': [canSwipe: boolean] 'update:file': [file: IFile] // 'update:comparison': [comparison: 'side-by-side' | 'differences'] @@ -36,6 +37,9 @@ const isEncrypted = computed(() => Boolean(props.file.attributes?.['e2ee-is-encr const isVersion = computed(() => props.file.root?.startsWith('/versions/') ?? false) // Side by side, the current file is only read too, like the version next to it const forceSource = computed(() => isVersion.value || props.comparison === 'side-by-side') +// No editor saves an older version shown alone; side by side it waits with the +// current file, so both show a failed save, which the viewer clears once either loads +const skipClosingSave = computed(() => isVersion.value && props.comparison === undefined) const isMarkdown = (file: IFile) => openMimetypesMarkdown.includes(file.mime ?? '') @@ -92,8 +96,10 @@ useHost()?.addEventListener('before-download', (event) => { :mime="file.mime" :source="file.encodedSource" :e2EeIsEncrypted="isEncrypted" + :skipClosingSave active - :onLoadedHandler="() => emit('loaded')" /> + :onLoadedHandler="() => emit('loaded')" + @errored="(error: Error) => emit('errored', error)" />