Browse Source

Merge pull request #8302 from timvandermeij/es6-attachments-outline

Convert the attachments/outline view to ES6 syntax
Jonas Jenwald 8 years ago committed by GitHub
parent
commit
ece24dfe61
  1. 268
      web/pdf_attachment_viewer.js
  2. 327
      web/pdf_outline_viewer.js

268
web/pdf_attachment_viewer.js

@ -30,16 +30,13 @@ import {
* @property {Array|null} attachments - An array of attachment objects. * @property {Array|null} attachments - An array of attachment objects.
*/ */
/** class PDFAttachmentViewer {
* @class
*/
var PDFAttachmentViewer = (function PDFAttachmentViewerClosure() {
/** /**
* @constructs PDFAttachmentViewer
* @param {PDFAttachmentViewerOptions} options * @param {PDFAttachmentViewerOptions} options
*/ */
function PDFAttachmentViewer(options) { constructor(options) {
this.attachments = null; this.attachments = null;
this.container = options.container; this.container = options.container;
this.eventBus = options.eventBus; this.eventBus = options.eventBus;
this.downloadManager = options.downloadManager; this.downloadManager = options.downloadManager;
@ -49,152 +46,145 @@ var PDFAttachmentViewer = (function PDFAttachmentViewerClosure() {
this._appendAttachment.bind(this)); this._appendAttachment.bind(this));
} }
PDFAttachmentViewer.prototype = { reset(keepRenderedCapability = false) {
reset: function PDFAttachmentViewer_reset(keepRenderedCapability) { this.attachments = null;
this.attachments = null;
// Remove the attachments from the DOM. // Remove the attachments from the DOM.
this.container.textContent = ''; this.container.textContent = '';
if (!keepRenderedCapability) { if (!keepRenderedCapability) {
// NOTE: The *only* situation in which the `_renderedCapability` should // NOTE: The *only* situation in which the `_renderedCapability` should
// not be replaced is when appending file attachment annotations. // not be replaced is when appending file attachment annotations.
this._renderedCapability = createPromiseCapability(); this._renderedCapability = createPromiseCapability();
} }
}, }
/** /**
* @private * @private
*/ */
_dispatchEvent: _dispatchEvent(attachmentsCount) {
function PDFAttachmentViewer_dispatchEvent(attachmentsCount) { this.eventBus.dispatch('attachmentsloaded', {
this.eventBus.dispatch('attachmentsloaded', { source: this,
source: this, attachmentsCount,
attachmentsCount: attachmentsCount, });
});
this._renderedCapability.resolve(); this._renderedCapability.resolve();
}, }
/** /**
* @private * @private
*/ */
_bindPdfLink(button, content, filename) { _bindPdfLink(button, content, filename) {
if (PDFJS.disableCreateObjectURL) { if (PDFJS.disableCreateObjectURL) {
throw new Error('bindPdfLink: ' + throw new Error('bindPdfLink: ' +
'Unsupported "PDFJS.disableCreateObjectURL" value.'); 'Unsupported "PDFJS.disableCreateObjectURL" value.');
}
var blobUrl;
button.onclick = function() {
if (!blobUrl) {
blobUrl = createObjectURL(content, 'application/pdf');
} }
var blobUrl; var viewerUrl;
button.onclick = function() { if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {
if (!blobUrl) { // The current URL is the viewer, let's use it and append the file.
blobUrl = createObjectURL(content, 'application/pdf'); viewerUrl = '?file=' + encodeURIComponent(blobUrl + '#' + filename);
} } else if (PDFJSDev.test('CHROME')) {
var viewerUrl; // In the Chrome extension, the URL is rewritten using the history API
if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) { // in viewer.js, so an absolute URL must be generated.
// The current URL is the viewer, let's use it and append the file. // eslint-disable-next-line no-undef
viewerUrl = '?file=' + encodeURIComponent(blobUrl + '#' + filename); viewerUrl = chrome.runtime.getURL('/content/web/viewer.html') +
} else if (PDFJSDev.test('CHROME')) { '?file=' + encodeURIComponent(blobUrl + '#' + filename);
// In the Chrome extension, the URL is rewritten using the history API } else if (PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
// in viewer.js, so an absolute URL must be generated. // Let Firefox's content handler catch the URL and display the PDF.
// eslint-disable-next-line no-undef viewerUrl = blobUrl + '?' + encodeURIComponent(filename);
viewerUrl = chrome.runtime.getURL('/content/web/viewer.html') +
'?file=' + encodeURIComponent(blobUrl + '#' + filename);
} else if (PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
// Let Firefox's content handler catch the URL and display the PDF.
viewerUrl = blobUrl + '?' + encodeURIComponent(filename);
}
window.open(viewerUrl);
return false;
};
},
/**
* @private
*/
_bindLink:
function PDFAttachmentViewer_bindLink(button, content, filename) {
button.onclick = function downloadFile(e) {
this.downloadManager.downloadData(content, filename, '');
return false;
}.bind(this);
},
/**
* @param {PDFAttachmentViewerRenderParameters} params
*/
render: function PDFAttachmentViewer_render(params) {
params = params || {};
var attachments = params.attachments || null;
var attachmentsCount = 0;
if (this.attachments) {
var keepRenderedCapability = params.keepRenderedCapability === true;
this.reset(keepRenderedCapability);
} }
this.attachments = attachments; window.open(viewerUrl);
return false;
};
}
if (!attachments) { /**
this._dispatchEvent(attachmentsCount); * @private
return; */
} _bindLink(button, content, filename) {
button.onclick = () => {
this.downloadManager.downloadData(content, filename, '');
return false;
};
}
var names = Object.keys(attachments).sort(function(a, b) { /**
return a.toLowerCase().localeCompare(b.toLowerCase()); * @param {PDFAttachmentViewerRenderParameters} params
}); */
attachmentsCount = names.length; render(params = {}) {
var attachments = params.attachments || null;
for (var i = 0; i < attachmentsCount; i++) { var attachmentsCount = 0;
var item = attachments[names[i]];
var filename = removeNullCharacters(getFilenameFromUrl(item.filename));
var div = document.createElement('div');
div.className = 'attachmentsItem';
var button = document.createElement('button');
button.textContent = filename;
if (/\.pdf$/i.test(filename) && !PDFJS.disableCreateObjectURL) {
this._bindPdfLink(button, item.content, filename);
} else {
this._bindLink(button, item.content, filename);
}
div.appendChild(button); if (this.attachments) {
this.container.appendChild(div); var keepRenderedCapability = params.keepRenderedCapability === true;
} this.reset(keepRenderedCapability);
}
this.attachments = attachments;
if (!attachments) {
this._dispatchEvent(attachmentsCount); this._dispatchEvent(attachmentsCount);
}, return;
}
/**
* Used to append FileAttachment annotations to the sidebar. var names = Object.keys(attachments).sort(function(a, b) {
* @private return a.toLowerCase().localeCompare(b.toLowerCase());
*/ });
_appendAttachment: function PDFAttachmentViewer_appendAttachment(item) { attachmentsCount = names.length;
this._renderedCapability.promise.then(function (id, filename, content) {
var attachments = this.attachments; for (var i = 0; i < attachmentsCount; i++) {
var item = attachments[names[i]];
if (!attachments) { var filename = removeNullCharacters(getFilenameFromUrl(item.filename));
attachments = Object.create(null);
} else { var div = document.createElement('div');
for (var name in attachments) { div.className = 'attachmentsItem';
if (id === name) { var button = document.createElement('button');
return; // Ignore the new attachment if it already exists. button.textContent = filename;
} if (/\.pdf$/i.test(filename) && !PDFJS.disableCreateObjectURL) {
this._bindPdfLink(button, item.content, filename);
} else {
this._bindLink(button, item.content, filename);
}
div.appendChild(button);
this.container.appendChild(div);
}
this._dispatchEvent(attachmentsCount);
}
/**
* Used to append FileAttachment annotations to the sidebar.
* @private
*/
_appendAttachment(item) {
this._renderedCapability.promise.then(function (id, filename, content) {
var attachments = this.attachments;
if (!attachments) {
attachments = Object.create(null);
} else {
for (var name in attachments) {
if (id === name) {
return; // Ignore the new attachment if it already exists.
} }
} }
attachments[id] = { }
filename: filename, attachments[id] = {
content: content, filename,
}; content,
this.render({ };
attachments: attachments, this.render({
keepRenderedCapability: true, attachments,
}); keepRenderedCapability: true,
}.bind(this, item.id, item.filename, item.content)); });
}, }.bind(this, item.id, item.filename, item.content));
}; }
}
return PDFAttachmentViewer;
})();
export { export {
PDFAttachmentViewer, PDFAttachmentViewer,

327
web/pdf_outline_viewer.js

@ -17,7 +17,7 @@ import {
addLinkAttributes, PDFJS, removeNullCharacters addLinkAttributes, PDFJS, removeNullCharacters
} from './pdfjs'; } from './pdfjs';
var DEFAULT_TITLE = '\u2013'; const DEFAULT_TITLE = '\u2013';
/** /**
* @typedef {Object} PDFOutlineViewerOptions * @typedef {Object} PDFOutlineViewerOptions
@ -31,194 +31,187 @@ var DEFAULT_TITLE = '\u2013';
* @property {Array|null} outline - An array of outline objects. * @property {Array|null} outline - An array of outline objects.
*/ */
/** class PDFOutlineViewer {
* @class
*/
var PDFOutlineViewer = (function PDFOutlineViewerClosure() {
/** /**
* @constructs PDFOutlineViewer
* @param {PDFOutlineViewerOptions} options * @param {PDFOutlineViewerOptions} options
*/ */
function PDFOutlineViewer(options) { constructor(options) {
this.outline = null; this.outline = null;
this.lastToggleIsShow = true; this.lastToggleIsShow = true;
this.container = options.container; this.container = options.container;
this.linkService = options.linkService; this.linkService = options.linkService;
this.eventBus = options.eventBus; this.eventBus = options.eventBus;
} }
PDFOutlineViewer.prototype = { reset() {
reset: function PDFOutlineViewer_reset() { this.outline = null;
this.outline = null; this.lastToggleIsShow = true;
this.lastToggleIsShow = true;
// Remove the outline from the DOM.
// Remove the outline from the DOM. this.container.textContent = '';
this.container.textContent = '';
// Ensure that the left (right in RTL locales) margin is always reset, // Ensure that the left (right in RTL locales) margin is always reset,
// to prevent incorrect outline alignment if a new document is opened. // to prevent incorrect outline alignment if a new document is opened.
this.container.classList.remove('outlineWithDeepNesting'); this.container.classList.remove('outlineWithDeepNesting');
}, }
/** /**
* @private * @private
*/ */
_dispatchEvent: function PDFOutlineViewer_dispatchEvent(outlineCount) { _dispatchEvent(outlineCount) {
this.eventBus.dispatch('outlineloaded', { this.eventBus.dispatch('outlineloaded', {
source: this, source: this,
outlineCount: outlineCount outlineCount,
});
}
/**
* @private
*/
_bindLink(element, item) {
if (item.url) {
addLinkAttributes(element, {
url: item.url,
target: (item.newWindow ? PDFJS.LinkTarget.BLANK : undefined),
}); });
}, return;
}
/** var destination = item.dest;
* @private
*/
_bindLink: function PDFOutlineViewer_bindLink(element, item) {
if (item.url) {
addLinkAttributes(element, {
url: item.url,
target: (item.newWindow ? PDFJS.LinkTarget.BLANK : undefined),
});
return;
}
var self = this, destination = item.dest;
element.href = self.linkService.getDestinationHash(destination); element.href = this.linkService.getDestinationHash(destination);
element.onclick = function () { element.onclick = () => {
if (destination) { if (destination) {
self.linkService.navigateTo(destination); this.linkService.navigateTo(destination);
}
return false;
};
},
/**
* @private
*/
_setStyles: function PDFOutlineViewer_setStyles(element, item) {
var styleStr = '';
if (item.bold) {
styleStr += 'font-weight: bold;';
}
if (item.italic) {
styleStr += 'font-style: italic;';
} }
return false;
};
}
if (styleStr) { /**
element.setAttribute('style', styleStr); * @private
} */
}, _setStyles(element, item) {
var styleStr = '';
/** if (item.bold) {
* Prepend a button before an outline item which allows the user to toggle styleStr += 'font-weight: bold;';
* the visibility of all outline items at that level. }
* if (item.italic) {
* @private styleStr += 'font-style: italic;';
*/ }
_addToggleButton: function PDFOutlineViewer_addToggleButton(div) {
var toggler = document.createElement('div');
toggler.className = 'outlineItemToggler';
toggler.onclick = function(event) {
event.stopPropagation();
toggler.classList.toggle('outlineItemsHidden');
if (event.shiftKey) {
var shouldShowAll = !toggler.classList.contains('outlineItemsHidden');
this._toggleOutlineItem(div, shouldShowAll);
}
}.bind(this);
div.insertBefore(toggler, div.firstChild);
},
/**
* Toggle the visibility of the subtree of an outline item.
*
* @param {Element} root - the root of the outline (sub)tree.
* @param {boolean} show - whether to show the outline (sub)tree. If false,
* the outline subtree rooted at |root| will be collapsed.
*
* @private
*/
_toggleOutlineItem:
function PDFOutlineViewer_toggleOutlineItem(root, show) {
this.lastToggleIsShow = show;
var togglers = root.querySelectorAll('.outlineItemToggler');
for (var i = 0, ii = togglers.length; i < ii; ++i) {
togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden');
}
},
/**
* Collapse or expand all subtrees of the outline.
*/
toggleOutlineTree: function PDFOutlineViewer_toggleOutlineTree() {
if (!this.outline) {
return;
}
this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
},
/**
* @param {PDFOutlineViewerRenderParameters} params
*/
render: function PDFOutlineViewer_render(params) {
var outline = (params && params.outline) || null;
var outlineCount = 0;
if (this.outline) {
this.reset();
}
this.outline = outline;
if (!outline) { if (styleStr) {
this._dispatchEvent(outlineCount); element.setAttribute('style', styleStr);
return; }
} }
var fragment = document.createDocumentFragment(); /**
var queue = [{ parent: fragment, items: this.outline }]; * Prepend a button before an outline item which allows the user to toggle
var hasAnyNesting = false; * the visibility of all outline items at that level.
while (queue.length > 0) { *
var levelData = queue.shift(); * @private
for (var i = 0, len = levelData.items.length; i < len; i++) { */
var item = levelData.items[i]; _addToggleButton(div) {
var toggler = document.createElement('div');
var div = document.createElement('div'); toggler.className = 'outlineItemToggler';
div.className = 'outlineItem'; toggler.onclick = (evt) => {
evt.stopPropagation();
var element = document.createElement('a'); toggler.classList.toggle('outlineItemsHidden');
this._bindLink(element, item);
this._setStyles(element, item); if (evt.shiftKey) {
element.textContent = var shouldShowAll = !toggler.classList.contains('outlineItemsHidden');
removeNullCharacters(item.title) || DEFAULT_TITLE; this._toggleOutlineItem(div, shouldShowAll);
div.appendChild(element);
if (item.items.length > 0) {
hasAnyNesting = true;
this._addToggleButton(div);
var itemsDiv = document.createElement('div');
itemsDiv.className = 'outlineItems';
div.appendChild(itemsDiv);
queue.push({ parent: itemsDiv, items: item.items });
}
levelData.parent.appendChild(div);
outlineCount++;
}
}
if (hasAnyNesting) {
this.container.classList.add('outlineWithDeepNesting');
} }
};
div.insertBefore(toggler, div.firstChild);
}
this.container.appendChild(fragment); /**
* Toggle the visibility of the subtree of an outline item.
*
* @param {Element} root - the root of the outline (sub)tree.
* @param {boolean} show - whether to show the outline (sub)tree. If false,
* the outline subtree rooted at |root| will be collapsed.
*
* @private
*/
_toggleOutlineItem(root, show) {
this.lastToggleIsShow = show;
var togglers = root.querySelectorAll('.outlineItemToggler');
for (var i = 0, ii = togglers.length; i < ii; ++i) {
togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden');
}
}
/**
* Collapse or expand all subtrees of the outline.
*/
toggleOutlineTree() {
if (!this.outline) {
return;
}
this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
}
/**
* @param {PDFOutlineViewerRenderParameters} params
*/
render(params = {}) {
var outline = params.outline || null;
var outlineCount = 0;
if (this.outline) {
this.reset();
}
this.outline = outline;
if (!outline) {
this._dispatchEvent(outlineCount); this._dispatchEvent(outlineCount);
return;
}
var fragment = document.createDocumentFragment();
var queue = [{ parent: fragment, items: this.outline }];
var hasAnyNesting = false;
while (queue.length > 0) {
var levelData = queue.shift();
for (var i = 0, len = levelData.items.length; i < len; i++) {
var item = levelData.items[i];
var div = document.createElement('div');
div.className = 'outlineItem';
var element = document.createElement('a');
this._bindLink(element, item);
this._setStyles(element, item);
element.textContent =
removeNullCharacters(item.title) || DEFAULT_TITLE;
div.appendChild(element);
if (item.items.length > 0) {
hasAnyNesting = true;
this._addToggleButton(div);
var itemsDiv = document.createElement('div');
itemsDiv.className = 'outlineItems';
div.appendChild(itemsDiv);
queue.push({ parent: itemsDiv, items: item.items });
}
levelData.parent.appendChild(div);
outlineCount++;
}
} }
}; if (hasAnyNesting) {
this.container.classList.add('outlineWithDeepNesting');
}
this.container.appendChild(fragment);
return PDFOutlineViewer; this._dispatchEvent(outlineCount);
})(); }
}
export { export {
PDFOutlineViewer, PDFOutlineViewer,

Loading…
Cancel
Save