Re-factor the dispatching of "attachmentsloaded" events, when the PDF document contains no "regular" attachments

Since the attachment fetching/parsing is already asynchronous, possibly delaying the dispatching of an "attachmentsloaded" event should thus not be a problem in general.
Note that in some cases, i.e. PDF documents with no "regular" attachments and only FileAttachment annotations, we'll thus no longer dispatch an "attachmentsloaded" event when `attachmentsCount === 0` and instead wait for the FileAttachment parsing to finish. (The use of a timeout still guarantees that an "attachmentsloaded" event is *eventually* dispatched though.)

This patch *considerably* simplifies the "attachmentsloaded" event handler, in `PDFSidebar`, since the details are now abstracted away from the consumer.

Finally, add a check in `_appendAttachment` to ensure (indirectly) that the FileAttachment annotation is actually relevant for the active document.
This commit is contained in:
Jonas Jenwald 2020-08-03 13:58:58 +02:00
parent 24d8933023
commit 0b65d4cacd
2 changed files with 39 additions and 25 deletions

View file

@ -55,10 +55,14 @@ class PDFAttachmentViewer {
this.container.textContent = "";
if (!keepRenderedCapability) {
// NOTE: The *only* situation in which the `_renderedCapability` should
// not be replaced is when appending file attachment annotations.
// The only situation in which the `_renderedCapability` should *not* be
// replaced is when appending FileAttachment annotations.
this._renderedCapability = createPromiseCapability();
}
if (this._pendingDispatchEvent) {
clearTimeout(this._pendingDispatchEvent);
}
this._pendingDispatchEvent = null;
}
/**
@ -67,6 +71,25 @@ class PDFAttachmentViewer {
_dispatchEvent(attachmentsCount) {
this._renderedCapability.resolve();
if (this._pendingDispatchEvent) {
clearTimeout(this._pendingDispatchEvent);
this._pendingDispatchEvent = null;
}
if (attachmentsCount === 0) {
// Delay the event when no "regular" attachments exist, to allow time for
// parsing of any FileAttachment annotations that may be present on the
// *initially* rendered page; this reduces the likelihood of temporarily
// disabling the attachmentsView when the `PDFSidebar` handles the event.
this._pendingDispatchEvent = setTimeout(() => {
this.eventBus.dispatch("attachmentsloaded", {
source: this,
attachmentsCount: 0,
});
this._pendingDispatchEvent = null;
});
return;
}
this.eventBus.dispatch("attachmentsloaded", {
source: this,
attachmentsCount,
@ -175,7 +198,12 @@ class PDFAttachmentViewer {
* @private
*/
_appendAttachment({ id, filename, content }) {
this._renderedCapability.promise.then(() => {
const renderedPromise = this._renderedCapability.promise;
renderedPromise.then(() => {
if (renderedPromise !== this._renderedCapability.promise) {
return; // The FileAttachment annotation belongs to a previous document.
}
let attachments = this.attachments;
if (!attachments) {