Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor code in the web/ folder to use async/await #9995

Merged
merged 6 commits into from
Sep 8, 2018
109 changes: 43 additions & 66 deletions web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,23 +133,22 @@ let PDFViewerApplication = {
contentDispositionFilename: null,

// Called once when the document is loaded.
initialize(appConfig) {
async initialize(appConfig) {
this.preferences = this.externalServices.createPreferences();
this.appConfig = appConfig;

return this._readPreferences().then(() => {
return this._parseHashParameters();
}).then(() => {
return this._initializeL10n();
}).then(() => {
await this._readPreferences();
await this._parseHashParameters();
await this._initializeL10n();

if (this.isViewerEmbedded &&
AppOptions.get('externalLinkTarget') === LinkTarget.NONE) {
// Prevent external links from "replacing" the viewer,
// when it's embedded in e.g. an <iframe> or an <object>.
AppOptions.set('externalLinkTarget', LinkTarget.TOP);
}
return this._initializeViewerComponents();
}).then(() => {
await this._initializeViewerComponents();

// Bind the various event handlers *after* the viewer has been
// initialized, to prevent errors if an event arrives too soon.
this.bindEvents();
Expand All @@ -164,13 +163,12 @@ let PDFViewerApplication = {
});

this.initialized = true;
});
},

/**
* @private
*/
_readPreferences() {
async _readPreferences() {
// A subset of the Preferences that `AppOptions`, for compatibility reasons,
// is allowed to override if the `AppOptions` values matches the ones below.
const OVERRIDES = {
Expand All @@ -180,24 +178,27 @@ let PDFViewerApplication = {
textLayerMode: TextLayerMode.DISABLE,
};

return this.preferences.getAll().then(function(prefs) {
try {
const prefs = await this.preferences.getAll();
for (let name in prefs) {
if ((name in OVERRIDES) && AppOptions.get(name) === OVERRIDES[name]) {
continue;
}
AppOptions.set(name, prefs[name]);
}
}, function(reason) { });
} catch (reason) { }
},

/**
* @private
*/
_parseHashParameters() {
async _parseHashParameters() {
if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('PRODUCTION') &&
!AppOptions.get('pdfBugEnabled')) {
return;
}
const waitOn = [];

if (typeof PDFJSDev === 'undefined' || !PDFJSDev.test('PRODUCTION') ||
AppOptions.get('pdfBugEnabled')) {
// Special debugging flags in the hash section of the URL.
let hash = document.location.hash.substring(1);
let hashParams = parseQueryString(hash);
Expand All @@ -221,15 +222,13 @@ let PDFViewerApplication = {
hashParams['disablefontface'] === 'true');
}
if ('disablehistory' in hashParams) {
AppOptions.set('disableHistory',
hashParams['disablehistory'] === 'true');
AppOptions.set('disableHistory', hashParams['disablehistory'] === 'true');
}
if ('webgl' in hashParams) {
AppOptions.set('enableWebGL', hashParams['webgl'] === 'true');
}
if ('useonlycsszoom' in hashParams) {
AppOptions.set('useOnlyCssZoom',
hashParams['useonlycsszoom'] === 'true');
AppOptions.set('useOnlyCssZoom', hashParams['useonlycsszoom'] === 'true');
}
if ('verbosity' in hashParams) {
AppOptions.set('verbosity', hashParams['verbosity'] | 0);
Expand Down Expand Up @@ -262,30 +261,27 @@ let PDFViewerApplication = {
PDFJSDev.test('!PRODUCTION || GENERIC')) && 'locale' in hashParams) {
AppOptions.set('locale', hashParams['locale']);
}
}

return Promise.all(waitOn);
},

/**
* @private
*/
_initializeL10n() {
async _initializeL10n() {
this.l10n = this.externalServices.createL10n({
locale: AppOptions.get('locale'),
});
return this.l10n.getDirection().then((dir) => {
const dir = await this.l10n.getDirection();
document.getElementsByTagName('html')[0].dir = dir;
});
},

/**
* @private
*/
_initializeViewerComponents() {
let { appConfig, } = this;
async _initializeViewerComponents() {
const appConfig = this.appConfig;

return new Promise((resolve, reject) => {
this.overlayManager = new OverlayManager();

const dispatchToDOM = AppOptions.get('eventBusDispatchToDOM');
Expand Down Expand Up @@ -426,8 +422,6 @@ let PDFViewerApplication = {

this.pdfSidebarResizer = new PDFSidebarResizer(appConfig.sidebarResizer,
eventBus, this.l10n);
resolve(undefined);
});
},

run(config) {
Expand Down Expand Up @@ -582,12 +576,12 @@ let PDFViewerApplication = {
* @returns {Promise} - Returns the promise, which is resolved when all
* destruction is completed.
*/
close() {
async close() {
let errorWrapper = this.appConfig.errorWrapper.container;
errorWrapper.setAttribute('hidden', 'true');

if (!this.pdfLoadingTask) {
return Promise.resolve();
return;
}

let promise = this.pdfLoadingTask.destroy();
Expand Down Expand Up @@ -632,13 +626,10 @@ let PDFViewerApplication = {
* @returns {Promise} - Returns the promise, which is resolved when document
* is opened.
*/
open(file, args) {
async open(file, args) {
if (this.pdfLoadingTask) {
// We need to destroy already opened document.
return this.close().then(() => {
// ... and repeat the open() call.
return this.open(file, args);
});
await this.close();
}
// Set the necessary global worker parameters, using the available options.
const workerParameters = AppOptions.getAll('worker');
Expand Down Expand Up @@ -951,10 +942,6 @@ let PDFViewerApplication = {
}
}

let initialParams = {
bookmark: null,
hash: null,
};
let storePromise = store.getMultiple({
page: null,
zoom: DEFAULT_SCALE_VALUE,
Expand All @@ -966,8 +953,10 @@ let PDFViewerApplication = {
spreadMode: null,
}).catch(() => { /* Unable to read from storage; ignoring errors. */ });

Promise.all([storePromise, pageModePromise]).then(
([values = {}, pageMode]) => {
Promise.all([
storePromise, pageModePromise,
]).then(async ([values = {}, pageMode]) => {
const initialBookmark = this.initialBookmark;
// Initialize the default values, from user preferences.
const zoom = AppOptions.get('defaultZoomValue');
let hash = zoom ? `zoom=${zoom}` : null;
Expand All @@ -990,52 +979,40 @@ let PDFViewerApplication = {
// Always let the user preference/history take precedence.
sidebarView = sidebarView || apiPageModeToSidebarView(pageMode);
}
return {
hash,
rotation,
sidebarView,
scrollMode,
spreadMode,
};
}).then(({ hash, rotation, sidebarView, scrollMode, spreadMode, }) => {
initialParams.bookmark = this.initialBookmark;
initialParams.hash = hash;

this.setInitialView(hash, {
rotation, sidebarView, scrollMode, spreadMode,
});
this.eventBus.dispatch('documentinit', { source: this, });

// Make all navigation keys work on document load,
// unless the viewer is embedded in a web page.
if (!this.isViewerEmbedded) {
pdfViewer.focus();
}

return Promise.race([
// For documents with different page sizes, once all pages are resolved,
// ensure that the correct location becomes visible on load.
// (To reduce the risk, in very large and/or slow loading documents,
// that the location changes *after* the user has started interacting
// with the viewer, wait for either `pagesPromise` or a timeout.)
await Promise.race([
pagesPromise,
new Promise((resolve) => {
setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT);
}),
]);
}).then(() => {
// For documents with different page sizes, once all pages are resolved,
// ensure that the correct location becomes visible on load.
// To reduce the risk, in very large and/or slow loading documents,
// that the location changes *after* the user has started interacting
// with the viewer, wait for either `pagesPromise` or a timeout above.

if (!initialParams.bookmark && !initialParams.hash) {
if (!initialBookmark && !hash) {
return;
}
if (pdfViewer.hasEqualPageSizes) {
return;
}
this.initialBookmark = initialParams.bookmark;
this.initialBookmark = initialBookmark;

// eslint-disable-next-line no-self-assign
pdfViewer.currentScaleValue = pdfViewer.currentScaleValue;
this.setInitialView(initialParams.hash);
// Re-apply the initial document location.
this.setInitialView(hash);
}).then(function() {
// At this point, rendering of the initial page(s) should always have
// started (and may even have completed).
Expand Down Expand Up @@ -1629,14 +1606,14 @@ function webViewerInitialized() {
PDFViewerApplication.pdfSidebar.toggle();
});

Promise.resolve().then(function() {
try {
webViewerOpenFileViaURL(file);
}).catch(function(reason) {
} catch (reason) {
PDFViewerApplication.l10n.get('loading_error', null,
'An error occurred while loading the PDF.').then((msg) => {
PDFViewerApplication.error(msg, reason);
});
});
}
}

let webViewerOpenFileViaURL;
Expand Down
4 changes: 2 additions & 2 deletions web/chromecom.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ function setReferer(url, callback) {
let storageArea = chrome.storage.sync || chrome.storage.local;

class ChromePreferences extends BasePreferences {
_writeToStorage(prefObj) {
async _writeToStorage(prefObj) {
return new Promise((resolve) => {
if (prefObj === this.defaults) {
let keysToRemove = Object.keys(this.defaults);
Expand All @@ -317,7 +317,7 @@ class ChromePreferences extends BasePreferences {
});
}

_readFromStorage(prefObj) {
async _readFromStorage(prefObj) {
return new Promise((resolve) => {
let getPreferences = (defaultPrefs) => {
if (chrome.runtime.lastError) {
Expand Down
19 changes: 9 additions & 10 deletions web/firefoxcom.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,13 @@ class DownloadManager {
}

class FirefoxPreferences extends BasePreferences {
_writeToStorage(prefObj) {
async _writeToStorage(prefObj) {
return new Promise(function(resolve) {
FirefoxCom.request('setPreferences', prefObj, resolve);
});
}

_readFromStorage(prefObj) {
async _readFromStorage(prefObj) {
return new Promise(function(resolve) {
FirefoxCom.request('getPreferences', prefObj, function(prefStr) {
let readPrefs = JSON.parse(prefStr);
Expand All @@ -145,21 +145,20 @@ class MozL10n {
this.mozL10n = mozL10n;
}

getLanguage() {
return Promise.resolve(this.mozL10n.getLanguage());
async getLanguage() {
return this.mozL10n.getLanguage();
}

getDirection() {
return Promise.resolve(this.mozL10n.getDirection());
async getDirection() {
return this.mozL10n.getDirection();
}

get(property, args, fallback) {
return Promise.resolve(this.mozL10n.get(property, args, fallback));
async get(property, args, fallback) {
return this.mozL10n.get(property, args, fallback);
}

translate(element) {
async translate(element) {
this.mozL10n.translate(element);
return Promise.resolve();
}
}

Expand Down
12 changes: 3 additions & 9 deletions web/genericcom.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,12 @@ if (typeof PDFJSDev !== 'undefined' && !PDFJSDev.test('GENERIC')) {
let GenericCom = {};

class GenericPreferences extends BasePreferences {
_writeToStorage(prefObj) {
return new Promise(function(resolve) {
async _writeToStorage(prefObj) {
localStorage.setItem('pdfjs.preferences', JSON.stringify(prefObj));
resolve();
});
}

_readFromStorage(prefObj) {
return new Promise(function(resolve) {
let readPrefs = JSON.parse(localStorage.getItem('pdfjs.preferences'));
resolve(readPrefs);
});
async _readFromStorage(prefObj) {
return JSON.parse(localStorage.getItem('pdfjs.preferences'));
}
}

Expand Down
20 changes: 8 additions & 12 deletions web/genericl10n.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,24 @@ class GenericL10n {
});
}

getLanguage() {
return this._ready.then((l10n) => {
async getLanguage() {
const l10n = await this._ready;
return l10n.getLanguage();
});
}

getDirection() {
return this._ready.then((l10n) => {
async getDirection() {
const l10n = await this._ready;
return l10n.getDirection();
});
}

get(property, args, fallback) {
return this._ready.then((l10n) => {
async get(property, args, fallback) {
const l10n = await this._ready;
return l10n.get(property, args, fallback);
});
}

translate(element) {
return this._ready.then((l10n) => {
async translate(element) {
const l10n = await this._ready;
return l10n.translate(element);
});
}
}

Expand Down