diff --git a/appinfo/routes.php b/appinfo/routes.php index 7495440142d..46a4df4622f 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -69,5 +69,7 @@ ['name' => 'Workspace#publicFolder', 'url' => '/public/workspace', 'verb' => 'GET'], /** @see Controller\WorkspaceController::direct() */ ['name' => 'Workspace#direct', 'url' => '/workspace/direct', 'verb' => 'POST'], + /** @see Controller\VersionsController::index() */ + ['name' => 'Versions#index', 'url' => '/versions/{fileId}', 'verb' => 'GET'], ] ]; diff --git a/composer/composer/autoload_classmap.php b/composer/composer/autoload_classmap.php index 91dc2b839a3..b3b58419e7f 100644 --- a/composer/composer/autoload_classmap.php +++ b/composer/composer/autoload_classmap.php @@ -28,6 +28,7 @@ 'OCA\\Text\\Controller\\SettingsController' => $baseDir . '/../lib/Controller/SettingsController.php', 'OCA\\Text\\Controller\\TSessionAwareController' => $baseDir . '/../lib/Controller/TSessionAwareController.php', 'OCA\\Text\\Controller\\UserApiController' => $baseDir . '/../lib/Controller/UserApiController.php', + 'OCA\\Text\\Controller\\VersionsController' => $baseDir . '/../lib/Controller/VersionsController.php', 'OCA\\Text\\Controller\\WorkspaceController' => $baseDir . '/../lib/Controller/WorkspaceController.php', 'OCA\\Text\\Cron\\Cleanup' => $baseDir . '/../lib/Cron/Cleanup.php', 'OCA\\Text\\DAV\\WorkspacePlugin' => $baseDir . '/../lib/DAV/WorkspacePlugin.php', @@ -85,6 +86,7 @@ 'OCA\\Text\\Migration\\Version090000Date20260819110024' => $baseDir . '/../lib/Migration/Version090000Date20260819110024.php', 'OCA\\Text\\Migration\\Version090000Date20260820132113' => $baseDir . '/../lib/Migration/Version090000Date20260820132113.php', 'OCA\\Text\\Migration\\Version100000Date20261011000000' => $baseDir . '/../lib/Migration/Version100000Date20261011000000.php', + 'OCA\\Text\\Model\\VersionEnd' => $baseDir . '/../lib/Model/VersionEnd.php', 'OCA\\Text\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php', 'OCA\\Text\\Service\\AiTagService' => $baseDir . '/../lib/Service/AiTagService.php', 'OCA\\Text\\Service\\ApiService' => $baseDir . '/../lib/Service/ApiService.php', @@ -97,6 +99,7 @@ 'OCA\\Text\\Service\\LockService' => $baseDir . '/../lib/Service/LockService.php', 'OCA\\Text\\Service\\NotificationService' => $baseDir . '/../lib/Service/NotificationService.php', 'OCA\\Text\\Service\\SessionService' => $baseDir . '/../lib/Service/SessionService.php', + 'OCA\\Text\\Service\\VersionAccessService' => $baseDir . '/../lib/Service/VersionAccessService.php', 'OCA\\Text\\Service\\WorkspaceService' => $baseDir . '/../lib/Service/WorkspaceService.php', 'OCA\\Text\\TextFile' => $baseDir . '/../lib/TextFile.php', 'OCA\\Text\\YjsMessage' => $baseDir . '/../lib/YjsMessage.php', diff --git a/composer/composer/autoload_static.php b/composer/composer/autoload_static.php index 0a506511f39..a1f2f79f3ab 100644 --- a/composer/composer/autoload_static.php +++ b/composer/composer/autoload_static.php @@ -43,6 +43,7 @@ class ComposerStaticInitText 'OCA\\Text\\Controller\\SettingsController' => __DIR__ . '/..' . '/../lib/Controller/SettingsController.php', 'OCA\\Text\\Controller\\TSessionAwareController' => __DIR__ . '/..' . '/../lib/Controller/TSessionAwareController.php', 'OCA\\Text\\Controller\\UserApiController' => __DIR__ . '/..' . '/../lib/Controller/UserApiController.php', + 'OCA\\Text\\Controller\\VersionsController' => __DIR__ . '/..' . '/../lib/Controller/VersionsController.php', 'OCA\\Text\\Controller\\WorkspaceController' => __DIR__ . '/..' . '/../lib/Controller/WorkspaceController.php', 'OCA\\Text\\Cron\\Cleanup' => __DIR__ . '/..' . '/../lib/Cron/Cleanup.php', 'OCA\\Text\\DAV\\WorkspacePlugin' => __DIR__ . '/..' . '/../lib/DAV/WorkspacePlugin.php', @@ -100,6 +101,7 @@ class ComposerStaticInitText 'OCA\\Text\\Migration\\Version090000Date20260819110024' => __DIR__ . '/..' . '/../lib/Migration/Version090000Date20260819110024.php', 'OCA\\Text\\Migration\\Version090000Date20260820132113' => __DIR__ . '/..' . '/../lib/Migration/Version090000Date20260820132113.php', 'OCA\\Text\\Migration\\Version100000Date20261011000000' => __DIR__ . '/..' . '/../lib/Migration/Version100000Date20261011000000.php', + 'OCA\\Text\\Model\\VersionEnd' => __DIR__ . '/..' . '/../lib/Model/VersionEnd.php', 'OCA\\Text\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php', 'OCA\\Text\\Service\\AiTagService' => __DIR__ . '/..' . '/../lib/Service/AiTagService.php', 'OCA\\Text\\Service\\ApiService' => __DIR__ . '/..' . '/../lib/Service/ApiService.php', @@ -112,6 +114,7 @@ class ComposerStaticInitText 'OCA\\Text\\Service\\LockService' => __DIR__ . '/..' . '/../lib/Service/LockService.php', 'OCA\\Text\\Service\\NotificationService' => __DIR__ . '/..' . '/../lib/Service/NotificationService.php', 'OCA\\Text\\Service\\SessionService' => __DIR__ . '/..' . '/../lib/Service/SessionService.php', + 'OCA\\Text\\Service\\VersionAccessService' => __DIR__ . '/..' . '/../lib/Service/VersionAccessService.php', 'OCA\\Text\\Service\\WorkspaceService' => __DIR__ . '/..' . '/../lib/Service/WorkspaceService.php', 'OCA\\Text\\TextFile' => __DIR__ . '/..' . '/../lib/TextFile.php', 'OCA\\Text\\YjsMessage' => __DIR__ . '/..' . '/../lib/YjsMessage.php', diff --git a/lib/Controller/VersionsController.php b/lib/Controller/VersionsController.php new file mode 100644 index 00000000000..ca1e9560834 --- /dev/null +++ b/lib/Controller/VersionsController.php @@ -0,0 +1,60 @@ +userSession->getUser(); + if ($user === null) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } + try { + $file = $this->versionAccessService->resolveFile($user, $fileId); + $versions = $this->versionAccessService->listVersions($user, $file); + } catch (NotFoundException) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } + $path = $this->rootFolder->getUserFolder($user->getUID())->getRelativePath($file->getPath()); + return new DataResponse([ + 'fileId' => $fileId, + 'path' => $path, + 'versions' => $versions, + // Without Files Versions there is only ever the current file + 'versionsAvailable' => $this->versionAccessService->hasVersions(), + ]); + } +} diff --git a/lib/Model/VersionEnd.php b/lib/Model/VersionEnd.php new file mode 100644 index 00000000000..e4cbd09782e --- /dev/null +++ b/lib/Model/VersionEnd.php @@ -0,0 +1,44 @@ + $this->id, + 'mtime' => $this->mtime, + 'size' => $this->size, + 'label' => $this->label, + 'author' => $this->authorId === null + ? null + : ['id' => $this->authorId, 'displayName' => $this->authorName ?? $this->authorId], + ]; + } +} diff --git a/lib/Service/VersionAccessService.php b/lib/Service/VersionAccessService.php new file mode 100644 index 00000000000..4140f5dee4c --- /dev/null +++ b/lib/Service/VersionAccessService.php @@ -0,0 +1,133 @@ +rootFolder->getUserFolder($user->getUID()); + $file = $userFolder->getFirstNodeById($fileId); + if (!$file instanceof File + || !$file->isReadable() + || $file->getMimetype() !== 'text/markdown' + || $this->isEndToEndEncrypted($file, $userFolder)) { + throw new NotFoundException('No comparable file ' . $fileId); + } + return $file; + } + + /** + * The current file and its retained versions, newest first. + * + * Backends list the current file as a version with the file's own + * timestamp; it becomes the end `current`. + * + * @return list + * @throws NotFoundException When the versions backend cannot find the file + */ + public function listVersions(IUser $user, File $file): array { + try { + $versions = $this->versionManager()?->getVersionsForFile($user, $file) ?? []; + } catch (BackendNotFoundException) { + // A storage that keeps no versions + $versions = []; + } + + $currentVersion = null; + $ends = []; + foreach ($versions as $version) { + if ((string)$version->getRevisionId() === (string)$file->getMTime()) { + $currentVersion = $version; + continue; + } + $ends[] = $this->end((string)$version->getRevisionId(), $version->getTimestamp(), $version->getSize(), $version); + } + usort($ends, static fn (VersionEnd $a, VersionEnd $b) => $b->mtime <=> $a->mtime); + + $current = $this->end(VersionEnd::CURRENT, $file->getMTime(), $file->getSize(), $currentVersion); + return [$current, ...$ends]; + } + + private function end(string $id, int $mtime, int|float $size, ?IVersion $metadata): VersionEnd { + $label = ''; + $authorId = null; + if ($metadata instanceof IMetadataVersion) { + $label = $metadata->getMetadataValue('label') ?? ''; + $author = $metadata->getMetadataValue('author'); + $authorId = $author === null || $author === '' ? null : $author; + } + $authorName = $authorId === null ? null : $this->userManager->getDisplayName($authorId); + return new VersionEnd($id, $mtime, $size, $label, $authorId, $authorName); + } + + /** + * Whether a folder between the file and the user folder is end-to-end + * encrypted (`isEncrypted()` means end-to-end on a folder). + */ + private function isEndToEndEncrypted(File $file, Folder $userFolder): bool { + $folder = $file->getParent(); + while (str_starts_with($folder->getPath(), $userFolder->getPath() . '/')) { + if ($folder->isEncrypted()) { + return true; + } + $folder = $folder->getParent(); + } + return false; + } + + /** + * Whether files keep versions at all + */ + public function hasVersions(): bool { + return $this->versionManager() !== null; + } + + /** + * Files Versions registers its manager only while it is enabled + */ + private function versionManager(): ?IVersionManager { + try { + $manager = $this->container->get(IVersionManager::class); + } catch (ContainerExceptionInterface) { + return null; + } + return $manager instanceof IVersionManager ? $manager : null; + } +} diff --git a/playwright/e2e/version-picker.spec.ts b/playwright/e2e/version-picker.spec.ts new file mode 100644 index 00000000000..82ed6d21493 --- /dev/null +++ b/playwright/e2e/version-picker.spec.ts @@ -0,0 +1,87 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { Page } from '@playwright/test' + +import { expect, mergeTests } from '@playwright/test' +import { test as randomUserTest } from '../support/fixtures/random-user.ts' +import { test as uploadFileTest } from '../support/fixtures/upload-file.ts' + +const test = mergeTests(randomUserTest, uploadFileTest) + +// Choose another version for one end of the open comparison +async function choose(page: Page, end: 'from' | 'to', index: number) { + await page.locator(`[data-comparison-picker="${end}"]`).getByRole('button').click() + await page.getByRole('menuitemradio').nth(index).click() +} + +const before = (page: Page) => page.getByRole('article', { name: 'Before' }) +const after = (page: Page) => page.getByRole('article', { name: 'After' }) + +test.describe('Changing the versions compared', () => { + test.use({ + fileName: 'picker.md', + fileContent: '# V3', + oldVersions: [ + [ + { content: '# V1', mtime: 1691420501 }, + { content: '# V2', mtime: 1691424242 }, + ], + { scope: 'test' }, + ], + }) + + test('changes either end in Files, side by side and in the list of changes', async ({ open, page, viewer }) => { + await open() + 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(before(page).getByRole('heading', { name: 'V1' })).toBeVisible() + + // The older end: V2 instead of V1, slow to load, and the keyboard still comes back + await page.route('**/remote.php/dav/versions/**', async (route) => { + await new Promise((resolve) => setTimeout(resolve, 2500)) + await route.continue() + }) + await choose(page, 'from', 1) + await expect(before(page).getByRole('heading', { name: 'V2' })).toBeVisible() + await expect(after(page).getByRole('heading', { name: 'V3' })).toBeVisible() + await expect(page.locator('[data-comparison-picker="from"]').getByRole('button')).toBeFocused() + await expect(page.locator('[aria-live]').filter({ hasText: 'Comparing' })).toHaveText(/^Comparing .* with the current version$/) + await page.unrouteAll({ behavior: 'wait' }) + + // The newer end can only be newer than the older one + await page.locator('[data-comparison-picker="to"]').getByRole('button').click() + await expect(page.getByRole('menuitemradio').nth(1)).toBeDisabled() + await expect(page.getByRole('menuitemradio').nth(2)).toBeDisabled() + await page.locator('[data-comparison-picker="to"]').getByRole('button').click() + + // The list of changes stays the view when the older end changes again + await page.keyboard.press('d') + await expect(page.locator('[data-comparison-select]')).toHaveCount(1) + await choose(page, 'from', 2) + await expect(page.locator('[data-comparison-select] del')).toHaveText('1') + await expect(before(page)).toHaveCount(0) + + // The newer end: V2 instead of the current file + await choose(page, 'to', 1) + await expect(page.locator('[data-comparison-select] ins')).toHaveText('2') + await expect(page.locator('[data-comparison-picker="to"]').getByRole('button')).toBeFocused() + }) + + test('fits a narrow window', async ({ open, page, viewer }) => { + await open() + const versions = await viewer.openSidebarTab('Versions') + await versions.getByRole('button').nth(2).click() + await page.getByRole('menuitem', { name: 'Compare to current version' }).click() + await page.keyboard.press('d') + await page.setViewportSize({ width: 600, height: 800 }) + + const header = page.locator('.text-comparison__header') + await expect(header.locator('[data-comparison-picker]')).toHaveCount(2) + const { scrollWidth, clientWidth } = await header.evaluate((el) => ({ scrollWidth: el.scrollWidth, clientWidth: el.clientWidth })) + expect(scrollWidth).toBeLessThanOrEqual(clientWidth) + }) +}) diff --git a/src/comparison/focus.ts b/src/comparison/focus.ts new file mode 100644 index 00000000000..1f3b92f6e4a --- /dev/null +++ b/src/comparison/focus.ts @@ -0,0 +1,63 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { ComparedEnds, End } from './versionEnds.ts' + +import { getViewer } from '@nextcloud/viewer' + +/** + * What to restore once the viewer shows the pair a picker chose: the picker + * that had the keyboard, and what to announce. The elements showing that + * pair take each part once when they mount, however long it took to load. + */ +let handover: { pair: string, focus?: End, announcement?: string } | undefined +let watchingViewer = false + +const pairOf = (ends: ComparedEnds) => `${ends.fileId}:${ends.from}:${ends.to}` + +/** + * Remember what to restore after changing the versions compared. + * + * @param ends The pair the viewer shows next. + * @param end The end whose picker had the keyboard. + * @param announcement What screen readers should hear. + */ +export function handOver(ends: ComparedEnds, end: End, announcement: string) { + if (!watchingViewer) { + watchingViewer = true + getViewer().addEventListener('close', () => { + handover = undefined + }) + } + handover = { pair: pairOf(ends), focus: end, announcement } +} + +/** + * Whether this picker takes the keyboard back, which it can do once. + * + * @param ends The pair the picker belongs to. + * @param end The end of the picker. + */ +export function takeFocus(ends: ComparedEnds, end: End): boolean { + if (handover?.pair !== pairOf(ends) || handover.focus !== end) { + return false + } + handover.focus = undefined + return true +} + +/** + * The announcement for this pair, which can be taken once. + * + * @param ends The pair shown. + */ +export function takeAnnouncement(ends: ComparedEnds): string | undefined { + if (handover?.pair !== pairOf(ends)) { + return undefined + } + const { announcement } = handover + handover.announcement = undefined + return announcement +} diff --git a/src/comparison/sharedComparison.ts b/src/comparison/sharedComparison.ts index 9824b907a7c..ab4aa987164 100644 --- a/src/comparison/sharedComparison.ts +++ b/src/comparison/sharedComparison.ts @@ -8,15 +8,37 @@ import type { Ref, ShallowRef } from 'vue' import type { ComparisonSession } from './session.ts' import axios from '@nextcloud/axios' -import { onScopeDispose, ref, shallowRef } from 'vue' +import { nextTick, onScopeDispose, ref, shallowRef } from 'vue' import { closingSaveOf } from '../helpers/closingSaves.ts' import { logger } from '../helpers/logger.ts' import { createComparisonSession } from './session.ts' +import { comparedEnds, endOf, isCurrent } from './versionEnds.ts' +import { useFileVersions } from './versions.ts' + +/** A file as it was loaded */ +interface LoadedText { + text: string + /** When the server last changed it, in seconds, if it said */ + modified?: number +} + +/** Both texts compared, as they were loaded */ +export interface ComparedTexts { + before: LoadedText + after: LoadedText +} interface SharedComparison { users: number + /** Counts loads: only the latest one fills in the comparison */ + loads: number session: ShallowRef + texts: ShallowRef + /** Path of the file, which links and images in it are relative to */ + path: Ref error: Ref + /** Whether the error is that the editor it replaces could not save */ + unsaved: Ref /** Etag of the newer file as loaded */ etag?: string } @@ -48,7 +70,7 @@ export function useSharedComparison(base: IFile, file: IFile) { comparison = undefined } if (!comparison) { - comparison = { users: 0, session: shallowRef(), error: ref(false) } + comparison = { users: 0, loads: 0, session: shallowRef(), texts: shallowRef(), path: ref(), error: ref(false), unsaved: ref(false) } comparisons.set(key, comparison) load(key, comparison, base, file) } @@ -69,7 +91,21 @@ export function useSharedComparison(base: IFile, file: IFile) { }) }) - return { session: shared.session, error: shared.error } + /** + * Load both files again, as they are now, in place of what is shown. + */ + function reload() { + const previous = shared.session.value + shared.session.value = undefined + shared.texts.value = undefined + shared.error.value = false + shared.unsaved.value = false + // Once the views showing it are gone + nextTick(() => previous?.destroy()) + load(key, shared, base, file) + } + + return { session: shared.session, texts: shared.texts, path: shared.path, error: shared.error, unsaved: shared.unsaved, reload } } /** @@ -81,25 +117,37 @@ 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 + const thisLoad = ++comparison.loads + // Nobody waits for it anymore, or a newer load replaced it + const stale = () => comparisons.get(key) !== comparison || comparison.loads !== thisLoad try { - // The editor this comparison replaces may still be saving the newer file - await closingSaveOf(file.fileid) + // The editor this comparison replaces may still be saving the newer file, + // unless that is an old version + const newer = endOf(file) + if (!newer || isCurrent(newer.id)) { + await closingSaveOf(file.fileid).catch((error) => { + comparison.unsaved.value = true + throw error + }) + } 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([ + const [before, after, path] = await Promise.all([ axios.get(base.encodedSource, options), axios.get(file.encodedSource, options), + documentPath(base, file), ]) if (stale()) { return } + const texts = { before: loaded(before), after: loaded(after) } + comparison.path.value = path + comparison.texts.value = texts comparison.etag = etagOf(after.headers.etag) - comparison.session.value = createComparisonSession(before.data, after.data, { filePath: file.path }) + comparison.session.value = createComparisonSession(texts.before.text, texts.after.text, { filePath: path }) } catch (exception) { if (stale()) { return @@ -108,3 +156,31 @@ async function load(key: string, comparison: SharedComparison, base: IFile, file comparison.error.value = true } } + +function loaded(response: { data: string, headers: Record }): LoadedText { + const modified = Date.parse(String(response.headers['last-modified'] ?? '')) + return { text: response.data, modified: Number.isNaN(modified) ? undefined : modified / 1000 } +} + +/** + * Path of the file compared, as the current file has it: the node of an old + * version has only its revision for a path. + * + * @param base The older file. + * @param file The newer file. + */ +async function documentPath(base: IFile, file: IFile): Promise { + const current = [file, base].find((node) => isCurrent(endOf(node)?.id)) + if (current) { + return current.path + } + const ends = comparedEnds(base, file) + if (ends) { + const versions = useFileVersions(ends.fileId) + await versions.load() + if (versions.path.value) { + return versions.path.value + } + } + return file.path +} diff --git a/src/comparison/versionEnds.ts b/src/comparison/versionEnds.ts new file mode 100644 index 00000000000..11984808662 --- /dev/null +++ b/src/comparison/versionEnds.ts @@ -0,0 +1,214 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { IFile } from '@nextcloud/files' + +import { getCurrentUser } from '@nextcloud/auth' +import { File, Permission } from '@nextcloud/files' +import { getCanonicalLocale } from '@nextcloud/l10n' +import { generateRemoteUrl } from '@nextcloud/router' +import { isPublicShare } from '@nextcloud/sharing/public' + +/** One end of a comparison: the older or the newer */ +export type End = 'from' | 'to' + +/** Two versions of one file, compared from the older to the newer: 'current' or the revision of a retained version */ +export interface ComparedEnds { + fileId: number + from: string + to: string +} + +/** Two versions of one file compared, with the node and the time of each end */ +export interface ComparedPair extends ComparedEnds { + /** The node the viewer shows at each end */ + nodes: Record + /** + * When each end was saved, in seconds: for the current file as the server + * sent the text compared, once loaded, as it may have been saved after its + * node was made; otherwise its node's time, which for a version is the version's + */ + saved: Record +} + +/** A version as the versions endpoint lists it */ +export interface VersionEntry { + id: string + /** Seconds since the epoch */ + mtime: number + size: number + label: string + author: { id: string, displayName: string } | null +} + +const VERSION_PATH = /\/remote\.php\/dav\/versions\/[^/]+\/versions\/(\d+)\/([^/]+)$/ +/** The id of the current file among its versions, as the server names it too */ +const CURRENT = 'current' + +/** + * Whether an end is the current file. + * + * @param id The id of the end. + */ +export function isCurrent(id: string | undefined): boolean { + return id === CURRENT +} + +/** + * Which end of which file a node of the viewer is, read from its source as + * Files and Collectives build them: a version under the versions endpoint, the + * current file under the files endpoint. + * + * @param node A node the viewer compares. + */ +export function endOf(node: IFile): { fileId: number, id: string } | undefined { + let path: string + try { + path = new URL(node.source).pathname + } catch { + return undefined + } + const version = path.match(VERSION_PATH) + if (version) { + return { fileId: Number(version[1]), id: decodeURIComponent(version[2]!) } + } + if (path.includes('/remote.php/dav/files/') && node.fileid !== undefined) { + return { fileId: node.fileid, id: CURRENT } + } + return undefined +} + +/** + * The ends of a comparison of two versions of one file, or nothing for a + * comparison of anything else, or where the versions cannot be listed: a + * public share, or nobody signed in. + * + * @param base The older file. + * @param file The newer file. + */ +export function comparedEnds(base: IFile, file: IFile): ComparedEnds | undefined { + if (getCurrentUser() === null || isPublicShare()) { + return undefined + } + const from = endOf(base) + const to = endOf(file) + if (!from || !to || from.fileId !== to.fileId || from.id === to.id) { + return undefined + } + return { fileId: from.fileId, from: from.id, to: to.id } +} + +/** + * The pair a comparison shows: nothing wherever comparedEnds() gives nothing. + * + * @param base The older file. + * @param file The newer file. + * @param loaded The texts compared, once loaded. + * @param loaded.before The older text. + * @param loaded.before.modified When the server last changed it, in seconds. + * @param loaded.after The newer text. + * @param loaded.after.modified When the server last changed it, in seconds. + */ +export function comparedPair(base: IFile, file: IFile, loaded?: { before: { modified?: number }, after: { modified?: number } }): ComparedPair | undefined { + const ends = comparedEnds(base, file) + if (!ends) { + return undefined + } + const saved = (id: string, node: IFile, modified?: number) => isCurrent(id) && modified !== undefined + ? modified + : Math.floor((node.mtime?.getTime() ?? 0) / 1000) + return { + ...ends, + nodes: { from: base, to: file }, + saved: { from: saved(ends.from, base, loaded?.before.modified), to: saved(ends.to, file, loaded?.after.modified) }, + } +} + +/** + * Whether one end is older than the other: the current file is the newest + * whatever its time, which restoring a version sets back to that version's. + * + * @param end An end. + * @param end.id Its id. + * @param end.mtime When it was saved, in seconds. + * @param other The other end. + * @param other.id Its id. + * @param other.mtime When it was saved, in seconds. + */ +export function isOlder(end: { id: string, mtime: number }, other: { id: string, mtime: number }): boolean { + if (isCurrent(end.id)) { + return false + } + return isCurrent(other.id) || end.mtime < other.mtime +} + +/** + * A node of a version, or of the current file, for the viewer to compare. + * + * @param entry The version. + * @param fileId Id of the file. + * @param path Path of the file in the user's files. + */ +export function versionNode(entry: VersionEntry, fileId: number, path: string): File { + const uid = getCurrentUser()!.uid + const common = { + id: fileId, + mime: 'text/markdown', + size: entry.size, + mtime: new Date(entry.mtime * 1000), + owner: uid, + permissions: Permission.READ, + } + if (isCurrent(entry.id)) { + return new File({ + ...common, + source: generateRemoteUrl(`dav/files/${uid}`) + path, + root: `/files/${uid}`, + }) + } + // Named after its date, as Files names a version + return new File({ + ...common, + source: generateRemoteUrl(`dav/versions/${uid}/versions/${fileId}/${entry.id}`), + root: `/versions/${uid}/versions/${fileId}`, + displayname: formatDate(entry.mtime, 'long'), + attributes: { hasPreview: false }, + }) +} + +/** + * Dates shown together, in the user's language: to the minute and without + * this year's number, with seconds where another of them falls in the same minute. + * + * @param seconds Seconds since the epoch of each. + */ +export function formatDates(seconds: readonly number[]): string[] { + const minutes = seconds.map((time) => formatDate(time)) + return seconds.map((time, index) => minutes.indexOf(minutes[index]!) === minutes.lastIndexOf(minutes[index]!) ? minutes[index]! : formatDate(time, 'seconds')) +} + +/** + * A date and time in the user's language: short, to the minute and without + * this year's number; with seconds; or long, as Files names versions. + * + * @param seconds Seconds since the epoch. + * @param style How much to show. + */ +export function formatDate(seconds: number, style: 'short' | 'seconds' | 'long' = 'short'): string { + const locale = getCanonicalLocale() + const locales = [locale, locale.split('-')[0]!] + const date = new Date(seconds * 1000) + if (style === 'long') { + return date.toLocaleString(locales, { dateStyle: 'medium', timeStyle: 'long' }) + } + return date.toLocaleString(locales, { + year: date.getFullYear() === new Date().getFullYear() ? undefined : 'numeric', + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + second: style === 'seconds' ? '2-digit' : undefined, + }) +} diff --git a/src/comparison/versions.ts b/src/comparison/versions.ts new file mode 100644 index 00000000000..1e31c02d0f2 --- /dev/null +++ b/src/comparison/versions.ts @@ -0,0 +1,118 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { Ref } from 'vue' +import type { VersionEntry } from './versionEnds.ts' + +import axios from '@nextcloud/axios' +import { generateOcsUrl } from '@nextcloud/router' +import { getViewer } from '@nextcloud/viewer' +import { ref } from 'vue' +import { logger } from '../helpers/logger.ts' + +export interface FileVersions { + /** The current file first, then the retained versions, newest first */ + versions: Ref + /** Path of the file in the user's files */ + path: Ref + failed: Ref + /** Fetch them, unless they are here; resolves once they are, or the fetch failed */ + load: () => Promise + /** Fetch them again, as they are now */ + refresh: () => Promise +} + +interface CachedVersions extends FileVersions { + /** Forget what was fetched, and what is on its way */ + invalidate: () => void +} + +const cache = new Map() +let watchingViewer = false + +/** + * The versions of a file, fetched the first time they are needed and kept + * until the viewer closes, so changing the versions compared asks only once. + * + * @param fileId Id of the file. + */ +export function useFileVersions(fileId: number): FileVersions { + if (!watchingViewer) { + watchingViewer = true + getViewer().addEventListener('close', () => cache.clear()) + } + let entry = cache.get(fileId) + if (!entry) { + entry = createFileVersions(fileId) + cache.set(fileId, entry) + } + return entry +} + +/** + * Forget the versions of a file, after it changed or a version went away; + * the pickers showing them fetch them again when opened. + * + * @param fileId Id of the file. + */ +export function invalidateFileVersions(fileId: number) { + cache.get(fileId)?.invalidate() +} + +/** + * @param fileId Id of the file. + */ +function createFileVersions(fileId: number): CachedVersions { + const versions = ref() + const path = ref() + const failed = ref(false) + /** Counts invalidations: a fetch started before one is stale */ + let generation = 0 + /** The fetch on its way */ + let pending: Promise | undefined + + function load() { + if (versions.value) { + return Promise.resolve() + } + pending ??= fetchVersions() + return pending + } + + async function fetchVersions() { + const started = generation + failed.value = false + try { + const { data } = await axios.get(generateOcsUrl('apps/text/versions/{fileId}', { fileId }), { timeout: 30_000 }) + if (started === generation) { + versions.value = data.ocs.data.versions + path.value = data.ocs.data.path + } + } catch (exception) { + if (started === generation) { + logger.error('Could not load the versions to compare', { exception }) + failed.value = true + } + } finally { + if (started === generation) { + pending = undefined + } + } + } + + function invalidate() { + generation++ + pending = undefined + versions.value = undefined + failed.value = false + } + + function refresh() { + invalidate() + return load() + } + + return { versions, path, failed, load, refresh, invalidate } +} diff --git a/src/components/ComparisonDocument.vue b/src/components/ComparisonDocument.vue index a352e4b68ed..b439f8b378b 100644 --- a/src/components/ComparisonDocument.vue +++ b/src/components/ComparisonDocument.vue @@ -9,7 +9,11 @@ :class="`text-comparison__document--${side}`" :aria-label="session.labels[side]">
-

{{ session.labels[side] }}

+

+ + {{ session.labels[side] }} + +

{{ session.legends[side] }}
@@ -53,16 +57,19 @@ onBeforeUnmount(() => props.session.attachScroller(props.side, null)) &-header { display: flex; + align-items: center; justify-content: space-between; padding: calc(2 * $g) calc(4 * $g); border-block-end: 1px solid var(--color-border); h2 { + min-inline-size: 0; margin: 0; font-size: var(--default-font-size); } span { + flex-shrink: 0; color: var(--color-text-maxcontrast); } } diff --git a/src/components/ComparisonFilter.vue b/src/components/ComparisonFilter.vue index 2eb818dbcf2..b58f190a84c 100644 --- a/src/components/ComparisonFilter.vue +++ b/src/components/ComparisonFilter.vue @@ -6,7 +6,7 @@ @@ -27,9 +27,25 @@ const hideFormatting = props.session.hideFormatting gap: var(--default-grid-baseline); color: var(--color-text-maxcontrast); + flex-shrink: 0; + min-inline-size: 0; + // The global margin of inputs would make this header taller than the other pane's input { margin: 0; } + + // One line, so a narrow pane's header keeps the other pane's height + &-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +@container (max-width: 480px) { + .text-comparison__filter { + flex-shrink: 1; + } } diff --git a/src/components/ComparisonVersionPicker.vue b/src/components/ComparisonVersionPicker.vue new file mode 100644 index 00000000000..1f8839e4136 --- /dev/null +++ b/src/components/ComparisonVersionPicker.vue @@ -0,0 +1,202 @@ + + + + + + + diff --git a/src/components/MarkdownSourceFallback.vue b/src/components/MarkdownSourceFallback.vue index 8ef2b90dc47..380c49587db 100644 --- a/src/components/MarkdownSourceFallback.vue +++ b/src/components/MarkdownSourceFallback.vue @@ -8,11 +8,19 @@

{{ t('text', 'Complete Markdown source is shown because a detailed comparison is unavailable.') }}

-

{{ t('text', 'Before') }}

+

+ + {{ t('text', 'Before') }} + +

{{ beforeContent }}
-

{{ t('text', 'After') }}

+

+ + {{ t('text', 'After') }} + +

{{ afterContent }}
diff --git a/src/components/ViewerVersionComparison.vue b/src/components/ViewerVersionComparison.vue index 8f44c711a98..875c9fa6f84 100644 --- a/src/components/ViewerVersionComparison.vue +++ b/src/components/ViewerVersionComparison.vue @@ -6,22 +6,80 @@