feat(pdf-reader): add manual save to the top bar functionality for document edits (#1426)

Co-authored-by: Alex <25013571+alexhb1@users.noreply.github.com>
This commit is contained in:
brios
2026-05-22 15:56:23 +01:00
committed by GitHub
co-authored by Alex
parent b210265599
commit 0e76b381aa
7 changed files with 256 additions and 44 deletions
@@ -50,7 +50,8 @@ export type ReaderIconName =
| 'moon'
| 'dots-horizontal'
| 'zoom-in'
| 'zoom-out';
| 'zoom-out'
| 'save';
interface IconPath {
d: string;
@@ -290,6 +291,11 @@ const ICONS: Record<ReaderIconName, IconPath[]> = {
{d: 'M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0', type: 'path'},
{d: 'M21 21l-4.35-4.35'},
{d: 'M8 11h6'}
],
'save': [
{d: 'M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z'},
{d: 'M17 21v-8H7v8'},
{d: 'M7 3v5h8'}
]
};
@@ -5,7 +5,7 @@
}
@if (!isLoading()) {
<div class="pdf-reader-container" [class.dark]="isDarkTheme()" [class.v-hidden]="viewerMode() === 'book' && !isInitialScrollDone()">
<div class="pdf-reader-container" [class.dark]="isDarkTheme()" [class.v-hidden]="viewerMode() === 'book' && !isInitialScrollDone()" [class.footer-hidden]="!footerVisible()">
<!-- Footer trigger zone -->
<div class="footer-trigger-zone" [class.inactive]="footerVisible()" (mouseenter)="onFooterTriggerZoneEnter()"></div>
@@ -25,6 +25,18 @@
</div>
}
<div class="embed-header-actions">
<button class="embed-action-btn save-btn" [title]="'readerPdf.docViewer.saveDocument' | transloco" [attr.aria-label]="'readerPdf.docViewer.saveDocument' | transloco"
[disabled]="isSavingDocument() || isClosingReader()" [attr.aria-busy]="isSavingDocument()"
(click)="saveDocument()">
<app-reader-icon name="save" [size]="18" />
</button>
<button class="embed-action-btn close-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco" [attr.aria-label]="'readerPdf.toolbar.closePdfReader' | transloco"
[disabled]="isClosingReader()" (pointerdown)="onCloseReaderPointerDown($event)" (click)="onCloseReaderClick($event)">
<app-reader-icon name="close" [size]="18" />
</button>
</div>
<div id="embedpdf-viewer"></div>
}
@@ -563,41 +563,85 @@ $transition-fast: 150ms ease;
}
}
.embed-close-btn {
.embed-header-actions {
position: fixed;
top: 0;
right: 10px;
z-index: 11000;
color: #fff;
width: 38px;
height: $header-height;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
gap: 4px;
z-index: 11000;
pointer-events: auto;
color: #fff;
@media (width <= 1024px) {
top: env(safe-area-inset-top);
height: calc(#{$header-height} + 4px);
right: 8px;
}
}
.embed-action-btn {
background: none;
border: none;
border-left: none;
color: inherit;
cursor: pointer;
padding: 0;
transition: background $transition-fast;
padding: 7px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
display: flex;
align-items: center;
justify-content: center;
touch-action: manipulation;
-webkit-tap-highlight-color: rgb(255 255 255 / 12%);
border-radius: 0;
width: 32px;
height: 32px;
&:hover {
background: rgb(255 255 255 / 10%);
background: $hover-bg;
}
&:active {
background: rgb(255 255 255 / 16%);
&.close-btn:hover {
background: rgb(239 68 68 / 20%);
color: #ef4444;
}
&.save-btn:hover {
background: rgb(74 144 226 / 20%);
color: #4a90e2;
}
&:disabled {
opacity: 0.8;
opacity: 0.65;
cursor: default;
}
}
.pdf-reader-container:not(.dark) {
.embed-header-actions {
color: rgb(0 0 0 / 87%);
.embed-action-btn {
color: rgb(0 0 0 / 87%);
&:hover {
background: rgb(0 0 0 / 6%);
}
&.close-btn:hover {
background: rgb(239 68 68 / 15%);
color: #dc2626;
}
&.save-btn:hover {
background: rgb(74 144 226 / 15%);
color: #1d4ed8;
}
}
}
}
.doc-viewer-info {
position: fixed;
top: 48px;
@@ -653,6 +697,7 @@ $transition-fast: 150ms ease;
width: 100%;
height: 100%;
display: flex;
transition: inset 0.25s ease-out, height 0.25s ease-out;
iframe {
width: 100%;
@@ -661,6 +706,13 @@ $transition-fast: 150ms ease;
}
}
.pdf-reader-container.footer-hidden {
#embedpdf-viewer {
inset: 0;
height: 100%;
}
}
.goto-page {
display: flex;
@@ -791,6 +843,14 @@ $transition-fast: 150ms ease;
// Tablet (portrait) switches to mobile toolbar layout
@media (width <= 1024px) {
// When footer is visible on mobile/tablet, it pushes the PDF viewer
.pdf-reader-container:not(.footer-hidden) {
#embedpdf-viewer {
inset: 0 0 $footer-height;
height: calc(100% - #{$footer-height});
}
}
.pdf-header-toolbar {
height: calc(#{$header-height} + 4px + env(safe-area-inset-top));
padding: 0 8px;
@@ -803,17 +863,6 @@ $transition-fast: 150ms ease;
border-radius: 8px;
}
.embed-close-btn {
top: calc(env(safe-area-inset-top) + 2px);
right: 10px;
width: 38px;
height: $header-height;
min-width: 38px;
min-height: $header-height;
border-radius: 0;
border-left: none;
}
.desktop-actions {
display: none;
}
@@ -1,14 +1,92 @@
import {describe, it} from 'vitest';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
// NOTE(frontend-seam): Real coverage here needs seams around ngx-extended-pdf-viewer,
// reader-session lifecycle, route-driven book loading, and annotation persistence so the
// component can be tested without booting the full PDF runtime and browser document hooks.
describe.skip('PdfReaderComponent', () => {
it('needs a viewer-runtime seam to verify page, zoom, spread, and annotation flows deterministically', () => {
// TODO(seam): Cover load, navigation, and annotation persistence after wrapping the PDF viewer and reader-session integrations.
import {PdfReaderComponent} from './pdf-reader.component';
interface PdfReaderHarness {
embedPdfIframe: {contentWindow: {postMessage: ReturnType<typeof vi.fn>}} | null;
embedPdfSaveResolve?: (buffer: ArrayBuffer | null) => void;
cachedPdfBuffer: ArrayBuffer | null;
pdfBlobUrl: string | null;
authService: {getInternalAccessToken: () => string | null};
cacheStorageService: {delete: ReturnType<typeof vi.fn>};
bookId: number;
saveEmbedPdfDocument: () => Promise<boolean>;
}
function bytes(buffer: ArrayBuffer): number[] {
return Array.from(new Uint8Array(buffer));
}
function makeComponent(savedBuffer: ArrayBuffer): PdfReaderHarness {
const component = Object.create(PdfReaderComponent.prototype) as PdfReaderHarness;
component.embedPdfIframe = {
contentWindow: {
postMessage: vi.fn(() => {
setTimeout(() => component.embedPdfSaveResolve?.(savedBuffer.slice(0)));
})
}
};
component.cachedPdfBuffer = new Uint8Array([9, 9, 9]).buffer;
component.pdfBlobUrl = 'blob:old-pdf';
component.authService = {getInternalAccessToken: () => null};
component.cacheStorageService = {delete: vi.fn(() => Promise.resolve(true))};
component.bookId = 123;
return component;
}
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('PdfReaderComponent save handling', () => {
it('shares one iframe export and upload across concurrent saves', async () => {
const savedBuffer = new Uint8Array([1, 2, 3]).buffer;
const component = makeComponent(savedBuffer);
const fetchMock = vi.fn(() => Promise.resolve({ok: true} as Response));
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:saved-pdf');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
const firstSave = component.saveEmbedPdfDocument();
const secondSave = component.saveEmbedPdfDocument();
vi.advanceTimersByTime(0);
await expect(Promise.all([firstSave, secondSave])).resolves.toEqual([true, true]);
expect(component.embedPdfIframe?.contentWindow.postMessage).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(component.cacheStorageService.delete).toHaveBeenCalledTimes(1);
});
it('needs a route-and-session seam to verify startup and teardown side effects without real browser navigation', () => {
// TODO(seam): Cover session start/end and progress persistence once route/book-detail dependencies are injectable test adapters.
it('refreshes local PDF bytes and evicts the shared cache after upload succeeds', async () => {
const savedBuffer = new Uint8Array([4, 5, 6]).buffer;
const component = makeComponent(savedBuffer);
const fetchMock = vi.fn(() => Promise.resolve({ok: true} as Response));
const createObjectUrl = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:saved-pdf');
const revokeObjectUrl = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.stubGlobal('fetch', fetchMock);
const save = component.saveEmbedPdfDocument();
vi.advanceTimersByTime(0);
await expect(save).resolves.toBe(true);
expect(bytes(component.cachedPdfBuffer!)).toEqual([4, 5, 6]);
expect(component.cachedPdfBuffer).not.toBe(savedBuffer);
expect(revokeObjectUrl).toHaveBeenCalledWith('blob:old-pdf');
expect(createObjectUrl).toHaveBeenCalledTimes(1);
expect(component.pdfBlobUrl).toBe('blob:saved-pdf');
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('/api/v1/books/123/content'),
expect.objectContaining({body: expect.any(ArrayBuffer)})
);
expect(component.cacheStorageService.delete).toHaveBeenCalledWith(
expect.stringContaining('/api/v1/books/123/content')
);
});
});
@@ -118,6 +118,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private embedPdfMessageHandler?: (e: MessageEvent) => void;
private embedPdfSaveResolve?: (buffer: ArrayBuffer | null) => void;
private embedPdfSaveTimer?: ReturnType<typeof setTimeout>;
private embedPdfSavePromise?: Promise<boolean>;
private embedPdfInitTime = 0;
private pendingPdfBuffer?: ArrayBuffer;
private initTimeout?: ReturnType<typeof setTimeout>;
@@ -130,6 +131,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private docProgressReleaseTimer?: ReturnType<typeof setTimeout>;
private closeReaderPromise: Promise<void> | null = null;
readonly isClosingReader = signal(false);
readonly isSavingDocument = signal(false);
// Book mode state
private bookViewerInitialized = false;
@@ -1092,8 +1094,19 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
}
private async saveEmbedPdfDocument(): Promise<void> {
if (!this.embedPdfIframe?.contentWindow) return;
private async saveEmbedPdfDocument(): Promise<boolean> {
if (this.embedPdfSavePromise) return this.embedPdfSavePromise;
this.embedPdfSavePromise = this.performEmbedPdfSave();
try {
return await this.embedPdfSavePromise;
} finally {
this.embedPdfSavePromise = undefined;
}
}
private async performEmbedPdfSave(): Promise<boolean> {
if (!this.embedPdfIframe?.contentWindow) return false;
try {
const buffer: ArrayBuffer | null = await new Promise((resolve) => {
@@ -1113,7 +1126,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.embedPdfSaveTimer = undefined;
}
if (!buffer) return;
if (!buffer) return false;
const headers: Record<string, string> = { 'Content-Type': 'application/pdf' };
const uploadToken = this.authService.getInternalAccessToken();
@@ -1133,9 +1146,49 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
});
if (!uploadResponse.ok) {
console.error('[EmbedPDF] Upload failed:', uploadResponse.status);
return false;
}
this.updateSavedPdfCache(buffer);
await this.cacheStorageService.delete(url);
return true;
} catch (err) {
console.error('[EmbedPDF] Failed to save document:', err);
return false;
}
}
private updateSavedPdfCache(buffer: ArrayBuffer): void {
const savedBuffer = buffer.slice(0);
this.cachedPdfBuffer = savedBuffer;
this.revokePdfBlobUrl();
this.pdfBlobUrl = URL.createObjectURL(new Blob([savedBuffer], { type: 'application/pdf' }));
}
async saveDocument(): Promise<void> {
if (this.viewerMode() !== 'document' || !this.embedPdfIframe) return;
if (this.isSavingDocument()) return;
this.isSavingDocument.set(true);
try {
const saved = await this.saveEmbedPdfDocument();
this.messageService.add(saved ? {
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('readerPdf.docViewer.changesSaved') || 'Changes saved successfully.'
} : {
severity: 'error',
summary: this.t.translate('common.error'),
detail: this.t.translate('readerPdf.docViewer.saveFailed') || 'Failed to save changes.'
});
} catch (err) {
console.error('[PDF Reader] Manually saving document failed:', err);
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: this.t.translate('readerPdf.docViewer.saveFailed') || 'Failed to save changes.'
});
} finally {
this.isSavingDocument.set(false);
}
}
+15 -4
View File
@@ -167,7 +167,7 @@
border-bottom-color: #404040 !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.30) !important;
height: 38px !important;
padding-right: 64px !important;
padding-right: 96px !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
box-sizing: border-box !important;
@@ -179,6 +179,17 @@
box-shadow: 0 2px 8px rgba(0,0,0,0.10) !important;
}
[data-epdf-i="right-group"] {
position: relative !important;
right: 80px !important;
}
@media (max-width: 600px) {
[data-epdf-i="right-group"] {
display: none !important;
}
}
/* Keep viewer popups/menus visible; only hide explicit file controls. */
[data-epdf-i="open-document"],
@@ -293,9 +304,9 @@
/* ── Silence non-editable selection menus EXCEPT for navigation links ── */
/* If the menu has no user-editing tools OR navigation, hide the whole menu. */
[role="toolbar"]:not(:has([data-epdf-i*="appearance"])):not(:has([data-epdf-i*="comment"])):not(:has([data-epdf-i*="navigate"])),
[role="menu"]:not(:has([data-epdf-i*="appearance"])):not(:has([data-epdf-i*="comment"])):not(:has([data-epdf-i*="navigate"])) {
/* If the menu has no user-editing tools OR navigation OR redact, hide the whole menu. */
[role="toolbar"]:not(:has([data-epdf-i*="appearance"])):not(:has([data-epdf-i*="comment"])):not(:has([data-epdf-i*="navigate"])):not(:has([data-epdf-i*="redact"])),
[role="menu"]:not(:has([data-epdf-i*="appearance"])):not(:has([data-epdf-i*="comment"])):not(:has([data-epdf-i*="navigate"])):not(:has([data-epdf-i*="redact"])) {
display: none !important;
}
+4 -1
View File
@@ -70,6 +70,9 @@
},
"docViewer": {
"changesSavedInfo": "Edits in the Document Viewer are automatically saved to the PDF.",
"dismiss": "Dismiss"
"dismiss": "Dismiss",
"saveDocument": "Save Changes",
"changesSaved": "Changes saved successfully.",
"saveFailed": "Failed to save changes."
}
}