Skip to content

Commit

Permalink
Extract common methods from PDFOutlineViewer/PDFAttachmentViewer
Browse files Browse the repository at this point in the history
…into a new abstract `BaseTreeViewer` class

These two classes are unsurprisingly quite similar, and with upcoming changes[1] the amount of (essentially) duplicated code will increase even further.

Notable changes:
 - Collect shared functionality in the `BaseTreeViewer` class, reducing both current and future code-duplication.
 - Reduce unnecessary duplication in the CSS rules, which will be particularly useful with upcoming changes.
 - Tweak the attachmentsView to use links, rather than buttons, to simplify (primarily) the CSS rules.

---
[1] Once API support for "Optional Content" lands, I've got more-or-less finished patches to add viewer support as well.
  • Loading branch information
Snuffleupagus committed Aug 5, 2020
1 parent 95e102c commit 292843d
Show file tree
Hide file tree
Showing 4 changed files with 195 additions and 156 deletions.
111 changes: 111 additions & 0 deletions web/base_tree_viewer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/* Copyright 2020 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { removeNullCharacters } from "pdfjs-lib";

class BaseTreeViewer {
constructor(options) {
if (this.constructor === BaseTreeViewer) {
throw new Error("Cannot initialize BaseTreeViewer.");
}
this.container = options.container;
this.eventBus = options.eventBus;

this.reset();
}

reset() {
this._lastToggleIsShow = true;

// Remove the tree from the DOM.
this.container.textContent = "";
// Ensure that the left (right in RTL locales) margin is always reset,
// to prevent incorrect tree alignment if a new document is opened.
this.container.classList.remove("treeWithDeepNesting");
}

/**
* @private
*/
_dispatchEvent(count) {
throw new Error("Not implemented: _dispatchEvent");
}

/**
* @private
*/
_bindLink(element, params) {
throw new Error("Not implemented: _bindLink");
}

/**
* @private
*/
_normalizeTextContent(str) {
return removeNullCharacters(str) || /* en dash = */ "\u2013";
}

/**
* Prepend a button before a tree item which allows the user to collapse or
* expand all tree items at that level; see `_toggleTreeItem`.
* @private
*/
_addToggleButton(div, hidden = false) {
const toggler = document.createElement("div");
toggler.className = "treeItemToggler";
if (hidden) {
toggler.classList.add("treeItemsHidden");
}
toggler.onclick = evt => {
evt.stopPropagation();
toggler.classList.toggle("treeItemsHidden");

if (evt.shiftKey) {
const shouldShowAll = !toggler.classList.contains("treeItemsHidden");
this._toggleTreeItem(div, shouldShowAll);
}
};
div.insertBefore(toggler, div.firstChild);
}

/**
* Collapse or expand the subtree of a tree item.
*
* @param {Element} root - the root of the item (sub)tree.
* @param {boolean} show - whether to show the item (sub)tree. If false,
* the item subtree rooted at `root` will be collapsed.
* @private
*/
_toggleTreeItem(root, show = false) {
this._lastToggleIsShow = show;
for (const toggler of root.querySelectorAll(".treeItemToggler")) {
toggler.classList.toggle("treeItemsHidden", !show);
}
}

/**
* Collapse or expand all subtrees of the `container`.
* @private
*/
_toggleAllTreeItems() {
this._toggleTreeItem(this.container, !this._lastToggleIsShow);
}

render(params) {
throw new Error("Not implemented: render");
}
}

export { BaseTreeViewer };
65 changes: 30 additions & 35 deletions web/pdf_attachment_viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@
* limitations under the License.
*/

import {
createPromiseCapability,
getFilenameFromUrl,
removeNullCharacters,
} from "pdfjs-lib";
import { createPromiseCapability, getFilenameFromUrl } from "pdfjs-lib";
import { BaseTreeViewer } from "./base_tree_viewer.js";

/**
* @typedef {Object} PDFAttachmentViewerOptions
Expand All @@ -31,16 +28,13 @@ import {
* @property {Object|null} attachments - A lookup table of attachment objects.
*/

class PDFAttachmentViewer {
class PDFAttachmentViewer extends BaseTreeViewer {
/**
* @param {PDFAttachmentViewerOptions} options
*/
constructor({ container, eventBus, downloadManager }) {
this.container = container;
this.eventBus = eventBus;
this.downloadManager = downloadManager;

this.reset();
constructor(options) {
super(options);
this.downloadManager = options.downloadManager;

this.eventBus._on(
"fileattachmentannotation",
Expand All @@ -49,10 +43,8 @@ class PDFAttachmentViewer {
}

reset(keepRenderedCapability = false) {
this.attachments = null;

// Remove the attachments from the DOM.
this.container.textContent = "";
super.reset();
this._attachments = null;

if (!keepRenderedCapability) {
// The only situation in which the `_renderedCapability` should *not* be
Expand Down Expand Up @@ -100,9 +92,9 @@ class PDFAttachmentViewer {
* NOTE: Should only be used when `URL.createObjectURL` is natively supported.
* @private
*/
_bindPdfLink(button, content, filename) {
_bindPdfLink(element, { content, filename }) {
let blobUrl;
button.onclick = () => {
element.onclick = () => {
if (!blobUrl) {
blobUrl = URL.createObjectURL(
new Blob([content], { type: "application/pdf" })
Expand Down Expand Up @@ -141,8 +133,8 @@ class PDFAttachmentViewer {
/**
* @private
*/
_bindLink(button, content, filename) {
button.onclick = () => {
_bindLink(element, { content, filename }) {
element.onclick = () => {
this.downloadManager.downloadData(content, filename, "");
return false;
};
Expand All @@ -152,42 +144,45 @@ class PDFAttachmentViewer {
* @param {PDFAttachmentViewerRenderParameters} params
*/
render({ attachments, keepRenderedCapability = false }) {
if (this.attachments) {
this.reset(keepRenderedCapability === true);
if (this._attachments) {
this.reset(keepRenderedCapability);
}
this.attachments = attachments || null;
this._attachments = attachments || null;

if (!attachments) {
this._dispatchEvent(/* attachmentsCount = */ 0);
return;
}

const names = Object.keys(attachments).sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
const attachmentsCount = names.length;

const fragment = document.createDocumentFragment();
for (let i = 0; i < attachmentsCount; i++) {
const item = attachments[names[i]];
const filename = removeNullCharacters(getFilenameFromUrl(item.filename));
let attachmentsCount = 0;
for (const name of names) {
const item = attachments[name];
const filename = getFilenameFromUrl(item.filename);

const div = document.createElement("div");
div.className = "attachmentsItem";
const button = document.createElement("button");
button.textContent = filename;
div.className = "treeItem";

const element = document.createElement("a");
if (
/\.pdf$/i.test(filename) &&
!this.downloadManager.disableCreateObjectURL
) {
this._bindPdfLink(button, item.content, filename);
this._bindPdfLink(element, { content: item.content, filename });
} else {
this._bindLink(button, item.content, filename);
this._bindLink(element, { content: item.content, filename });
}
element.textContent = this._normalizeTextContent(filename);

div.appendChild(element);

div.appendChild(button);
fragment.appendChild(div);
attachmentsCount++;
}

this.container.appendChild(fragment);

this._dispatchEvent(attachmentsCount);
Expand All @@ -204,7 +199,7 @@ class PDFAttachmentViewer {
if (renderedPromise !== this._renderedCapability.promise) {
return; // The FileAttachment annotation belongs to a previous document.
}
let attachments = this.attachments;
let attachments = this._attachments;

if (!attachments) {
attachments = Object.create(null);
Expand Down
Loading

0 comments on commit 292843d

Please sign in to comment.