Skip to content
Draft
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
19 changes: 19 additions & 0 deletions playwright/e2e/versions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,25 @@
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()
})
})

/**
Expand All @@ -93,9 +112,9 @@
expect(await versions.getByRole('link')).toHaveCount(3)
// the oldest version is at the end of the versions list
await versions.getByRole('link').nth(2).click()
await expect(editor.getHeading({ name: 'V1' })).toBeVisible()

Check failure on line 115 in playwright/e2e/versions.spec.ts

View workflow job for this annotation

GitHub Actions / playwright (3, 3)

[chromium] › playwright/e2e/versions.spec.ts:32:2 › Versions with close timestamps › Show up separately

2) [chromium] › playwright/e2e/versions.spec.ts:32:2 › Versions with close timestamps › Show up separately Error: expect(locator).toBeVisible() failed Locator: locator('.editor').first().getByRole('textbox').getByRole('heading', { name: 'V1' }) Expected: visible Timeout: 5000ms Error: element(s) not found Call log: - Expect "toBeVisible" locator('.editor').first().getByRole('textbox').getByRole('heading', { name: 'V1' }) with timeout 5000ms - waiting for locator('.editor').first().getByRole('textbox').getByRole('heading', { name: 'V1' }) 113 | // the oldest version is at the end of the versions list 114 | await versions.getByRole('link').nth(2).click() > 115 | await expect(editor.getHeading({ name: 'V1' })).toBeVisible() | ^ 116 | await versions.getByRole('link').nth(1).click() 117 | await expect(editor.getHeading({ name: 'V2' })).toBeVisible() 118 | // current version at checkVersions (/home/runner/actions-runner/_work/text/text/playwright/e2e/versions.spec.ts:115:50) at /home/runner/actions-runner/_work/text/text/playwright/e2e/versions.spec.ts:35:3
await versions.getByRole('link').nth(1).click()
await expect(editor.getHeading({ name: 'V2' })).toBeVisible()

Check failure on line 117 in playwright/e2e/versions.spec.ts

View workflow job for this annotation

GitHub Actions / playwright (3, 3)

[chromium] › playwright/e2e/versions.spec.ts:32:2 › Versions with close timestamps › Show up separately

2) [chromium] › playwright/e2e/versions.spec.ts:32:2 › Versions with close timestamps › Show up separately Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── Error: expect(locator).toBeVisible() failed Locator: locator('.editor').first().getByRole('textbox').getByRole('heading', { name: 'V2' }) Expected: visible Timeout: 5000ms Error: element(s) not found Call log: - Expect "toBeVisible" locator('.editor').first().getByRole('textbox').getByRole('heading', { name: 'V2' }) with timeout 5000ms - waiting for locator('.editor').first().getByRole('textbox').getByRole('heading', { name: 'V2' }) 115 | await expect(editor.getHeading({ name: 'V1' })).toBeVisible() 116 | await versions.getByRole('link').nth(1).click() > 117 | await expect(editor.getHeading({ name: 'V2' })).toBeVisible() | ^ 118 | // current version 119 | await versions.getByRole('link').nth(0).click() 120 | // https://github.com/nextcloud/viewer/issues/3052 at checkVersions (/home/runner/actions-runner/_work/text/text/playwright/e2e/versions.spec.ts:117:50) at /home/runner/actions-runner/_work/text/text/playwright/e2e/versions.spec.ts:35:3
// current version
await versions.getByRole('link').nth(0).click()
// https://github.com/nextcloud/viewer/issues/3052
Expand Down
41 changes: 35 additions & 6 deletions src/comparison/sharedComparison.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,27 @@ 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'

interface SharedComparison {
users: number
session: ShallowRef<ComparisonSession | undefined>
error: Ref<boolean>
/** Etag of the newer file as loaded */
etag?: string
}

const comparisons = new Map<string, SharedComparison>()

/**
* 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,
Expand All @@ -31,7 +41,12 @@ const comparisons = new Map<string, SharedComparison>()
*/
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)
Expand All @@ -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()
}
})
Expand All @@ -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<string>(base.encodedSource, { responseType: 'text' }),
axios.get<string>(file.encodedSource, { responseType: 'text' }),
axios.get<string>(base.encodedSource, options),
axios.get<string>(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
}
Expand Down
23 changes: 19 additions & 4 deletions src/components/CollaborativeEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
},
Expand Down Expand Up @@ -812,10 +817,20 @@ export default defineComponent({
return await this.saveService.save()
},

/**
* Save unsaved changes.
*
* @return {Promise<boolean>} 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() {
Expand Down
23 changes: 21 additions & 2 deletions src/components/SourceView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down
69 changes: 69 additions & 0 deletions src/helpers/closingSaves.ts
Original file line number Diff line number Diff line change
@@ -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<number, Promise<unknown>>()
/** 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<boolean>) {
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<unknown>) {
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<typeof setTimeout> | undefined
const late = new Promise<never>((_, 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)
}
}
Loading
Loading