Merge pull request #11450 from Snuffleupagus/eslint-web-prefer-const

Enable the ESLint `prefer-const` rule in the `web/` directory
This commit is contained in:
Tim van der Meij 2019-12-27 12:12:51 +01:00 committed by GitHub
commit 47ab4b839f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 377 additions and 378 deletions

View File

@ -9,5 +9,6 @@
// ECMAScript 6 // ECMAScript 6
"no-var": "error", "no-var": "error",
"prefer-const": "error",
}, },
} }

View File

@ -64,7 +64,7 @@ class AnnotationLayerBuilder {
return; return;
} }
let parameters = { const parameters = {
viewport: viewport.clone({ dontFlip: true }), viewport: viewport.clone({ dontFlip: true }),
div: this.div, div: this.div,
annotations, annotations,

View File

@ -108,7 +108,7 @@ const DefaultExternalServices = {
}, },
}; };
let PDFViewerApplication = { const PDFViewerApplication = {
initialBookmark: document.location.hash.substring(1), initialBookmark: document.location.hash.substring(1),
initialized: false, initialized: false,
fellback: false, fellback: false,
@ -190,7 +190,7 @@ let PDFViewerApplication = {
this.bindWindowEvents(); this.bindWindowEvents();
// We can start UI localization now. // We can start UI localization now.
let appContainer = appConfig.appContainer || document.documentElement; const appContainer = appConfig.appContainer || document.documentElement;
this.l10n.translate(appContainer).then(() => { this.l10n.translate(appContainer).then(() => {
// Dispatch the 'localized' event on the `eventBus` once the viewer // Dispatch the 'localized' event on the `eventBus` once the viewer
// has been fully initialized and translated. // has been fully initialized and translated.
@ -233,8 +233,8 @@ let PDFViewerApplication = {
const waitOn = []; const waitOn = [];
// Special debugging flags in the hash section of the URL. // Special debugging flags in the hash section of the URL.
let hash = document.location.hash.substring(1); const hash = document.location.hash.substring(1);
let hashParams = parseQueryString(hash); const hashParams = parseQueryString(hash);
if ( if (
"disableworker" in hashParams && "disableworker" in hashParams &&
@ -280,14 +280,14 @@ let PDFViewerApplication = {
case "visible": case "visible":
case "shadow": case "shadow":
case "hover": case "hover":
let viewer = this.appConfig.viewerContainer; const viewer = this.appConfig.viewerContainer;
viewer.classList.add("textLayer-" + hashParams["textlayer"]); viewer.classList.add("textLayer-" + hashParams["textlayer"]);
break; break;
} }
} }
if ("pdfbug" in hashParams) { if ("pdfbug" in hashParams) {
AppOptions.set("pdfBug", true); AppOptions.set("pdfBug", true);
let enabled = hashParams["pdfbug"].split(","); const enabled = hashParams["pdfbug"].split(",");
waitOn.push(loadAndEnablePDFBug(enabled)); waitOn.push(loadAndEnablePDFBug(enabled));
} }
// It is not possible to change locale for the (various) extension builds. // It is not possible to change locale for the (various) extension builds.
@ -328,18 +328,18 @@ let PDFViewerApplication = {
getGlobalEventBus(AppOptions.get("eventBusDispatchToDOM")); getGlobalEventBus(AppOptions.get("eventBusDispatchToDOM"));
this.eventBus = eventBus; this.eventBus = eventBus;
let pdfRenderingQueue = new PDFRenderingQueue(); const pdfRenderingQueue = new PDFRenderingQueue();
pdfRenderingQueue.onIdle = this.cleanup.bind(this); pdfRenderingQueue.onIdle = this.cleanup.bind(this);
this.pdfRenderingQueue = pdfRenderingQueue; this.pdfRenderingQueue = pdfRenderingQueue;
let pdfLinkService = new PDFLinkService({ const pdfLinkService = new PDFLinkService({
eventBus, eventBus,
externalLinkTarget: AppOptions.get("externalLinkTarget"), externalLinkTarget: AppOptions.get("externalLinkTarget"),
externalLinkRel: AppOptions.get("externalLinkRel"), externalLinkRel: AppOptions.get("externalLinkRel"),
}); });
this.pdfLinkService = pdfLinkService; this.pdfLinkService = pdfLinkService;
let downloadManager = this.externalServices.createDownloadManager({ const downloadManager = this.externalServices.createDownloadManager({
disableCreateObjectURL: AppOptions.get("disableCreateObjectURL"), disableCreateObjectURL: AppOptions.get("disableCreateObjectURL"),
}); });
this.downloadManager = downloadManager; this.downloadManager = downloadManager;
@ -519,7 +519,7 @@ let PDFViewerApplication = {
document.fullscreenEnabled === true || document.fullscreenEnabled === true ||
document.mozFullScreenEnabled === true; document.mozFullScreenEnabled === true;
} else { } else {
let doc = document.documentElement; const doc = document.documentElement;
support = !!( support = !!(
doc.requestFullscreen || doc.requestFullscreen ||
doc.mozRequestFullScreen || doc.mozRequestFullScreen ||
@ -552,7 +552,7 @@ let PDFViewerApplication = {
}, },
get loadingBar() { get loadingBar() {
let bar = new ProgressBar("#loadingBar"); const bar = new ProgressBar("#loadingBar");
return shadow(this, "loadingBar", bar); return shadow(this, "loadingBar", bar);
}, },
@ -632,14 +632,14 @@ let PDFViewerApplication = {
* destruction is completed. * destruction is completed.
*/ */
async close() { async close() {
let errorWrapper = this.appConfig.errorWrapper.container; const errorWrapper = this.appConfig.errorWrapper.container;
errorWrapper.setAttribute("hidden", "true"); errorWrapper.setAttribute("hidden", "true");
if (!this.pdfLoadingTask) { if (!this.pdfLoadingTask) {
return undefined; return undefined;
} }
let promise = this.pdfLoadingTask.destroy(); const promise = this.pdfLoadingTask.destroy();
this.pdfLoadingTask = null; this.pdfLoadingTask = null;
if (this.pdfDocument) { if (this.pdfDocument) {
@ -692,11 +692,11 @@ let PDFViewerApplication = {
} }
// Set the necessary global worker parameters, using the available options. // Set the necessary global worker parameters, using the available options.
const workerParameters = AppOptions.getAll(OptionKind.WORKER); const workerParameters = AppOptions.getAll(OptionKind.WORKER);
for (let key in workerParameters) { for (const key in workerParameters) {
GlobalWorkerOptions[key] = workerParameters[key]; GlobalWorkerOptions[key] = workerParameters[key];
} }
let parameters = Object.create(null); const parameters = Object.create(null);
if (typeof file === "string") { if (typeof file === "string") {
// URL // URL
this.setTitleUsingUrl(file); this.setTitleUsingUrl(file);
@ -710,7 +710,7 @@ let PDFViewerApplication = {
} }
// Set the necessary API parameters, using the available options. // Set the necessary API parameters, using the available options.
const apiParameters = AppOptions.getAll(OptionKind.API); const apiParameters = AppOptions.getAll(OptionKind.API);
for (let key in apiParameters) { for (const key in apiParameters) {
let value = apiParameters[key]; let value = apiParameters[key];
if (key === "docBaseUrl" && !value) { if (key === "docBaseUrl" && !value) {
@ -727,7 +727,7 @@ let PDFViewerApplication = {
} }
if (args) { if (args) {
for (let key in args) { for (const key in args) {
const value = args[key]; const value = args[key];
if (key === "length") { if (key === "length") {
@ -737,7 +737,7 @@ let PDFViewerApplication = {
} }
} }
let loadingTask = getDocument(parameters); const loadingTask = getDocument(parameters);
this.pdfLoadingTask = loadingTask; this.pdfLoadingTask = loadingTask;
loadingTask.onPassword = (updateCallback, reason) => { loadingTask.onPassword = (updateCallback, reason) => {
@ -762,7 +762,7 @@ let PDFViewerApplication = {
return undefined; // Ignore errors for previously opened PDF files. return undefined; // Ignore errors for previously opened PDF files.
} }
let message = exception && exception.message; const message = exception && exception.message;
let loadingErrorMessage; let loadingErrorMessage;
if (exception instanceof InvalidPDFException) { if (exception instanceof InvalidPDFException) {
// change error message also for other builds // change error message also for other builds
@ -805,12 +805,12 @@ let PDFViewerApplication = {
downloadManager.downloadUrl(url, filename); downloadManager.downloadUrl(url, filename);
} }
let url = this.baseUrl; const url = this.baseUrl;
// Use this.url instead of this.baseUrl to perform filename detection based // Use this.url instead of this.baseUrl to perform filename detection based
// on the reference fragment as ultimate fallback if needed. // on the reference fragment as ultimate fallback if needed.
let filename = const filename =
this.contentDispositionFilename || getPDFFileNameFromURL(this.url); this.contentDispositionFilename || getPDFFileNameFromURL(this.url);
let downloadManager = this.downloadManager; const downloadManager = this.downloadManager;
downloadManager.onerror = err => { downloadManager.onerror = err => {
// This error won't really be helpful because it's likely the // This error won't really be helpful because it's likely the
// fallback won't work either (or is already open). // fallback won't work either (or is already open).
@ -867,7 +867,7 @@ let PDFViewerApplication = {
* optionally a 'stack' property. * optionally a 'stack' property.
*/ */
error(message, moreInfo) { error(message, moreInfo) {
let moreInfoText = [ const moreInfoText = [
this.l10n.get( this.l10n.get(
"error_version_info", "error_version_info",
{ version: version || "?", build: build || "?" }, { version: version || "?", build: build || "?" },
@ -916,21 +916,21 @@ let PDFViewerApplication = {
typeof PDFJSDev === "undefined" || typeof PDFJSDev === "undefined" ||
!PDFJSDev.test("FIREFOX || MOZCENTRAL") !PDFJSDev.test("FIREFOX || MOZCENTRAL")
) { ) {
let errorWrapperConfig = this.appConfig.errorWrapper; const errorWrapperConfig = this.appConfig.errorWrapper;
let errorWrapper = errorWrapperConfig.container; const errorWrapper = errorWrapperConfig.container;
errorWrapper.removeAttribute("hidden"); errorWrapper.removeAttribute("hidden");
let errorMessage = errorWrapperConfig.errorMessage; const errorMessage = errorWrapperConfig.errorMessage;
errorMessage.textContent = message; errorMessage.textContent = message;
let closeButton = errorWrapperConfig.closeButton; const closeButton = errorWrapperConfig.closeButton;
closeButton.onclick = function() { closeButton.onclick = function() {
errorWrapper.setAttribute("hidden", "true"); errorWrapper.setAttribute("hidden", "true");
}; };
let errorMoreInfo = errorWrapperConfig.errorMoreInfo; const errorMoreInfo = errorWrapperConfig.errorMoreInfo;
let moreInfoButton = errorWrapperConfig.moreInfoButton; const moreInfoButton = errorWrapperConfig.moreInfoButton;
let lessInfoButton = errorWrapperConfig.lessInfoButton; const lessInfoButton = errorWrapperConfig.lessInfoButton;
moreInfoButton.onclick = function() { moreInfoButton.onclick = function() {
errorMoreInfo.removeAttribute("hidden"); errorMoreInfo.removeAttribute("hidden");
moreInfoButton.setAttribute("hidden", "true"); moreInfoButton.setAttribute("hidden", "true");
@ -964,7 +964,7 @@ let PDFViewerApplication = {
// already been fetched (only an issue when disableAutoFetch is enabled). // already been fetched (only an issue when disableAutoFetch is enabled).
return; return;
} }
let percent = Math.round(level * 100); const percent = Math.round(level * 100);
// When we transition from full request to range requests, it's possible // When we transition from full request to range requests, it's possible
// that we discard some of the loaded data. This can cause the loading // that we discard some of the loaded data. This can cause the loading
// bar to move backwards. So prevent this by only updating the bar if it // bar to move backwards. So prevent this by only updating the bar if it
@ -1038,13 +1038,13 @@ let PDFViewerApplication = {
this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl); this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl);
this.pdfDocumentProperties.setDocument(pdfDocument, this.url); this.pdfDocumentProperties.setDocument(pdfDocument, this.url);
let pdfViewer = this.pdfViewer; const pdfViewer = this.pdfViewer;
pdfViewer.setDocument(pdfDocument); pdfViewer.setDocument(pdfDocument);
let firstPagePromise = pdfViewer.firstPagePromise; const firstPagePromise = pdfViewer.firstPagePromise;
let pagesPromise = pdfViewer.pagesPromise; const pagesPromise = pdfViewer.pagesPromise;
let onePageRendered = pdfViewer.onePageRendered; const onePageRendered = pdfViewer.onePageRendered;
let pdfThumbnailViewer = this.pdfThumbnailViewer; const pdfThumbnailViewer = this.pdfThumbnailViewer;
pdfThumbnailViewer.setDocument(pdfDocument); pdfThumbnailViewer.setDocument(pdfDocument);
firstPagePromise.then(pdfPage => { firstPagePromise.then(pdfPage => {
@ -1182,8 +1182,7 @@ let PDFViewerApplication = {
if (!labels || AppOptions.get("disablePageLabels")) { if (!labels || AppOptions.get("disablePageLabels")) {
return; return;
} }
let i = 0, const numLabels = labels.length;
numLabels = labels.length;
if (numLabels !== this.pagesCount) { if (numLabels !== this.pagesCount) {
console.error( console.error(
"The number of Page Labels does not match " + "The number of Page Labels does not match " +
@ -1191,6 +1190,7 @@ let PDFViewerApplication = {
); );
return; return;
} }
let i = 0;
// Ignore page labels that correspond to standard page numbering. // Ignore page labels that correspond to standard page numbering.
while (i < numLabels && labels[i] === (i + 1).toString()) { while (i < numLabels && labels[i] === (i + 1).toString()) {
i++; i++;
@ -1354,7 +1354,7 @@ let PDFViewerApplication = {
}.bind(null, info.Producer.toLowerCase()) }.bind(null, info.Producer.toLowerCase())
); );
} }
let formType = !info.IsAcroFormPresent const formType = !info.IsAcroFormPresent
? null ? null
: info.IsXFAPresent : info.IsXFAPresent
? "xfa" ? "xfa"
@ -1507,9 +1507,9 @@ let PDFViewerApplication = {
return; return;
} }
let pagesOverview = this.pdfViewer.getPagesOverview(); const pagesOverview = this.pdfViewer.getPagesOverview();
let printContainer = this.appConfig.printContainer; const printContainer = this.appConfig.printContainer;
let printService = PDFPrintServiceFactory.instance.createPrintService( const printService = PDFPrintServiceFactory.instance.createPrintService(
this.pdfDocument, this.pdfDocument,
pagesOverview, pagesOverview,
printContainer, printContainer,
@ -1542,7 +1542,7 @@ let PDFViewerApplication = {
if (!this.pdfDocument) { if (!this.pdfDocument) {
return; return;
} }
let newRotation = (this.pdfViewer.pagesRotation + 360 + delta) % 360; const newRotation = (this.pdfViewer.pagesRotation + 360 + delta) % 360;
this.pdfViewer.pagesRotation = newRotation; this.pdfViewer.pagesRotation = newRotation;
// Note that the thumbnail viewer is updated, and rendering is triggered, // Note that the thumbnail viewer is updated, and rendering is triggered,
// in the 'rotationchanging' event handler. // in the 'rotationchanging' event handler.
@ -1556,7 +1556,7 @@ let PDFViewerApplication = {
}, },
bindEvents() { bindEvents() {
let { eventBus, _boundEvents } = this; const { eventBus, _boundEvents } = this;
_boundEvents.beforePrint = this.beforePrint.bind(this); _boundEvents.beforePrint = this.beforePrint.bind(this);
_boundEvents.afterPrint = this.afterPrint.bind(this); _boundEvents.afterPrint = this.afterPrint.bind(this);
@ -1605,7 +1605,7 @@ let PDFViewerApplication = {
}, },
bindWindowEvents() { bindWindowEvents() {
let { eventBus, _boundEvents } = this; const { eventBus, _boundEvents } = this;
_boundEvents.windowResize = () => { _boundEvents.windowResize = () => {
eventBus.dispatch("resize", { source: window }); eventBus.dispatch("resize", { source: window });
@ -1634,7 +1634,7 @@ let PDFViewerApplication = {
}, },
unbindEvents() { unbindEvents() {
let { eventBus, _boundEvents } = this; const { eventBus, _boundEvents } = this;
eventBus.off("resize", webViewerResize); eventBus.off("resize", webViewerResize);
eventBus.off("hashchange", webViewerHashchange); eventBus.off("hashchange", webViewerHashchange);
@ -1683,7 +1683,7 @@ let PDFViewerApplication = {
}, },
unbindWindowEvents() { unbindWindowEvents() {
let { _boundEvents } = this; const { _boundEvents } = this;
window.removeEventListener("visibilitychange", webViewerVisibilityChange); window.removeEventListener("visibilitychange", webViewerVisibilityChange);
window.removeEventListener("wheel", webViewerWheel); window.removeEventListener("wheel", webViewerWheel);
@ -1713,12 +1713,12 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
return; return;
} }
try { try {
let viewerOrigin = new URL(window.location.href).origin || "null"; const viewerOrigin = new URL(window.location.href).origin || "null";
if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) { if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) {
// Hosted or local viewer, allow for any file locations // Hosted or local viewer, allow for any file locations
return; return;
} }
let { origin, protocol } = new URL(file, window.location.href); const { origin, protocol } = new URL(file, window.location.href);
// Removing of the following line will not guarantee that the viewer will // Removing of the following line will not guarantee that the viewer will
// start accepting URLs from foreign origin -- CORS headers on the remote // start accepting URLs from foreign origin -- CORS headers on the remote
// server must be properly configured. // server must be properly configured.
@ -1729,7 +1729,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
throw new Error("file origin does not match viewer's"); throw new Error("file origin does not match viewer's");
} }
} catch (ex) { } catch (ex) {
let message = ex && ex.message; const message = ex && ex.message;
PDFViewerApplication.l10n PDFViewerApplication.l10n
.get("loading_error", null, "An error occurred while loading the PDF.") .get("loading_error", null, "An error occurred while loading the PDF.")
.then(loadingErrorMessage => { .then(loadingErrorMessage => {
@ -1755,7 +1755,7 @@ async function loadFakeWorker() {
} }
function loadAndEnablePDFBug(enabledTabs) { function loadAndEnablePDFBug(enabledTabs) {
let appConfig = PDFViewerApplication.appConfig; const appConfig = PDFViewerApplication.appConfig;
return loadScript(appConfig.debuggerScriptPath).then(function() { return loadScript(appConfig.debuggerScriptPath).then(function() {
PDFBug.enable(enabledTabs); PDFBug.enable(enabledTabs);
PDFBug.init( PDFBug.init(
@ -1769,11 +1769,11 @@ function loadAndEnablePDFBug(enabledTabs) {
} }
function webViewerInitialized() { function webViewerInitialized() {
let appConfig = PDFViewerApplication.appConfig; const appConfig = PDFViewerApplication.appConfig;
let file; let file;
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
let queryString = document.location.search.substring(1); const queryString = document.location.search.substring(1);
let params = parseQueryString(queryString); const params = parseQueryString(queryString);
file = "file" in params ? params.file : AppOptions.get("defaultUrl"); file = "file" in params ? params.file : AppOptions.get("defaultUrl");
validateFileURL(file); validateFileURL(file);
} else if (PDFJSDev.test("FIREFOX || MOZCENTRAL")) { } else if (PDFJSDev.test("FIREFOX || MOZCENTRAL")) {
@ -1783,7 +1783,7 @@ function webViewerInitialized() {
} }
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
let fileInput = document.createElement("input"); const fileInput = document.createElement("input");
fileInput.id = appConfig.openFileInputName; fileInput.id = appConfig.openFileInputName;
fileInput.className = "fileInput"; fileInput.className = "fileInput";
fileInput.setAttribute("type", "file"); fileInput.setAttribute("type", "file");
@ -1803,7 +1803,7 @@ function webViewerInitialized() {
} }
fileInput.addEventListener("change", function(evt) { fileInput.addEventListener("change", function(evt) {
let files = evt.target.files; const files = evt.target.files;
if (!files || files.length === 0) { if (!files || files.length === 0) {
return; return;
} }
@ -1924,9 +1924,9 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
} }
function webViewerPageRendered(evt) { function webViewerPageRendered(evt) {
let pageNumber = evt.pageNumber; const pageNumber = evt.pageNumber;
let pageIndex = pageNumber - 1; const pageIndex = pageNumber - 1;
let pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex); const pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
// If the page is still visible when it has finished rendering, // If the page is still visible when it has finished rendering,
// ensure that the page number input loading indicator is hidden. // ensure that the page number input loading indicator is hidden.
@ -1942,7 +1942,7 @@ function webViewerPageRendered(evt) {
// Use the rendered page to set the corresponding thumbnail image. // Use the rendered page to set the corresponding thumbnail image.
if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) { if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) {
let thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail( const thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(
pageIndex pageIndex
); );
thumbnailView.setImage(pageView); thumbnailView.setImage(pageView);
@ -2004,10 +2004,9 @@ function webViewerTextLayerRendered(evt) {
} }
} }
function webViewerPageMode(evt) { function webViewerPageMode({ mode }) {
// Handle the 'pagemode' hash parameter, see also `PDFLinkService_setHash`. // Handle the 'pagemode' hash parameter, see also `PDFLinkService_setHash`.
let mode = evt.mode, let view;
view;
switch (mode) { switch (mode) {
case "thumbs": case "thumbs":
view = SidebarView.THUMBS; view = SidebarView.THUMBS;
@ -2032,7 +2031,7 @@ function webViewerPageMode(evt) {
function webViewerNamedAction(evt) { function webViewerNamedAction(evt) {
// Processing couple of named actions that might be useful. // Processing couple of named actions that might be useful.
// See also PDFLinkService.executeNamedAction // See also PDFLinkService.executeNamedAction
let action = evt.action; const action = evt.action;
switch (action) { switch (action) {
case "GoToPage": case "GoToPage":
PDFViewerApplication.appConfig.toolbar.pageNumber.select(); PDFViewerApplication.appConfig.toolbar.pageNumber.select();
@ -2047,7 +2046,7 @@ function webViewerNamedAction(evt) {
} }
function webViewerPresentationModeChanged(evt) { function webViewerPresentationModeChanged(evt) {
let { active, switchInProgress } = evt; const { active, switchInProgress } = evt;
PDFViewerApplication.pdfViewer.presentationModeState = switchInProgress PDFViewerApplication.pdfViewer.presentationModeState = switchInProgress
? PresentationModeState.CHANGING ? PresentationModeState.CHANGING
: active : active
@ -2059,7 +2058,7 @@ function webViewerSidebarViewChanged(evt) {
PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled =
PDFViewerApplication.pdfSidebar.isThumbnailViewVisible; PDFViewerApplication.pdfSidebar.isThumbnailViewVisible;
let store = PDFViewerApplication.store; const store = PDFViewerApplication.store;
if (store && PDFViewerApplication.isInitialViewSet) { if (store && PDFViewerApplication.isInitialViewSet) {
// Only update the storage when the document has been loaded *and* rendered. // Only update the storage when the document has been loaded *and* rendered.
store.set("sidebarView", evt.view).catch(function() {}); store.set("sidebarView", evt.view).catch(function() {});
@ -2067,7 +2066,7 @@ function webViewerSidebarViewChanged(evt) {
} }
function webViewerUpdateViewarea(evt) { function webViewerUpdateViewarea(evt) {
let location = evt.location, const location = evt.location,
store = PDFViewerApplication.store; store = PDFViewerApplication.store;
if (store && PDFViewerApplication.isInitialViewSet) { if (store && PDFViewerApplication.isInitialViewSet) {
@ -2083,22 +2082,22 @@ function webViewerUpdateViewarea(evt) {
/* unable to write to storage */ /* unable to write to storage */
}); });
} }
let href = PDFViewerApplication.pdfLinkService.getAnchorUrl( const href = PDFViewerApplication.pdfLinkService.getAnchorUrl(
location.pdfOpenParams location.pdfOpenParams
); );
PDFViewerApplication.appConfig.toolbar.viewBookmark.href = href; PDFViewerApplication.appConfig.toolbar.viewBookmark.href = href;
PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href; PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href;
// Show/hide the loading indicator in the page number input element. // Show/hide the loading indicator in the page number input element.
let currentPage = PDFViewerApplication.pdfViewer.getPageView( const currentPage = PDFViewerApplication.pdfViewer.getPageView(
PDFViewerApplication.page - 1 PDFViewerApplication.page - 1
); );
let loading = currentPage.renderingState !== RenderingStates.FINISHED; const loading = currentPage.renderingState !== RenderingStates.FINISHED;
PDFViewerApplication.toolbar.updateLoadingIndicatorState(loading); PDFViewerApplication.toolbar.updateLoadingIndicatorState(loading);
} }
function webViewerScrollModeChanged(evt) { function webViewerScrollModeChanged(evt) {
let store = PDFViewerApplication.store; const store = PDFViewerApplication.store;
if (store && PDFViewerApplication.isInitialViewSet) { if (store && PDFViewerApplication.isInitialViewSet) {
// Only update the storage when the document has been loaded *and* rendered. // Only update the storage when the document has been loaded *and* rendered.
store.set("scrollMode", evt.mode).catch(function() {}); store.set("scrollMode", evt.mode).catch(function() {});
@ -2106,7 +2105,7 @@ function webViewerScrollModeChanged(evt) {
} }
function webViewerSpreadModeChanged(evt) { function webViewerSpreadModeChanged(evt) {
let store = PDFViewerApplication.store; const store = PDFViewerApplication.store;
if (store && PDFViewerApplication.isInitialViewSet) { if (store && PDFViewerApplication.isInitialViewSet) {
// Only update the storage when the document has been loaded *and* rendered. // Only update the storage when the document has been loaded *and* rendered.
store.set("spreadMode", evt.mode).catch(function() {}); store.set("spreadMode", evt.mode).catch(function() {});
@ -2114,11 +2113,11 @@ function webViewerSpreadModeChanged(evt) {
} }
function webViewerResize() { function webViewerResize() {
let { pdfDocument, pdfViewer } = PDFViewerApplication; const { pdfDocument, pdfViewer } = PDFViewerApplication;
if (!pdfDocument) { if (!pdfDocument) {
return; return;
} }
let currentScaleValue = pdfViewer.currentScaleValue; const currentScaleValue = pdfViewer.currentScaleValue;
if ( if (
currentScaleValue === "auto" || currentScaleValue === "auto" ||
currentScaleValue === "page-fit" || currentScaleValue === "page-fit" ||
@ -2131,7 +2130,7 @@ function webViewerResize() {
} }
function webViewerHashchange(evt) { function webViewerHashchange(evt) {
let hash = evt.hash; const hash = evt.hash;
if (!hash) { if (!hash) {
return; return;
} }
@ -2151,7 +2150,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
) { ) {
return; // Opening a new PDF file isn't supported in Presentation Mode. return; // Opening a new PDF file isn't supported in Presentation Mode.
} }
let file = evt.fileInput.files[0]; const file = evt.fileInput.files[0];
if (URL.createObjectURL && !AppOptions.get("disableCreateObjectURL")) { if (URL.createObjectURL && !AppOptions.get("disableCreateObjectURL")) {
let url = URL.createObjectURL(file); let url = URL.createObjectURL(file);
@ -2162,16 +2161,16 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
} else { } else {
PDFViewerApplication.setTitleUsingUrl(file.name); PDFViewerApplication.setTitleUsingUrl(file.name);
// Read the local file into a Uint8Array. // Read the local file into a Uint8Array.
let fileReader = new FileReader(); const fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) { fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
let buffer = evt.target.result; const buffer = evt.target.result;
PDFViewerApplication.open(new Uint8Array(buffer)); PDFViewerApplication.open(new Uint8Array(buffer));
}; };
fileReader.readAsArrayBuffer(file); fileReader.readAsArrayBuffer(file);
} }
// URL does not reflect proper document location - hiding some icons. // URL does not reflect proper document location - hiding some icons.
let appConfig = PDFViewerApplication.appConfig; const appConfig = PDFViewerApplication.appConfig;
appConfig.toolbar.viewBookmark.setAttribute("hidden", "true"); appConfig.toolbar.viewBookmark.setAttribute("hidden", "true");
appConfig.secondaryToolbar.viewBookmarkButton.setAttribute( appConfig.secondaryToolbar.viewBookmarkButton.setAttribute(
"hidden", "hidden",
@ -2187,7 +2186,7 @@ function webViewerPresentationMode() {
} }
function webViewerOpenFile() { function webViewerOpenFile() {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
let openFileInputName = PDFViewerApplication.appConfig.openFileInputName; const openFileInputName = PDFViewerApplication.appConfig.openFileInputName;
document.getElementById(openFileInputName).click(); document.getElementById(openFileInputName).click();
} }
} }
@ -2223,7 +2222,7 @@ function webViewerZoomReset() {
PDFViewerApplication.zoomReset(); PDFViewerApplication.zoomReset();
} }
function webViewerPageNumberChanged(evt) { function webViewerPageNumberChanged(evt) {
let pdfViewer = PDFViewerApplication.pdfViewer; const pdfViewer = PDFViewerApplication.pdfViewer;
// Note that for `<input type="number">` HTML elements, an empty string will // Note that for `<input type="number">` HTML elements, an empty string will
// be returned for non-number inputs; hence we simply do nothing in that case. // be returned for non-number inputs; hence we simply do nothing in that case.
if (evt.value !== "") { if (evt.value !== "") {
@ -2318,7 +2317,7 @@ function webViewerRotationChanging(evt) {
} }
function webViewerPageChanging(evt) { function webViewerPageChanging(evt) {
let page = evt.pageNumber; const page = evt.pageNumber;
PDFViewerApplication.toolbar.setPageNumber(page, evt.pageLabel || null); PDFViewerApplication.toolbar.setPageNumber(page, evt.pageLabel || null);
PDFViewerApplication.secondaryToolbar.setPageNumber(page); PDFViewerApplication.secondaryToolbar.setPageNumber(page);
@ -2329,7 +2328,7 @@ function webViewerPageChanging(evt) {
// We need to update stats. // We need to update stats.
if (typeof Stats !== "undefined" && Stats.enabled) { if (typeof Stats !== "undefined" && Stats.enabled) {
let pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1); const pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1);
if (pageView && pageView.stats) { if (pageView && pageView.stats) {
Stats.add(page, pageView.stats); Stats.add(page, pageView.stats);
} }
@ -2374,27 +2373,27 @@ function webViewerWheel(evt) {
return; return;
} }
let previousScale = pdfViewer.currentScale; const previousScale = pdfViewer.currentScale;
let delta = normalizeWheelEventDelta(evt); const delta = normalizeWheelEventDelta(evt);
const MOUSE_WHEEL_DELTA_PER_PAGE_SCALE = 3.0; const MOUSE_WHEEL_DELTA_PER_PAGE_SCALE = 3.0;
let ticks = delta * MOUSE_WHEEL_DELTA_PER_PAGE_SCALE; const ticks = delta * MOUSE_WHEEL_DELTA_PER_PAGE_SCALE;
if (ticks < 0) { if (ticks < 0) {
PDFViewerApplication.zoomOut(-ticks); PDFViewerApplication.zoomOut(-ticks);
} else { } else {
PDFViewerApplication.zoomIn(ticks); PDFViewerApplication.zoomIn(ticks);
} }
let currentScale = pdfViewer.currentScale; const currentScale = pdfViewer.currentScale;
if (previousScale !== currentScale) { if (previousScale !== currentScale) {
// After scaling the page via zoomIn/zoomOut, the position of the upper- // After scaling the page via zoomIn/zoomOut, the position of the upper-
// left corner is restored. When the mouse wheel is used, the position // left corner is restored. When the mouse wheel is used, the position
// under the cursor should be restored instead. // under the cursor should be restored instead.
let scaleCorrectionFactor = currentScale / previousScale - 1; const scaleCorrectionFactor = currentScale / previousScale - 1;
let rect = pdfViewer.container.getBoundingClientRect(); const rect = pdfViewer.container.getBoundingClientRect();
let dx = evt.clientX - rect.left; const dx = evt.clientX - rect.left;
let dy = evt.clientY - rect.top; const dy = evt.clientY - rect.top;
pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor; pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor;
pdfViewer.container.scrollTop += dy * scaleCorrectionFactor; pdfViewer.container.scrollTop += dy * scaleCorrectionFactor;
} }
@ -2407,7 +2406,7 @@ function webViewerClick(evt) {
if (!PDFViewerApplication.secondaryToolbar.isOpen) { if (!PDFViewerApplication.secondaryToolbar.isOpen) {
return; return;
} }
let appConfig = PDFViewerApplication.appConfig; const appConfig = PDFViewerApplication.appConfig;
if ( if (
PDFViewerApplication.pdfViewer.containsElement(evt.target) || PDFViewerApplication.pdfViewer.containsElement(evt.target) ||
(appConfig.toolbar.container.contains(evt.target) && (appConfig.toolbar.container.contains(evt.target) &&
@ -2424,14 +2423,15 @@ function webViewerKeyDown(evt) {
let handled = false, let handled = false,
ensureViewerFocused = false; ensureViewerFocused = false;
let cmd = const cmd =
(evt.ctrlKey ? 1 : 0) | (evt.ctrlKey ? 1 : 0) |
(evt.altKey ? 2 : 0) | (evt.altKey ? 2 : 0) |
(evt.shiftKey ? 4 : 0) | (evt.shiftKey ? 4 : 0) |
(evt.metaKey ? 8 : 0); (evt.metaKey ? 8 : 0);
let pdfViewer = PDFViewerApplication.pdfViewer; const pdfViewer = PDFViewerApplication.pdfViewer;
let isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode; const isViewerInPresentationMode =
pdfViewer && pdfViewer.isInPresentationMode;
// First, handle the key bindings that are independent whether an input // First, handle the key bindings that are independent whether an input
// control is selected or not. // control is selected or not.
@ -2446,7 +2446,7 @@ function webViewerKeyDown(evt) {
break; break;
case 71: // g case 71: // g
if (!PDFViewerApplication.supportsIntegratedFind) { if (!PDFViewerApplication.supportsIntegratedFind) {
let findState = PDFViewerApplication.findController.state; const findState = PDFViewerApplication.findController.state;
if (findState) { if (findState) {
PDFViewerApplication.findController.executeCommand("findagain", { PDFViewerApplication.findController.executeCommand("findagain", {
query: findState.query, query: findState.query,
@ -2549,8 +2549,8 @@ function webViewerKeyDown(evt) {
// Some shortcuts should not get handled if a control/input element // Some shortcuts should not get handled if a control/input element
// is selected. // is selected.
let curElement = document.activeElement || document.querySelector(":focus"); const curElement = document.activeElement || document.querySelector(":focus");
let curElementTagName = curElement && curElement.tagName.toUpperCase(); const curElementTagName = curElement && curElement.tagName.toUpperCase();
if ( if (
curElementTagName === "INPUT" || curElementTagName === "INPUT" ||
curElementTagName === "TEXTAREA" || curElementTagName === "TEXTAREA" ||
@ -2777,7 +2777,7 @@ function apiPageModeToSidebarView(mode) {
} }
/* Abstract factory for the print service. */ /* Abstract factory for the print service. */
let PDFPrintServiceFactory = { const PDFPrintServiceFactory = {
instance: { instance: {
supportsPrinting: false, supportsPrinting: false,
createPrintService() { createPrintService() {

View File

@ -82,9 +82,9 @@ const DEFAULT_CACHE_SIZE = 10;
*/ */
function PDFPageViewBuffer(size) { function PDFPageViewBuffer(size) {
let data = []; const data = [];
this.push = function(view) { this.push = function(view) {
let i = data.indexOf(view); const i = data.indexOf(view);
if (i >= 0) { if (i >= 0) {
data.splice(i, 1); data.splice(i, 1);
} }
@ -279,7 +279,7 @@ class BaseViewer {
} }
let page = val | 0; // Fallback page number. let page = val | 0; // Fallback page number.
if (this._pageLabels) { if (this._pageLabels) {
let i = this._pageLabels.indexOf(val); const i = this._pageLabels.indexOf(val);
if (i >= 0) { if (i >= 0) {
page = i + 1; page = i + 1;
} }
@ -353,10 +353,10 @@ class BaseViewer {
} }
this._pagesRotation = rotation; this._pagesRotation = rotation;
let pageNumber = this._currentPageNumber; const pageNumber = this._currentPageNumber;
for (let i = 0, ii = this._pages.length; i < ii; i++) { for (let i = 0, ii = this._pages.length; i < ii; i++) {
let pageView = this._pages[i]; const pageView = this._pages[i];
pageView.update(pageView.scale, rotation); pageView.update(pageView.scale, rotation);
} }
// Prevent errors in case the rotation changes *before* the scale has been // Prevent errors in case the rotation changes *before* the scale has been
@ -398,9 +398,9 @@ class BaseViewer {
if (!pdfDocument) { if (!pdfDocument) {
return; return;
} }
let pagesCount = pdfDocument.numPages; const pagesCount = pdfDocument.numPages;
let pagesCapability = createPromiseCapability(); const pagesCapability = createPromiseCapability();
this.pagesPromise = pagesCapability.promise; this.pagesPromise = pagesCapability.promise;
pagesCapability.promise.then(() => { pagesCapability.promise.then(() => {
@ -443,14 +443,14 @@ class BaseViewer {
// viewport for all pages // viewport for all pages
firstPagePromise firstPagePromise
.then(firstPdfPage => { .then(firstPdfPage => {
let scale = this.currentScale; const scale = this.currentScale;
const viewport = firstPdfPage.getViewport({ scale: scale * CSS_UNITS }); const viewport = firstPdfPage.getViewport({ scale: scale * CSS_UNITS });
for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
let textLayerFactory = null; let textLayerFactory = null;
if (this.textLayerMode !== TextLayerMode.DISABLE) { if (this.textLayerMode !== TextLayerMode.DISABLE) {
textLayerFactory = this; textLayerFactory = this;
} }
let pageView = new PDFPageView({ const pageView = new PDFPageView({
container: this._setDocumentViewerElement, container: this._setDocumentViewerElement,
eventBus: this.eventBus, eventBus: this.eventBus,
id: pageNum, id: pageNum,
@ -509,7 +509,7 @@ class BaseViewer {
for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
pdfDocument.getPage(pageNum).then( pdfDocument.getPage(pageNum).then(
pdfPage => { pdfPage => {
let pageView = this._pages[pageNum - 1]; const pageView = this._pages[pageNum - 1];
if (!pageView.pdfPage) { if (!pageView.pdfPage) {
pageView.setPdfPage(pdfPage); pageView.setPdfPage(pdfPage);
} }
@ -561,8 +561,8 @@ class BaseViewer {
} }
// Update all the `PDFPageView` instances. // Update all the `PDFPageView` instances.
for (let i = 0, ii = this._pages.length; i < ii; i++) { for (let i = 0, ii = this._pages.length; i < ii; i++) {
let pageView = this._pages[i]; const pageView = this._pages[i];
let label = this._pageLabels && this._pageLabels[i]; const label = this._pageLabels && this._pageLabels[i];
pageView.setPageLabel(label); pageView.setPageLabel(label);
} }
} }
@ -665,7 +665,7 @@ class BaseViewer {
if (scale > 0) { if (scale > 0) {
this._setScaleUpdatePages(scale, value, noScroll, /* preset = */ false); this._setScaleUpdatePages(scale, value, noScroll, /* preset = */ false);
} else { } else {
let currentPage = this._pages[this._currentPageNumber - 1]; const currentPage = this._pages[this._currentPageNumber - 1];
if (!currentPage) { if (!currentPage) {
return; return;
} }
@ -676,10 +676,10 @@ class BaseViewer {
if (!noPadding && this._isScrollModeHorizontal) { if (!noPadding && this._isScrollModeHorizontal) {
[hPadding, vPadding] = [vPadding, hPadding]; // Swap the padding values. [hPadding, vPadding] = [vPadding, hPadding]; // Swap the padding values.
} }
let pageWidthScale = const pageWidthScale =
((this.container.clientWidth - hPadding) / currentPage.width) * ((this.container.clientWidth - hPadding) / currentPage.width) *
currentPage.scale; currentPage.scale;
let pageHeightScale = const pageHeightScale =
((this.container.clientHeight - vPadding) / currentPage.height) * ((this.container.clientHeight - vPadding) / currentPage.height) *
currentPage.scale; currentPage.scale;
switch (value) { switch (value) {
@ -698,7 +698,7 @@ class BaseViewer {
case "auto": case "auto":
// For pages in landscape mode, fit the page height to the viewer // For pages in landscape mode, fit the page height to the viewer
// *unless* the page would thus become too wide to fit horizontally. // *unless* the page would thus become too wide to fit horizontally.
let horizontalScale = isPortraitOrientation(currentPage) const horizontalScale = isPortraitOrientation(currentPage)
? pageWidthScale ? pageWidthScale
: Math.min(pageHeightScale, pageWidthScale); : Math.min(pageHeightScale, pageWidthScale);
scale = Math.min(MAX_AUTO_SCALE, horizontalScale); scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
@ -723,7 +723,7 @@ class BaseViewer {
this._setScale(this._currentScaleValue, true); this._setScale(this._currentScaleValue, true);
} }
let pageView = this._pages[this._currentPageNumber - 1]; const pageView = this._pages[this._currentPageNumber - 1];
this._scrollIntoView({ pageDiv: pageView.div }); this._scrollIntoView({ pageDiv: pageView.div });
} }
@ -768,12 +768,12 @@ class BaseViewer {
height = 0, height = 0,
widthScale, widthScale,
heightScale; heightScale;
let changeOrientation = pageView.rotation % 180 === 0 ? false : true; const changeOrientation = pageView.rotation % 180 === 0 ? false : true;
let pageWidth = const pageWidth =
(changeOrientation ? pageView.height : pageView.width) / (changeOrientation ? pageView.height : pageView.width) /
pageView.scale / pageView.scale /
CSS_UNITS; CSS_UNITS;
let pageHeight = const pageHeight =
(changeOrientation ? pageView.width : pageView.height) / (changeOrientation ? pageView.width : pageView.height) /
pageView.scale / pageView.scale /
CSS_UNITS; CSS_UNITS;
@ -817,8 +817,8 @@ class BaseViewer {
y = destArray[3]; y = destArray[3];
width = destArray[4] - x; width = destArray[4] - x;
height = destArray[5] - y; height = destArray[5] - y;
let hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING; const hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
let vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING; const vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
widthScale = widthScale =
(this.container.clientWidth - hPadding) / width / CSS_UNITS; (this.container.clientWidth - hPadding) / width / CSS_UNITS;
@ -848,7 +848,7 @@ class BaseViewer {
return; return;
} }
let boundingRect = [ const boundingRect = [
pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x, y),
pageView.viewport.convertToViewportPoint(x + width, y + height), pageView.viewport.convertToViewportPoint(x + width, y + height),
]; ];
@ -870,24 +870,24 @@ class BaseViewer {
} }
_updateLocation(firstPage) { _updateLocation(firstPage) {
let currentScale = this._currentScale; const currentScale = this._currentScale;
let currentScaleValue = this._currentScaleValue; const currentScaleValue = this._currentScaleValue;
let normalizedScaleValue = const normalizedScaleValue =
parseFloat(currentScaleValue) === currentScale parseFloat(currentScaleValue) === currentScale
? Math.round(currentScale * 10000) / 100 ? Math.round(currentScale * 10000) / 100
: currentScaleValue; : currentScaleValue;
let pageNumber = firstPage.id; const pageNumber = firstPage.id;
let pdfOpenParams = "#page=" + pageNumber; let pdfOpenParams = "#page=" + pageNumber;
pdfOpenParams += "&zoom=" + normalizedScaleValue; pdfOpenParams += "&zoom=" + normalizedScaleValue;
let currentPageView = this._pages[pageNumber - 1]; const currentPageView = this._pages[pageNumber - 1];
let container = this.container; const container = this.container;
let topLeft = currentPageView.getPagePoint( const topLeft = currentPageView.getPagePoint(
container.scrollLeft - firstPage.x, container.scrollLeft - firstPage.x,
container.scrollTop - firstPage.y container.scrollTop - firstPage.y
); );
let intLeft = Math.round(topLeft[0]); const intLeft = Math.round(topLeft[0]);
let intTop = Math.round(topLeft[1]); const intTop = Math.round(topLeft[1]);
pdfOpenParams += "," + intLeft + "," + intTop; pdfOpenParams += "," + intLeft + "," + intTop;
this._location = { this._location = {
@ -1066,11 +1066,11 @@ class BaseViewer {
} }
forceRendering(currentlyVisiblePages) { forceRendering(currentlyVisiblePages) {
let visiblePages = currentlyVisiblePages || this._getVisiblePages(); const visiblePages = currentlyVisiblePages || this._getVisiblePages();
let scrollAhead = this._isScrollModeHorizontal const scrollAhead = this._isScrollModeHorizontal
? this.scroll.right ? this.scroll.right
: this.scroll.down; : this.scroll.down;
let pageView = this.renderingQueue.getHighestPriority( const pageView = this.renderingQueue.getHighestPriority(
visiblePages, visiblePages,
this._pages, this._pages,
scrollAhead scrollAhead
@ -1140,9 +1140,9 @@ class BaseViewer {
* widths and heights. * widths and heights.
*/ */
get hasEqualPageSizes() { get hasEqualPageSizes() {
let firstPageView = this._pages[0]; const firstPageView = this._pages[0];
for (let i = 1, ii = this._pages.length; i < ii; ++i) { for (let i = 1, ii = this._pages.length; i < ii; ++i) {
let pageView = this._pages[i]; const pageView = this._pages[i];
if ( if (
pageView.width !== firstPageView.width || pageView.width !== firstPageView.width ||
pageView.height !== firstPageView.height pageView.height !== firstPageView.height
@ -1158,8 +1158,8 @@ class BaseViewer {
* @returns {Array} Array of objects with width/height/rotation fields. * @returns {Array} Array of objects with width/height/rotation fields.
*/ */
getPagesOverview() { getPagesOverview() {
let pagesOverview = this._pages.map(function(pageView) { const pagesOverview = this._pages.map(function(pageView) {
let viewport = pageView.pdfPage.getViewport({ scale: 1 }); const viewport = pageView.pdfPage.getViewport({ scale: 1 });
return { return {
width: viewport.width, width: viewport.width,
height: viewport.height, height: viewport.height,
@ -1169,7 +1169,7 @@ class BaseViewer {
if (!this.enablePrintAutoRotate) { if (!this.enablePrintAutoRotate) {
return pagesOverview; return pagesOverview;
} }
let isFirstPagePortrait = isPortraitOrientation(pagesOverview[0]); const isFirstPagePortrait = isPortraitOrientation(pagesOverview[0]);
return pagesOverview.map(function(size) { return pagesOverview.map(function(size) {
if (isFirstPagePortrait === isPortraitOrientation(size)) { if (isFirstPagePortrait === isPortraitOrientation(size)) {
return size; return size;

View File

@ -26,7 +26,7 @@ if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("CHROME")) {
); );
} }
let ChromeCom = { const ChromeCom = {
/** /**
* Creates an event that the extension is listening for and will * Creates an event that the extension is listening for and will
* asynchronously respond by calling the callback. * asynchronously respond by calling the callback.
@ -38,7 +38,7 @@ let ChromeCom = {
* immediately invoked with no arguments. * immediately invoked with no arguments.
*/ */
request(action, data, callback) { request(action, data, callback) {
let message = { const message = {
action, action,
data, data,
}; };
@ -110,7 +110,7 @@ let ChromeCom = {
}; };
function getEmbedderOrigin(callback) { function getEmbedderOrigin(callback) {
let origin = window === top ? location.origin : location.ancestorOrigins[0]; const origin = window === top ? location.origin : location.ancestorOrigins[0];
if (origin === "null") { if (origin === "null") {
// file:-URLs, data-URLs, sandboxed frames, etc. // file:-URLs, data-URLs, sandboxed frames, etc.
getParentOrigin(callback); getParentOrigin(callback);
@ -171,14 +171,14 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) {
); );
} }
chromeFileAccessOverlayPromise.then(function() { chromeFileAccessOverlayPromise.then(function() {
let iconPath = chrome.runtime.getManifest().icons[48]; const iconPath = chrome.runtime.getManifest().icons[48];
document.getElementById("chrome-pdfjs-logo-bg").style.backgroundImage = document.getElementById("chrome-pdfjs-logo-bg").style.backgroundImage =
"url(" + chrome.runtime.getURL(iconPath) + ")"; "url(" + chrome.runtime.getURL(iconPath) + ")";
// Use Chrome's definition of UI language instead of PDF.js's #lang=..., // Use Chrome's definition of UI language instead of PDF.js's #lang=...,
// because the shown string should match the UI at chrome://extensions. // because the shown string should match the UI at chrome://extensions.
// These strings are from chrome/app/resources/generated_resources_*.xtb. // These strings are from chrome/app/resources/generated_resources_*.xtb.
let i18nFileAccessLabel = PDFJSDev.json( const i18nFileAccessLabel = PDFJSDev.json(
"$ROOT/web/chrome-i18n-allow-access-to-file-urls.json" "$ROOT/web/chrome-i18n-allow-access-to-file-urls.json"
)[chrome.i18n.getUILanguage && chrome.i18n.getUILanguage()]; )[chrome.i18n.getUILanguage && chrome.i18n.getUILanguage()];
@ -188,7 +188,7 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) {
).textContent = i18nFileAccessLabel; ).textContent = i18nFileAccessLabel;
} }
let link = document.getElementById("chrome-link-to-extensions-page"); const link = document.getElementById("chrome-link-to-extensions-page");
link.href = "chrome://extensions/?id=" + chrome.runtime.id; link.href = "chrome://extensions/?id=" + chrome.runtime.id;
link.onclick = function(e) { link.onclick = function(e) {
// Direct navigation to chrome:// URLs is blocked by Chrome, so we // Direct navigation to chrome:// URLs is blocked by Chrome, so we
@ -207,12 +207,12 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) {
document.getElementById("chrome-url-of-local-file").textContent = fileUrl; document.getElementById("chrome-url-of-local-file").textContent = fileUrl;
document.getElementById("chrome-file-fallback").onchange = function() { document.getElementById("chrome-file-fallback").onchange = function() {
let file = this.files[0]; const file = this.files[0];
if (file) { if (file) {
let originalFilename = decodeURIComponent(fileUrl.split("/").pop()); const originalFilename = decodeURIComponent(fileUrl.split("/").pop());
let originalUrl = fileUrl; let originalUrl = fileUrl;
if (originalFilename !== file.name) { if (originalFilename !== file.name) {
let msg = const msg =
"The selected file does not match the original file." + "The selected file does not match the original file." +
"\nOriginal: " + "\nOriginal: " +
originalFilename + originalFilename +
@ -288,7 +288,7 @@ function setReferer(url, callback) {
// back and forward, the background page will not observe a HTTP request // back and forward, the background page will not observe a HTTP request
// with Referer. To make sure that the Referer is preserved, store it in // with Referer. To make sure that the Referer is preserved, store it in
// history.state, which is preserved across reloads/navigations. // history.state, which is preserved across reloads/navigations.
let state = window.history.state || {}; const state = window.history.state || {};
state.chromecomState = referer; state.chromecomState = referer;
window.history.replaceState(state, ""); window.history.replaceState(state, "");
} }
@ -309,13 +309,13 @@ function setReferer(url, callback) {
// chrome.storage.sync is not supported in every Chromium-derivate. // chrome.storage.sync is not supported in every Chromium-derivate.
// Note: The background page takes care of migrating values from // Note: The background page takes care of migrating values from
// chrome.storage.local to chrome.storage.sync when needed. // chrome.storage.local to chrome.storage.sync when needed.
let storageArea = chrome.storage.sync || chrome.storage.local; const storageArea = chrome.storage.sync || chrome.storage.local;
class ChromePreferences extends BasePreferences { class ChromePreferences extends BasePreferences {
async _writeToStorage(prefObj) { async _writeToStorage(prefObj) {
return new Promise(resolve => { return new Promise(resolve => {
if (prefObj === this.defaults) { if (prefObj === this.defaults) {
let keysToRemove = Object.keys(this.defaults); const keysToRemove = Object.keys(this.defaults);
// If the storage is reset, remove the keys so that the values from // If the storage is reset, remove the keys so that the values from
// managed storage are applied again. // managed storage are applied again.
storageArea.remove(keysToRemove, function() { storageArea.remove(keysToRemove, function() {
@ -331,7 +331,7 @@ class ChromePreferences extends BasePreferences {
async _readFromStorage(prefObj) { async _readFromStorage(prefObj) {
return new Promise(resolve => { return new Promise(resolve => {
let getPreferences = defaultPrefs => { const getPreferences = defaultPrefs => {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
// Managed storage not supported, e.g. in Opera. // Managed storage not supported, e.g. in Opera.
defaultPrefs = this.defaults; defaultPrefs = this.defaults;
@ -349,7 +349,7 @@ class ChromePreferences extends BasePreferences {
// Deprecated preferences are removed from web/default_preferences.json, // Deprecated preferences are removed from web/default_preferences.json,
// but kept in extensions/chromium/preferences_schema.json for backwards // but kept in extensions/chromium/preferences_schema.json for backwards
// compatibility with managed preferences. // compatibility with managed preferences.
let defaultManagedPrefs = Object.assign( const defaultManagedPrefs = Object.assign(
{ {
enableHandToolOnLoad: false, enableHandToolOnLoad: false,
disableTextLayer: false, disableTextLayer: false,
@ -404,9 +404,9 @@ class ChromePreferences extends BasePreferences {
} }
} }
let ChromeExternalServices = Object.create(DefaultExternalServices); const ChromeExternalServices = Object.create(DefaultExternalServices);
ChromeExternalServices.initPassiveLoading = function(callbacks) { ChromeExternalServices.initPassiveLoading = function(callbacks) {
let { overlayManager } = PDFViewerApplication; const { overlayManager } = PDFViewerApplication;
// defaultUrl is set in viewer.js // defaultUrl is set in viewer.js
ChromeCom.resolvePDFFile( ChromeCom.resolvePDFFile(
AppOptions.get("defaultUrl"), AppOptions.get("defaultUrl"),

View File

@ -21,20 +21,22 @@ var FontInspector = (function FontInspectorClosure() {
var active = false; var active = false;
var fontAttribute = "data-font-name"; var fontAttribute = "data-font-name";
function removeSelection() { function removeSelection() {
let divs = document.querySelectorAll(`span[${fontAttribute}]`); const divs = document.querySelectorAll(`span[${fontAttribute}]`);
for (let div of divs) { for (const div of divs) {
div.className = ""; div.className = "";
} }
} }
function resetSelection() { function resetSelection() {
let divs = document.querySelectorAll(`span[${fontAttribute}]`); const divs = document.querySelectorAll(`span[${fontAttribute}]`);
for (let div of divs) { for (const div of divs) {
div.className = "debuggerHideText"; div.className = "debuggerHideText";
} }
} }
function selectFont(fontName, show) { function selectFont(fontName, show) {
let divs = document.querySelectorAll(`span[${fontAttribute}=${fontName}]`); const divs = document.querySelectorAll(
for (let div of divs) { `span[${fontAttribute}=${fontName}]`
);
for (const div of divs) {
div.className = show ? "debuggerShowText" : "debuggerHideText"; div.className = show ? "debuggerShowText" : "debuggerHideText";
} }
} }

View File

@ -30,7 +30,7 @@ const DISABLE_CREATE_OBJECT_URL =
apiCompatibilityParams.disableCreateObjectURL || false; apiCompatibilityParams.disableCreateObjectURL || false;
function download(blobUrl, filename) { function download(blobUrl, filename) {
let a = document.createElement("a"); const a = document.createElement("a");
if (!a.click) { if (!a.click) {
throw new Error('DownloadManager: "a.click()" is not supported.'); throw new Error('DownloadManager: "a.click()" is not supported.');
} }
@ -66,7 +66,7 @@ class DownloadManager {
navigator.msSaveBlob(new Blob([data], { type: contentType }), filename); navigator.msSaveBlob(new Blob([data], { type: contentType }), filename);
return; return;
} }
let blobUrl = createObjectURL( const blobUrl = createObjectURL(
data, data,
contentType, contentType,
this.disableCreateObjectURL this.disableCreateObjectURL
@ -89,7 +89,7 @@ class DownloadManager {
return; return;
} }
let blobUrl = URL.createObjectURL(blob); const blobUrl = URL.createObjectURL(blob);
download(blobUrl, filename); download(blobUrl, filename);
} }
} }

View File

@ -20,7 +20,7 @@ import { shadow } from "pdfjs-lib";
// Creates a placeholder with div and canvas with right size for the page. // Creates a placeholder with div and canvas with right size for the page.
function composePage(pdfDocument, pageNumber, size, printContainer) { function composePage(pdfDocument, pageNumber, size, printContainer) {
let canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
// The size of the canvas in pixels for printing. // The size of the canvas in pixels for printing.
const PRINT_RESOLUTION = AppOptions.get("printResolution") || 150; const PRINT_RESOLUTION = AppOptions.get("printResolution") || 150;
@ -32,13 +32,13 @@ function composePage(pdfDocument, pageNumber, size, printContainer) {
canvas.style.width = Math.floor(size.width * CSS_UNITS) + "px"; canvas.style.width = Math.floor(size.width * CSS_UNITS) + "px";
canvas.style.height = Math.floor(size.height * CSS_UNITS) + "px"; canvas.style.height = Math.floor(size.height * CSS_UNITS) + "px";
let canvasWrapper = document.createElement("div"); const canvasWrapper = document.createElement("div");
canvasWrapper.appendChild(canvas); canvasWrapper.appendChild(canvas);
printContainer.appendChild(canvasWrapper); printContainer.appendChild(canvasWrapper);
canvas.mozPrintCallback = function(obj) { canvas.mozPrintCallback = function(obj) {
// Printing/rendering the page. // Printing/rendering the page.
let ctx = obj.context; const ctx = obj.context;
ctx.save(); ctx.save();
ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillStyle = "rgb(255, 255, 255)";
@ -48,7 +48,7 @@ function composePage(pdfDocument, pageNumber, size, printContainer) {
pdfDocument pdfDocument
.getPage(pageNumber) .getPage(pageNumber)
.then(function(pdfPage) { .then(function(pdfPage) {
let renderContext = { const renderContext = {
canvasContext: ctx, canvasContext: ctx,
transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0], transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
viewport: pdfPage.getViewport({ scale: 1, rotation: size.rotation }), viewport: pdfPage.getViewport({ scale: 1, rotation: size.rotation }),
@ -103,8 +103,8 @@ FirefoxPrintService.prototype = {
PDFPrintServiceFactory.instance = { PDFPrintServiceFactory.instance = {
get supportsPrinting() { get supportsPrinting() {
let canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
let value = "mozPrintCallback" in canvas; const value = "mozPrintCallback" in canvas;
return shadow(this, "supportsPrinting", value); return shadow(this, "supportsPrinting", value);
}, },

View File

@ -29,7 +29,7 @@ if (
); );
} }
let FirefoxCom = (function FirefoxComClosure() { const FirefoxCom = (function FirefoxComClosure() {
return { return {
/** /**
* Creates an event that the extension is listening for and will * Creates an event that the extension is listening for and will
@ -41,17 +41,17 @@ let FirefoxCom = (function FirefoxComClosure() {
* @returns {*} The response. * @returns {*} The response.
*/ */
requestSync(action, data) { requestSync(action, data) {
let request = document.createTextNode(""); const request = document.createTextNode("");
document.documentElement.appendChild(request); document.documentElement.appendChild(request);
let sender = document.createEvent("CustomEvent"); const sender = document.createEvent("CustomEvent");
sender.initCustomEvent("pdf.js.message", true, false, { sender.initCustomEvent("pdf.js.message", true, false, {
action, action,
data, data,
sync: true, sync: true,
}); });
request.dispatchEvent(sender); request.dispatchEvent(sender);
let response = sender.detail.response; const response = sender.detail.response;
document.documentElement.removeChild(request); document.documentElement.removeChild(request);
return response; return response;
}, },
@ -65,11 +65,11 @@ let FirefoxCom = (function FirefoxComClosure() {
* with one data argument. * with one data argument.
*/ */
request(action, data, callback) { request(action, data, callback) {
let request = document.createTextNode(""); const request = document.createTextNode("");
if (callback) { if (callback) {
document.addEventListener("pdf.js.response", function listener(event) { document.addEventListener("pdf.js.response", function listener(event) {
let node = event.target; const node = event.target;
let response = event.detail.response; const response = event.detail.response;
document.documentElement.removeChild(node); document.documentElement.removeChild(node);
@ -79,7 +79,7 @@ let FirefoxCom = (function FirefoxComClosure() {
} }
document.documentElement.appendChild(request); document.documentElement.appendChild(request);
let sender = document.createEvent("CustomEvent"); const sender = document.createEvent("CustomEvent");
sender.initCustomEvent("pdf.js.message", true, false, { sender.initCustomEvent("pdf.js.message", true, false, {
action, action,
data, data,
@ -104,7 +104,7 @@ class DownloadManager {
} }
downloadData(data, filename, contentType) { downloadData(data, filename, contentType) {
let blobUrl = createObjectURL(data, contentType); const blobUrl = createObjectURL(data, contentType);
FirefoxCom.request("download", { FirefoxCom.request("download", {
blobUrl, blobUrl,
@ -115,8 +115,8 @@ class DownloadManager {
} }
download(blob, url, filename) { download(blob, url, filename) {
let blobUrl = URL.createObjectURL(blob); const blobUrl = URL.createObjectURL(blob);
let onResponse = err => { const onResponse = err => {
if (err && this.onerror) { if (err && this.onerror) {
this.onerror(err); this.onerror(err);
} }
@ -145,7 +145,7 @@ class FirefoxPreferences extends BasePreferences {
async _readFromStorage(prefObj) { async _readFromStorage(prefObj) {
return new Promise(function(resolve) { return new Promise(function(resolve) {
FirefoxCom.request("getPreferences", prefObj, function(prefStr) { FirefoxCom.request("getPreferences", prefObj, function(prefStr) {
let readPrefs = JSON.parse(prefStr); const readPrefs = JSON.parse(prefStr);
resolve(readPrefs); resolve(readPrefs);
}); });
}); });
@ -259,7 +259,7 @@ PDFViewerApplication.externalServices = {
console.warn("Rejected untrusted message from " + e.origin); console.warn("Rejected untrusted message from " + e.origin);
return; return;
} }
let args = e.data; const args = e.data;
if (typeof args !== "object" || !("pdfjsLoadAction" in args)) { if (typeof args !== "object" || !("pdfjsLoadAction" in args)) {
return; return;
@ -328,28 +328,30 @@ PDFViewerApplication.externalServices = {
}, },
createL10n(options) { createL10n(options) {
let mozL10n = document.mozL10n; const mozL10n = document.mozL10n;
// TODO refactor mozL10n.setExternalLocalizerServices // TODO refactor mozL10n.setExternalLocalizerServices
return new MozL10n(mozL10n); return new MozL10n(mozL10n);
}, },
get supportsIntegratedFind() { get supportsIntegratedFind() {
let support = FirefoxCom.requestSync("supportsIntegratedFind"); const support = FirefoxCom.requestSync("supportsIntegratedFind");
return shadow(this, "supportsIntegratedFind", support); return shadow(this, "supportsIntegratedFind", support);
}, },
get supportsDocumentFonts() { get supportsDocumentFonts() {
let support = FirefoxCom.requestSync("supportsDocumentFonts"); const support = FirefoxCom.requestSync("supportsDocumentFonts");
return shadow(this, "supportsDocumentFonts", support); return shadow(this, "supportsDocumentFonts", support);
}, },
get supportsDocumentColors() { get supportsDocumentColors() {
let support = FirefoxCom.requestSync("supportsDocumentColors"); const support = FirefoxCom.requestSync("supportsDocumentColors");
return shadow(this, "supportsDocumentColors", support); return shadow(this, "supportsDocumentColors", support);
}, },
get supportedMouseWheelZoomModifierKeys() { get supportedMouseWheelZoomModifierKeys() {
let support = FirefoxCom.requestSync("supportedMouseWheelZoomModifierKeys"); const support = FirefoxCom.requestSync(
"supportedMouseWheelZoomModifierKeys"
);
return shadow(this, "supportedMouseWheelZoomModifierKeys", support); return shadow(this, "supportedMouseWheelZoomModifierKeys", support);
}, },
}; };

View File

@ -25,7 +25,7 @@ if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("GENERIC")) {
); );
} }
let GenericCom = {}; const GenericCom = {};
class GenericPreferences extends BasePreferences { class GenericPreferences extends BasePreferences {
async _writeToStorage(prefObj) { async _writeToStorage(prefObj) {
@ -37,7 +37,7 @@ class GenericPreferences extends BasePreferences {
} }
} }
let GenericExternalServices = Object.create(DefaultExternalServices); const GenericExternalServices = Object.create(DefaultExternalServices);
GenericExternalServices.createDownloadManager = function(options) { GenericExternalServices.createDownloadManager = function(options) {
return new DownloadManager(options); return new DownloadManager(options);
}; };

View File

@ -15,7 +15,7 @@
import "../external/webL10n/l10n"; import "../external/webL10n/l10n";
let webL10n = document.webL10n; const webL10n = document.webL10n;
class GenericL10n { class GenericL10n {
constructor(lang) { constructor(lang) {

View File

@ -97,7 +97,7 @@ class PasswordPrompt {
} }
verify() { verify() {
let password = this.input.value; const password = this.input.value;
if (password && password.length > 0) { if (password && password.length > 0) {
this.close(); this.close();
this.updateCallback(password); this.updateCallback(password);

View File

@ -135,18 +135,18 @@ class PDFAttachmentViewer {
return; return;
} }
let names = Object.keys(attachments).sort(function(a, b) { const names = Object.keys(attachments).sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase()); return a.toLowerCase().localeCompare(b.toLowerCase());
}); });
attachmentsCount = names.length; attachmentsCount = names.length;
for (let i = 0; i < attachmentsCount; i++) { for (let i = 0; i < attachmentsCount; i++) {
let item = attachments[names[i]]; const item = attachments[names[i]];
let filename = removeNullCharacters(getFilenameFromUrl(item.filename)); const filename = removeNullCharacters(getFilenameFromUrl(item.filename));
let div = document.createElement("div"); const div = document.createElement("div");
div.className = "attachmentsItem"; div.className = "attachmentsItem";
let button = document.createElement("button"); const button = document.createElement("button");
button.textContent = filename; button.textContent = filename;
if ( if (
/\.pdf$/i.test(filename) && /\.pdf$/i.test(filename) &&
@ -175,7 +175,7 @@ class PDFAttachmentViewer {
if (!attachments) { if (!attachments) {
attachments = Object.create(null); attachments = Object.create(null);
} else { } else {
for (let name in attachments) { for (const name in attachments) {
if (id === name) { if (id === name) {
return; // Ignore the new attachment if it already exists. return; // Ignore the new attachment if it already exists.
} }

View File

@ -74,7 +74,7 @@ class PDFCursorTools {
return; // The requested tool is already active. return; // The requested tool is already active.
} }
let disableActiveTool = () => { const disableActiveTool = () => {
switch (this.active) { switch (this.active) {
case CursorTool.SELECT: case CursorTool.SELECT:
break; break;

View File

@ -102,7 +102,7 @@ class PDFDocumentProperties {
* Open the document properties overlay. * Open the document properties overlay.
*/ */
open() { open() {
let freezeFieldData = data => { const freezeFieldData = data => {
Object.defineProperty(this, "fieldData", { Object.defineProperty(this, "fieldData", {
value: Object.freeze(data), value: Object.freeze(data),
writable: false, writable: false,
@ -193,7 +193,7 @@ class PDFDocumentProperties {
if (fileSize === this.fieldData["fileSize"]) { if (fileSize === this.fieldData["fileSize"]) {
return; // The fileSize has already been correctly set. return; // The fileSize has already been correctly set.
} }
let data = Object.assign(Object.create(null), this.fieldData); const data = Object.assign(Object.create(null), this.fieldData);
data["fileSize"] = fileSize; data["fileSize"] = fileSize;
freezeFieldData(data); freezeFieldData(data);
@ -267,7 +267,7 @@ class PDFDocumentProperties {
*/ */
_updateUI(reset = false) { _updateUI(reset = false) {
if (reset || !this.fieldData) { if (reset || !this.fieldData) {
for (let id in this.fields) { for (const id in this.fields) {
this.fields[id].textContent = DEFAULT_FIELD_CONTENT; this.fields[id].textContent = DEFAULT_FIELD_CONTENT;
} }
return; return;
@ -277,8 +277,8 @@ class PDFDocumentProperties {
// since it will be updated the next time `this.open` is called. // since it will be updated the next time `this.open` is called.
return; return;
} }
for (let id in this.fields) { for (const id in this.fields) {
let content = this.fieldData[id]; const content = this.fieldData[id];
this.fields[id].textContent = this.fields[id].textContent =
content || content === 0 ? content : DEFAULT_FIELD_CONTENT; content || content === 0 ? content : DEFAULT_FIELD_CONTENT;
} }
@ -288,7 +288,7 @@ class PDFDocumentProperties {
* @private * @private
*/ */
async _parseFileSize(fileSize = 0) { async _parseFileSize(fileSize = 0) {
let kb = fileSize / 1024; const kb = fileSize / 1024;
if (!kb) { if (!kb) {
return undefined; return undefined;
} else if (kb < 1024) { } else if (kb < 1024) {

View File

@ -153,8 +153,8 @@ class PDFFindBar {
if (!this.findResultsCount) { if (!this.findResultsCount) {
return; // No UI control is provided. return; // No UI control is provided.
} }
let matchesCountMsg = "", const limit = MATCHES_COUNT_LIMIT;
limit = MATCHES_COUNT_LIMIT; let matchesCountMsg = "";
if (total > 0) { if (total > 0) {
if (total > limit) { if (total > limit) {
@ -255,8 +255,8 @@ class PDFFindBar {
// wrapped). Here we detect and fix that. // wrapped). Here we detect and fix that.
this.bar.classList.remove("wrapContainers"); this.bar.classList.remove("wrapContainers");
let findbarHeight = this.bar.clientHeight; const findbarHeight = this.bar.clientHeight;
let inputContainerHeight = this.bar.firstElementChild.clientHeight; const inputContainerHeight = this.bar.firstElementChild.clientHeight;
if (findbarHeight > inputContainerHeight) { if (findbarHeight > inputContainerHeight) {
// The findbar is taller than the input container, which means that // The findbar is taller than the input container, which means that

View File

@ -136,7 +136,7 @@ class PDFHistory {
// The browser history contains a valid entry, ensure that the history is // The browser history contains a valid entry, ensure that the history is
// initialized correctly on PDF document load. // initialized correctly on PDF document load.
let destination = state.destination; const destination = state.destination;
this._updateInternalState( this._updateInternalState(
destination, destination,
state.uid, state.uid,
@ -221,7 +221,7 @@ class PDFHistory {
} }
} }
let hash = namedDest || JSON.stringify(explicitDest); const hash = namedDest || JSON.stringify(explicitDest);
if (!hash) { if (!hash) {
// The hash *should* never be undefined, but if that were to occur, // The hash *should* never be undefined, but if that were to occur,
// avoid any possible issues by not updating the browser history. // avoid any possible issues by not updating the browser history.
@ -288,7 +288,7 @@ class PDFHistory {
if (!this._initialized || this._popStateInProgress) { if (!this._initialized || this._popStateInProgress) {
return; return;
} }
let state = window.history.state; const state = window.history.state;
if (this._isValidState(state) && state.uid > 0) { if (this._isValidState(state) && state.uid > 0) {
window.history.back(); window.history.back();
} }
@ -302,7 +302,7 @@ class PDFHistory {
if (!this._initialized || this._popStateInProgress) { if (!this._initialized || this._popStateInProgress) {
return; return;
} }
let state = window.history.state; const state = window.history.state;
if (this._isValidState(state) && state.uid < this._maxUid) { if (this._isValidState(state) && state.uid < this._maxUid) {
window.history.forward(); window.history.forward();
} }
@ -331,8 +331,8 @@ class PDFHistory {
* @private * @private
*/ */
_pushOrReplaceState(destination, forceReplace = false) { _pushOrReplaceState(destination, forceReplace = false) {
let shouldReplace = forceReplace || !this._destination; const shouldReplace = forceReplace || !this._destination;
let newState = { const newState = {
fingerprint: this._fingerprint, fingerprint: this._fingerprint,
uid: shouldReplace ? this._uid : this._uid + 1, uid: shouldReplace ? this._uid : this._uid + 1,
destination, destination,
@ -575,7 +575,7 @@ class PDFHistory {
* @private * @private
*/ */
_popState({ state }) { _popState({ state }) {
let newHash = getCurrentHash(), const newHash = getCurrentHash(),
hashChanged = this._currentHash !== newHash; hashChanged = this._currentHash !== newHash;
this._currentHash = newHash; this._currentHash = newHash;
@ -628,7 +628,7 @@ class PDFHistory {
} }
// Navigate to the new destination. // Navigate to the new destination.
let destination = state.destination; const destination = state.destination;
this._updateInternalState( this._updateInternalState(
destination, destination,
state.uid, state.uid,
@ -711,7 +711,7 @@ function isDestHashesEqual(destHash, pushHash) {
if (destHash === pushHash) { if (destHash === pushHash) {
return true; return true;
} }
let { nameddest } = parseQueryString(destHash); const { nameddest } = parseQueryString(destHash);
if (nameddest === pushHash) { if (nameddest === pushHash) {
return true; return true;
} }
@ -730,7 +730,7 @@ function isDestArraysEqual(firstDest, secondDest) {
if (Object.keys(first).length !== Object.keys(second).length) { if (Object.keys(first).length !== Object.keys(second).length) {
return false; return false;
} }
for (let key in first) { for (const key in first) {
if (!isEntryEqual(first[key], second[key])) { if (!isEntryEqual(first[key], second[key])) {
return false; return false;
} }

View File

@ -106,10 +106,10 @@ class PDFLinkService {
* @param {string|Array} dest - The named, or explicit, PDF destination. * @param {string|Array} dest - The named, or explicit, PDF destination.
*/ */
navigateTo(dest) { navigateTo(dest) {
let goToDestination = ({ namedDest, explicitDest }) => { const goToDestination = ({ namedDest, explicitDest }) => {
// Dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..> // Dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
let destRef = explicitDest[0], const destRef = explicitDest[0];
pageNumber; let pageNumber;
if (destRef instanceof Object) { if (destRef instanceof Object) {
pageNumber = this._cachedPageNumber(destRef); pageNumber = this._cachedPageNumber(destRef);
@ -196,7 +196,7 @@ class PDFLinkService {
return this.getAnchorUrl("#" + escape(dest)); return this.getAnchorUrl("#" + escape(dest));
} }
if (Array.isArray(dest)) { if (Array.isArray(dest)) {
let str = JSON.stringify(dest); const str = JSON.stringify(dest);
return this.getAnchorUrl("#" + escape(str)); return this.getAnchorUrl("#" + escape(str));
} }
return this.getAnchorUrl(""); return this.getAnchorUrl("");
@ -218,7 +218,7 @@ class PDFLinkService {
setHash(hash) { setHash(hash) {
let pageNumber, dest; let pageNumber, dest;
if (hash.includes("=")) { if (hash.includes("=")) {
let params = parseQueryString(hash); const params = parseQueryString(hash);
if ("search" in params) { if ("search" in params) {
this.eventBus.dispatch("findfromurlhash", { this.eventBus.dispatch("findfromurlhash", {
source: this, source: this,
@ -236,9 +236,9 @@ class PDFLinkService {
} }
if ("zoom" in params) { if ("zoom" in params) {
// Build the destination array. // Build the destination array.
let zoomArgs = params.zoom.split(","); // scale,left,top const zoomArgs = params.zoom.split(","); // scale,left,top
let zoomArg = zoomArgs[0]; const zoomArg = zoomArgs[0];
let zoomArgNumber = parseFloat(zoomArg); const zoomArgNumber = parseFloat(zoomArg);
if (!zoomArg.includes("Fit")) { if (!zoomArg.includes("Fit")) {
// If the zoomArg is a number, it has to get divided by 100. If it's // If the zoomArg is a number, it has to get divided by 100. If it's
@ -405,12 +405,11 @@ function isValidExplicitDestination(dest) {
if (!Array.isArray(dest)) { if (!Array.isArray(dest)) {
return false; return false;
} }
let destLength = dest.length, const destLength = dest.length;
allowNull = true;
if (destLength < 2) { if (destLength < 2) {
return false; return false;
} }
let page = dest[0]; const page = dest[0];
if ( if (
!( !(
typeof page === "object" && typeof page === "object" &&
@ -421,10 +420,11 @@ function isValidExplicitDestination(dest) {
) { ) {
return false; return false;
} }
let zoom = dest[1]; const zoom = dest[1];
if (!(typeof zoom === "object" && typeof zoom.name === "string")) { if (!(typeof zoom === "object" && typeof zoom.name === "string")) {
return false; return false;
} }
let allowNull = true;
switch (zoom.name) { switch (zoom.name) {
case "XYZ": case "XYZ":
if (destLength !== 5) { if (destLength !== 5) {
@ -452,7 +452,7 @@ function isValidExplicitDestination(dest) {
return false; return false;
} }
for (let i = 2; i < destLength; i++) { for (let i = 2; i < destLength; i++) {
let param = dest[i]; const param = dest[i];
if (!(typeof param === "number" || (allowNull && param === null))) { if (!(typeof param === "number" || (allowNull && param === null))) {
return false; return false;
} }

View File

@ -69,7 +69,7 @@ class PDFOutlineViewer {
* @private * @private
*/ */
_bindLink(element, { url, newWindow, dest }) { _bindLink(element, { url, newWindow, dest }) {
let { linkService } = this; const { linkService } = this;
if (url) { if (url) {
addLinkAttributes(element, { addLinkAttributes(element, {
@ -114,7 +114,7 @@ class PDFOutlineViewer {
* @private * @private
*/ */
_addToggleButton(div, { count, items }) { _addToggleButton(div, { count, items }) {
let toggler = document.createElement("div"); const toggler = document.createElement("div");
toggler.className = "outlineItemToggler"; toggler.className = "outlineItemToggler";
if (count < 0 && Math.abs(count) === items.length) { if (count < 0 && Math.abs(count) === items.length) {
toggler.classList.add("outlineItemsHidden"); toggler.classList.add("outlineItemsHidden");
@ -124,7 +124,7 @@ class PDFOutlineViewer {
toggler.classList.toggle("outlineItemsHidden"); toggler.classList.toggle("outlineItemsHidden");
if (evt.shiftKey) { if (evt.shiftKey) {
let shouldShowAll = !toggler.classList.contains("outlineItemsHidden"); const shouldShowAll = !toggler.classList.contains("outlineItemsHidden");
this._toggleOutlineItem(div, shouldShowAll); this._toggleOutlineItem(div, shouldShowAll);
} }
}; };
@ -173,16 +173,16 @@ class PDFOutlineViewer {
return; return;
} }
let fragment = document.createDocumentFragment(); const fragment = document.createDocumentFragment();
let queue = [{ parent: fragment, items: this.outline }]; const queue = [{ parent: fragment, items: this.outline }];
let hasAnyNesting = false; let hasAnyNesting = false;
while (queue.length > 0) { while (queue.length > 0) {
const levelData = queue.shift(); const levelData = queue.shift();
for (const item of levelData.items) { for (const item of levelData.items) {
let div = document.createElement("div"); const div = document.createElement("div");
div.className = "outlineItem"; div.className = "outlineItem";
let element = document.createElement("a"); const element = document.createElement("a");
this._bindLink(element, item); this._bindLink(element, item);
this._setStyles(element, item); this._setStyles(element, item);
element.textContent = removeNullCharacters(item.title) || DEFAULT_TITLE; element.textContent = removeNullCharacters(item.title) || DEFAULT_TITLE;
@ -193,7 +193,7 @@ class PDFOutlineViewer {
hasAnyNesting = true; hasAnyNesting = true;
this._addToggleButton(div, item); this._addToggleButton(div, item);
let itemsDiv = document.createElement("div"); const itemsDiv = document.createElement("div");
itemsDiv.className = "outlineItems"; itemsDiv.className = "outlineItems";
div.appendChild(itemsDiv); div.appendChild(itemsDiv);
queue.push({ parent: itemsDiv, items: item.items }); queue.push({ parent: itemsDiv, items: item.items });

View File

@ -71,8 +71,8 @@ class PDFPageView {
* @param {PDFPageViewOptions} options * @param {PDFPageViewOptions} options
*/ */
constructor(options) { constructor(options) {
let container = options.container; const container = options.container;
let defaultViewport = options.defaultViewport; const defaultViewport = options.defaultViewport;
this.id = options.id; this.id = options.id;
this.renderingId = "page" + this.id; this.renderingId = "page" + this.id;
@ -110,7 +110,7 @@ class PDFPageView {
this.textLayer = null; this.textLayer = null;
this.zoomLayer = null; this.zoomLayer = null;
let div = document.createElement("div"); const div = document.createElement("div");
div.className = "page"; div.className = "page";
div.style.width = Math.floor(this.viewport.width) + "px"; div.style.width = Math.floor(this.viewport.width) + "px";
div.style.height = Math.floor(this.viewport.height) + "px"; div.style.height = Math.floor(this.viewport.height) + "px";
@ -124,7 +124,7 @@ class PDFPageView {
this.pdfPage = pdfPage; this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate; this.pdfPageRotate = pdfPage.rotate;
let totalRotation = (this.rotation + this.pdfPageRotate) % 360; const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport({ this.viewport = pdfPage.getViewport({
scale: this.scale * CSS_UNITS, scale: this.scale * CSS_UNITS,
rotation: totalRotation, rotation: totalRotation,
@ -147,7 +147,7 @@ class PDFPageView {
if (!this.zoomLayer) { if (!this.zoomLayer) {
return; return;
} }
let zoomLayerCanvas = this.zoomLayer.firstChild; const zoomLayerCanvas = this.zoomLayer.firstChild;
this.paintedViewportMap.delete(zoomLayerCanvas); this.paintedViewportMap.delete(zoomLayerCanvas);
// Zeroing the width and height causes Firefox to release graphics // Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption. // resources immediately, which can greatly reduce memory consumption.
@ -165,17 +165,17 @@ class PDFPageView {
this.cancelRendering(keepAnnotations); this.cancelRendering(keepAnnotations);
this.renderingState = RenderingStates.INITIAL; this.renderingState = RenderingStates.INITIAL;
let div = this.div; const div = this.div;
div.style.width = Math.floor(this.viewport.width) + "px"; div.style.width = Math.floor(this.viewport.width) + "px";
div.style.height = Math.floor(this.viewport.height) + "px"; div.style.height = Math.floor(this.viewport.height) + "px";
let childNodes = div.childNodes; const childNodes = div.childNodes;
let currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null; const currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
let currentAnnotationNode = const currentAnnotationNode =
(keepAnnotations && this.annotationLayer && this.annotationLayer.div) || (keepAnnotations && this.annotationLayer && this.annotationLayer.div) ||
null; null;
for (let i = childNodes.length - 1; i >= 0; i--) { for (let i = childNodes.length - 1; i >= 0; i--) {
let node = childNodes[i]; const node = childNodes[i];
if (currentZoomLayerNode === node || currentAnnotationNode === node) { if (currentZoomLayerNode === node || currentAnnotationNode === node) {
continue; continue;
} }
@ -220,7 +220,7 @@ class PDFPageView {
this.rotation = rotation; this.rotation = rotation;
} }
let totalRotation = (this.rotation + this.pdfPageRotate) % 360; const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({ this.viewport = this.viewport.clone({
scale: this.scale * CSS_UNITS, scale: this.scale * CSS_UNITS,
rotation: totalRotation, rotation: totalRotation,
@ -240,7 +240,7 @@ class PDFPageView {
let isScalingRestricted = false; let isScalingRestricted = false;
if (this.canvas && this.maxCanvasPixels > 0) { if (this.canvas && this.maxCanvasPixels > 0) {
let outputScale = this.outputScale; const outputScale = this.outputScale;
if ( if (
((Math.floor(this.viewport.width) * outputScale.sx) | 0) * ((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
((Math.floor(this.viewport.height) * outputScale.sy) | 0) > ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
@ -299,17 +299,17 @@ class PDFPageView {
cssTransform(target, redrawAnnotations = false) { cssTransform(target, redrawAnnotations = false) {
// Scale target (canvas or svg), its wrapper and page container. // Scale target (canvas or svg), its wrapper and page container.
let width = this.viewport.width; const width = this.viewport.width;
let height = this.viewport.height; const height = this.viewport.height;
let div = this.div; const div = this.div;
target.style.width = target.parentNode.style.width = div.style.width = target.style.width = target.parentNode.style.width = div.style.width =
Math.floor(width) + "px"; Math.floor(width) + "px";
target.style.height = target.parentNode.style.height = div.style.height = target.style.height = target.parentNode.style.height = div.style.height =
Math.floor(height) + "px"; Math.floor(height) + "px";
// The canvas may have been originally rotated; rotate relative to that. // The canvas may have been originally rotated; rotate relative to that.
let relativeRotation = const relativeRotation =
this.viewport.rotation - this.paintedViewportMap.get(target).rotation; this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
let absRotation = Math.abs(relativeRotation); const absRotation = Math.abs(relativeRotation);
let scaleX = 1, let scaleX = 1,
scaleY = 1; scaleY = 1;
if (absRotation === 90 || absRotation === 270) { if (absRotation === 90 || absRotation === 270) {
@ -317,7 +317,7 @@ class PDFPageView {
scaleX = height / width; scaleX = height / width;
scaleY = width / height; scaleY = width / height;
} }
let cssTransform = const cssTransform =
"rotate(" + "rotate(" +
relativeRotation + relativeRotation +
"deg) " + "deg) " +
@ -333,15 +333,15 @@ class PDFPageView {
// the text layer are rotated. // the text layer are rotated.
// TODO: This could probably be simplified by drawing the text layer in // TODO: This could probably be simplified by drawing the text layer in
// one orientation and then rotating overall. // one orientation and then rotating overall.
let textLayerViewport = this.textLayer.viewport; const textLayerViewport = this.textLayer.viewport;
let textRelativeRotation = const textRelativeRotation =
this.viewport.rotation - textLayerViewport.rotation; this.viewport.rotation - textLayerViewport.rotation;
let textAbsRotation = Math.abs(textRelativeRotation); const textAbsRotation = Math.abs(textRelativeRotation);
let scale = width / textLayerViewport.width; let scale = width / textLayerViewport.width;
if (textAbsRotation === 90 || textAbsRotation === 270) { if (textAbsRotation === 90 || textAbsRotation === 270) {
scale = width / textLayerViewport.height; scale = width / textLayerViewport.height;
} }
let textLayerDiv = this.textLayer.textLayerDiv; const textLayerDiv = this.textLayer.textLayerDiv;
let transX, transY; let transX, transY;
switch (textAbsRotation) { switch (textAbsRotation) {
case 0: case 0:
@ -411,11 +411,11 @@ class PDFPageView {
this.renderingState = RenderingStates.RUNNING; this.renderingState = RenderingStates.RUNNING;
let pdfPage = this.pdfPage; const pdfPage = this.pdfPage;
let div = this.div; const div = this.div;
// Wrap the canvas so that if it has a CSS transform for high DPI the // Wrap the canvas so that if it has a CSS transform for high DPI the
// overflow will be hidden in Firefox. // overflow will be hidden in Firefox.
let canvasWrapper = document.createElement("div"); const canvasWrapper = document.createElement("div");
canvasWrapper.style.width = div.style.width; canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height; canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add("canvasWrapper"); canvasWrapper.classList.add("canvasWrapper");
@ -429,7 +429,7 @@ class PDFPageView {
let textLayer = null; let textLayer = null;
if (this.textLayerMode !== TextLayerMode.DISABLE && this.textLayerFactory) { if (this.textLayerMode !== TextLayerMode.DISABLE && this.textLayerFactory) {
let textLayerDiv = document.createElement("div"); const textLayerDiv = document.createElement("div");
textLayerDiv.className = "textLayer"; textLayerDiv.className = "textLayer";
textLayerDiv.style.width = canvasWrapper.style.width; textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height; textLayerDiv.style.height = canvasWrapper.style.height;
@ -500,18 +500,18 @@ class PDFPageView {
} }
}; };
let paintTask = const paintTask =
this.renderer === RendererType.SVG this.renderer === RendererType.SVG
? this.paintOnSvg(canvasWrapper) ? this.paintOnSvg(canvasWrapper)
: this.paintOnCanvas(canvasWrapper); : this.paintOnCanvas(canvasWrapper);
paintTask.onRenderContinue = renderContinueCallback; paintTask.onRenderContinue = renderContinueCallback;
this.paintTask = paintTask; this.paintTask = paintTask;
let resultPromise = paintTask.promise.then( const resultPromise = paintTask.promise.then(
function() { function() {
return finishPaintTask(null).then(function() { return finishPaintTask(null).then(function() {
if (textLayer) { if (textLayer) {
let readableStream = pdfPage.streamTextContent({ const readableStream = pdfPage.streamTextContent({
normalizeWhitespace: true, normalizeWhitespace: true,
}); });
textLayer.setTextContentStream(readableStream); textLayer.setTextContentStream(readableStream);
@ -546,8 +546,8 @@ class PDFPageView {
} }
paintOnCanvas(canvasWrapper) { paintOnCanvas(canvasWrapper) {
let renderCapability = createPromiseCapability(); const renderCapability = createPromiseCapability();
let result = { const result = {
promise: renderCapability.promise, promise: renderCapability.promise,
onRenderContinue(cont) { onRenderContinue(cont) {
cont(); cont();
@ -557,15 +557,15 @@ class PDFPageView {
}, },
}; };
let viewport = this.viewport; const viewport = this.viewport;
let canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
canvas.id = this.renderingId; canvas.id = this.renderingId;
// Keep the canvas hidden until the first draw callback, or until drawing // Keep the canvas hidden until the first draw callback, or until drawing
// is complete when `!this.renderingQueue`, to prevent black flickering. // is complete when `!this.renderingQueue`, to prevent black flickering.
canvas.setAttribute("hidden", "hidden"); canvas.setAttribute("hidden", "hidden");
let isCanvasHidden = true; let isCanvasHidden = true;
let showCanvas = function() { const showCanvas = function() {
if (isCanvasHidden) { if (isCanvasHidden) {
canvas.removeAttribute("hidden"); canvas.removeAttribute("hidden");
isCanvasHidden = false; isCanvasHidden = false;
@ -582,12 +582,12 @@ class PDFPageView {
canvas.mozOpaque = true; canvas.mozOpaque = true;
} }
let ctx = canvas.getContext("2d", { alpha: false }); const ctx = canvas.getContext("2d", { alpha: false });
let outputScale = getOutputScale(ctx); const outputScale = getOutputScale(ctx);
this.outputScale = outputScale; this.outputScale = outputScale;
if (this.useOnlyCssZoom) { if (this.useOnlyCssZoom) {
let actualSizeViewport = viewport.clone({ scale: CSS_UNITS }); const actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
// Use a scale that makes the canvas have the originally intended size // Use a scale that makes the canvas have the originally intended size
// of the page. // of the page.
outputScale.sx *= actualSizeViewport.width / viewport.width; outputScale.sx *= actualSizeViewport.width / viewport.width;
@ -596,8 +596,8 @@ class PDFPageView {
} }
if (this.maxCanvasPixels > 0) { if (this.maxCanvasPixels > 0) {
let pixelsInViewport = viewport.width * viewport.height; const pixelsInViewport = viewport.width * viewport.height;
let maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport);
if (outputScale.sx > maxScale || outputScale.sy > maxScale) { if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
outputScale.sx = maxScale; outputScale.sx = maxScale;
outputScale.sy = maxScale; outputScale.sy = maxScale;
@ -608,8 +608,8 @@ class PDFPageView {
} }
} }
let sfx = approximateFraction(outputScale.sx); const sfx = approximateFraction(outputScale.sx);
let sfy = approximateFraction(outputScale.sy); const sfy = approximateFraction(outputScale.sy);
canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]); canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]); canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
canvas.style.width = roundToDivide(viewport.width, sfx[1]) + "px"; canvas.style.width = roundToDivide(viewport.width, sfx[1]) + "px";
@ -618,17 +618,17 @@ class PDFPageView {
this.paintedViewportMap.set(canvas, viewport); this.paintedViewportMap.set(canvas, viewport);
// Rendering area // Rendering area
let transform = !outputScale.scaled const transform = !outputScale.scaled
? null ? null
: [outputScale.sx, 0, 0, outputScale.sy, 0, 0]; : [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
let renderContext = { const renderContext = {
canvasContext: ctx, canvasContext: ctx,
transform, transform,
viewport: this.viewport, viewport: this.viewport,
enableWebGL: this.enableWebGL, enableWebGL: this.enableWebGL,
renderInteractiveForms: this.renderInteractiveForms, renderInteractiveForms: this.renderInteractiveForms,
}; };
let renderTask = this.pdfPage.render(renderContext); const renderTask = this.pdfPage.render(renderContext);
renderTask.onContinue = function(cont) { renderTask.onContinue = function(cont) {
showCanvas(); showCanvas();
if (result.onRenderContinue) { if (result.onRenderContinue) {
@ -666,7 +666,7 @@ class PDFPageView {
} }
let cancelled = false; let cancelled = false;
let ensureNotCancelled = () => { const ensureNotCancelled = () => {
if (cancelled) { if (cancelled) {
throw new RenderingCancelledException( throw new RenderingCancelledException(
"Rendering cancelled, page " + this.id, "Rendering cancelled, page " + this.id,
@ -675,11 +675,11 @@ class PDFPageView {
} }
}; };
let pdfPage = this.pdfPage; const pdfPage = this.pdfPage;
let actualSizeViewport = this.viewport.clone({ scale: CSS_UNITS }); const actualSizeViewport = this.viewport.clone({ scale: CSS_UNITS });
let promise = pdfPage.getOperatorList().then(opList => { const promise = pdfPage.getOperatorList().then(opList => {
ensureNotCancelled(); ensureNotCancelled();
let svgGfx = new SVGGraphics(pdfPage.commonObjs, pdfPage.objs); const svgGfx = new SVGGraphics(pdfPage.commonObjs, pdfPage.objs);
return svgGfx.getSVG(opList, actualSizeViewport).then(svg => { return svgGfx.getSVG(opList, actualSizeViewport).then(svg => {
ensureNotCancelled(); ensureNotCancelled();
this.svg = svg; this.svg = svg;

View File

@ -116,9 +116,9 @@ class PDFPresentationMode {
evt.preventDefault(); evt.preventDefault();
let delta = normalizeWheelEventDelta(evt); const delta = normalizeWheelEventDelta(evt);
let currentTime = new Date().getTime(); const currentTime = new Date().getTime();
let storedTime = this.mouseScrollTimeStamp; const storedTime = this.mouseScrollTimeStamp;
// If we've already switched page, avoid accidentally switching again. // If we've already switched page, avoid accidentally switching again.
if ( if (
@ -137,9 +137,9 @@ class PDFPresentationMode {
this.mouseScrollDelta += delta; this.mouseScrollDelta += delta;
if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) { if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
let totalDelta = this.mouseScrollDelta; const totalDelta = this.mouseScrollDelta;
this._resetMouseScrollState(); this._resetMouseScrollState();
let success = const success =
totalDelta > 0 ? this._goToPreviousPage() : this._goToNextPage(); totalDelta > 0 ? this._goToPreviousPage() : this._goToNextPage();
if (success) { if (success) {
this.mouseScrollTimeStamp = currentTime; this.mouseScrollTimeStamp = currentTime;
@ -160,7 +160,7 @@ class PDFPresentationMode {
* @private * @private
*/ */
_goToPreviousPage() { _goToPreviousPage() {
let page = this.pdfViewer.currentPageNumber; const page = this.pdfViewer.currentPageNumber;
// If we're at the first page, we don't need to do anything. // If we're at the first page, we don't need to do anything.
if (page <= 1) { if (page <= 1) {
return false; return false;
@ -173,7 +173,7 @@ class PDFPresentationMode {
* @private * @private
*/ */
_goToNextPage() { _goToNextPage() {
let page = this.pdfViewer.currentPageNumber; const page = this.pdfViewer.currentPageNumber;
// If we're at the last page, we don't need to do anything. // If we're at the last page, we don't need to do anything.
if (page >= this.pdfViewer.pagesCount) { if (page >= this.pdfViewer.pagesCount) {
return false; return false;
@ -254,7 +254,7 @@ class PDFPresentationMode {
* @private * @private
*/ */
_exit() { _exit() {
let page = this.pdfViewer.currentPageNumber; const page = this.pdfViewer.currentPageNumber;
this.container.classList.remove(ACTIVE_SELECTOR); this.container.classList.remove(ACTIVE_SELECTOR);
// Ensure that the correct page is scrolled into view when exiting // Ensure that the correct page is scrolled into view when exiting
@ -288,7 +288,7 @@ class PDFPresentationMode {
if (evt.button === 0) { if (evt.button === 0) {
// Enable clicking of links in presentation mode. Note: only links // Enable clicking of links in presentation mode. Note: only links
// pointing to destinations in the current PDF document work. // pointing to destinations in the current PDF document work.
let isInternalLink = const isInternalLink =
evt.target.href && evt.target.classList.contains("internalLink"); evt.target.href && evt.target.classList.contains("internalLink");
if (!isInternalLink) { if (!isInternalLink) {
// Unless an internal link was clicked, advance one page. // Unless an internal link was clicked, advance one page.
@ -384,9 +384,9 @@ class PDFPresentationMode {
return; return;
} }
let delta = 0; let delta = 0;
let dx = this.touchSwipeState.endX - this.touchSwipeState.startX; const dx = this.touchSwipeState.endX - this.touchSwipeState.startX;
let dy = this.touchSwipeState.endY - this.touchSwipeState.startY; const dy = this.touchSwipeState.endY - this.touchSwipeState.startY;
let absAngle = Math.abs(Math.atan2(dy, dx)); const absAngle = Math.abs(Math.atan2(dy, dx));
if ( if (
Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD &&
(absAngle <= SWIPE_ANGLE_THRESHOLD || (absAngle <= SWIPE_ANGLE_THRESHOLD ||

View File

@ -23,7 +23,7 @@ let overlayManager = null;
// Renders the page to the canvas of the given print service, and returns // Renders the page to the canvas of the given print service, and returns
// the suggested dimensions of the output page. // the suggested dimensions of the output page.
function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) { function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
let scratchCanvas = activeService.scratchCanvas; const scratchCanvas = activeService.scratchCanvas;
// The size of the canvas in pixels for printing. // The size of the canvas in pixels for printing.
const PRINT_RESOLUTION = AppOptions.get("printResolution") || 150; const PRINT_RESOLUTION = AppOptions.get("printResolution") || 150;
@ -32,10 +32,10 @@ function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
scratchCanvas.height = Math.floor(size.height * PRINT_UNITS); scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
// The physical size of the img as specified by the PDF document. // The physical size of the img as specified by the PDF document.
let width = Math.floor(size.width * CSS_UNITS) + "px"; const width = Math.floor(size.width * CSS_UNITS) + "px";
let height = Math.floor(size.height * CSS_UNITS) + "px"; const height = Math.floor(size.height * CSS_UNITS) + "px";
let ctx = scratchCanvas.getContext("2d"); const ctx = scratchCanvas.getContext("2d");
ctx.save(); ctx.save();
ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height); ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
@ -44,7 +44,7 @@ function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
return pdfDocument return pdfDocument
.getPage(pageNumber) .getPage(pageNumber)
.then(function(pdfPage) { .then(function(pdfPage) {
let renderContext = { const renderContext = {
canvasContext: ctx, canvasContext: ctx,
transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0], transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
viewport: pdfPage.getViewport({ scale: 1, rotation: size.rotation }), viewport: pdfPage.getViewport({ scale: 1, rotation: size.rotation }),
@ -79,7 +79,7 @@ PDFPrintService.prototype = {
const body = document.querySelector("body"); const body = document.querySelector("body");
body.setAttribute("data-pdfjsprinting", true); body.setAttribute("data-pdfjsprinting", true);
let hasEqualPageSizes = this.pagesOverview.every(function(size) { const hasEqualPageSizes = this.pagesOverview.every(function(size) {
return ( return (
size.width === this.pagesOverview[0].width && size.width === this.pagesOverview[0].width &&
size.height === this.pagesOverview[0].height size.height === this.pagesOverview[0].height
@ -102,7 +102,7 @@ PDFPrintService.prototype = {
// https://bugzil.la/851441), the next stylesheet will be ignored and the // https://bugzil.la/851441), the next stylesheet will be ignored and the
// user has to select the correct paper size in the UI if wanted. // user has to select the correct paper size in the UI if wanted.
this.pageStyleSheet = document.createElement("style"); this.pageStyleSheet = document.createElement("style");
let pageSize = this.pagesOverview[0]; const pageSize = this.pagesOverview[0];
this.pageStyleSheet.textContent = this.pageStyleSheet.textContent =
// "size:<width> <height>" is what we need. But also add "A4" because // "size:<width> <height>" is what we need. But also add "A4" because
// Firefox incorrectly reports support for the other value. // Firefox incorrectly reports support for the other value.
@ -144,15 +144,15 @@ PDFPrintService.prototype = {
}, },
renderPages() { renderPages() {
let pageCount = this.pagesOverview.length; const pageCount = this.pagesOverview.length;
let renderNextPage = (resolve, reject) => { const renderNextPage = (resolve, reject) => {
this.throwIfInactive(); this.throwIfInactive();
if (++this.currentPage >= pageCount) { if (++this.currentPage >= pageCount) {
renderProgress(pageCount, pageCount, this.l10n); renderProgress(pageCount, pageCount, this.l10n);
resolve(); resolve();
return; return;
} }
let index = this.currentPage; const index = this.currentPage;
renderProgress(index, pageCount, this.l10n); renderProgress(index, pageCount, this.l10n);
renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index]) renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index])
.then(this.useRenderedPage.bind(this)) .then(this.useRenderedPage.bind(this))
@ -165,11 +165,11 @@ PDFPrintService.prototype = {
useRenderedPage(printItem) { useRenderedPage(printItem) {
this.throwIfInactive(); this.throwIfInactive();
let img = document.createElement("img"); const img = document.createElement("img");
img.style.width = printItem.width; img.style.width = printItem.width;
img.style.height = printItem.height; img.style.height = printItem.height;
let scratchCanvas = this.scratchCanvas; const scratchCanvas = this.scratchCanvas;
if ("toBlob" in scratchCanvas && !this.disableCreateObjectURL) { if ("toBlob" in scratchCanvas && !this.disableCreateObjectURL) {
scratchCanvas.toBlob(function(blob) { scratchCanvas.toBlob(function(blob) {
img.src = URL.createObjectURL(blob); img.src = URL.createObjectURL(blob);
@ -178,7 +178,7 @@ PDFPrintService.prototype = {
img.src = scratchCanvas.toDataURL(); img.src = scratchCanvas.toDataURL();
} }
let wrapper = document.createElement("div"); const wrapper = document.createElement("div");
wrapper.appendChild(img); wrapper.appendChild(img);
this.printContainer.appendChild(wrapper); this.printContainer.appendChild(wrapper);
@ -217,7 +217,7 @@ PDFPrintService.prototype = {
}, },
}; };
let print = window.print; const print = window.print;
window.print = function print() { window.print = function print() {
if (activeService) { if (activeService) {
console.warn("Ignored window.print() because of a pending print job."); console.warn("Ignored window.print() because of a pending print job.");
@ -241,7 +241,7 @@ window.print = function print() {
}); });
return; // eslint-disable-line no-unsafe-finally return; // eslint-disable-line no-unsafe-finally
} }
let activeServiceOnEntry = activeService; const activeServiceOnEntry = activeService;
activeService activeService
.renderPages() .renderPages()
.then(function() { .then(function() {
@ -264,7 +264,7 @@ window.print = function print() {
}; };
function dispatchEvent(eventType) { function dispatchEvent(eventType) {
let event = document.createEvent("CustomEvent"); const event = document.createEvent("CustomEvent");
event.initCustomEvent(eventType, false, false, "custom"); event.initCustomEvent(eventType, false, false, "custom");
window.dispatchEvent(event); window.dispatchEvent(event);
} }
@ -277,10 +277,10 @@ function abort() {
} }
function renderProgress(index, total, l10n) { function renderProgress(index, total, l10n) {
let progressContainer = document.getElementById("printServiceOverlay"); const progressContainer = document.getElementById("printServiceOverlay");
let progress = Math.round((100 * index) / total); const progress = Math.round((100 * index) / total);
let progressBar = progressContainer.querySelector("progress"); const progressBar = progressContainer.querySelector("progress");
let progressPerc = progressContainer.querySelector(".relative-progress"); const progressPerc = progressContainer.querySelector(".relative-progress");
progressBar.value = progress; progressBar.value = progress;
l10n.get("print_progress_percent", { progress }, progress + "%").then(msg => { l10n.get("print_progress_percent", { progress }, progress + "%").then(msg => {
progressPerc.textContent = msg; progressPerc.textContent = msg;
@ -316,7 +316,7 @@ window.addEventListener(
if ("onbeforeprint" in window) { if ("onbeforeprint" in window) {
// Do not propagate before/afterprint events when they are not triggered // Do not propagate before/afterprint events when they are not triggered
// from within this polyfill. (FF /IE / Chrome 63+). // from within this polyfill. (FF /IE / Chrome 63+).
let stopPropagationIfNeeded = function(event) { const stopPropagationIfNeeded = function(event) {
if (event.detail !== "custom" && event.stopImmediatePropagation) { if (event.detail !== "custom" && event.stopImmediatePropagation) {
event.stopImmediatePropagation(); event.stopImmediatePropagation();
} }

View File

@ -103,14 +103,14 @@ class PDFRenderingQueue {
* 2. if last scrolled down, the page after the visible pages, or * 2. if last scrolled down, the page after the visible pages, or
* if last scrolled up, the page before the visible pages * if last scrolled up, the page before the visible pages
*/ */
let visibleViews = visible.views; const visibleViews = visible.views;
let numVisible = visibleViews.length; const numVisible = visibleViews.length;
if (numVisible === 0) { if (numVisible === 0) {
return null; return null;
} }
for (let i = 0; i < numVisible; ++i) { for (let i = 0; i < numVisible; ++i) {
let view = visibleViews[i].view; const view = visibleViews[i].view;
if (!this.isViewFinished(view)) { if (!this.isViewFinished(view)) {
return view; return view;
} }
@ -118,13 +118,13 @@ class PDFRenderingQueue {
// All the visible views have rendered; try to render next/previous pages. // All the visible views have rendered; try to render next/previous pages.
if (scrolledDown) { if (scrolledDown) {
let nextPageIndex = visible.last.id; const nextPageIndex = visible.last.id;
// IDs start at 1, so no need to add 1. // IDs start at 1, so no need to add 1.
if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) { if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex]; return views[nextPageIndex];
} }
} else { } else {
let previousPageIndex = visible.first.id - 2; const previousPageIndex = visible.first.id - 2;
if ( if (
views[previousPageIndex] && views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex]) !this.isViewFinished(views[previousPageIndex])

View File

@ -307,14 +307,14 @@ class PDFSidebar {
* @private * @private
*/ */
_updateThumbnailViewer() { _updateThumbnailViewer() {
let { pdfViewer, pdfThumbnailViewer } = this; const { pdfViewer, pdfThumbnailViewer } = this;
// Use the rendered pages to set the corresponding thumbnail images. // Use the rendered pages to set the corresponding thumbnail images.
let pagesCount = pdfViewer.pagesCount; const pagesCount = pdfViewer.pagesCount;
for (let pageIndex = 0; pageIndex < pagesCount; pageIndex++) { for (let pageIndex = 0; pageIndex < pagesCount; pageIndex++) {
let pageView = pdfViewer.getPageView(pageIndex); const pageView = pdfViewer.getPageView(pageIndex);
if (pageView && pageView.renderingState === RenderingStates.FINISHED) { if (pageView && pageView.renderingState === RenderingStates.FINISHED) {
let thumbnailView = pdfThumbnailViewer.getThumbnail(pageIndex); const thumbnailView = pdfThumbnailViewer.getThumbnail(pageIndex);
thumbnailView.setImage(pageView); thumbnailView.setImage(pageView);
} }
} }
@ -367,7 +367,7 @@ class PDFSidebar {
return; return;
} }
let removeNotification = view => { const removeNotification = view => {
switch (view) { switch (view) {
case SidebarView.OUTLINE: case SidebarView.OUTLINE:
this.outlineButton.classList.remove(UI_NOTIFICATION_CLASS); this.outlineButton.classList.remove(UI_NOTIFICATION_CLASS);
@ -431,7 +431,7 @@ class PDFSidebar {
// Disable/enable views. // Disable/enable views.
this.eventBus.on("outlineloaded", evt => { this.eventBus.on("outlineloaded", evt => {
let outlineCount = evt.outlineCount; const outlineCount = evt.outlineCount;
this.outlineButton.disabled = !outlineCount; this.outlineButton.disabled = !outlineCount;

View File

@ -123,7 +123,7 @@ class PDFSidebarResizer {
// ... and ensure that rendering will always be triggered. // ... and ensure that rendering will always be triggered.
this.eventBus.dispatch("resize", { source: this }); this.eventBus.dispatch("resize", { source: this });
let _boundEvents = this._boundEvents; const _boundEvents = this._boundEvents;
window.removeEventListener("mousemove", _boundEvents.mouseMove); window.removeEventListener("mousemove", _boundEvents.mouseMove);
window.removeEventListener("mouseup", _boundEvents.mouseUp); window.removeEventListener("mouseup", _boundEvents.mouseUp);
} }
@ -135,7 +135,7 @@ class PDFSidebarResizer {
if (!this.enabled) { if (!this.enabled) {
return; return;
} }
let _boundEvents = this._boundEvents; const _boundEvents = this._boundEvents;
_boundEvents.mouseMove = this._mouseMove.bind(this); _boundEvents.mouseMove = this._mouseMove.bind(this);
_boundEvents.mouseUp = this._mouseUp.bind(this); _boundEvents.mouseUp = this._mouseUp.bind(this);
@ -175,7 +175,7 @@ class PDFSidebarResizer {
return; return;
} }
this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); this.outerContainer.classList.add(SIDEBAR_RESIZING_CLASS);
let updated = this._updateWidth(this._width); const updated = this._updateWidth(this._width);
Promise.resolve().then(() => { Promise.resolve().then(() => {
this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS);

View File

@ -43,10 +43,10 @@ class PDFSinglePageViewer extends BaseViewer {
} }
_ensurePageViewVisible() { _ensurePageViewVisible() {
let pageView = this._pages[this._currentPageNumber - 1]; const pageView = this._pages[this._currentPageNumber - 1];
let previousPageView = this._pages[this._previousPageNumber - 1]; const previousPageView = this._pages[this._previousPageNumber - 1];
let viewerNodes = this.viewer.childNodes; const viewerNodes = this.viewer.childNodes;
switch (viewerNodes.length) { switch (viewerNodes.length) {
case 0: // Should *only* occur on initial loading. case 0: // Should *only* occur on initial loading.
this.viewer.appendChild(pageView.div); this.viewer.appendChild(pageView.div);

View File

@ -59,7 +59,7 @@ const TempImageFactory = (function TempImageFactoryClosure() {
tempCanvas.mozOpaque = true; tempCanvas.mozOpaque = true;
} }
let ctx = tempCanvas.getContext("2d", { alpha: false }); const ctx = tempCanvas.getContext("2d", { alpha: false });
ctx.save(); ctx.save();
ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillRect(0, 0, width, height); ctx.fillRect(0, 0, width, height);
@ -68,7 +68,7 @@ const TempImageFactory = (function TempImageFactoryClosure() {
}, },
destroyCanvas() { destroyCanvas() {
let tempCanvas = tempCanvasCache; const tempCanvas = tempCanvasCache;
if (tempCanvas) { if (tempCanvas) {
// Zeroing the width and height causes Firefox to release graphics // Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption. // resources immediately, which can greatly reduce memory consumption.
@ -123,7 +123,7 @@ class PDFThumbnailView {
this.l10n = l10n; this.l10n = l10n;
let anchor = document.createElement("a"); const anchor = document.createElement("a");
anchor.href = linkService.getAnchorUrl("#page=" + id); anchor.href = linkService.getAnchorUrl("#page=" + id);
this.l10n this.l10n
.get("thumb_page_title", { page: id }, "Page {{page}}") .get("thumb_page_title", { page: id }, "Page {{page}}")
@ -136,14 +136,14 @@ class PDFThumbnailView {
}; };
this.anchor = anchor; this.anchor = anchor;
let div = document.createElement("div"); const div = document.createElement("div");
div.className = "thumbnail"; div.className = "thumbnail";
div.setAttribute("data-page-number", this.id); div.setAttribute("data-page-number", this.id);
this.div = div; this.div = div;
let ring = document.createElement("div"); const ring = document.createElement("div");
ring.className = "thumbnailSelectionRing"; ring.className = "thumbnailSelectionRing";
let borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH; const borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
ring.style.width = this.canvasWidth + borderAdjustment + "px"; ring.style.width = this.canvasWidth + borderAdjustment + "px";
ring.style.height = this.canvasHeight + borderAdjustment + "px"; ring.style.height = this.canvasHeight + borderAdjustment + "px";
this.ring = ring; this.ring = ring;
@ -156,7 +156,7 @@ class PDFThumbnailView {
setPdfPage(pdfPage) { setPdfPage(pdfPage) {
this.pdfPage = pdfPage; this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate; this.pdfPageRotate = pdfPage.rotate;
let totalRotation = (this.rotation + this.pdfPageRotate) % 360; const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport({ scale: 1, rotation: totalRotation }); this.viewport = pdfPage.getViewport({ scale: 1, rotation: totalRotation });
this.reset(); this.reset();
} }
@ -173,12 +173,12 @@ class PDFThumbnailView {
this.scale = this.canvasWidth / this.pageWidth; this.scale = this.canvasWidth / this.pageWidth;
this.div.removeAttribute("data-loaded"); this.div.removeAttribute("data-loaded");
let ring = this.ring; const ring = this.ring;
let childNodes = ring.childNodes; const childNodes = ring.childNodes;
for (let i = childNodes.length - 1; i >= 0; i--) { for (let i = childNodes.length - 1; i >= 0; i--) {
ring.removeChild(childNodes[i]); ring.removeChild(childNodes[i]);
} }
let borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH; const borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
ring.style.width = this.canvasWidth + borderAdjustment + "px"; ring.style.width = this.canvasWidth + borderAdjustment + "px";
ring.style.height = this.canvasHeight + borderAdjustment + "px"; ring.style.height = this.canvasHeight + borderAdjustment + "px";
@ -199,7 +199,7 @@ class PDFThumbnailView {
if (typeof rotation !== "undefined") { if (typeof rotation !== "undefined") {
this.rotation = rotation; this.rotation = rotation;
} }
let totalRotation = (this.rotation + this.pdfPageRotate) % 360; const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({ this.viewport = this.viewport.clone({
scale: 1, scale: 1,
rotation: totalRotation, rotation: totalRotation,
@ -223,7 +223,7 @@ class PDFThumbnailView {
* @private * @private
*/ */
_getPageDrawContext(noCtxScale = false) { _getPageDrawContext(noCtxScale = false) {
let canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
// Keep the no-thumbnail outline visible, i.e. `data-loaded === false`, // Keep the no-thumbnail outline visible, i.e. `data-loaded === false`,
// until rendering/image conversion is complete, to avoid display issues. // until rendering/image conversion is complete, to avoid display issues.
this.canvas = canvas; this.canvas = canvas;
@ -234,8 +234,8 @@ class PDFThumbnailView {
) { ) {
canvas.mozOpaque = true; canvas.mozOpaque = true;
} }
let ctx = canvas.getContext("2d", { alpha: false }); const ctx = canvas.getContext("2d", { alpha: false });
let outputScale = getOutputScale(ctx); const outputScale = getOutputScale(ctx);
canvas.width = (this.canvasWidth * outputScale.sx) | 0; canvas.width = (this.canvasWidth * outputScale.sx) | 0;
canvas.height = (this.canvasHeight * outputScale.sy) | 0; canvas.height = (this.canvasHeight * outputScale.sy) | 0;
@ -258,8 +258,8 @@ class PDFThumbnailView {
if (this.renderingState !== RenderingStates.FINISHED) { if (this.renderingState !== RenderingStates.FINISHED) {
return; return;
} }
let id = this.renderingId; const id = this.renderingId;
let className = "thumbnailImage"; const className = "thumbnailImage";
if (this.disableCanvasToImageConversion) { if (this.disableCanvasToImageConversion) {
this.canvas.id = id; this.canvas.id = id;
@ -278,7 +278,7 @@ class PDFThumbnailView {
this.ring.appendChild(this.canvas); this.ring.appendChild(this.canvas);
return; return;
} }
let image = document.createElement("img"); const image = document.createElement("img");
image.id = id; image.id = id;
image.className = className; image.className = className;
this.l10n this.l10n
@ -314,8 +314,8 @@ class PDFThumbnailView {
} }
this.renderingState = RenderingStates.RUNNING; this.renderingState = RenderingStates.RUNNING;
let renderCapability = createPromiseCapability(); const renderCapability = createPromiseCapability();
let finishRenderTask = error => { const finishRenderTask = error => {
// The renderTask may have been replaced by a new one, so only remove // The renderTask may have been replaced by a new one, so only remove
// the reference to the renderTask if it matches the one that is // the reference to the renderTask if it matches the one that is
// triggering this callback. // triggering this callback.
@ -338,9 +338,9 @@ class PDFThumbnailView {
} }
}; };
let ctx = this._getPageDrawContext(); const ctx = this._getPageDrawContext();
let drawViewport = this.viewport.clone({ scale: this.scale }); const drawViewport = this.viewport.clone({ scale: this.scale });
let renderContinueCallback = cont => { const renderContinueCallback = cont => {
if (!this.renderingQueue.isHighestPriority(this)) { if (!this.renderingQueue.isHighestPriority(this)) {
this.renderingState = RenderingStates.PAUSED; this.renderingState = RenderingStates.PAUSED;
this.resume = () => { this.resume = () => {
@ -352,11 +352,11 @@ class PDFThumbnailView {
cont(); cont();
}; };
let renderContext = { const renderContext = {
canvasContext: ctx, canvasContext: ctx,
viewport: drawViewport, viewport: drawViewport,
}; };
let renderTask = (this.renderTask = this.pdfPage.render(renderContext)); const renderTask = (this.renderTask = this.pdfPage.render(renderContext));
renderTask.onContinue = renderContinueCallback; renderTask.onContinue = renderContinueCallback;
renderTask.promise.then( renderTask.promise.then(
@ -374,7 +374,7 @@ class PDFThumbnailView {
if (this.renderingState !== RenderingStates.INITIAL) { if (this.renderingState !== RenderingStates.INITIAL) {
return; return;
} }
let img = pageView.canvas; const img = pageView.canvas;
if (!img) { if (!img) {
return; return;
} }
@ -384,8 +384,8 @@ class PDFThumbnailView {
this.renderingState = RenderingStates.FINISHED; this.renderingState = RenderingStates.FINISHED;
let ctx = this._getPageDrawContext(true); const ctx = this._getPageDrawContext(true);
let canvas = ctx.canvas; const canvas = ctx.canvas;
if (img.width <= 2 * canvas.width) { if (img.width <= 2 * canvas.width) {
ctx.drawImage( ctx.drawImage(
img, img,
@ -405,8 +405,11 @@ class PDFThumbnailView {
// drawImage does an awful job of rescaling the image, doing it gradually. // drawImage does an awful job of rescaling the image, doing it gradually.
let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS; let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS; let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
let reducedImage = TempImageFactory.getCanvas(reducedWidth, reducedHeight); const reducedImage = TempImageFactory.getCanvas(
let reducedImageCtx = reducedImage.getContext("2d"); reducedWidth,
reducedHeight
);
const reducedImageCtx = reducedImage.getContext("2d");
while (reducedWidth > img.width || reducedHeight > img.height) { while (reducedWidth > img.width || reducedHeight > img.height) {
reducedWidth >>= 1; reducedWidth >>= 1;

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
import { import {
getVisibleElements, getVisibleElements,

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
let defaultPreferences = null; let defaultPreferences = null;
function getDefaultPreferences() { function getDefaultPreferences() {

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
import { SCROLLBAR_PADDING, ScrollMode, SpreadMode } from "./ui_utils"; import { SCROLLBAR_PADDING, ScrollMode, SpreadMode } from "./ui_utils";
import { CursorTool } from "./pdf_cursor_tools"; import { CursorTool } from "./pdf_cursor_tools";

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
import { getGlobalEventBus } from "./ui_utils"; import { getGlobalEventBus } from "./ui_utils";
import { renderTextLayer } from "pdfjs-lib"; import { renderTextLayer } from "pdfjs-lib";

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
import { import {
animationStarted, animationStarted,

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
const CSS_UNITS = 96.0 / 72.0; const CSS_UNITS = 96.0 / 72.0;
const DEFAULT_SCALE_VALUE = "auto"; const DEFAULT_SCALE_VALUE = "auto";

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20; const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
"use strict"; "use strict";

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* eslint no-var: error, prefer-const: error */
const compatibilityParams = Object.create(null); const compatibilityParams = Object.create(null);
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {