Frontend handle this

This commit is contained in:
shamoon
2026-02-17 00:46:45 -08:00
parent 18f3821598
commit 0e9ca57d39
3 changed files with 105 additions and 29 deletions

View File

@@ -95,6 +95,21 @@
<div class="col-md-6 col-xl-5 mb-4"> <div class="col-md-6 col-xl-5 mb-4">
<form [formGroup]='documentForm' (ngSubmit)="save()"> <form [formGroup]='documentForm' (ngSubmit)="save()">
@if (remoteUpdateDetected) {
<div class="alert alert-warning d-flex flex-column flex-md-row align-items-md-center gap-2" role="alert">
<div class="flex-fill">
<div class="fw-semibold" i18n>Document was updated.</div>
@if (remoteUpdateModified) {
<div class="small" i18n>Remote update detected at {{ remoteUpdateModified | date:'medium' }}.</div>
}
<div class="small" i18n>Saving your local edits now may overwrite remote changes.</div>
</div>
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-warning" (click)="reloadRemoteVersion()" i18n>Reload</button>
<button type="button" class="btn btn-outline-secondary" (click)="dismissRemoteUpdateWarning()" i18n>Dismiss</button>
</div>
</div>
}
<div class="btn-toolbar mb-1 border-bottom"> <div class="btn-toolbar mb-1 border-bottom">
<div class="btn-group pb-3"> <div class="btn-group pb-3">

View File

@@ -1205,17 +1205,19 @@ describe('DocumentDetailComponent', () => {
expect(errorSpy).toHaveBeenCalled() expect(errorSpy).toHaveBeenCalled()
}) })
it('should warn when open document does not match doc retrieved from backend on init', () => { it('should show remote update warning when open local draft is older than backend on init', () => {
let openModal: NgbModalRef
modalService.activeInstances.subscribe((modals) => (openModal = modals[0]))
const modalSpy = jest.spyOn(modalService, 'open') const modalSpy = jest.spyOn(modalService, 'open')
const openDoc = Object.assign({}, doc) const openDoc = Object.assign({}, doc, {
__changedFields: ['title'],
})
// simulate a document being modified elsewhere and db updated // simulate a document being modified elsewhere and db updated
doc.modified = new Date() const remoteDoc = Object.assign({}, doc, {
modified: new Date(new Date(doc.modified).getTime() + 1000),
})
jest jest
.spyOn(activatedRoute, 'paramMap', 'get') .spyOn(activatedRoute, 'paramMap', 'get')
.mockReturnValue(of(convertToParamMap({ id: 3, section: 'details' }))) .mockReturnValue(of(convertToParamMap({ id: 3, section: 'details' })))
jest.spyOn(documentService, 'get').mockReturnValueOnce(of(doc)) jest.spyOn(documentService, 'get').mockReturnValueOnce(of(remoteDoc))
jest.spyOn(openDocumentsService, 'getOpenDocument').mockReturnValue(openDoc) jest.spyOn(openDocumentsService, 'getOpenDocument').mockReturnValue(openDoc)
jest.spyOn(customFieldsService, 'listAll').mockReturnValue( jest.spyOn(customFieldsService, 'listAll').mockReturnValue(
of({ of({
@@ -1225,11 +1227,11 @@ describe('DocumentDetailComponent', () => {
}) })
) )
fixture.detectChanges() // calls ngOnInit fixture.detectChanges() // calls ngOnInit
expect(modalSpy).toHaveBeenCalledWith(ConfirmDialogComponent) expect(component.remoteUpdateDetected).toBeTruthy()
const closeSpy = jest.spyOn(openModal, 'close') expect(component.remoteUpdateModified).toEqual(
const confirmDialog = openModal.componentInstance as ConfirmDialogComponent remoteDoc.modified.toISOString()
confirmDialog.confirmClicked.next(confirmDialog) )
expect(closeSpy).toHaveBeenCalled() expect(modalSpy).not.toHaveBeenCalledWith(ConfirmDialogComponent)
}) })
it('should change preview element by render type', () => { it('should change preview element by render type', () => {

View File

@@ -1,4 +1,4 @@
import { AsyncPipe, NgTemplateOutlet } from '@angular/common' import { AsyncPipe, DatePipe, NgTemplateOutlet } from '@angular/common'
import { HttpClient, HttpResponse } from '@angular/common/http' import { HttpClient, HttpResponse } from '@angular/common/http'
import { Component, inject, OnDestroy, OnInit, ViewChild } from '@angular/core' import { Component, inject, OnDestroy, OnInit, ViewChild } from '@angular/core'
import { import {
@@ -80,6 +80,7 @@ import { TagService } from 'src/app/services/rest/tag.service'
import { UserService } from 'src/app/services/rest/user.service' import { UserService } from 'src/app/services/rest/user.service'
import { SettingsService } from 'src/app/services/settings.service' import { SettingsService } from 'src/app/services/settings.service'
import { ToastService } from 'src/app/services/toast.service' import { ToastService } from 'src/app/services/toast.service'
import { WebsocketStatusService } from 'src/app/services/websocket-status.service'
import { getFilenameFromContentDisposition } from 'src/app/utils/http' import { getFilenameFromContentDisposition } from 'src/app/utils/http'
import { ISODateAdapter } from 'src/app/utils/ngb-iso-date-adapter' import { ISODateAdapter } from 'src/app/utils/ngb-iso-date-adapter'
import * as UTIF from 'utif' import * as UTIF from 'utif'
@@ -163,6 +164,7 @@ enum ContentRenderType {
MonetaryComponent, MonetaryComponent,
UrlComponent, UrlComponent,
SuggestionsDropdownComponent, SuggestionsDropdownComponent,
DatePipe,
CustomDatePipe, CustomDatePipe,
FileSizePipe, FileSizePipe,
IfPermissionsDirective, IfPermissionsDirective,
@@ -205,6 +207,7 @@ export class DocumentDetailComponent
private componentRouterService = inject(ComponentRouterService) private componentRouterService = inject(ComponentRouterService)
private deviceDetectorService = inject(DeviceDetectorService) private deviceDetectorService = inject(DeviceDetectorService)
private savedViewService = inject(SavedViewService) private savedViewService = inject(SavedViewService)
private websocketStatusService = inject(WebsocketStatusService)
@ViewChild('inputTitle') @ViewChild('inputTitle')
titleInput: TextComponent titleInput: TextComponent
@@ -270,6 +273,8 @@ export class DocumentDetailComponent
customFields: CustomField[] customFields: CustomField[]
public downloading: boolean = false public downloading: boolean = false
remoteUpdateDetected: boolean = false
remoteUpdateModified: string | null = null
public readonly CustomFieldDataType = CustomFieldDataType public readonly CustomFieldDataType = CustomFieldDataType
@@ -432,7 +437,14 @@ export class DocumentDetailComponent
) )
} }
private loadDocument(documentId: number): void { private hasLocalEdits(doc: Document): boolean {
return (
this.openDocumentService.isDirty(doc) || !!doc.__changedFields?.length
)
}
private loadDocument(documentId: number, forceRemote: boolean = false): void {
this.dismissRemoteUpdateWarning()
this.previewUrl = this.documentsService.getPreviewUrl(documentId) this.previewUrl = this.documentsService.getPreviewUrl(documentId)
this.updatePdfSource() this.updatePdfSource()
this.http this.http
@@ -477,21 +489,28 @@ export class DocumentDetailComponent
openDocument.duplicate_documents = doc.duplicate_documents openDocument.duplicate_documents = doc.duplicate_documents
this.openDocumentService.save() this.openDocumentService.save()
} }
const useDoc = openDocument || doc let useDoc = openDocument || doc
if (openDocument) { if (openDocument && forceRemote) {
if ( Object.assign(openDocument, doc)
new Date(doc.modified) > new Date(openDocument.modified) && openDocument.__changedFields = []
!this.modalService.hasOpenModals() this.openDocumentService.setDirty(openDocument, false)
) { this.openDocumentService.save()
const modal = this.modalService.open(ConfirmDialogComponent) useDoc = openDocument
modal.componentInstance.title = $localize`Document changes detected` } else if (openDocument) {
modal.componentInstance.messageBold = $localize`The version of this document in your browser session appears older than the existing version.` if (new Date(doc.modified) > new Date(openDocument.modified)) {
modal.componentInstance.message = $localize`Saving the document here may overwrite other changes that were made. To restore the existing version, discard your changes or close the document.` if (this.hasLocalEdits(openDocument)) {
modal.componentInstance.cancelBtnClass = 'visually-hidden' this.remoteUpdateDetected = true
modal.componentInstance.btnCaption = $localize`Ok` this.remoteUpdateModified = doc.modified
modal.componentInstance.confirmClicked.subscribe(() => ? new Date(doc.modified).toISOString()
modal.close() : null
) } else {
// No local edits to preserve, so keep the tab in sync automatically.
Object.assign(openDocument, doc)
openDocument.__changedFields = []
this.openDocumentService.setDirty(openDocument, false)
this.openDocumentService.save()
useDoc = openDocument
}
} }
} else { } else {
this.openDocumentService this.openDocumentService
@@ -522,6 +541,38 @@ export class DocumentDetailComponent
}) })
} }
private handleIncomingDocumentUpdated(data: {
document_id: number
modified?: string
}): void {
if (!this.documentId || data.document_id !== this.documentId) return
if (!this.document || this.networkActive) return
if (this.openDocumentService.isDirty(this.document)) {
this.remoteUpdateDetected = true
this.remoteUpdateModified = data.modified ?? null
} else {
this.docChangeNotifier.next(this.documentId)
this.loadDocument(this.documentId, true)
this.toastService.showInfo(
$localize`Document reloaded with latest changes.`
)
}
}
dismissRemoteUpdateWarning() {
this.remoteUpdateDetected = false
this.remoteUpdateModified = null
}
reloadRemoteVersion() {
if (!this.documentId) return
this.docChangeNotifier.next(this.documentId)
this.loadDocument(this.documentId, true)
this.toastService.showInfo($localize`Document reloaded.`)
}
ngOnInit(): void { ngOnInit(): void {
this.setZoom( this.setZoom(
this.settings.get(SETTINGS_KEYS.PDF_VIEWER_ZOOM_SETTING) as PdfZoomScale this.settings.get(SETTINGS_KEYS.PDF_VIEWER_ZOOM_SETTING) as PdfZoomScale
@@ -580,6 +631,11 @@ export class DocumentDetailComponent
this.getCustomFields() this.getCustomFields()
this.websocketStatusService
.onDocumentUpdated()
.pipe(takeUntil(this.unsubscribeNotifier))
.subscribe((data) => this.handleIncomingDocumentUpdated(data))
this.route.paramMap this.route.paramMap
.pipe( .pipe(
filter( filter(
@@ -914,6 +970,7 @@ export class DocumentDetailComponent
) )
.subscribe({ .subscribe({
next: (doc) => { next: (doc) => {
this.dismissRemoteUpdateWarning()
Object.assign(this.document, doc) Object.assign(this.document, doc)
doc['permissions_form'] = { doc['permissions_form'] = {
owner: doc.owner, owner: doc.owner,
@@ -960,6 +1017,7 @@ export class DocumentDetailComponent
.pipe(first()) .pipe(first())
.subscribe({ .subscribe({
next: (docValues) => { next: (docValues) => {
this.dismissRemoteUpdateWarning()
// in case data changed while saving eg removing inbox_tags // in case data changed while saving eg removing inbox_tags
this.documentForm.patchValue(docValues) this.documentForm.patchValue(docValues)
const newValues = Object.assign({}, this.documentForm.value) const newValues = Object.assign({}, this.documentForm.value)
@@ -1039,6 +1097,7 @@ export class DocumentDetailComponent
.pipe(first()) .pipe(first())
.subscribe({ .subscribe({
next: ({ updateResult, nextDocId, closeResult }) => { next: ({ updateResult, nextDocId, closeResult }) => {
this.dismissRemoteUpdateWarning()
this.error = null this.error = null
this.networkActive = false this.networkActive = false
if (closeResult && updateResult && nextDocId) { if (closeResult && updateResult && nextDocId) {
@@ -1135,7 +1194,7 @@ export class DocumentDetailComponent
.subscribe({ .subscribe({
next: () => { next: () => {
this.toastService.showInfo( this.toastService.showInfo(
$localize`Reprocess operation for "${this.document.title}" will begin in the background. Close and re-open or reload this document after the operation has completed to see new content.` $localize`Reprocess operation for "${this.document.title}" will begin in the background.`
) )
if (modal) { if (modal) {
modal.close() modal.close()