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
15 changes: 15 additions & 0 deletions lib/Listeners/LoadViewerListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,24 @@

namespace OCA\Text\Listeners;

use OCA\Text\Service\ConfigService;
use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\IUserSession;
use OCP\Util;

/** @implements IEventListener<BeforeTemplateRenderedEvent> */
class LoadViewerListener implements IEventListener {
public function __construct(
private readonly IInitialState $initialState,
private readonly IUserSession $userSession,
private readonly ConfigService $configService,
) {
}

public function handle(Event $event): void {
if (!($event instanceof BeforeTemplateRenderedEvent)) {
return;
Expand All @@ -27,5 +37,10 @@ public function handle(Event $event): void {

// Only registers the handler: the editor loads when a text file opens
Util::addInitScript('text', 'text-viewer');
// Whether comparisons offer summaries, known without a request
$this->initialState->provideLazyInitialState(
'version_summaries',
fn () => $this->configService->isVersionSummariesAvailableFor($this->userSession->getUser()),
);
}
}
421 changes: 421 additions & 0 deletions playwright/e2e/version-summaries.spec.ts

Large diffs are not rendered by default.

74 changes: 74 additions & 0 deletions src/comparison/decode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { toHexString } from 'lib0/buffer'
import { digest } from 'lib0/hash/sha256'

/** What the comparison knows of one end beyond its text */
export interface LoadedText {
text: string
/** Hex SHA-256 of the raw bytes, as the server computes it */
sha256: string
/** Whether the bytes are valid UTF-8, the only encoding summaries take */
utf8: boolean
/** When the server last changed it, in seconds, if it said */
modified?: number
}

/**
* Read a fetched file the way a browser reads a text response: a byte order
* mark decides the encoding, then the charset of the response, then UTF-8.
*
* @param bytes The raw bytes.
* @param contentType The `Content-Type` of the response.
*/
export function decodeText(bytes: Uint8Array, contentType?: string): string {
const boms: [number[], string][] = [[[0xEF, 0xBB, 0xBF], 'utf-8'], [[0xFE, 0xFF], 'utf-16be'], [[0xFF, 0xFE], 'utf-16le']]
for (const [bom, encoding] of boms) {
if (bom.every((byte, i) => bytes[i] === byte)) {
return new TextDecoder(encoding, { ignoreBOM: true }).decode(bytes.subarray(bom.length))
}
}
const charset = contentType?.match(/charset=["']?([^;"'\s]+)/i)?.[1]
try {
return new TextDecoder(charset ?? 'utf-8', { ignoreBOM: true }).decode(bytes)
} catch {
// An unknown label
return new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes)
}
}

/**
* The text of a fetched file and what identifies it.
*
* @param buffer The raw response.
* @param headers The response headers.
*/
export function loadText(buffer: ArrayBuffer, headers: Record<string, unknown> = {}): LoadedText {
const bytes = new Uint8Array(buffer)
const lastModified = Date.parse(String(headers['last-modified'] ?? ''))
// Worked out only for a summary, which most comparisons never ask for
let sha256: string | undefined
let utf8: boolean | undefined
return {
text: decodeText(bytes, headers['content-type'] as string | undefined),
get sha256() {
sha256 ??= toHexString(digest(bytes))
return sha256
},
get utf8() {
if (utf8 === undefined) {
try {
new TextDecoder('utf-8', { fatal: true }).decode(bytes)
utf8 = true
} catch {
utf8 = false
}
}
return utf8
},
modified: Number.isNaN(lastModified) ? undefined : lastModified / 1000,
}
}
1 change: 1 addition & 0 deletions src/comparison/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ export function createComparisonSession(beforeContent: string, afterContent: str
editors,
labels,
legends,
changeCount: changes.length,
formattingCount: changes.filter(({ category }) => category === 'formatting').length,
...state,
select,
Expand Down
33 changes: 15 additions & 18 deletions src/comparison/sharedComparison.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,18 @@

import type { IFile } from '@nextcloud/files'
import type { Ref, ShallowRef } from 'vue'
import type { LoadedText } from './decode.ts'
import type { ComparisonSession } from './session.ts'

import axios from '@nextcloud/axios'
import { nextTick, onScopeDispose, ref, shallowRef } from 'vue'
import { closingSaveOf } from '../helpers/closingSaves.ts'
import { logger } from '../helpers/logger.ts'
import { loadText } from './decode.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
Expand All @@ -39,6 +34,10 @@ interface SharedComparison {
error: Ref<boolean>
/** Whether the error is that the editor it replaces could not save */
unsaved: Ref<boolean>
/** Height of the summary in one pane, which the other pane leaves free so both documents start level */
summaryHeight: Ref<number>
/** The newer document's pane side by side, which the summary spans too */
afterPane: ShallowRef<HTMLElement | undefined>
/** Etag of the newer file as loaded */
etag?: string
}
Expand Down Expand Up @@ -70,7 +69,7 @@ export function useSharedComparison(base: IFile, file: IFile) {
comparison = undefined
}
if (!comparison) {
comparison = { users: 0, loads: 0, session: shallowRef(), texts: shallowRef(), path: ref(), error: ref(false), unsaved: ref(false) }
comparison = { users: 0, loads: 0, session: shallowRef(), texts: shallowRef(), path: ref(), error: ref(false), unsaved: ref(false), summaryHeight: ref(0), afterPane: shallowRef() }
comparisons.set(key, comparison)
load(key, comparison, base, file)
}
Expand Down Expand Up @@ -105,7 +104,7 @@ export function useSharedComparison(base: IFile, file: IFile) {
load(key, shared, base, file)
}

return { session: shared.session, texts: shared.texts, path: shared.path, error: shared.error, unsaved: shared.unsaved, reload }
return { session: shared.session, texts: shared.texts, path: shared.path, error: shared.error, unsaved: shared.unsaved, summaryHeight: shared.summaryHeight, afterPane: shared.afterPane, reload }
}

/**
Expand Down Expand Up @@ -134,16 +133,19 @@ async function load(key: string, comparison: SharedComparison, base: IFile, file
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 options = { responseType: 'arraybuffer', headers: { 'Cache-Control': 'no-cache' }, timeout: 120_000 } as const
const [before, after, path] = await Promise.all([
axios.get<string>(base.encodedSource, options),
axios.get<string>(file.encodedSource, options),
axios.get<ArrayBuffer>(base.encodedSource, options),
axios.get<ArrayBuffer>(file.encodedSource, options),
documentPath(base, file),
])
if (stale()) {
return
}
const texts = { before: loaded(before), after: loaded(after) }
const texts = {
before: loadText(before.data, before.headers),
after: loadText(after.data, after.headers),
}
comparison.path.value = path
comparison.texts.value = texts
comparison.etag = etagOf(after.headers.etag)
Expand All @@ -157,11 +159,6 @@ async function load(key: string, comparison: SharedComparison, base: IFile, file
}
}

function loaded(response: { data: string, headers: Record<string, unknown> }): 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.
Expand Down
6 changes: 5 additions & 1 deletion src/comparison/versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export interface FileVersions {
versions: Ref<VersionEntry[] | undefined>
/** Path of the file in the user's files */
path: Ref<string | undefined>
/** Whether this Nextcloud keeps versions at all */
available: Ref<boolean>
failed: Ref<boolean>
/** Fetch them, unless they are here; resolves once they are, or the fetch failed */
load: () => Promise<void>
Expand Down Expand Up @@ -67,6 +69,7 @@ export function invalidateFileVersions(fileId: number) {
function createFileVersions(fileId: number): CachedVersions {
const versions = ref<VersionEntry[]>()
const path = ref<string>()
const available = ref(true)
const failed = ref(false)
/** Counts invalidations: a fetch started before one is stale */
let generation = 0
Expand All @@ -89,6 +92,7 @@ function createFileVersions(fileId: number): CachedVersions {
if (started === generation) {
versions.value = data.ocs.data.versions
path.value = data.ocs.data.path
available.value = data.ocs.data.versionsAvailable
}
} catch (exception) {
if (started === generation) {
Expand All @@ -114,5 +118,5 @@ function createFileVersions(fileId: number): CachedVersions {
return load()
}

return { versions, path, failed, load, refresh, invalidate }
return { versions, path, available, failed, load, refresh, invalidate }
}
Loading
Loading