|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright (c) 2000 - 2026 Vaadin Ltd. |
| 4 | + * |
| 5 | + * This program is available under Vaadin Commercial License and Service Terms. |
| 6 | + * |
| 7 | + * |
| 8 | + * See https://vaadin.com/commercial-license-and-service-terms for the full |
| 9 | + * license. |
| 10 | + */ |
| 11 | +import { issueWarning } from '@vaadin/component-base/src/warnings.js'; |
| 12 | +import { acquireWorker, loadPdfjs, releaseWorker } from './pdfjs-loader.js'; |
| 13 | + |
| 14 | +/** |
| 15 | + * Maps a pdf.js loading error to the `reason` reported in the `document-error` |
| 16 | + * event. Any failure other than a password or an invalid file is reported as |
| 17 | + * `network`, since the file could not be fetched or read. |
| 18 | + * @param {Error} error |
| 19 | + * @return {'invalid' | 'network' | 'password'} |
| 20 | + */ |
| 21 | +function getErrorReason(error) { |
| 22 | + if (error && error.name === 'PasswordException') { |
| 23 | + return 'password'; |
| 24 | + } |
| 25 | + if (error && error.name === 'InvalidPDFException') { |
| 26 | + return 'invalid'; |
| 27 | + } |
| 28 | + return 'network'; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * @typedef {Object} PdfViewerDocumentCallbacks |
| 33 | + * @property {() => void} onLoadStart Called when loading starts. |
| 34 | + * @property {(pdfDocument: import('pdfjs-dist').PDFDocumentProxy, title: string) => void} onLoad |
| 35 | + * Called when the document has loaded, with the title from its metadata. |
| 36 | + * @property {(error: unknown, reason: 'invalid' | 'network' | 'password') => void} onError |
| 37 | + * Called when the document could not be loaded. |
| 38 | + * @property {() => void} onUnload Called when the document or the load in progress is dropped. |
| 39 | + */ |
| 40 | + |
| 41 | +/** |
| 42 | + * A controller that loads the document of the host's `src` with pdf.js, and |
| 43 | + * releases it while the host is detached. |
| 44 | + */ |
| 45 | +export class PdfViewerDocumentController { |
| 46 | + /** @type {HTMLElement & { src: string | null | undefined }} */ |
| 47 | + #host; |
| 48 | + |
| 49 | + /** @type {PdfViewerDocumentCallbacks} */ |
| 50 | + #callbacks; |
| 51 | + |
| 52 | + /** @type {import('pdfjs-dist').PDFDocumentLoadingTask | null} */ |
| 53 | + #loadingTask = null; |
| 54 | + |
| 55 | + /** @type {ReturnType<typeof acquireWorker> | null} */ |
| 56 | + #workerHandle = null; |
| 57 | + |
| 58 | + /** Incremented on every load, to detect results that belong to an outdated load. */ |
| 59 | + #loadId = 0; |
| 60 | + |
| 61 | + /** Set when the document is not loaded because the host is detached, to load it on attach. */ |
| 62 | + #released = false; |
| 63 | + |
| 64 | + /** |
| 65 | + * @param {HTMLElement & { src: string | null | undefined }} host |
| 66 | + * @param {PdfViewerDocumentCallbacks} callbacks |
| 67 | + */ |
| 68 | + constructor(host, callbacks) { |
| 69 | + this.#host = host; |
| 70 | + this.#callbacks = callbacks; |
| 71 | + } |
| 72 | + |
| 73 | + hostConnected() { |
| 74 | + if (this.#released) { |
| 75 | + this.#released = false; |
| 76 | + this.load(); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + hostDisconnected() { |
| 81 | + // Wait a microtask so that moving the host in the DOM does not reload the document. |
| 82 | + queueMicrotask(() => { |
| 83 | + if (!this.#host.isConnected && this.#host.src && !this.#released) { |
| 84 | + this.#loadId += 1; |
| 85 | + this.#unload(); |
| 86 | + this.#released = true; |
| 87 | + } |
| 88 | + }); |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Drops the current document and loads the one of the host's `src`. |
| 93 | + * A detached host does not hold on to a document. It loads it once attached. |
| 94 | + */ |
| 95 | + load() { |
| 96 | + this.#loadId += 1; |
| 97 | + const loadId = this.#loadId; |
| 98 | + this.#unload(); |
| 99 | + |
| 100 | + const { src } = this.#host; |
| 101 | + this.#released = !!src && !this.#host.isConnected; |
| 102 | + if (!src || this.#released) { |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + this.#callbacks.onLoadStart(); |
| 107 | + this.#open(loadId, src).catch((error) => { |
| 108 | + if (loadId === this.#loadId) { |
| 109 | + this.#unload(); |
| 110 | + this.#callbacks.onError(error, getErrorReason(error)); |
| 111 | + } |
| 112 | + }); |
| 113 | + } |
| 114 | + |
| 115 | + /** @private */ |
| 116 | + async #open(loadId, src) { |
| 117 | + const pdfjs = await loadPdfjs(); |
| 118 | + if (loadId !== this.#loadId) { |
| 119 | + return; |
| 120 | + } |
| 121 | + |
| 122 | + this.#workerHandle = acquireWorker(pdfjs); |
| 123 | + this.#loadingTask = pdfjs.getDocument({ |
| 124 | + url: new URL(src, document.baseURI).href, |
| 125 | + worker: this.#workerHandle.worker, |
| 126 | + // One request for the whole file, so that the server sends the document once. |
| 127 | + disableRange: true, |
| 128 | + // Security: no XFA forms. Scripting (pdf.sandbox) is never loaded either. |
| 129 | + enableXfa: false, |
| 130 | + }); |
| 131 | + |
| 132 | + const workerFailed = this.#workerHandle.failed.catch((error) => { |
| 133 | + issueWarning( |
| 134 | + 'The pdf.js worker of <vaadin-pdf-viewer> failed to load. If the page has a Content Security Policy, check that its worker-src directive allows the worker script.', |
| 135 | + ); |
| 136 | + throw error; |
| 137 | + }); |
| 138 | + const pdfDocument = await Promise.race([this.#loadingTask.promise, workerFailed]); |
| 139 | + if (loadId !== this.#loadId) { |
| 140 | + return; |
| 141 | + } |
| 142 | + |
| 143 | + const { info } = await pdfDocument.getMetadata(); |
| 144 | + if (loadId !== this.#loadId) { |
| 145 | + return; |
| 146 | + } |
| 147 | + this.#callbacks.onLoad(pdfDocument, (info && info.Title) || ''); |
| 148 | + } |
| 149 | + |
| 150 | + /** @private */ |
| 151 | + #unload() { |
| 152 | + const loadingTask = this.#loadingTask; |
| 153 | + const workerHandle = this.#workerHandle; |
| 154 | + this.#loadingTask = null; |
| 155 | + this.#workerHandle = null; |
| 156 | + if (loadingTask) { |
| 157 | + // Destroying the loading task also destroys its document. Release |
| 158 | + // the worker only afterwards, as destroying talks to the worker. |
| 159 | + loadingTask |
| 160 | + .destroy() |
| 161 | + .finally(() => releaseWorker(workerHandle)) |
| 162 | + .catch((error) => issueWarning(`Failed to release the PDF document: ${error.message}`)); |
| 163 | + } else if (workerHandle) { |
| 164 | + releaseWorker(workerHandle); |
| 165 | + } |
| 166 | + this.#callbacks.onUnload(); |
| 167 | + } |
| 168 | +} |
0 commit comments