diff --git a/epub.js/epub.js b/epub.js/epub.js deleted file mode 100644 index 05a97ce..0000000 --- a/epub.js/epub.js +++ /dev/null @@ -1,7989 +0,0 @@ -/*! - * @overview RSVP - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE - * @version 3.1.0 - */ - -(function() { - "use strict"; - function lib$rsvp$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$rsvp$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$rsvp$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$rsvp$utils$$_isArray; - if (!Array.isArray) { - lib$rsvp$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$rsvp$utils$$_isArray = Array.isArray; - } - - var lib$rsvp$utils$$isArray = lib$rsvp$utils$$_isArray; - - var lib$rsvp$utils$$now = Date.now || function() { return new Date().getTime(); }; - - function lib$rsvp$utils$$F() { } - - var lib$rsvp$utils$$o_create = (Object.create || function (o) { - if (arguments.length > 1) { - throw new Error('Second argument not supported'); - } - if (typeof o !== 'object') { - throw new TypeError('Argument must be an object'); - } - lib$rsvp$utils$$F.prototype = o; - return new lib$rsvp$utils$$F(); - }); - function lib$rsvp$events$$indexOf(callbacks, callback) { - for (var i=0, l=callbacks.length; i 0.5) { - throw new Error(); - } - return new Author(); - } - - try { - return findAuthor(); // succeed or fail - } catch(error) { - return findOtherAuther(); - } finally { - // always runs - // doesn't affect the return value - } - ``` - - Asynchronous example: - - ```js - findAuthor().catch(function(reason){ - return findOtherAuther(); - }).finally(function(){ - // author was either found, or not - }); - ``` - - @method finally - @param {Function} callback - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - 'finally': function(callback, label) { - var promise = this; - var constructor = promise.constructor; - - return promise.then(function(value) { - return constructor.resolve(callback()).then(function(){ - return value; - }); - }, function(reason) { - return constructor.resolve(callback()).then(function(){ - throw reason; - }); - }, label); - } - }; - - function lib$rsvp$all$settled$$AllSettled(Constructor, entries, label) { - this._superConstructor(Constructor, entries, false /* don't abort on reject */, label); - } - - lib$rsvp$all$settled$$AllSettled.prototype = lib$rsvp$utils$$o_create(lib$rsvp$enumerator$$default.prototype); - lib$rsvp$all$settled$$AllSettled.prototype._superConstructor = lib$rsvp$enumerator$$default; - lib$rsvp$all$settled$$AllSettled.prototype._makeResult = lib$rsvp$enumerator$$makeSettledResult; - lib$rsvp$all$settled$$AllSettled.prototype._validationError = function() { - return new Error('allSettled must be called with an array'); - }; - - function lib$rsvp$all$settled$$allSettled(entries, label) { - return new lib$rsvp$all$settled$$AllSettled(lib$rsvp$promise$$default, entries, label).promise; - } - var lib$rsvp$all$settled$$default = lib$rsvp$all$settled$$allSettled; - function lib$rsvp$all$$all(array, label) { - return lib$rsvp$promise$$default.all(array, label); - } - var lib$rsvp$all$$default = lib$rsvp$all$$all; - var lib$rsvp$asap$$len = 0; - var lib$rsvp$asap$$toString = {}.toString; - var lib$rsvp$asap$$vertxNext; - function lib$rsvp$asap$$asap(callback, arg) { - lib$rsvp$asap$$queue[lib$rsvp$asap$$len] = callback; - lib$rsvp$asap$$queue[lib$rsvp$asap$$len + 1] = arg; - lib$rsvp$asap$$len += 2; - if (lib$rsvp$asap$$len === 2) { - // If len is 1, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$rsvp$asap$$scheduleFlush(); - } - } - - var lib$rsvp$asap$$default = lib$rsvp$asap$$asap; - - var lib$rsvp$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$rsvp$asap$$browserGlobal = lib$rsvp$asap$$browserWindow || {}; - var lib$rsvp$asap$$BrowserMutationObserver = lib$rsvp$asap$$browserGlobal.MutationObserver || lib$rsvp$asap$$browserGlobal.WebKitMutationObserver; - var lib$rsvp$asap$$isNode = typeof self === 'undefined' && - typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$rsvp$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$rsvp$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$rsvp$asap$$flush); - }; - } - - // vertx - function lib$rsvp$asap$$useVertxTimer() { - return function() { - lib$rsvp$asap$$vertxNext(lib$rsvp$asap$$flush); - }; - } - - function lib$rsvp$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$rsvp$asap$$BrowserMutationObserver(lib$rsvp$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$rsvp$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$rsvp$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$rsvp$asap$$useSetTimeout() { - return function() { - setTimeout(lib$rsvp$asap$$flush, 1); - }; - } - - var lib$rsvp$asap$$queue = new Array(1000); - function lib$rsvp$asap$$flush() { - for (var i = 0; i < lib$rsvp$asap$$len; i+=2) { - var callback = lib$rsvp$asap$$queue[i]; - var arg = lib$rsvp$asap$$queue[i+1]; - - callback(arg); - - lib$rsvp$asap$$queue[i] = undefined; - lib$rsvp$asap$$queue[i+1] = undefined; - } - - lib$rsvp$asap$$len = 0; - } - - function lib$rsvp$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$rsvp$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$rsvp$asap$$useVertxTimer(); - } catch(e) { - return lib$rsvp$asap$$useSetTimeout(); - } - } - - var lib$rsvp$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$rsvp$asap$$isNode) { - lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useNextTick(); - } else if (lib$rsvp$asap$$BrowserMutationObserver) { - lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useMutationObserver(); - } else if (lib$rsvp$asap$$isWorker) { - lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useMessageChannel(); - } else if (lib$rsvp$asap$$browserWindow === undefined && typeof require === 'function') { - lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$attemptVertex(); - } else { - lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useSetTimeout(); - } - function lib$rsvp$defer$$defer(label) { - var deferred = {}; - - deferred['promise'] = new lib$rsvp$promise$$default(function(resolve, reject) { - deferred['resolve'] = resolve; - deferred['reject'] = reject; - }, label); - - return deferred; - } - var lib$rsvp$defer$$default = lib$rsvp$defer$$defer; - function lib$rsvp$filter$$filter(promises, filterFn, label) { - return lib$rsvp$promise$$default.all(promises, label).then(function(values) { - if (!lib$rsvp$utils$$isFunction(filterFn)) { - throw new TypeError("You must pass a function as filter's second argument."); - } - - var length = values.length; - var filtered = new Array(length); - - for (var i = 0; i < length; i++) { - filtered[i] = filterFn(values[i]); - } - - return lib$rsvp$promise$$default.all(filtered, label).then(function(filtered) { - var results = new Array(length); - var newLength = 0; - - for (var i = 0; i < length; i++) { - if (filtered[i]) { - results[newLength] = values[i]; - newLength++; - } - } - - results.length = newLength; - - return results; - }); - }); - } - var lib$rsvp$filter$$default = lib$rsvp$filter$$filter; - - function lib$rsvp$promise$hash$$PromiseHash(Constructor, object, label) { - this._superConstructor(Constructor, object, true, label); - } - - var lib$rsvp$promise$hash$$default = lib$rsvp$promise$hash$$PromiseHash; - - lib$rsvp$promise$hash$$PromiseHash.prototype = lib$rsvp$utils$$o_create(lib$rsvp$enumerator$$default.prototype); - lib$rsvp$promise$hash$$PromiseHash.prototype._superConstructor = lib$rsvp$enumerator$$default; - lib$rsvp$promise$hash$$PromiseHash.prototype._init = function() { - this._result = {}; - }; - - lib$rsvp$promise$hash$$PromiseHash.prototype._validateInput = function(input) { - return input && typeof input === 'object'; - }; - - lib$rsvp$promise$hash$$PromiseHash.prototype._validationError = function() { - return new Error('Promise.hash must be called with an object'); - }; - - lib$rsvp$promise$hash$$PromiseHash.prototype._enumerate = function() { - var enumerator = this; - var promise = enumerator.promise; - var input = enumerator._input; - var results = []; - - for (var key in input) { - if (promise._state === lib$rsvp$$internal$$PENDING && Object.prototype.hasOwnProperty.call(input, key)) { - results.push({ - position: key, - entry: input[key] - }); - } - } - - var length = results.length; - enumerator._remaining = length; - var result; - - for (var i = 0; promise._state === lib$rsvp$$internal$$PENDING && i < length; i++) { - result = results[i]; - enumerator._eachEntry(result.entry, result.position); - } - }; - - function lib$rsvp$hash$settled$$HashSettled(Constructor, object, label) { - this._superConstructor(Constructor, object, false, label); - } - - lib$rsvp$hash$settled$$HashSettled.prototype = lib$rsvp$utils$$o_create(lib$rsvp$promise$hash$$default.prototype); - lib$rsvp$hash$settled$$HashSettled.prototype._superConstructor = lib$rsvp$enumerator$$default; - lib$rsvp$hash$settled$$HashSettled.prototype._makeResult = lib$rsvp$enumerator$$makeSettledResult; - - lib$rsvp$hash$settled$$HashSettled.prototype._validationError = function() { - return new Error('hashSettled must be called with an object'); - }; - - function lib$rsvp$hash$settled$$hashSettled(object, label) { - return new lib$rsvp$hash$settled$$HashSettled(lib$rsvp$promise$$default, object, label).promise; - } - var lib$rsvp$hash$settled$$default = lib$rsvp$hash$settled$$hashSettled; - function lib$rsvp$hash$$hash(object, label) { - return new lib$rsvp$promise$hash$$default(lib$rsvp$promise$$default, object, label).promise; - } - var lib$rsvp$hash$$default = lib$rsvp$hash$$hash; - function lib$rsvp$map$$map(promises, mapFn, label) { - return lib$rsvp$promise$$default.all(promises, label).then(function(values) { - if (!lib$rsvp$utils$$isFunction(mapFn)) { - throw new TypeError("You must pass a function as map's second argument."); - } - - var length = values.length; - var results = new Array(length); - - for (var i = 0; i < length; i++) { - results[i] = mapFn(values[i]); - } - - return lib$rsvp$promise$$default.all(results, label); - }); - } - var lib$rsvp$map$$default = lib$rsvp$map$$map; - - function lib$rsvp$node$$Result() { - this.value = undefined; - } - - var lib$rsvp$node$$ERROR = new lib$rsvp$node$$Result(); - var lib$rsvp$node$$GET_THEN_ERROR = new lib$rsvp$node$$Result(); - - function lib$rsvp$node$$getThen(obj) { - try { - return obj.then; - } catch(error) { - lib$rsvp$node$$ERROR.value= error; - return lib$rsvp$node$$ERROR; - } - } - - - function lib$rsvp$node$$tryApply(f, s, a) { - try { - f.apply(s, a); - } catch(error) { - lib$rsvp$node$$ERROR.value = error; - return lib$rsvp$node$$ERROR; - } - } - - function lib$rsvp$node$$makeObject(_, argumentNames) { - var obj = {}; - var name; - var i; - var length = _.length; - var args = new Array(length); - - for (var x = 0; x < length; x++) { - args[x] = _[x]; - } - - for (i = 0; i < argumentNames.length; i++) { - name = argumentNames[i]; - obj[name] = args[i + 1]; - } - - return obj; - } - - function lib$rsvp$node$$arrayResult(_) { - var length = _.length; - var args = new Array(length - 1); - - for (var i = 1; i < length; i++) { - args[i - 1] = _[i]; - } - - return args; - } - - function lib$rsvp$node$$wrapThenable(then, promise) { - return { - then: function(onFulFillment, onRejection) { - return then.call(promise, onFulFillment, onRejection); - } - }; - } - - function lib$rsvp$node$$denodeify(nodeFunc, options) { - var fn = function() { - var self = this; - var l = arguments.length; - var args = new Array(l + 1); - var arg; - var promiseInput = false; - - for (var i = 0; i < l; ++i) { - arg = arguments[i]; - - if (!promiseInput) { - // TODO: clean this up - promiseInput = lib$rsvp$node$$needsPromiseInput(arg); - if (promiseInput === lib$rsvp$node$$GET_THEN_ERROR) { - var p = new lib$rsvp$promise$$default(lib$rsvp$$internal$$noop); - lib$rsvp$$internal$$reject(p, lib$rsvp$node$$GET_THEN_ERROR.value); - return p; - } else if (promiseInput && promiseInput !== true) { - arg = lib$rsvp$node$$wrapThenable(promiseInput, arg); - } - } - args[i] = arg; - } - - var promise = new lib$rsvp$promise$$default(lib$rsvp$$internal$$noop); - - args[l] = function(err, val) { - if (err) - lib$rsvp$$internal$$reject(promise, err); - else if (options === undefined) - lib$rsvp$$internal$$resolve(promise, val); - else if (options === true) - lib$rsvp$$internal$$resolve(promise, lib$rsvp$node$$arrayResult(arguments)); - else if (lib$rsvp$utils$$isArray(options)) - lib$rsvp$$internal$$resolve(promise, lib$rsvp$node$$makeObject(arguments, options)); - else - lib$rsvp$$internal$$resolve(promise, val); - }; - - if (promiseInput) { - return lib$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self); - } else { - return lib$rsvp$node$$handleValueInput(promise, args, nodeFunc, self); - } - }; - - fn.__proto__ = nodeFunc; - - return fn; - } - - var lib$rsvp$node$$default = lib$rsvp$node$$denodeify; - - function lib$rsvp$node$$handleValueInput(promise, args, nodeFunc, self) { - var result = lib$rsvp$node$$tryApply(nodeFunc, self, args); - if (result === lib$rsvp$node$$ERROR) { - lib$rsvp$$internal$$reject(promise, result.value); - } - return promise; - } - - function lib$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self){ - return lib$rsvp$promise$$default.all(args).then(function(args){ - var result = lib$rsvp$node$$tryApply(nodeFunc, self, args); - if (result === lib$rsvp$node$$ERROR) { - lib$rsvp$$internal$$reject(promise, result.value); - } - return promise; - }); - } - - function lib$rsvp$node$$needsPromiseInput(arg) { - if (arg && typeof arg === 'object') { - if (arg.constructor === lib$rsvp$promise$$default) { - return true; - } else { - return lib$rsvp$node$$getThen(arg); - } - } else { - return false; - } - } - var lib$rsvp$platform$$platform; - - /* global self */ - if (typeof self === 'object') { - lib$rsvp$platform$$platform = self; - - /* global global */ - } else if (typeof global === 'object') { - lib$rsvp$platform$$platform = global; - } else { - throw new Error('no global: `self` or `global` found'); - } - - var lib$rsvp$platform$$default = lib$rsvp$platform$$platform; - function lib$rsvp$race$$race(array, label) { - return lib$rsvp$promise$$default.race(array, label); - } - var lib$rsvp$race$$default = lib$rsvp$race$$race; - function lib$rsvp$reject$$reject(reason, label) { - return lib$rsvp$promise$$default.reject(reason, label); - } - var lib$rsvp$reject$$default = lib$rsvp$reject$$reject; - function lib$rsvp$resolve$$resolve(value, label) { - return lib$rsvp$promise$$default.resolve(value, label); - } - var lib$rsvp$resolve$$default = lib$rsvp$resolve$$resolve; - function lib$rsvp$rethrow$$rethrow(reason) { - setTimeout(function() { - throw reason; - }); - throw reason; - } - var lib$rsvp$rethrow$$default = lib$rsvp$rethrow$$rethrow; - - // defaults - lib$rsvp$config$$config.async = lib$rsvp$asap$$default; - lib$rsvp$config$$config.after = function(cb) { - setTimeout(cb, 0); - }; - var lib$rsvp$$cast = lib$rsvp$resolve$$default; - function lib$rsvp$$async(callback, arg) { - lib$rsvp$config$$config.async(callback, arg); - } - - function lib$rsvp$$on() { - lib$rsvp$config$$config['on'].apply(lib$rsvp$config$$config, arguments); - } - - function lib$rsvp$$off() { - lib$rsvp$config$$config['off'].apply(lib$rsvp$config$$config, arguments); - } - - // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` - if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { - var lib$rsvp$$callbacks = window['__PROMISE_INSTRUMENTATION__']; - lib$rsvp$config$$configure('instrument', true); - for (var lib$rsvp$$eventName in lib$rsvp$$callbacks) { - if (lib$rsvp$$callbacks.hasOwnProperty(lib$rsvp$$eventName)) { - lib$rsvp$$on(lib$rsvp$$eventName, lib$rsvp$$callbacks[lib$rsvp$$eventName]); - } - } - } - - var lib$rsvp$umd$$RSVP = { - 'race': lib$rsvp$race$$default, - 'Promise': lib$rsvp$promise$$default, - 'allSettled': lib$rsvp$all$settled$$default, - 'hash': lib$rsvp$hash$$default, - 'hashSettled': lib$rsvp$hash$settled$$default, - 'denodeify': lib$rsvp$node$$default, - 'on': lib$rsvp$$on, - 'off': lib$rsvp$$off, - 'map': lib$rsvp$map$$default, - 'filter': lib$rsvp$filter$$default, - 'resolve': lib$rsvp$resolve$$default, - 'reject': lib$rsvp$reject$$default, - 'all': lib$rsvp$all$$default, - 'rethrow': lib$rsvp$rethrow$$default, - 'defer': lib$rsvp$defer$$default, - 'EventTarget': lib$rsvp$events$$default, - 'configure': lib$rsvp$config$$configure, - 'async': lib$rsvp$$async - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$rsvp$umd$$RSVP; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$rsvp$umd$$RSVP; - } else if (typeof lib$rsvp$platform$$default !== 'undefined') { - lib$rsvp$platform$$default['RSVP'] = lib$rsvp$umd$$RSVP; - } -}).call(this); - - -'use strict'; - -var EPUBJS = EPUBJS || {}; -EPUBJS.VERSION = "0.2.12"; - -EPUBJS.plugins = EPUBJS.plugins || {}; - -EPUBJS.filePath = EPUBJS.filePath || "/epubjs/"; - -EPUBJS.Render = {}; - -(function(root) { - - var previousEpub = root.ePub || {}; - - var ePub = root.ePub = function() { - var bookPath, options; - - //-- var book = ePub("path/to/book.epub", { restore: true }) - if(typeof(arguments[0]) != 'undefined' && - (typeof arguments[0] === 'string' || arguments[0] instanceof ArrayBuffer)) { - - bookPath = arguments[0]; - - if( arguments[1] && typeof arguments[1] === 'object' ) { - options = arguments[1]; - options.bookPath = bookPath; - } else { - options = { 'bookPath' : bookPath }; - } - - } - - /* - * var book = ePub({ bookPath: "path/to/book.epub", restore: true }); - * - * - OR - - * - * var book = ePub({ restore: true }); - * book.open("path/to/book.epub"); - */ - - if( arguments[0] && typeof arguments[0] === 'object' && !(arguments[0] instanceof ArrayBuffer)) { - options = arguments[0]; - } - - - return new EPUBJS.Book(options); - }; - - //exports to multiple environments - if (typeof define === 'function' && define.amd) { - //AMD - define(['rsvp'], function(){ return ePub; }); - } else if (typeof module != "undefined" && module.exports) { - //Node - module.exports = ePub; - } - -})(window); - -EPUBJS.Book = function(options){ - - var book = this; - - this.settings = EPUBJS.core.defaults(options || {}, { - bookPath : undefined, - bookKey : undefined, - packageUrl : undefined, - storage: false, //-- true (auto) or false (none) | override: 'ram', 'websqldatabase', 'indexeddb', 'filesystem' - fromStorage : false, - saved : false, - online : true, - contained : false, - width : undefined, - height: undefined, - layoutOveride : undefined, // Default: { spread: 'reflowable', layout: 'auto', orientation: 'auto'} - orientation : undefined, - minSpreadWidth: 768, //-- overridden by spread: none (never) / both (always) - gap: "auto", //-- "auto" or int - version: 1, - restore: false, - reload : false, - goto : false, - styles : {}, - headTags : {}, - withCredentials: false, - render_method: "Iframe" - }); - - this.settings.EPUBJSVERSION = EPUBJS.VERSION; - - this.spinePos = 0; - this.stored = false; - - //-- All Book events for listening - /* - book:ready - book:stored - book:online - book:offline - book:pageChanged - book:loadFailed - book:loadChapterFailed - */ - - //-- Adds Hook methods to the Book prototype - // Hooks will all return before triggering the callback. - // EPUBJS.Hooks.mixin(this); - //-- Get pre-registered hooks for events - // this.getHooks("beforeChapterDisplay"); - - this.online = this.settings.online || navigator.onLine; - this.networkListeners(); - - this.ready = { - manifest: new RSVP.defer(), - spine: new RSVP.defer(), - metadata: new RSVP.defer(), - cover: new RSVP.defer(), - toc: new RSVP.defer(), - pageList: new RSVP.defer() - }; - - this.readyPromises = [ - this.ready.manifest.promise, - this.ready.spine.promise, - this.ready.metadata.promise, - this.ready.cover.promise, - this.ready.toc.promise - ]; - - this.pageList = []; - this.pagination = new EPUBJS.Pagination(); - this.pageListReady = this.ready.pageList.promise; - - this.ready.all = RSVP.all(this.readyPromises); - - this.ready.all.then(this._ready.bind(this)); - - // Queue for methods used before rendering - this.isRendered = false; - this._q = EPUBJS.core.queue(this); - // Queue for rendering - this._rendering = false; - this._displayQ = EPUBJS.core.queue(this); - // Queue for going to another location - this._moving = false; - this._gotoQ = EPUBJS.core.queue(this); - - /** - * Creates a new renderer. - * The renderer will handle displaying the content using the method provided in the settings - */ - this.renderer = new EPUBJS.Renderer(this.settings.render_method); - //-- Set the width at which to switch from spreads to single pages - this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); - this.renderer.setGap(this.settings.gap); - //-- Pass through the renderer events - this.listenToRenderer(this.renderer); - - this.defer_opened = new RSVP.defer(); - this.opened = this.defer_opened.promise; - - this.store = false; //-- False if not using storage; - - //-- Determine storage method - //-- Override options: none | ram | websqldatabase | indexeddb | filesystem - if(this.settings.storage !== false){ - // this.storage = new fileStorage.storage(this.settings.storage); - this.fromStorage(true); - } - - // BookUrl is optional, but if present start loading process - if(typeof this.settings.bookPath === 'string' || this.settings.bookPath instanceof ArrayBuffer) { - this.open(this.settings.bookPath, this.settings.reload); - } - - window.addEventListener("beforeunload", this.unload.bind(this), false); - - //-- Listen for these promises: - //-- book.opened.then() - //-- book.rendered.then() -}; - -//-- Check bookUrl and start parsing book Assets or load them from storage -EPUBJS.Book.prototype.open = function(bookPath, forceReload){ - var book = this, - epubpackage, - opened = new RSVP.defer(); - - this.settings.bookPath = bookPath; - - if(this.settings.contained || this.isContained(bookPath)){ - - this.settings.contained = this.contained = true; - - this.bookUrl = ''; - - epubpackage = this.unarchive(bookPath). - then(function(){ - return book.loadPackage(); - }); - - } else { - //-- Get a absolute URL from the book path - this.bookUrl = this.urlFrom(bookPath); - - epubpackage = this.loadPackage(); - } - - if(this.settings.restore && !forceReload && localStorage){ - //-- Will load previous package json, or re-unpack if error - epubpackage.then(function(packageXml) { - var identifier = book.packageIdentifier(packageXml); - var restored = book.restore(identifier); - - if(!restored) { - book.unpack(packageXml); - } - opened.resolve(); - book.defer_opened.resolve(); - }); - - }else{ - - //-- Get package information from epub opf - epubpackage.then(function(packageXml) { - book.unpack(packageXml); - opened.resolve(); - book.defer_opened.resolve(); - }); - } - - this._registerReplacements(this.renderer); - - return opened.promise; - -}; - -EPUBJS.Book.prototype.loadPackage = function(_containerPath){ - var book = this, - parse = new EPUBJS.Parser(), - containerPath = _containerPath || "META-INF/container.xml", - containerXml, - packageXml; - - if(!this.settings.packageUrl) { //-- provide the packageUrl to skip this step - packageXml = book.loadXml(book.bookUrl + containerPath). - then(function(containerXml){ - return parse.container(containerXml); // Container has path to content - }). - then(function(paths){ - book.settings.contentsPath = book.bookUrl + paths.basePath; - book.settings.packageUrl = book.bookUrl + paths.packagePath; - book.settings.encoding = paths.encoding; - return book.loadXml(book.settings.packageUrl); // Containes manifest, spine and metadata - }); - } else { - packageXml = book.loadXml(book.settings.packageUrl); - } - - packageXml.catch(function(error) { - // handle errors in either of the two requests - console.error("Could not load book at: "+ containerPath); - book.trigger("book:loadFailed", containerPath); - }); - return packageXml; -}; - -EPUBJS.Book.prototype.packageIdentifier = function(packageXml){ - var book = this, - parse = new EPUBJS.Parser(); - - return parse.identifier(packageXml); -}; - -EPUBJS.Book.prototype.unpack = function(packageXml){ - var book = this, - parse = new EPUBJS.Parser(); - - book.contents = parse.packageContents(packageXml, book.settings.contentsPath); // Extract info from contents - - book.manifest = book.contents.manifest; - book.spine = book.contents.spine; - book.spineIndexByURL = book.contents.spineIndexByURL; - book.metadata = book.contents.metadata; - if(!book.settings.bookKey) { - book.settings.bookKey = book.generateBookKey(book.metadata.identifier); - } - - //-- Set Globbal Layout setting based on metadata - book.globalLayoutProperties = book.parseLayoutProperties(book.metadata); - - if(book.contents.coverPath) { - book.cover = book.contents.cover = book.settings.contentsPath + book.contents.coverPath; - } - - book.spineNodeIndex = book.contents.spineNodeIndex; - - book.ready.manifest.resolve(book.contents.manifest); - book.ready.spine.resolve(book.contents.spine); - book.ready.metadata.resolve(book.contents.metadata); - book.ready.cover.resolve(book.contents.cover); - - book.locations = new EPUBJS.Locations(book.spine, book.store, book.settings.withCredentials); - - //-- Load the TOC, optional; either the EPUB3 XHTML Navigation file or the EPUB2 NCX file - if(book.contents.navPath) { - book.settings.navUrl = book.settings.contentsPath + book.contents.navPath; - - book.loadXml(book.settings.navUrl). - then(function(navHtml){ - return parse.nav(navHtml, book.spineIndexByURL, book.spine); // Grab Table of Contents - }).then(function(toc){ - book.toc = book.contents.toc = toc; - book.ready.toc.resolve(book.contents.toc); - }, function(error) { - book.ready.toc.resolve(false); - }); - - // Load the optional pageList - book.loadXml(book.settings.navUrl). - then(function(navHtml){ - return parse.pageList(navHtml, book.spineIndexByURL, book.spine); - }).then(function(pageList){ - var epubcfi = new EPUBJS.EpubCFI(); - var wait = 0; // need to generate a cfi - - // No pageList found - if(pageList.length === 0) { - return; - } - - book.pageList = book.contents.pageList = pageList; - - // Replace HREFs with CFI - book.pageList.forEach(function(pg){ - if(!pg.cfi) { - wait += 1; - epubcfi.generateCfiFromHref(pg.href, book).then(function(cfi){ - pg.cfi = cfi; - pg.packageUrl = book.settings.packageUrl; - - wait -= 1; - if(wait === 0) { - book.pagination.process(book.pageList); - book.ready.pageList.resolve(book.pageList); - } - }); - } - }); - - if(!wait) { - book.pagination.process(book.pageList); - book.ready.pageList.resolve(book.pageList); - } - - }, function(error) { - book.ready.pageList.resolve([]); - }); - } else if(book.contents.tocPath) { - book.settings.tocUrl = book.settings.contentsPath + book.contents.tocPath; - - book.loadXml(book.settings.tocUrl). - then(function(tocXml){ - return parse.toc(tocXml, book.spineIndexByURL, book.spine); // Grab Table of Contents - }).then(function(toc){ - book.toc = book.contents.toc = toc; - book.ready.toc.resolve(book.contents.toc); - }, function(error) { - book.ready.toc.resolve(false); - }); - - } else { - book.ready.toc.resolve(false); - } - -}; - -EPUBJS.Book.prototype.createHiddenRender = function(renderer, _width, _height) { - var box = this.element.getBoundingClientRect(); - var width = _width || this.settings.width || box.width; - var height = _height || this.settings.height || box.height; - var hiddenContainer; - var hiddenEl; - renderer.setMinSpreadWidth(this.settings.minSpreadWidth); - renderer.setGap(this.settings.gap); - - this._registerReplacements(renderer); - if(this.settings.forceSingle) { - renderer.forceSingle(true); - } - - hiddenContainer = document.createElement("div"); - hiddenContainer.style.visibility = "hidden"; - hiddenContainer.style.overflow = "hidden"; - hiddenContainer.style.width = "0"; - hiddenContainer.style.height = "0"; - this.element.appendChild(hiddenContainer); - - hiddenEl = document.createElement("div"); - hiddenEl.style.visibility = "hidden"; - hiddenEl.style.overflow = "hidden"; - hiddenEl.style.width = width + "px";//"0"; - hiddenEl.style.height = height +"px"; //"0"; - hiddenContainer.appendChild(hiddenEl); - - renderer.initialize(hiddenEl); - return hiddenContainer; -}; - -// Generates the pageList array by loading every chapter and paging through them -EPUBJS.Book.prototype.generatePageList = function(width, height){ - var pageList = []; - var pager = new EPUBJS.Renderer(this.settings.render_method, false); //hidden - var hiddenContainer = this.createHiddenRender(pager, width, height); - var deferred = new RSVP.defer(); - var spinePos = -1; - var spineLength = this.spine.length; - var totalPages = 0; - var currentPage = 0; - var nextChapter = function(deferred){ - var chapter; - var next = spinePos + 1; - var done = deferred || new RSVP.defer(); - var loaded; - if(next >= spineLength) { - done.resolve(); - } else { - spinePos = next; - chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); - pager.displayChapter(chapter, this.globalLayoutProperties).then(function(chap){ - pager.pageMap.forEach(function(item){ - currentPage += 1; - pageList.push({ - "cfi" : item.start, - "page" : currentPage - }); - - }); - - if(pager.pageMap.length % 2 > 0 && - pager.spreads) { - currentPage += 1; // Handle Spreads - pageList.push({ - "cfi" : pager.pageMap[pager.pageMap.length - 1].end, - "page" : currentPage - }); - } - - // Load up the next chapter - setTimeout(function(){ - nextChapter(done); - }, 1); - }); - } - return done.promise; - }.bind(this); - - var finished = nextChapter().then(function(){ - pager.remove(); - this.element.removeChild(hiddenContainer); - deferred.resolve(pageList); - }.bind(this)); - - return deferred.promise; -}; - -// Render out entire book and generate the pagination -// Width and Height are optional and will default to the current dimensions -EPUBJS.Book.prototype.generatePagination = function(width, height) { - var book = this; - var defered = new RSVP.defer(); - - this.ready.spine.promise.then(function(){ - book.generatePageList(width, height).then(function(pageList){ - book.pageList = book.contents.pageList = pageList; - book.pagination.process(pageList); - book.ready.pageList.resolve(book.pageList); - defered.resolve(book.pageList); - }); - }); - - return defered.promise; -}; - -// Process the pagination from a JSON array containing the pagelist -EPUBJS.Book.prototype.loadPagination = function(pagelistJSON) { - var pageList = JSON.parse(pagelistJSON); - - if(pageList && pageList.length) { - this.pageList = pageList; - this.pagination.process(this.pageList); - this.ready.pageList.resolve(this.pageList); - } - return this.pageList; -}; - -EPUBJS.Book.prototype.getPageList = function() { - return this.ready.pageList.promise; -}; - -EPUBJS.Book.prototype.getMetadata = function() { - return this.ready.metadata.promise; -}; - -EPUBJS.Book.prototype.getToc = function() { - return this.ready.toc.promise; -}; - -/* Private Helpers */ - -//-- Listeners for browser events -EPUBJS.Book.prototype.networkListeners = function(){ - var book = this; - window.addEventListener("offline", function(e) { - book.online = false; - if (book.settings.storage) { - book.fromStorage(true); - } - book.trigger("book:offline"); - }, false); - - window.addEventListener("online", function(e) { - book.online = true; - if (book.settings.storage) { - book.fromStorage(false); - } - book.trigger("book:online"); - }, false); - -}; - -// Listen to all events the renderer triggers and pass them as book events -EPUBJS.Book.prototype.listenToRenderer = function(renderer){ - var book = this; - renderer.Events.forEach(function(eventName){ - renderer.on(eventName, function(e){ - book.trigger(eventName, e); - }); - }); - - renderer.on("renderer:visibleRangeChanged", function(range) { - var startPage, endPage, percent; - var pageRange = []; - - if(this.pageList.length > 0) { - startPage = this.pagination.pageFromCfi(range.start); - percent = this.pagination.percentageFromPage(startPage); - pageRange.push(startPage); - - if(range.end) { - endPage = this.pagination.pageFromCfi(range.end); - //if(startPage != endPage) { - pageRange.push(endPage); - //} - } - this.trigger("book:pageChanged", { - "anchorPage": startPage, - "percentage": percent, - "pageRange" : pageRange - }); - - // TODO: Add event for first and last page. - // (though last is going to be hard, since it could be several reflowed pages long) - } - }.bind(this)); - - renderer.on("render:loaded", this.loadChange.bind(this)); -}; - -// Listens for load events from the Renderer and checks against the current chapter -// Prevents the Render from loading a different chapter when back button is pressed -EPUBJS.Book.prototype.loadChange = function(url){ - var uri = EPUBJS.core.uri(url); - var chapterUri = EPUBJS.core.uri(this.currentChapter.absolute); - var spinePos, chapter; - - if(uri.path != chapterUri.path){ - console.warn("Miss Match", uri.path, this.currentChapter.absolute); - // this.goto(uri.filename); - - // Set the current chapter to what is being displayed - spinePos = this.spineIndexByURL[uri.filename]; - chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); - this.currentChapter = chapter; - - // setup the renderer with the displayed chapter - this.renderer.currentChapter = chapter; - this.renderer.afterLoad(this.renderer.render.docEl); - this.renderer.beforeDisplay(function () { - this.renderer.afterDisplay(); - }.bind(this)); - - } else if(!this._rendering) { - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.unlistenToRenderer = function(renderer){ - renderer.Events.forEach(function(eventName){ - renderer.off(eventName); - }); -}; - -//-- Choose between a request from store or a request from network -EPUBJS.Book.prototype.loadXml = function(url){ - if(this.settings.fromStorage) { - return this.store.getXml(url, this.settings.encoding); - } else if(this.settings.contained) { - return this.zip.getXml(url, this.settings.encoding); - }else{ - return EPUBJS.core.request(url, 'xml', this.settings.withCredentials); - } -}; - -//-- Turns a url into a absolute url -EPUBJS.Book.prototype.urlFrom = function(bookPath){ - var uri = EPUBJS.core.uri(bookPath), - absolute = uri.protocol, - fromRoot = uri.path[0] == "/", - location = window.location, - //-- Get URL orgin, try for native or combine - origin = location.origin || location.protocol + "//" + location.host, - baseTag = document.getElementsByTagName('base'), - base; - - - //-- Check is Base tag is set - - if(baseTag.length) { - base = baseTag[0].href; - } - - //-- 1. Check if url is absolute - if(uri.protocol){ - return uri.origin + uri.path; - } - - //-- 2. Check if url starts with /, add base url - if(!absolute && fromRoot){ - return (base || origin) + uri.path; - } - - //-- 3. Or find full path to url and add that - if(!absolute && !fromRoot){ - return EPUBJS.core.resolveUrl(base || location.pathname, uri.path); - } - -}; - - -EPUBJS.Book.prototype.unarchive = function(bookPath){ - var book = this, - unarchived; - - //-- Must use storage - // if(this.settings.storage == false ){ - // this.settings.storage = true; - // this.storage = new fileStorage.storage(); - // } - - this.zip = new EPUBJS.Unarchiver(); - this.store = this.zip; // Use zip storaged in ram - return this.zip.open(bookPath); -}; - -//-- Checks if url has a .epub or .zip extension, or is ArrayBuffer (of zip/epub) -EPUBJS.Book.prototype.isContained = function(bookUrl){ - if (bookUrl instanceof ArrayBuffer) { - return true; - } - var uri = EPUBJS.core.uri(bookUrl); - - if(uri.extension && (uri.extension == "epub" || uri.extension == "zip")){ - return true; - } - - return false; -}; - -//-- Checks if the book can be retrieved from localStorage -EPUBJS.Book.prototype.isSaved = function(bookKey) { - var storedSettings; - - if(!localStorage) { - return false; - } - - storedSettings = localStorage.getItem(bookKey); - - if( !localStorage || - storedSettings === null) { - return false; - } else { - return true; - } -}; - -// Generates the Book Key using the identifer in the manifest or other string provided -EPUBJS.Book.prototype.generateBookKey = function(identifier){ - return "epubjs:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; -}; - -EPUBJS.Book.prototype.saveContents = function(){ - if(!localStorage) { - return false; - } - localStorage.setItem(this.settings.bookKey, JSON.stringify(this.contents)); -}; - -EPUBJS.Book.prototype.removeSavedContents = function() { - if(!localStorage) { - return false; - } - localStorage.removeItem(this.settings.bookKey); -}; - - - -//-- Takes a string or a element -EPUBJS.Book.prototype.renderTo = function(elem){ - var book = this, - rendered; - - if(EPUBJS.core.isElement(elem)) { - this.element = elem; - } else if (typeof elem == "string") { - this.element = EPUBJS.core.getEl(elem); - } else { - console.error("Not an Element"); - return; - } - - rendered = this.opened. - then(function(){ - // book.render = new EPUBJS.Renderer[this.settings.renderer](book); - book.renderer.initialize(book.element, book.settings.width, book.settings.height); - - if(book.metadata.direction) { - book.renderer.setDirection(book.metadata.direction); - } - - book._rendered(); - return book.startDisplay(); - }); - - // rendered.then(null, function(error) { console.error(error); }); - - return rendered; -}; - -EPUBJS.Book.prototype.startDisplay = function(){ - var display; - - if(this.settings.goto) { - display = this.goto(this.settings.goto); - }else if(this.settings.previousLocationCfi) { - display = this.gotoCfi(this.settings.previousLocationCfi); - }else{ - display = this.displayChapter(this.spinePos); - } - - return display; -}; - -EPUBJS.Book.prototype.restore = function(identifier){ - - var book = this, - fetch = ['manifest', 'spine', 'metadata', 'cover', 'toc', 'spineNodeIndex', 'spineIndexByURL', 'globalLayoutProperties'], - reject = false, - bookKey = this.generateBookKey(identifier), - fromStore = localStorage.getItem(bookKey), - len = fetch.length, - i; - - if(this.settings.clearSaved) reject = true; - - if(!reject && fromStore != 'undefined' && fromStore !== null){ - book.contents = JSON.parse(fromStore); - - for(i = 0; i < len; i++) { - var item = fetch[i]; - - if(!book.contents[item]) { - reject = true; - break; - } - book[item] = book.contents[item]; - } - } - - if(reject || !fromStore || !this.contents || !this.settings.contentsPath){ - return false; - }else{ - this.settings.bookKey = bookKey; - this.ready.manifest.resolve(this.manifest); - this.ready.spine.resolve(this.spine); - this.ready.metadata.resolve(this.metadata); - this.ready.cover.resolve(this.cover); - this.ready.toc.resolve(this.toc); - return true; - } - -}; - -EPUBJS.Book.prototype.displayChapter = function(chap, end, deferred){ - var book = this, - render, - cfi, - pos, - store, - defer = deferred || new RSVP.defer(); - - var chapter; - - if(!this.isRendered) { - this._q.enqueue("displayChapter", arguments); - // Reject for now. TODO: pass promise to queue - defer.reject({ - message : "Rendering", - stack : new Error().stack - }); - return defer.promise; - } - - - if(this._rendering || this._rendering) { - // Pass along the current defer - this._displayQ.enqueue("displayChapter", [chap, end, defer]); - return defer.promise; - } - - if(EPUBJS.core.isNumber(chap)){ - pos = chap; - }else{ - cfi = new EPUBJS.EpubCFI(chap); - pos = cfi.spinePos; - } - - if(pos < 0 || pos >= this.spine.length){ - console.warn("Not A Valid Location"); - pos = 0; - end = false; - cfi = false; - } - - //-- Create a new chapter - chapter = new EPUBJS.Chapter(this.spine[pos], this.store); - - this._rendering = true; - - if(this._needsAssetReplacement()) { - - chapter.registerHook("beforeChapterRender", [ - EPUBJS.replace.head, - EPUBJS.replace.resources, - EPUBJS.replace.svg - ], true); - - } - - book.currentChapter = chapter; - - render = book.renderer.displayChapter(chapter, this.globalLayoutProperties); - if(cfi) { - book.renderer.gotoCfi(cfi); - } else if(end) { - book.renderer.lastPage(); - } - //-- Success, Clear render queue - render.then(function(rendered){ - // var inwait; - //-- Set the book's spine position - book.spinePos = pos; - - defer.resolve(book.renderer); - - if(book.settings.fromStorage === false && - book.settings.contained === false) { - book.preloadNextChapter(); - } - - book._rendering = false; - book._displayQ.dequeue(); - if(book._displayQ.length() === 0) { - book._gotoQ.dequeue(); - } - - }, function(error) { - // handle errors in either of the two requests - console.error("Could not load Chapter: "+ chapter.absolute, error); - book.trigger("book:chapterLoadFailed", chapter.absolute); - book._rendering = false; - defer.reject(error); - }); - - return defer.promise; -}; - -EPUBJS.Book.prototype.nextPage = function(){ - var next; - - if(!this.isRendered) return this._q.enqueue("nextPage", arguments); - - next = this.renderer.nextPage(); - - if(!next){ - return this.nextChapter(); - } -}; - -EPUBJS.Book.prototype.prevPage = function() { - var prev; - - if(!this.isRendered) return this._q.enqueue("prevPage", arguments); - - prev = this.renderer.prevPage(); - - if(!prev){ - return this.prevChapter(); - } -}; - -EPUBJS.Book.prototype.nextChapter = function() { - var next; - if (this.spinePos < this.spine.length - 1) { - next = this.spinePos + 1; - // Skip non linear chapters - while (this.spine[next] && this.spine[next].linear && this.spine[next].linear == 'no') { - next++; - } - if (next < this.spine.length) { - return this.displayChapter(next); - } else { - this.trigger("book:atEnd"); - } - - } else { - this.trigger("book:atEnd"); - } -}; - -EPUBJS.Book.prototype.prevChapter = function() { - var prev; - if (this.spinePos > 0) { - prev = this.spinePos - 1; - while (this.spine[prev] && this.spine[prev].linear && this.spine[prev].linear == 'no') { - prev--; - } - if (prev >= 0) { - return this.displayChapter(prev, true); - } else { - this.trigger("book:atStart"); - } - - } else { - this.trigger("book:atStart"); - } -}; - -EPUBJS.Book.prototype.getCurrentLocationCfi = function() { - if(!this.isRendered) return false; - return this.renderer.currentLocationCfi; -}; - -EPUBJS.Book.prototype.goto = function(target){ - - if(target.indexOf("epubcfi(") === 0) { - return this.gotoCfi(target); - } else if(target.indexOf("%") === target.length-1) { - return this.gotoPercentage(parseInt(target.substring(0, target.length-1))/100); - } else if(typeof target === "number" || isNaN(target) === false){ - return this.gotoPage(target); - } else { - return this.gotoHref(target); - } - -}; - -EPUBJS.Book.prototype.gotoCfi = function(cfiString, defer){ - var cfi, - spinePos, - spineItem, - rendered, - deferred = defer || new RSVP.defer(); - - if(!this.isRendered) { - console.warn("Not yet Rendered"); - this.settings.previousLocationCfi = cfiString; - return false; - } - - // Currently going to a chapter - if(this._moving || this._rendering) { - console.warn("Renderer is moving"); - this._gotoQ.enqueue("gotoCfi", [cfiString, deferred]); - return false; - } - - cfi = new EPUBJS.EpubCFI(cfiString); - spinePos = cfi.spinePos; - - if(spinePos == -1) { - return false; - } - - spineItem = this.spine[spinePos]; - promise = deferred.promise; - this._moving = true; - //-- If same chapter only stay on current chapter - if(this.currentChapter && this.spinePos === spinePos){ - this.renderer.gotoCfi(cfi); - this._moving = false; - deferred.resolve(this.renderer.currentLocationCfi); - } else { - - if(!spineItem || spinePos == -1) { - spinePos = 0; - spineItem = this.spine[spinePos]; - } - - this.currentChapter = new EPUBJS.Chapter(spineItem, this.store); - - if(this.currentChapter) { - this.spinePos = spinePos; - render = this.renderer.displayChapter(this.currentChapter, this.globalLayoutProperties); - - this.renderer.gotoCfi(cfi); - render.then(function(rendered){ - this._moving = false; - deferred.resolve(rendered.currentLocationCfi); - }.bind(this)); - } - } - - promise.then(function(){ - this._gotoQ.dequeue(); - }.bind(this)); - - return promise; -}; - -EPUBJS.Book.prototype.gotoHref = function(url, defer){ - var split, chapter, section, relativeURL, spinePos; - var deferred = defer || new RSVP.defer(); - - if(!this.isRendered) { - this.settings.goto = url; - return false; - } - - // Currently going to a chapter - if(this._moving || this._rendering) { - this._gotoQ.enqueue("gotoHref", [url, deferred]); - return false; - } - - split = url.split("#"); - chapter = split[0]; - section = split[1] || false; - if (chapter.search("://") == -1) { - relativeURL = chapter.replace(EPUBJS.core.uri(this.settings.contentsPath).path, ''); - } else { - relativeURL = chapter.replace(this.settings.contentsPath, ''); - } - spinePos = this.spineIndexByURL[relativeURL]; - - //-- If link fragment only stay on current chapter - if(!chapter){ - spinePos = this.currentChapter ? this.currentChapter.spinePos : 0; - } - - //-- Check that URL is present in the index, or stop - if(typeof(spinePos) != "number") return false; - - if(!this.currentChapter || spinePos != this.currentChapter.spinePos){ - //-- Load new chapter if different than current - return this.displayChapter(spinePos).then(function(){ - if(section){ - this.renderer.section(section); - } - deferred.resolve(this.renderer.currentLocationCfi); - }.bind(this)); - }else{ - //-- Goto section - if(section) { - this.renderer.section(section); - } else { - // Or jump to the start - this.renderer.firstPage(); - } - deferred.resolve(this.renderer.currentLocationCfi); - } - - deferred.promise.then(function(){ - this._gotoQ.dequeue(); - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Book.prototype.gotoPage = function(pg){ - var cfi = this.pagination.cfiFromPage(pg); - return this.gotoCfi(cfi); -}; - -EPUBJS.Book.prototype.gotoPercentage = function(percent){ - var pg = this.pagination.pageFromPercentage(percent); - return this.gotoPage(pg); -}; - -EPUBJS.Book.prototype.preloadNextChapter = function() { - var next; - var chap = this.spinePos + 1; - - if(chap >= this.spine.length){ - return false; - } - - next = new EPUBJS.Chapter(this.spine[chap]); - if(next) { - EPUBJS.core.request(next.absolute); - } -}; - -EPUBJS.Book.prototype.storeOffline = function() { - var book = this, - assets = EPUBJS.core.values(this.manifest); - - //-- Creates a queue of all items to load - return this.store.put(assets). - then(function(){ - book.settings.stored = true; - book.trigger("book:stored"); - }); -}; - -EPUBJS.Book.prototype.availableOffline = function() { - return this.settings.stored > 0 ? true : false; -}; - -EPUBJS.Book.prototype.toStorage = function () { - var key = this.settings.bookKey; - this.store.isStored(key).then(function(stored) { - - if (stored === true) { - this.settings.stored = true; - return true; - } - - return this.storeOffline() - .then(function() { - this.store.token(key, true); - }.bind(this)); - - }.bind(this)); - -}; -EPUBJS.Book.prototype.fromStorage = function(stored) { - var hooks = [ - EPUBJS.replace.head, - EPUBJS.replace.resources, - EPUBJS.replace.svg - ]; - - if(this.contained || this.settings.contained) return; - - //-- If there is network connection, store the books contents - if(this.online){ - this.opened.then(this.toStorage.bind(this)); - } - - if(this.store && this.settings.fromStorage && stored === false){ - this.settings.fromStorage = false; - this.store.off("offline"); - // this.renderer.removeHook("beforeChapterRender", hooks, true); - this.store = false; - }else if(!this.settings.fromStorage){ - - this.store = new EPUBJS.Storage(this.settings.credentials); - this.store.on("offline", function (offline) { - if (!offline) { - // Online - this.offline = false; - this.settings.fromStorage = false; - // this.renderer.removeHook("beforeChapterRender", hooks, true); - this.trigger("book:online"); - } else { - // Offline - this.offline = true; - this.settings.fromStorage = true; - // this.renderer.registerHook("beforeChapterRender", hooks, true); - this.trigger("book:offline"); - } - }.bind(this)); - - } - -}; - -EPUBJS.Book.prototype.setStyle = function(style, val, prefixed) { - var noreflow = ["color", "background", "background-color"]; - - if(!this.isRendered) return this._q.enqueue("setStyle", arguments); - - this.settings.styles[style] = val; - - this.renderer.setStyle(style, val, prefixed); - - if(noreflow.indexOf(style) === -1) { - // clearTimeout(this.reformatTimeout); - // this.reformatTimeout = setTimeout(function(){ - this.renderer.reformat(); - // }.bind(this), 10); - } -}; - -EPUBJS.Book.prototype.removeStyle = function(style) { - if(!this.isRendered) return this._q.enqueue("removeStyle", arguments); - this.renderer.removeStyle(style); - this.renderer.reformat(); - delete this.settings.styles[style]; -}; - -EPUBJS.Book.prototype.addHeadTag = function(tag, attrs) { - if(!this.isRendered) return this._q.enqueue("addHeadTag", arguments); - this.settings.headTags[tag] = attrs; -}; - -EPUBJS.Book.prototype.useSpreads = function(use) { - console.warn("useSpreads is deprecated, use forceSingle or set a layoutOveride instead"); - if(use === false) { - this.forceSingle(true); - } else { - this.forceSingle(false); - } -}; - -EPUBJS.Book.prototype.forceSingle = function(_use) { - var force = typeof _use === "undefined" ? true : _use; - - this.renderer.forceSingle(force); - this.settings.forceSingle = force; - if(this.isRendered) { - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.setMinSpreadWidth = function(width) { - this.settings.minSpreadWidth = width; - if(this.isRendered) { - this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.setGap = function(gap) { - this.settings.gap = gap; - if(this.isRendered) { - this.renderer.setGap(this.settings.gap); - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.chapter = function(path) { - var spinePos = this.spineIndexByURL[path]; - var spineItem; - var chapter; - - if(spinePos){ - spineItem = this.spine[spinePos]; - chapter = new EPUBJS.Chapter(spineItem, this.store, this.settings.withCredentials); - chapter.load(); - } - return chapter; -}; - -EPUBJS.Book.prototype.unload = function(){ - - if(this.settings.restore && localStorage) { - this.saveContents(); - } - - this.unlistenToRenderer(this.renderer); - - this.trigger("book:unload"); -}; - -EPUBJS.Book.prototype.destroy = function() { - - window.removeEventListener("beforeunload", this.unload); - - if(this.currentChapter) this.currentChapter.unload(); - - this.unload(); - - if(this.renderer) this.renderer.remove(); - -}; - -EPUBJS.Book.prototype._ready = function() { - - this.trigger("book:ready"); - -}; - -EPUBJS.Book.prototype._rendered = function(err) { - var book = this; - - this.isRendered = true; - this.trigger("book:rendered"); - - this._q.flush(); -}; - - -EPUBJS.Book.prototype.applyStyles = function(renderer, callback){ - // if(!this.isRendered) return this._q.enqueue("applyStyles", arguments); - renderer.applyStyles(this.settings.styles); - callback(); -}; - -EPUBJS.Book.prototype.applyHeadTags = function(renderer, callback){ - // if(!this.isRendered) return this._q.enqueue("applyHeadTags", arguments); - renderer.applyHeadTags(this.settings.headTags); - callback(); -}; - -EPUBJS.Book.prototype._registerReplacements = function(renderer){ - renderer.registerHook("beforeChapterDisplay", this.applyStyles.bind(this, renderer), true); - renderer.registerHook("beforeChapterDisplay", this.applyHeadTags.bind(this, renderer), true); - renderer.registerHook("beforeChapterDisplay", EPUBJS.replace.hrefs.bind(this), true); -}; - -EPUBJS.Book.prototype._needsAssetReplacement = function(){ - if(this.settings.fromStorage) { - - //-- Filesystem api links are relative, so no need to replace them - // if(this.storage.getStorageType() == "filesystem") { - // return false; - // } - - return true; - - } else if(this.settings.contained) { - - return true; - - } else { - - return false; - - } -}; - - -//-- http://www.idpf.org/epub/fxl/ -EPUBJS.Book.prototype.parseLayoutProperties = function(metadata){ - var layout = (this.settings.layoutOveride && this.settings.layoutOveride.layout) || metadata.layout || "reflowable"; - var spread = (this.settings.layoutOveride && this.settings.layoutOveride.spread) || metadata.spread || "auto"; - var orientation = (this.settings.layoutOveride && this.settings.layoutOveride.orientation) || metadata.orientation || "auto"; - return { - layout : layout, - spread : spread, - orientation : orientation - }; -}; - -//-- Enable binding events to book -RSVP.EventTarget.mixin(EPUBJS.Book.prototype); - -//-- Handle RSVP Errors -RSVP.on('error', function(event) { - //console.error(event, event.detail); -}); - -RSVP.configure('instrument', false); //-- true | will logging out all RSVP rejections -// RSVP.on('created', listener); -// RSVP.on('chained', listener); -// RSVP.on('fulfilled', listener); -// RSVP.on('rejected', function(event){ -// console.error(event.detail.message, event.detail.stack); -// }); - -EPUBJS.Chapter = function(spineObject, store, credentials){ - this.href = spineObject.href; - this.absolute = spineObject.url; - this.id = spineObject.id; - this.spinePos = spineObject.index; - this.cfiBase = spineObject.cfiBase; - this.properties = spineObject.properties; - this.manifestProperties = spineObject.manifestProperties; - this.linear = spineObject.linear; - this.pages = 1; - this.store = store; - this.credentials = credentials; - this.epubcfi = new EPUBJS.EpubCFI(); - this.deferred = new RSVP.defer(); - this.loaded = this.deferred.promise; - - EPUBJS.Hooks.mixin(this); - //-- Get pre-registered hooks for events - this.getHooks("beforeChapterRender"); - - // Cached for replacement urls from storage - this.caches = {}; -}; - - -EPUBJS.Chapter.prototype.load = function(_store, _credentials){ - var store = _store || this.store; - var credentials = _credentials || this.credentials; - var promise; - // if(this.store && (!this.book.online || this.book.contained)) - if(store){ - promise = store.getXml(this.absolute); - }else{ - promise = EPUBJS.core.request(this.absolute, false, credentials); - } - - promise.then(function(xml){ - this.setDocument(xml); - this.deferred.resolve(this); - }.bind(this)); - - return promise; -}; - -EPUBJS.Chapter.prototype.render = function(_store){ - - return this.load().then(function(doc){ - - var head = doc.querySelector('head'); - var base = doc.createElement("base"); - - base.setAttribute("href", this.absolute); - head.insertBefore(base, head.firstChild); - - this.contents = doc; - - return new RSVP.Promise(function (resolve, reject) { - this.triggerHooks("beforeChapterRender", function () { - resolve(doc); - }.bind(this), this); - }.bind(this)); - - }.bind(this)) - .then(function(doc) { - var serializer = new XMLSerializer(); - var contents = serializer.serializeToString(doc); - return contents; - }.bind(this)); -}; - -EPUBJS.Chapter.prototype.url = function(_store){ - var deferred = new RSVP.defer(); - var store = _store || this.store; - var loaded; - var chapter = this; - var url; - - if(store){ - if(!this.tempUrl) { - store.getUrl(this.absolute).then(function(url){ - chapter.tempUrl = url; - deferred.resolve(url); - }); - } else { - url = this.tempUrl; - deferred.resolve(url); - } - }else{ - url = this.absolute; - deferred.resolve(url); - } - - return deferred.promise; -}; - -EPUBJS.Chapter.prototype.setPages = function(num){ - this.pages = num; -}; - -EPUBJS.Chapter.prototype.getPages = function(num){ - return this.pages; -}; - -EPUBJS.Chapter.prototype.getID = function(){ - return this.ID; -}; - -EPUBJS.Chapter.prototype.unload = function(store){ - this.document = null; - if(this.tempUrl && store) { - store.revokeUrl(this.tempUrl); - this.tempUrl = false; - } -}; - -EPUBJS.Chapter.prototype.setDocument = function(_document){ - var uri = _document.namespaceURI; - var doctype = _document.doctype; - - // Creates an empty document - this.document = _document.implementation.createDocument( - uri, - null, - null - ); - this.contents = this.document.importNode( - _document.documentElement, //node to import - true //clone its descendants - ); - - this.document.appendChild(this.contents); - - // Fix to apply wgxpath to new document in IE - if(!this.document.evaluate && document.evaluate) { - this.document.evaluate = document.evaluate; - } - - // this.deferred.resolve(this.contents); -}; - -EPUBJS.Chapter.prototype.cfiFromRange = function(_range) { - var range; - var startXpath, endXpath; - var startContainer, endContainer; - var cleanTextContent, cleanEndTextContent; - - // Check for Contents - if(!this.document) return; - - if(typeof document.evaluate != 'undefined') { - - startXpath = EPUBJS.core.getElementXPath(_range.startContainer); - // console.log(startContainer) - endXpath = EPUBJS.core.getElementXPath(_range.endContainer); - - startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - - if(!_range.collapsed) { - endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - } - - range = this.document.createRange(); - // Find Exact Range in original document - if(startContainer) { - try { - range.setStart(startContainer, _range.startOffset); - if(!_range.collapsed && endContainer) { - range.setEnd(endContainer, _range.endOffset); - } - } catch (e) { - console.log("missed"); - startContainer = false; - } - - } - - // Fuzzy Match - if(!startContainer) { - console.log("not found, try fuzzy match"); - cleanStartTextContent = EPUBJS.core.cleanStringForXpath(_range.startContainer.textContent); - startXpath = "//text()[contains(.," + cleanStartTextContent + ")]"; - - startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - - if(startContainer){ - // console.log("Found with Fuzzy"); - range.setStart(startContainer, _range.startOffset); - - if(!_range.collapsed) { - cleanEndTextContent = EPUBJS.core.cleanStringForXpath(_range.endContainer.textContent); - endXpath = "//text()[contains(.," + cleanEndTextContent + ")]"; - endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - if(endContainer) { - range.setEnd(endContainer, _range.endOffset); - } - } - - } - } - } else { - range = _range; // Just evaluate the current documents range - } - - // Generate the Cfi - return this.epubcfi.generateCfiFromRange(range, this.cfiBase); -}; - -EPUBJS.Chapter.prototype.find = function(_query){ - var chapter = this; - var matches = []; - var query = _query.toLowerCase(); - //var xpath = this.document.evaluate(".//text()[contains(translate(., '"+query.toUpperCase()+"', '"+query+"'),'"+query+"')]", this.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); - var find = function(node){ - // Search String - var text = node.textContent.toLowerCase(); - var range = chapter.document.createRange(); - var cfi; - var pos; - var last = -1; - var excerpt; - var limit = 150; - - while (pos != -1) { - pos = text.indexOf(query, last + 1); - - if(pos != -1) { - // If Found, Create Range - range = chapter.document.createRange(); - range.setStart(node, pos); - range.setEnd(node, pos + query.length); - - //Generate CFI - cfi = chapter.cfiFromRange(range); - - // Generate Excerpt - if(node.textContent.length < limit) { - excerpt = node.textContent; - } else { - excerpt = node.textContent.substring(pos-limit/2,pos+limit/2); - excerpt = "..." + excerpt + "..."; - } - - //Add CFI to list - matches.push({ - cfi: cfi, - excerpt: excerpt - }); - } - - last = pos; - } - - }; - - // Grab text nodes - - /* - for ( var i=0 ; i < xpath.snapshotLength; i++ ) { - find(xpath.snapshotItem(i)); - } - */ - - this.textSprint(this.document, function(node){ - find(node); - }); - - - // Return List of CFIs - return matches; -}; - - -EPUBJS.Chapter.prototype.textSprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: function (node) { - if (node.data && ! /^\s*$/.test(node.data) ) { - return NodeFilter.FILTER_ACCEPT; - } else { - return NodeFilter.FILTER_REJECT; - } - } - }, false); - var node; - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Chapter.prototype.replace = function(query, func, finished, progress){ - var items = this.contents.querySelectorAll(query), - resources = Array.prototype.slice.call(items), - count = resources.length; - - - if(count === 0) { - finished(false); - return; - } - resources.forEach(function(item){ - var called = false; - var after = function(result, full){ - if(called === false) { - count--; - if(progress) progress(result, full, count); - if(count <= 0 && finished) finished(true); - called = true; - } - }; - - func(item, after); - - }.bind(this)); - -}; - -EPUBJS.Chapter.prototype.replaceWithStored = function(query, attr, func, callback) { - var _oldUrls, - _newUrls = {}, - _store = this.store, - _cache = this.caches[query], - _uri = EPUBJS.core.uri(this.absolute), - _chapterBase = _uri.base, - _attr = attr, - _wait = 5, - progress = function(url, full, count) { - _newUrls[full] = url; - }, - finished = function(notempty) { - if(callback) callback(); - EPUBJS.core.values(_oldUrls).forEach(function(url){ - _store.revokeUrl(url); - }); - - _cache = _newUrls; - }; - - if(!_store) return; - - if(!_cache) _cache = {}; - _oldUrls = EPUBJS.core.clone(_cache); - - this.replace(query, function(link, done){ - var src = link.getAttribute(_attr), - full = EPUBJS.core.resolveUrl(_chapterBase, src); - - var replaceUrl = function(url) { - var timeout; - link.onload = function(){ - clearTimeout(timeout); - done(url, full); - }; - - link.onerror = function(e){ - clearTimeout(timeout); - done(url, full); - console.error(e); - }; - - if(query == "svg image") { - //-- SVG needs this to trigger a load event - link.setAttribute("externalResourcesRequired", "true"); - } - - if(query == "link[href]" && link.getAttribute("rel") !== "stylesheet") { - //-- Only Stylesheet links seem to have a load events, just continue others - done(url, full); - } else { - timeout = setTimeout(function(){ - done(url, full); - }, _wait); - } - - if (url) { - link.setAttribute(_attr, url); - } - - }; - - if(full in _oldUrls){ - replaceUrl(_oldUrls[full]); - _newUrls[full] = _oldUrls[full]; - delete _oldUrls[full]; - }else{ - func(_store, full, replaceUrl, link); - } - - }, finished, progress); -}; - -var EPUBJS = EPUBJS || {}; -EPUBJS.core = {}; - -//-- Get a element for an id -EPUBJS.core.getEl = function(elem) { - return document.getElementById(elem); -}; - -//-- Get all elements for a class -EPUBJS.core.getEls = function(classes) { - return document.getElementsByClassName(classes); -}; - -EPUBJS.core.request = function(url, type, withCredentials) { - var supportsURL = window.URL; - var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; - var deferred = new RSVP.defer(); - var xhr = new XMLHttpRequest(); - var uri; - - //-- Check from PDF.js: - // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js - var xhrPrototype = XMLHttpRequest.prototype; - - var handler = function() { - var r; - - if (this.readyState != this.DONE) return; - - if (this.status === 200 || (this.status === 0 && this.response) ) { // Android & Firefox reporting 0 for local & blob urls - if(type == 'xml'){ - // If this.responseXML wasn't set, try to parse using a DOMParser from text - if(!this.responseXML){ - r = new DOMParser().parseFromString(this.response, "application/xml"); - } else { - r = this.responseXML; - } - }else - if(type == 'xhtml'){ - if(!this.responseXML){ - r = new DOMParser().parseFromString(this.response, "application/xhtml+xml"); - } else { - r = this.responseXML; - } - }else - if(type == 'html'){ - if(!this.responseXML){ - r = new DOMParser().parseFromString(this.response, "text/html"); - } else { - r = this.responseXML; - } - } else - if(type == 'json'){ - r = JSON.parse(this.response); - }else - if(type == 'blob'){ - - if(supportsURL) { - r = this.response; - } else { - //-- Safari doesn't support responseType blob, so create a blob from arraybuffer - r = new Blob([this.response]); - } - - }else{ - r = this.response; - } - - deferred.resolve(r); - } else { - deferred.reject({ - message : this.response, - stack : new Error().stack - }); - } - }; - - if (!('overrideMimeType' in xhrPrototype)) { - // IE10 might have response, but not overrideMimeType - Object.defineProperty(xhrPrototype, 'overrideMimeType', { - value: function xmlHttpRequestOverrideMimeType(mimeType) {} - }); - } - - xhr.open("GET", url, true); - xhr.onreadystatechange = handler; - - if(withCredentials) { - xhr.withCredentials = true; - } - - // If type isn't set, determine it from the file extension - if(!type) { - uri = EPUBJS.core.uri(url); - type = uri.extension; - type = { - 'htm': 'html' - }[type] || type; - } - - if(type == 'blob'){ - xhr.responseType = BLOB_RESPONSE; - } - - if(type == "json") { - xhr.setRequestHeader("Accept", "application/json"); - } - - if(type == 'xml') { - xhr.responseType = "document"; - xhr.overrideMimeType('text/xml'); // for OPF parsing - } - - if(type == 'xhtml') { - xhr.responseType = "document"; - } - - if(type == 'html') { - xhr.responseType = "document"; - } - - if(type == "binary") { - xhr.responseType = "arraybuffer"; - } - - xhr.send(); - - return deferred.promise; -}; - -EPUBJS.core.toArray = function(obj) { - var arr = []; - - for (var member in obj) { - var newitm; - if ( obj.hasOwnProperty(member) ) { - newitm = obj[member]; - newitm.ident = member; - arr.push(newitm); - } - } - - return arr; -}; - -//-- Parse the different parts of a url, returning a object -EPUBJS.core.uri = function(url){ - var uri = { - protocol : '', - host : '', - path : '', - origin : '', - directory : '', - base : '', - filename : '', - extension : '', - fragment : '', - href : url - }, - blob = url.indexOf('blob:'), - doubleSlash = url.indexOf('://'), - search = url.indexOf('?'), - fragment = url.indexOf("#"), - withoutProtocol, - dot, - firstSlash; - - if(blob === 0) { - uri.protocol = "blob"; - uri.base = url.indexOf(0, fragment); - return uri; - } - - if(fragment != -1) { - uri.fragment = url.slice(fragment + 1); - url = url.slice(0, fragment); - } - - if(search != -1) { - uri.search = url.slice(search + 1); - url = url.slice(0, search); - href = url; - } - - if(doubleSlash != -1) { - uri.protocol = url.slice(0, doubleSlash); - withoutProtocol = url.slice(doubleSlash+3); - firstSlash = withoutProtocol.indexOf('/'); - - if(firstSlash === -1) { - uri.host = uri.path; - uri.path = ""; - } else { - uri.host = withoutProtocol.slice(0, firstSlash); - uri.path = withoutProtocol.slice(firstSlash); - } - - - uri.origin = uri.protocol + "://" + uri.host; - - uri.directory = EPUBJS.core.folder(uri.path); - - uri.base = uri.origin + uri.directory; - // return origin; - } else { - uri.path = url; - uri.directory = EPUBJS.core.folder(url); - uri.base = uri.directory; - } - - //-- Filename - uri.filename = url.replace(uri.base, ''); - dot = uri.filename.lastIndexOf('.'); - if(dot != -1) { - uri.extension = uri.filename.slice(dot+1); - } - return uri; -}; - -//-- Parse out the folder, will return everything before the last slash - -EPUBJS.core.folder = function(url){ - - var lastSlash = url.lastIndexOf('/'); - - if(lastSlash == -1) var folder = ''; - - folder = url.slice(0, lastSlash + 1); - - return folder; - -}; - -//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 -EPUBJS.core.dataURLToBlob = function(dataURL) { - var BASE64_MARKER = ';base64,', - parts, contentType, raw, rawLength, uInt8Array; - - if (dataURL.indexOf(BASE64_MARKER) == -1) { - parts = dataURL.split(','); - contentType = parts[0].split(':')[1]; - raw = parts[1]; - - return new Blob([raw], {type: contentType}); - } - - parts = dataURL.split(BASE64_MARKER); - contentType = parts[0].split(':')[1]; - raw = window.atob(parts[1]); - rawLength = raw.length; - - uInt8Array = new Uint8Array(rawLength); - - for (var i = 0; i < rawLength; ++i) { - uInt8Array[i] = raw.charCodeAt(i); - } - - return new Blob([uInt8Array], {type: contentType}); -}; - -//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously -EPUBJS.core.addScript = function(src, callback, target) { - var s, r; - r = false; - s = document.createElement('script'); - s.type = 'text/javascript'; - s.async = false; - s.src = src; - s.onload = s.onreadystatechange = function() { - if ( !r && (!this.readyState || this.readyState == 'complete') ) { - r = true; - if(callback) callback(); - } - }; - target = target || document.body; - target.appendChild(s); -}; - -EPUBJS.core.addScripts = function(srcArr, callback, target) { - var total = srcArr.length, - curr = 0, - cb = function(){ - curr++; - if(total == curr){ - if(callback) callback(); - }else{ - EPUBJS.core.addScript(srcArr[curr], cb, target); - } - }; - - EPUBJS.core.addScript(srcArr[curr], cb, target); -}; - -EPUBJS.core.addCss = function(src, callback, target) { - var s, r; - r = false; - s = document.createElement('link'); - s.type = 'text/css'; - s.rel = "stylesheet"; - s.href = src; - s.onload = s.onreadystatechange = function() { - if ( !r && (!this.readyState || this.readyState == 'complete') ) { - r = true; - if(callback) callback(); - } - }; - target = target || document.body; - target.appendChild(s); -}; - -EPUBJS.core.prefixed = function(unprefixed) { - var vendors = ["Webkit", "Moz", "O", "ms" ], - prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], - upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), - length = vendors.length; - - if (typeof(document.documentElement.style[unprefixed]) != 'undefined') { - return unprefixed; - } - - for ( var i=0; i < length; i++ ) { - if (typeof(document.documentElement.style[vendors[i] + upper]) != 'undefined') { - return vendors[i] + upper; - } - } - - return unprefixed; -}; - -EPUBJS.core.resolveUrl = function(base, path) { - var url, - segments = [], - uri = EPUBJS.core.uri(path), - folders = base.split("/"), - paths; - - if(uri.host) { - return path; - } - - folders.pop(); - - paths = path.split("/"); - paths.forEach(function(p){ - if(p === ".."){ - folders.pop(); - }else{ - segments.push(p); - } - }); - - url = folders.concat(segments); - - return url.join("/"); -}; - -// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript -EPUBJS.core.uuid = function() { - var d = new Date().getTime(); - var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = (d + Math.random()*16)%16 | 0; - d = Math.floor(d/16); - return (c=='x' ? r : (r&0x7|0x8)).toString(16); - }); - return uuid; -}; - -// Fast quicksort insert for sorted array -- based on: -// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers -EPUBJS.core.insert = function(item, array, compareFunction) { - var location = EPUBJS.core.locationOf(item, array, compareFunction); - array.splice(location, 0, item); - - return location; -}; - -EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { - var start = _start || 0; - var end = _end || array.length; - var pivot = parseInt(start + (end - start) / 2); - var compared; - if(!compareFunction){ - compareFunction = function(a, b) { - if(a > b) return 1; - if(a < b) return -1; - if(a = b) return 0; - }; - } - if(end-start <= 0) { - return pivot; - } - - compared = compareFunction(array[pivot], item); - if(end-start === 1) { - return compared > 0 ? pivot : pivot + 1; - } - - if(compared === 0) { - return pivot; - } - if(compared === -1) { - return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); - } else{ - return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); - } -}; - -EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { - var start = _start || 0; - var end = _end || array.length; - var pivot = parseInt(start + (end - start) / 2); - var compared; - if(!compareFunction){ - compareFunction = function(a, b) { - if(a > b) return 1; - if(a < b) return -1; - if(a = b) return 0; - }; - } - if(end-start <= 0) { - return -1; // Not found - } - - compared = compareFunction(array[pivot], item); - if(end-start === 1) { - return compared === 0 ? pivot : -1; - } - if(compared === 0) { - return pivot; // Found - } - if(compared === -1) { - return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); - } else{ - return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); - } -}; - - -EPUBJS.core.queue = function(_scope){ - var _q = []; - var scope = _scope; - // Add an item to the queue - var enqueue = function(funcName, args, context) { - _q.push({ - "funcName" : funcName, - "args" : args, - "context" : context - }); - return _q; - }; - // Run one item - var dequeue = function(){ - var inwait; - if(_q.length) { - inwait = _q.shift(); - // Defer to any current tasks - // setTimeout(function(){ - scope[inwait.funcName].apply(inwait.context || scope, inwait.args); - // }, 0); - } - }; - - // Run All - var flush = function(){ - while(_q.length) { - dequeue(); - } - }; - // Clear all items in wait - var clear = function(){ - _q = []; - }; - - var length = function(){ - return _q.length; - }; - - return { - "enqueue" : enqueue, - "dequeue" : dequeue, - "flush" : flush, - "clear" : clear, - "length" : length - }; -}; - -// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js -/** - * Gets an XPath for an element which describes its hierarchical location. - */ -EPUBJS.core.getElementXPath = function(element) { - if (element && element.id) { - return '//*[@id="' + element.id + '"]'; - } else { - return EPUBJS.core.getElementTreeXPath(element); - } -}; - -EPUBJS.core.getElementTreeXPath = function(element) { - var paths = []; - var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); - var index, nodeName, tagName, pathIndex; - - if(element.nodeType === Node.TEXT_NODE){ - // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; - index = EPUBJS.core.indexOfTextNode(element) + 1; - - paths.push("text()["+index+"]"); - element = element.parentNode; - } - - // Use nodeName (instead of localName) so namespace prefix is included (if any). - for (; element && element.nodeType == 1; element = element.parentNode) - { - index = 0; - for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) - { - // Ignore document type declaration. - if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { - continue; - } - if (sibling.nodeName == element.nodeName) { - ++index; - } - } - nodeName = element.nodeName.toLowerCase(); - tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); - pathIndex = (index ? "[" + (index+1) + "]" : ""); - paths.splice(0, 0, tagName + pathIndex); - } - - return paths.length ? "./" + paths.join("/") : null; -}; - -EPUBJS.core.nsResolver = function(prefix) { - var ns = { - 'xhtml' : 'http://www.w3.org/1999/xhtml', - 'epub': 'http://www.idpf.org/2007/ops' - }; - return ns[prefix] || null; -}; - -//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 -EPUBJS.core.cleanStringForXpath = function(str) { - var parts = str.match(/[^'"]+|['"]/g); - parts = parts.map(function(part){ - if (part === "'") { - return '\"\'\"'; // output "'" - } - - if (part === '"') { - return "\'\"\'"; // output '"' - } - return "\'" + part + "\'"; - }); - return "concat(\'\'," + parts.join(",") + ")"; -}; - -EPUBJS.core.indexOfTextNode = function(textNode){ - var parent = textNode.parentNode; - var children = parent.childNodes; - var sib; - var index = -1; - for (var i = 0; i < children.length; i++) { - sib = children[i]; - if(sib.nodeType === Node.TEXT_NODE){ - index++; - } - if(sib == textNode) break; - } - - return index; -}; - -// Underscore -EPUBJS.core.defaults = function(obj) { - for (var i = 1, length = arguments.length; i < length; i++) { - var source = arguments[i]; - for (var prop in source) { - if (obj[prop] === void 0) obj[prop] = source[prop]; - } - } - return obj; -}; - -EPUBJS.core.extend = function(target) { - var sources = [].slice.call(arguments, 1); - sources.forEach(function (source) { - if(!source) return; - Object.getOwnPropertyNames(source).forEach(function(propName) { - Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); - }); - }); - return target; -}; - -EPUBJS.core.clone = function(obj) { - return EPUBJS.core.isArray(obj) ? obj.slice() : EPUBJS.core.extend({}, obj); -}; - -EPUBJS.core.isElement = function(obj) { - return !!(obj && obj.nodeType == 1); -}; - -EPUBJS.core.isNumber = function(n) { - return !isNaN(parseFloat(n)) && isFinite(n); -}; - -EPUBJS.core.isString = function(str) { - return (typeof str === 'string' || str instanceof String); -}; - -EPUBJS.core.isArray = Array.isArray || function(obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; -}; - -// Lodash -EPUBJS.core.values = function(object) { - var index = -1; - var props, length, result; - - if(!object) return []; - - props = Object.keys(object); - length = props.length; - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; -}; - -EPUBJS.EpubCFI = function(cfiStr){ - if(cfiStr) return this.parse(cfiStr); -}; - -EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) { - var pos = parseInt(_pos), - spineNodeIndex = _spineNodeIndex + 1, - cfi = '/'+spineNodeIndex+'/'; - - cfi += (pos + 1) * 2; - - if(id) cfi += "[" + id + "]"; - - //cfi += "!"; - - return cfi; -}; - -EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) { - var parts = []; - - steps.forEach(function(part){ - var segment = ''; - segment += (part.index + 1) * 2; - - if(part.id) { - segment += "[" + part.id + "]"; - } - - parts.push(segment); - }); - - return parts.join('/'); -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) { - var steps = this.pathTo(element); - var path = this.generatePathComponent(steps); - if(!path.length) { - // Start of Chapter - return "epubcfi(" + chapter + "!/4/)"; - } else { - // First Text Node - return "epubcfi(" + chapter + "!" + path + "/1:0)"; - } -}; - -EPUBJS.EpubCFI.prototype.pathTo = function(node) { - var stack = [], - children; - - while(node && node.parentNode !== null && node.parentNode.nodeType != 9) { - children = node.parentNode.children; - - stack.unshift({ - 'id' : node.id, - // 'classList' : node.classList, - 'tagName' : node.tagName, - 'index' : children ? Array.prototype.indexOf.call(children, node) : 0 - }); - - node = node.parentNode; - } - - return stack; -}; - -EPUBJS.EpubCFI.prototype.getChapterComponent = function(cfiStr) { - - var splitStr = cfiStr.split("!"); - - return splitStr[0]; -}; - -EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) { - - var splitStr = cfiStr.split("!"); - var pathComponent = splitStr[1] ? splitStr[1].split(":") : ''; - - return pathComponent[0]; -}; - -EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) { - var splitStr = cfiStr.split(":"); - return splitStr[1] || ''; -}; - - -EPUBJS.EpubCFI.prototype.parse = function(cfiStr) { - var cfi = {}, - chapSegment, - chapterComponent, - pathComponent, - charecterOffsetComponent, - assertion, - chapId, - path, - end, - endInt, - text, - parseStep = function(part){ - var type, index, has_brackets, id; - - type = "element"; - index = parseInt(part) / 2 - 1; - has_brackets = part.match(/\[(.*)\]/); - if(has_brackets && has_brackets[1]){ - id = has_brackets[1]; - } - - return { - "type" : type, - 'index' : index, - 'id' : id || false - }; - }; - - if(typeof cfiStr !== "string") { - return {spinePos: -1}; - } - - cfi.str = cfiStr; - - if(cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length-1] === ")") { - // Remove intial epubcfi( and ending ) - cfiStr = cfiStr.slice(8, cfiStr.length-1); - } - - chapterComponent = this.getChapterComponent(cfiStr); - pathComponent = this.getPathComponent(cfiStr) || ''; - charecterOffsetComponent = this.getCharecterOffsetComponent(cfiStr); - // Make sure this is a valid cfi or return - if(!chapterComponent) { - return {spinePos: -1}; - } - - // Chapter segment is always the second one - chapSegment = chapterComponent.split("/")[2] || ''; - if(!chapSegment) return {spinePos:-1}; - - cfi.spinePos = (parseInt(chapSegment) / 2 - 1 ) || 0; - - chapId = chapSegment.match(/\[(.*)\]/); - - cfi.spineId = chapId ? chapId[1] : false; - - if(pathComponent.indexOf(',') != -1) { - // Handle ranges -- not supported yet - console.warn("CFI Ranges are not supported"); - } - - path = pathComponent.split('/'); - end = path.pop(); - - cfi.steps = []; - - path.forEach(function(part){ - var step; - - if(part) { - step = parseStep(part); - cfi.steps.push(step); - } - }); - - //-- Check if END is a text node or element - endInt = parseInt(end); - if(!isNaN(endInt)) { - - if(endInt % 2 === 0) { // Even = is an element - cfi.steps.push(parseStep(end)); - } else { - cfi.steps.push({ - "type" : "text", - 'index' : (endInt - 1 ) / 2 - }); - } - - } - - assertion = charecterOffsetComponent.match(/\[(.*)\]/); - if(assertion && assertion[1]){ - cfi.characterOffset = parseInt(charecterOffsetComponent.split('[')[0]); - // We arent handling these assertions yet - cfi.textLocationAssertion = assertion[1]; - } else { - cfi.characterOffset = parseInt(charecterOffsetComponent); - } - - return cfi; -}; - -EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) { - var doc = _doc || document; - var marker = _marker || this.createMarker(doc); - var parent; - var lastStep; - var text; - var split; - - if(typeof cfi === 'string') { - cfi = this.parse(cfi); - } - // Get the terminal step - lastStep = cfi.steps[cfi.steps.length-1]; - - // check spinePos - if(cfi.spinePos === -1) { - // Not a valid CFI - return false; - } - - // Find the CFI elements parent - parent = this.findParent(cfi, doc); - - if(!parent) { - // CFI didn't return an element - // Maybe it isnt in the current chapter? - return false; - } - - if(lastStep && lastStep.type === "text") { - text = parent.childNodes[lastStep.index]; - if(cfi.characterOffset){ - split = text.splitText(cfi.characterOffset); - marker.classList.add("EPUBJS-CFI-SPLIT"); - parent.insertBefore(marker, split); - } else { - parent.insertBefore(marker, text); - } - } else { - parent.insertBefore(marker, parent.firstChild); - } - - return marker; -}; - -EPUBJS.EpubCFI.prototype.createMarker = function(_doc) { - var doc = _doc || document; - var element = doc.createElement('span'); - element.id = "EPUBJS-CFI-MARKER:"+ EPUBJS.core.uuid(); - element.classList.add("EPUBJS-CFI-MARKER"); - - return element; -}; - -EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) { - var doc = _doc || document; - // var id = marker.id; - - // Cleanup textnodes if they were split - if(marker.classList.contains("EPUBJS-CFI-SPLIT")){ - nextSib = marker.nextSibling; - prevSib = marker.previousSibling; - if(nextSib && - prevSib && - nextSib.nodeType === 3 && - prevSib.nodeType === 3){ - - prevSib.textContent += nextSib.textContent; - marker.parentNode.removeChild(nextSib); - } - marker.parentNode.removeChild(marker); - } else if(marker.classList.contains("EPUBJS-CFI-MARKER")) { - // Remove only elements added as markers - marker.parentNode.removeChild(marker); - } - -}; - -EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) { - var doc = _doc || document, - element = doc.getElementsByTagName('html')[0], - children = Array.prototype.slice.call(element.children), - num, index, part, sections, - text, textBegin, textEnd; - - if(typeof cfi === 'string') { - cfi = this.parse(cfi); - } - - sections = cfi.steps.slice(0); // Clone steps array - if(!sections.length) { - return doc.getElementsByTagName('body')[0]; - } - - while(sections && sections.length > 0) { - part = sections.shift(); - // Find textNodes Parent - if(part.type === "text") { - text = element.childNodes[part.index]; - element = text.parentNode || element; - // Find element by id if present - } else if(part.id){ - element = doc.getElementById(part.id); - // Find element in parent - }else{ - element = children[part.index]; - } - // Element can't be found - if(typeof element === "undefined") { - console.error("No Element For", part, cfi.str); - return false; - } - // Get current element children and continue through steps - children = Array.prototype.slice.call(element.children); - } - - return element; -}; - -EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) { - if(typeof cfiOne === 'string') { - cfiOne = new EPUBJS.EpubCFI(cfiOne); - } - if(typeof cfiTwo === 'string') { - cfiTwo = new EPUBJS.EpubCFI(cfiTwo); - } - // Compare Spine Positions - if(cfiOne.spinePos > cfiTwo.spinePos) { - return 1; - } - if(cfiOne.spinePos < cfiTwo.spinePos) { - return -1; - } - - - // Compare Each Step in the First item - for (var i = 0; i < cfiOne.steps.length; i++) { - if(!cfiTwo.steps[i]) { - return 1; - } - if(cfiOne.steps[i].index > cfiTwo.steps[i].index) { - return 1; - } - if(cfiOne.steps[i].index < cfiTwo.steps[i].index) { - return -1; - } - // Otherwise continue checking - } - - // All steps in First present in Second - if(cfiOne.steps.length < cfiTwo.steps.length) { - return -1; - } - - // Compare the charecter offset of the text node - if(cfiOne.characterOffset > cfiTwo.characterOffset) { - return 1; - } - if(cfiOne.characterOffset < cfiTwo.characterOffset) { - return -1; - } - - // CFI's are equal - return 0; -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) { - var uri = EPUBJS.core.uri(href); - var path = uri.path; - var fragment = uri.fragment; - var spinePos = book.spineIndexByURL[path]; - var loaded; - var deferred = new RSVP.defer(); - var epubcfi = new EPUBJS.EpubCFI(); - var spineItem; - - if(typeof spinePos !== "undefined"){ - spineItem = book.spine[spinePos]; - loaded = book.loadXml(spineItem.url); - loaded.then(function(doc){ - var element = doc.getElementById(fragment); - var cfi; - cfi = epubcfi.generateCfiFromElement(element, spineItem.cfiBase); - deferred.resolve(cfi); - }); - } - - return deferred.promise; -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) { - var parent = anchor.parentNode; - var steps = this.pathTo(parent); - var path = this.generatePathComponent(steps); - var index = 1 + (2 * Array.prototype.indexOf.call(parent.childNodes, anchor)); - return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")"; -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) { - var anchor = range.anchorNode; - var offset = range.anchorOffset; - return this.generateCfiFromTextNode(anchor, offset, base); -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) { - var start, startElement, startSteps, startPath, startOffset, startIndex; - var end, endElement, endSteps, endPath, endOffset, endIndex; - - start = range.startContainer; - - if(start.nodeType === 3) { // text node - startElement = start.parentNode; - //startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start)); - startIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(start)); - startSteps = this.pathTo(startElement); - } else if(range.collapsed) { - return this.generateCfiFromElement(start, base); // single element - } else { - startSteps = this.pathTo(start); - } - - startPath = this.generatePathComponent(startSteps); - startOffset = range.startOffset; - - if(!range.collapsed) { - end = range.endContainer; - - if(end.nodeType === 3) { // text node - endElement = end.parentNode; - // endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end)); - endIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(end)); - - endSteps = this.pathTo(endElement); - } else { - endSteps = this.pathTo(end); - } - - endPath = this.generatePathComponent(endSteps); - endOffset = range.endOffset; - - // Remove steps present in startPath - endPath = endPath.replace(startPath, ''); - - if (endPath.length) { - endPath = endPath + "/"; - } - - return "epubcfi(" + base + "!" + startPath + "/" + startIndex + ":" + startOffset + "," + endPath + endIndex + ":" + endOffset + ")"; - - } else { - return "epubcfi(" + base + "!" + startPath + "/"+ startIndex +":"+ startOffset +")"; - } -}; - -EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) { - var xpath = [".", "*"]; - - steps.forEach(function(step){ - var position = step.index + 1; - - if(step.id){ - xpath.push("*[position()=" + position + " and @id='" + step.id + "']"); - } else if(step.type === "text") { - xpath.push("text()[" + position + "]"); - } else { - xpath.push("*[" + position + "]"); - } - }); - - return xpath.join("/"); -}; - -EPUBJS.EpubCFI.prototype.generateQueryFromSteps = function(steps) { - var query = ["html"]; - - steps.forEach(function(step){ - var position = step.index + 1; - - if(step.id){ - query.push("#" + step.id); - } else if(step.type === "text") { - // unsupported in querySelector - // query.push("text()[" + position + "]"); - } else { - query.push("*:nth-child(" + position + ")"); - } - }); - - return query.join(">"); -}; - - -EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) { - var doc = _doc || document; - var range = doc.createRange(); - var lastStep; - var xpath; - var startContainer; - var textLength; - var query; - var startContainerParent; - - if(typeof cfi === 'string') { - cfi = this.parse(cfi); - } - - // check spinePos - if(cfi.spinePos === -1) { - // Not a valid CFI - return false; - } - - // Get the terminal step - lastStep = cfi.steps[cfi.steps.length-1]; - - if(typeof document.evaluate != 'undefined') { - xpath = this.generateXpathFromSteps(cfi.steps); - startContainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - } else { - // Get the query string - query = this.generateQueryFromSteps(cfi.steps); - // Find the containing element - startContainerParent = doc.querySelector(query); - // Find the text node within that element - if(startContainerParent && lastStep.type == "text") { - startContainer = startContainerParent.childNodes[lastStep.index]; - } - } - - if(!startContainer) { - return null; - } - - if(startContainer && cfi.characterOffset >= 0) { - textLength = startContainer.length; - - if(cfi.characterOffset < textLength) { - range.setStart(startContainer, cfi.characterOffset); - range.setEnd(startContainer, textLength ); - } else { - console.debug("offset greater than length:", cfi.characterOffset, textLength); - range.setStart(startContainer, textLength - 1 ); - range.setEnd(startContainer, textLength ); - } - } else if(startContainer) { - range.selectNode(startContainer); - } - // doc.defaultView.getSelection().addRange(range); - return range; -}; - -EPUBJS.EpubCFI.prototype.isCfiString = function(target) { - if(typeof target === "string" && - target.indexOf("epubcfi(") === 0) { - return true; - } - - return false; -}; - -EPUBJS.Events = function(obj, el){ - - this.events = {}; - - if(!el){ - this.el = document.createElement('div'); - }else{ - this.el = el; - } - - obj.createEvent = this.createEvent; - obj.tell = this.tell; - obj.listen = this.listen; - obj.deafen = this.deafen; - obj.listenUntil = this.listenUntil; - - return this; -}; - -EPUBJS.Events.prototype.createEvent = function(evt){ - var e = new CustomEvent(evt); - this.events[evt] = e; - return e; -}; - -EPUBJS.Events.prototype.tell = function(evt, msg){ - var e; - - if(!this.events[evt]){ - console.warn("No event:", evt, "defined yet, creating."); - e = this.createEvent(evt); - }else{ - e = this.events[evt]; - } - - if(msg) e.msg = msg; - this.el.dispatchEvent(e); - -}; - -EPUBJS.Events.prototype.listen = function(evt, func, bindto){ - if(!this.events[evt]){ - console.warn("No event:", evt, "defined yet, creating."); - this.createEvent(evt); - return; - } - - if(bindto){ - this.el.addEventListener(evt, func.bind(bindto), false); - }else{ - this.el.addEventListener(evt, func, false); - } - -}; - -EPUBJS.Events.prototype.deafen = function(evt, func){ - this.el.removeEventListener(evt, func, false); -}; - -EPUBJS.Events.prototype.listenUntil = function(OnEvt, OffEvt, func, bindto){ - this.listen(OnEvt, func, bindto); - - function unlisten(){ - this.deafen(OnEvt, func); - this.deafen(OffEvt, unlisten); - } - - this.listen(OffEvt, unlisten, this); -}; -EPUBJS.hooks = {}; -EPUBJS.Hooks = (function(){ - function hooks(){} - - //-- Get pre-registered hooks - hooks.prototype.getHooks = function(){ - var plugs; - this.hooks = {}; - Array.prototype.slice.call(arguments).forEach(function(arg){ - this.hooks[arg] = []; - }, this); - - for (var plugType in this.hooks) { - plugs = EPUBJS.core.values(EPUBJS.hooks[plugType]); - - plugs.forEach(function(hook){ - this.registerHook(plugType, hook); - }, this); - } - }; - - //-- Hooks allow for injecting async functions that must all complete before continuing - // Functions must have a callback as their first argument. - hooks.prototype.registerHook = function(type, toAdd, toFront){ - - if(typeof(this.hooks[type]) != "undefined"){ - - if(typeof(toAdd) === "function"){ - if(toFront) { - this.hooks[type].unshift(toAdd); - }else{ - this.hooks[type].push(toAdd); - } - }else if(Array.isArray(toAdd)){ - toAdd.forEach(function(hook){ - if(toFront) { - this.hooks[type].unshift(hook); - }else{ - this.hooks[type].push(hook); - } - }, this); - } - }else{ - //-- Allows for undefined hooks - this.hooks[type] = [toAdd]; - - if(typeof(toAdd) === "function"){ - this.hooks[type] = [toAdd]; - }else if(Array.isArray(toAdd)){ - this.hooks[type] = []; - toAdd.forEach(function(hook){ - this.hooks[type].push(hook); - }, this); - } - - } - }; - - hooks.prototype.removeHook = function(type, toRemove){ - var index; - - if(typeof(this.hooks[type]) != "undefined"){ - - if(typeof(toRemove) === "function"){ - index = this.hooks[type].indexOf(toRemove); - if (index > -1) { - this.hooks[type].splice(index, 1); - } - }else if(Array.isArray(toRemove)){ - toRemove.forEach(function(hook){ - index = this.hooks[type].indexOf(hook); - if (index > -1) { - this.hooks[type].splice(index, 1); - } - }, this); - } - } - }; - - hooks.prototype.triggerHooks = function(type, callback, passed){ - var hooks, count; - - if(typeof(this.hooks[type]) == "undefined") return false; - - hooks = this.hooks[type]; - - count = hooks.length; - if(count === 0 && callback) { - callback(); - } - - function countdown(){ - count--; - if(count <= 0 && callback) callback(); - } - - hooks.forEach(function(hook){ - hook(countdown, passed); - }); - }; - - return { - register: function(name) { - if(EPUBJS.hooks[name] === undefined) { EPUBJS.hooks[name] = {}; } - if(typeof EPUBJS.hooks[name] !== 'object') { throw "Already registered: "+name; } - return EPUBJS.hooks[name]; - }, - mixin: function(object) { - for (var prop in hooks.prototype) { - object[prop] = hooks.prototype[prop]; - } - } - }; -})(); - -EPUBJS.Layout = EPUBJS.Layout || {}; - -EPUBJS.Layout.Reflowable = function(){ - this.documentElement = null; - this.spreadWidth = null; -}; - -EPUBJS.Layout.Reflowable.prototype.format = function(documentElement, _width, _height, _gap){ - // Get the prefixed CSS commands - var columnAxis = EPUBJS.core.prefixed('columnAxis'); - var columnGap = EPUBJS.core.prefixed('columnGap'); - var columnWidth = EPUBJS.core.prefixed('columnWidth'); - var columnFill = EPUBJS.core.prefixed('columnFill'); - - //-- Check the width and create even width columns - var width = Math.floor(_width); - // var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 0; // Not needed for single - var section = Math.floor(width / 8); - var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); - this.documentElement = documentElement; - //-- Single Page - this.spreadWidth = (width + gap); - - - documentElement.style.overflow = "hidden"; - - // Must be set to the new calculated width or the columns will be off - documentElement.style.width = width + "px"; - - //-- Adjust height - documentElement.style.height = _height + "px"; - - //-- Add columns - documentElement.style[columnAxis] = "horizontal"; - documentElement.style[columnFill] = "auto"; - documentElement.style[columnWidth] = width+"px"; - documentElement.style[columnGap] = gap+"px"; - this.colWidth = width; - this.gap = gap; - - return { - pageWidth : this.spreadWidth, - pageHeight : _height - }; -}; - -EPUBJS.Layout.Reflowable.prototype.calculatePages = function() { - var totalWidth, displayedPages; - this.documentElement.style.width = "auto"; //-- reset width for calculations - totalWidth = this.documentElement.scrollWidth; - displayedPages = Math.ceil(totalWidth / this.spreadWidth); - - return { - displayedPages : displayedPages, - pageCount : displayedPages - }; -}; - -EPUBJS.Layout.ReflowableSpreads = function(){ - this.documentElement = null; - this.spreadWidth = null; -}; - -EPUBJS.Layout.ReflowableSpreads.prototype.format = function(documentElement, _width, _height, _gap){ - var columnAxis = EPUBJS.core.prefixed('columnAxis'); - var columnGap = EPUBJS.core.prefixed('columnGap'); - var columnWidth = EPUBJS.core.prefixed('columnWidth'); - var columnFill = EPUBJS.core.prefixed('columnFill'); - - var divisor = 2, - cutoff = 800; - - //-- Check the width and create even width columns - var fullWidth = Math.floor(_width); - var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 1; - - var section = Math.floor(width / 8); - var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); - - //-- Double Page - var colWidth = Math.floor((width - gap) / divisor); - - this.documentElement = documentElement; - this.spreadWidth = (colWidth + gap) * divisor; - - - documentElement.style.overflow = "hidden"; - - // Must be set to the new calculated width or the columns will be off - documentElement.style.width = width + "px"; - - //-- Adjust height - documentElement.style.height = _height + "px"; - - //-- Add columns - documentElement.style[columnAxis] = "horizontal"; - documentElement.style[columnFill] = "auto"; - documentElement.style[columnGap] = gap+"px"; - documentElement.style[columnWidth] = colWidth+"px"; - - this.colWidth = colWidth; - this.gap = gap; - return { - pageWidth : this.spreadWidth, - pageHeight : _height - }; -}; - -EPUBJS.Layout.ReflowableSpreads.prototype.calculatePages = function() { - var totalWidth = this.documentElement.scrollWidth; - var displayedPages = Math.ceil(totalWidth / this.spreadWidth); - - //-- Add a page to the width of the document to account an for odd number of pages - this.documentElement.style.width = ((displayedPages * this.spreadWidth) - this.gap) + "px"; - - return { - displayedPages : displayedPages, - pageCount : displayedPages * 2 - }; -}; - -EPUBJS.Layout.Fixed = function(){ - this.documentElement = null; -}; - -EPUBJS.Layout.Fixed.prototype.format = function(documentElement, _width, _height, _gap){ - var columnWidth = EPUBJS.core.prefixed('columnWidth'); - var viewport = documentElement.querySelector("[name=viewport]"); - var content; - var contents; - var width, height; - this.documentElement = documentElement; - /** - * check for the viewport size - * - */ - if(viewport && viewport.hasAttribute("content")) { - content = viewport.getAttribute("content"); - contents = content.split(','); - if(contents[0]){ - width = contents[0].replace("width=", ''); - } - if(contents[1]){ - height = contents[1].replace("height=", ''); - } - } - - //-- Adjust width and height - documentElement.style.width = width + "px" || "auto"; - documentElement.style.height = height + "px" || "auto"; - - //-- Remove columns - documentElement.style[columnWidth] = "auto"; - - //-- Scroll - documentElement.style.overflow = "auto"; - - this.colWidth = width; - this.gap = 0; - - return { - pageWidth : width, - pageHeight : height - }; - -}; - -EPUBJS.Layout.Fixed.prototype.calculatePages = function(){ - return { - displayedPages : 1, - pageCount : 1 - }; -}; - -EPUBJS.Locations = function(spine, store, credentials) { - this.spine = spine; - this.store = store; - this.credentials = credentials; - - this.epubcfi = new EPUBJS.EpubCFI(); - - this._locations = []; - this.total = 0; - - this.break = 150; - - this._current = 0; - -}; - -EPUBJS.Locations.prototype.generate = function(chars) { - var deferred = new RSVP.defer(); - var spinePos = -1; - var spineLength = this.spine.length; - var finished; - var nextChapter = function(deferred){ - var chapter; - var next = spinePos + 1; - var done = deferred || new RSVP.defer(); - var loaded; - if(next >= spineLength) { - done.resolve(); - } else { - spinePos = next; - chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store, this.credentials); - - this.process(chapter).then(function() { - // Load up the next chapter - setTimeout(function(){ - nextChapter(done); - }, 1); - - }); - } - return done.promise; - }.bind(this); - - if(typeof chars === 'number') { - this.break = chars; - } - - finished = nextChapter().then(function(){ - this.total = this._locations.length-1; - - if (this._currentCfi) { - this.currentLocation = this._currentCfi; - } - deferred.resolve(this._locations); - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Locations.prototype.process = function(chapter) { - return chapter.load() - .then(function(_doc) { - - var range; - var doc = _doc; - var contents = doc.documentElement.querySelector("body"); - var counter = 0; - var prev; - - this.sprint(contents, function(node) { - var len = node.length; - var dist; - var pos = 0; - - // Start range - if (counter === 0) { - range = doc.createRange(); - range.setStart(node, 0); - } - - dist = this.break - counter; - - // Node is smaller than a break - if(dist > len){ - counter += len; - pos = len; - } - - while (pos < len) { - counter = this.break; - pos += this.break; - - // Gone over - if(pos >= len){ - // Continue counter for next node - counter = len - (pos - this.break); - - // At End - } else { - // End the previous range - range.setEnd(node, pos); - cfi = chapter.cfiFromRange(range); - this._locations.push(cfi); - counter = 0; - - // Start new range - pos += 1; - range = doc.createRange(); - range.setStart(node, pos); - } - - } - - prev = node; - - }.bind(this)); - - // Close remaining - if (range) { - range.setEnd(prev, prev.length); - cfi = chapter.cfiFromRange(range); - this._locations.push(cfi); - counter = 0; - } - - }.bind(this)); - -}; - -EPUBJS.Locations.prototype.sprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false); - - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Locations.prototype.locationFromCfi = function(cfi){ - // Check if the location has not been set yet - if(this._locations.length === 0) { - return -1; - } - - return EPUBJS.core.locationOf(cfi, this._locations, this.epubcfi.compare); -}; - -EPUBJS.Locations.prototype.percentageFromCfi = function(cfi) { - // Find closest cfi - var loc = this.locationFromCfi(cfi); - // Get percentage in total - return this.percentageFromLocation(loc); -}; - -EPUBJS.Locations.prototype.percentageFromLocation = function(loc) { - if (!loc || !this.total) { - return 0; - } - return (loc / this.total); -}; - -EPUBJS.Locations.prototype.cfiFromLocation = function(loc){ - var cfi = -1; - // check that pg is an int - if(typeof loc != "number"){ - loc = parseInt(loc); - } - - if(loc >= 0 && loc < this._locations.length) { - cfi = this._locations[loc]; - } - - return cfi; -}; - -EPUBJS.Locations.prototype.cfiFromPercentage = function(value){ - var percentage = (value > 1) ? value / 100 : value; // Normalize value to 0-1 - var loc = Math.ceil(this.total * percentage); - - return this.cfiFromLocation(loc); -}; - -EPUBJS.Locations.prototype.load = function(locations){ - this._locations = JSON.parse(locations); - this.total = this._locations.length-1; - return this._locations; -}; - -EPUBJS.Locations.prototype.save = function(json){ - return JSON.stringify(this._locations); -}; - -EPUBJS.Locations.prototype.getCurrent = function(json){ - return this._current; -}; - -EPUBJS.Locations.prototype.setCurrent = function(curr){ - var loc; - - if(typeof curr == "string"){ - this._currentCfi = curr; - } else if (typeof curr == "number") { - this._current = curr; - } else { - return; - } - - if(this._locations.length === 0) { - return; - } - - if(typeof curr == "string"){ - loc = this.locationFromCfi(curr); - this._current = loc; - } else { - loc = curr; - } - - this.trigger("changed", { - percentage: this.percentageFromLocation(loc) - }); -}; - -Object.defineProperty(EPUBJS.Locations.prototype, 'currentLocation', { - get: function () { - return this._current; - }, - set: function (curr) { - this.setCurrent(curr); - } -}); - -RSVP.EventTarget.mixin(EPUBJS.Locations.prototype); - -EPUBJS.Pagination = function(pageList) { - this.pages = []; - this.locations = []; - this.epubcfi = new EPUBJS.EpubCFI(); - if(pageList && pageList.length) { - this.process(pageList); - } -}; - -EPUBJS.Pagination.prototype.process = function(pageList){ - pageList.forEach(function(item){ - this.pages.push(item.page); - this.locations.push(item.cfi); - }, this); - - this.pageList = pageList; - this.firstPage = parseInt(this.pages[0]); - this.lastPage = parseInt(this.pages[this.pages.length-1]); - this.totalPages = this.lastPage - this.firstPage; -}; - -EPUBJS.Pagination.prototype.pageFromCfi = function(cfi){ - var pg = -1; - - // Check if the pageList has not been set yet - if(this.locations.length === 0) { - return -1; - } - - // TODO: check if CFI is valid? - - // check if the cfi is in the location list - // var index = this.locations.indexOf(cfi); - var index = EPUBJS.core.indexOfSorted(cfi, this.locations, this.epubcfi.compare); - if(index != -1 && index < (this.pages.length-1) ) { - pg = this.pages[index]; - } else { - // Otherwise add it to the list of locations - // Insert it in the correct position in the locations page - //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare); - index = EPUBJS.core.locationOf(cfi, this.locations, this.epubcfi.compare); - // Get the page at the location just before the new one, or return the first - pg = index-1 >= 0 ? this.pages[index-1] : this.pages[0]; - if(pg !== undefined) { - // Add the new page in so that the locations and page array match up - //this.pages.splice(index, 0, pg); - } else { - pg = -1; - } - - } - return pg; -}; - -EPUBJS.Pagination.prototype.cfiFromPage = function(pg){ - var cfi = -1; - // check that pg is an int - if(typeof pg != "number"){ - pg = parseInt(pg); - } - - // check if the cfi is in the page list - // Pages could be unsorted. - var index = this.pages.indexOf(pg); - if(index != -1) { - cfi = this.locations[index]; - } - // TODO: handle pages not in the list - return cfi; -}; - -EPUBJS.Pagination.prototype.pageFromPercentage = function(percent){ - var pg = Math.round(this.totalPages * percent); - return pg; -}; - -// Returns a value between 0 - 1 corresponding to the location of a page -EPUBJS.Pagination.prototype.percentageFromPage = function(pg){ - var percentage = (pg - this.firstPage) / this.totalPages; - return Math.round(percentage * 1000) / 1000; -}; - -// Returns a value between 0 - 1 corresponding to the location of a cfi -EPUBJS.Pagination.prototype.percentageFromCfi = function(cfi){ - var pg = this.pageFromCfi(cfi); - var percentage = this.percentageFromPage(pg); - return percentage; -}; -EPUBJS.Parser = function(baseUrl){ - this.baseUrl = baseUrl || ''; -}; - -EPUBJS.Parser.prototype.container = function(containerXml){ - //-- - var rootfile, fullpath, folder, encoding; - - if(!containerXml) { - console.error("Container File Not Found"); - return; - } - - rootfile = containerXml.querySelector("rootfile"); - - if(!rootfile) { - console.error("No RootFile Found"); - return; - } - - fullpath = rootfile.getAttribute('full-path'); - folder = EPUBJS.core.uri(fullpath).directory; - encoding = containerXml.xmlEncoding; - - //-- Now that we have the path we can parse the contents - return { - 'packagePath' : fullpath, - 'basePath' : folder, - 'encoding' : encoding - }; -}; - -EPUBJS.Parser.prototype.identifier = function(packageXml){ - var metadataNode; - - if(!packageXml) { - console.error("Package File Not Found"); - return; - } - - metadataNode = packageXml.querySelector("metadata"); - - if(!metadataNode) { - console.error("No Metadata Found"); - return; - } - - return this.getElementText(metadataNode, "identifier"); -}; - -EPUBJS.Parser.prototype.packageContents = function(packageXml, baseUrl){ - var parse = this; - var metadataNode, manifestNode, spineNode; - var manifest, navPath, tocPath, coverPath; - var spineNodeIndex; - var spine; - var spineIndexByURL; - var metadata; - - if(baseUrl) this.baseUrl = baseUrl; - - if(!packageXml) { - console.error("Package File Not Found"); - return; - } - - metadataNode = packageXml.querySelector("metadata"); - if(!metadataNode) { - console.error("No Metadata Found"); - return; - } - - manifestNode = packageXml.querySelector("manifest"); - if(!manifestNode) { - console.error("No Manifest Found"); - return; - } - - spineNode = packageXml.querySelector("spine"); - if(!spineNode) { - console.error("No Spine Found"); - return; - } - - manifest = parse.manifest(manifestNode); - navPath = parse.findNavPath(manifestNode); - tocPath = parse.findTocPath(manifestNode, spineNode); - coverPath = parse.findCoverPath(packageXml); - - spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); - - spine = parse.spine(spineNode, manifest); - - spineIndexByURL = {}; - spine.forEach(function(item){ - spineIndexByURL[item.href] = item.index; - }); - - metadata = parse.metadata(metadataNode); - - metadata.direction = spineNode.getAttribute("page-progression-direction"); - - return { - 'metadata' : metadata, - 'spine' : spine, - 'manifest' : manifest, - 'navPath' : navPath, - 'tocPath' : tocPath, - 'coverPath': coverPath, - 'spineNodeIndex' : spineNodeIndex, - 'spineIndexByURL' : spineIndexByURL - }; -}; - -//-- Find TOC NAV -EPUBJS.Parser.prototype.findNavPath = function(manifestNode){ - // Find item with property 'nav' - // Should catch nav irregardless of order - var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); - return node ? node.getAttribute('href') : false; -}; - -//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" -EPUBJS.Parser.prototype.findTocPath = function(manifestNode, spineNode){ - var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); - var tocId; - - // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as - // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2, - // "The item that describes the NCX must be referenced by the spine toc attribute." - if (!node) { - tocId = spineNode.getAttribute("toc"); - if(tocId) { - node = manifestNode.querySelector("item[id='" + tocId + "']"); - } - } - - return node ? node.getAttribute('href') : false; -}; - -//-- Expanded to match Readium web components -EPUBJS.Parser.prototype.metadata = function(xml){ - var metadata = {}, - p = this; - - metadata.bookTitle = p.getElementText(xml, 'title'); - metadata.creator = p.getElementText(xml, 'creator'); - metadata.description = p.getElementText(xml, 'description'); - - metadata.pubdate = p.getElementText(xml, 'date'); - - metadata.publisher = p.getElementText(xml, 'publisher'); - - metadata.identifier = p.getElementText(xml, "identifier"); - metadata.language = p.getElementText(xml, "language"); - metadata.rights = p.getElementText(xml, "rights"); - - metadata.modified_date = p.querySelectorText(xml, "meta[property='dcterms:modified']"); - metadata.layout = p.querySelectorText(xml, "meta[property='rendition:layout']"); - metadata.orientation = p.querySelectorText(xml, "meta[property='rendition:orientation']"); - metadata.spread = p.querySelectorText(xml, "meta[property='rendition:spread']"); - - return metadata; -}; - -//-- Find Cover: -//-- Fallback for Epub 2.0 -EPUBJS.Parser.prototype.findCoverPath = function(packageXml){ - - var epubVersion = packageXml.querySelector('package').getAttribute('version'); - if (epubVersion === '2.0') { - var metaCover = packageXml.querySelector('meta[name="cover"]'); - if (metaCover) { - var coverId = metaCover.getAttribute('content'); - var cover = packageXml.querySelector("item[id='" + coverId + "']"); - return cover ? cover.getAttribute('href') : false; - } - else { - return false; - } - } - else { - var node = packageXml.querySelector("item[properties='cover-image']"); - return node ? node.getAttribute('href') : false; - } -}; - -EPUBJS.Parser.prototype.getElementText = function(xml, tag){ - var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), - el; - - if(!found || found.length === 0) return ''; - - el = found[0]; - - if(el.childNodes.length){ - return el.childNodes[0].nodeValue; - } - - return ''; - -}; - -EPUBJS.Parser.prototype.querySelectorText = function(xml, q){ - var el = xml.querySelector(q); - - if(el && el.childNodes.length){ - return el.childNodes[0].nodeValue; - } - - return ''; -}; - -EPUBJS.Parser.prototype.manifest = function(manifestXml){ - var baseUrl = this.baseUrl, - manifest = {}; - - //-- Turn items into an array - var selected = manifestXml.querySelectorAll("item"), - items = Array.prototype.slice.call(selected); - - //-- Create an object with the id as key - items.forEach(function(item){ - var id = item.getAttribute('id'), - href = item.getAttribute('href') || '', - type = item.getAttribute('media-type') || '', - properties = item.getAttribute('properties') || ''; - - manifest[id] = { - 'href' : href, - 'url' : baseUrl + href, //-- Absolute URL for loading with a web worker - 'type' : type, - 'properties' : properties - }; - - }); - - return manifest; - -}; - -EPUBJS.Parser.prototype.spine = function(spineXml, manifest){ - var spine = []; - - var selected = spineXml.getElementsByTagName("itemref"), - items = Array.prototype.slice.call(selected); - - var spineNodeIndex = Array.prototype.indexOf.call(spineXml.parentNode.childNodes, spineXml); - - var epubcfi = new EPUBJS.EpubCFI(); - - //-- Add to array to mantain ordering and cross reference with manifest - items.forEach(function(item, index){ - var Id = item.getAttribute('idref'); - var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); - var props = item.getAttribute('properties') || ''; - var propArray = props.length ? props.split(' ') : []; - var manifestProps = manifest[Id].properties; - var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : []; - var vert = { - 'id' : Id, - 'linear' : item.getAttribute('linear') || '', - 'properties' : propArray, - 'manifestProperties' : manifestPropArray, - 'href' : manifest[Id].href, - 'url' : manifest[Id].url, - 'index' : index, - 'cfiBase' : cfiBase, - 'cfi' : "epubcfi(" + cfiBase + ")" - }; - spine.push(vert); - }); - - return spine; -}; - -EPUBJS.Parser.prototype.querySelectorByType = function(html, element, type){ - var query = html.querySelector(element+'[*|type="'+type+'"]'); - // Handle IE not supporting namespaced epub:type in querySelector - if(query === null || query.length === 0) { - query = html.querySelectorAll(element); - for (var i = 0; i < query.length; i++) { - if(query[i].getAttributeNS("http://www.idpf.org/2007/ops", "type") === type) { - return query[i]; - } - } - } else { - return query; - } -}; - -EPUBJS.Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ - var navElement = this.querySelectorByType(navHtml, "nav", "toc"); - var navItems = navElement ? navElement.querySelectorAll("ol li") : []; - var length = navItems.length; - var i; - var toc = {}; - var list = []; - var item, parent; - - if(!navItems || length === 0) return list; - - for (i = 0; i < length; ++i) { - item = this.navItem(navItems[i], spineIndexByURL, bookSpine); - toc[item.id] = item; - if(!item.parent) { - list.push(item); - } else { - parent = toc[item.parent]; - parent.subitems.push(item); - } - } - - return list; -}; - -EPUBJS.Parser.prototype.navItem = function(item, spineIndexByURL, bookSpine){ - var id = item.getAttribute('id') || false, - content = item.querySelector("a, span"), - src = content.getAttribute('href') || '', - text = content.textContent || "", - split = src.split("#"), - baseUrl = split[0], - spinePos = spineIndexByURL[baseUrl], - spineItem = bookSpine[spinePos], - subitems = [], - parentNode = item.parentNode, - parent, - cfi = spineItem ? spineItem.cfi : ''; - - if(parentNode && parentNode.nodeName === "navPoint") { - parent = parentNode.getAttribute('id'); - } - - if(!id) { - if(spinePos) { - spineItem = bookSpine[spinePos]; - id = spineItem.id; - cfi = spineItem.cfi; - } else { - id = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid(); - item.setAttribute('id', id); - } - } - - return { - "id": id, - "href": src, - "label": text, - "spinePos": spinePos, - "subitems" : subitems, - "parent" : parent, - "cfi" : cfi - }; -}; - -EPUBJS.Parser.prototype.toc = function(tocXml, spineIndexByURL, bookSpine){ - var navPoints = tocXml.querySelectorAll("navMap navPoint"); - var length = navPoints.length; - var i; - var toc = {}; - var list = []; - var item, parent; - - if(!navPoints || length === 0) return list; - - for (i = 0; i < length; ++i) { - item = this.tocItem(navPoints[i], spineIndexByURL, bookSpine); - toc[item.id] = item; - if(!item.parent) { - list.push(item); - } else { - parent = toc[item.parent]; - parent.subitems.push(item); - } - } - - return list; -}; - -EPUBJS.Parser.prototype.tocItem = function(item, spineIndexByURL, bookSpine){ - var id = item.getAttribute('id') || false, - content = item.querySelector("content"), - src = content.getAttribute('src'), - navLabel = item.querySelector("navLabel"), - text = navLabel.textContent ? navLabel.textContent : "", - split = src.split("#"), - baseUrl = split[0], - spinePos = spineIndexByURL[baseUrl], - spineItem = bookSpine[spinePos], - subitems = [], - parentNode = item.parentNode, - parent, - cfi = spineItem ? spineItem.cfi : ''; - - if(parentNode && parentNode.nodeName === "navPoint") { - parent = parentNode.getAttribute('id'); - } - - if(!id) { - if(spinePos) { - spineItem = bookSpine[spinePos]; - id = spineItem.id; - cfi = spineItem.cfi; - } else { - id = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid(); - item.setAttribute('id', id); - } - } - - return { - "id": id, - "href": src, - "label": text, - "spinePos": spinePos, - "subitems" : subitems, - "parent" : parent, - "cfi" : cfi - }; -}; - - -EPUBJS.Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ - var navElement = this.querySelectorByType(navHtml, "nav", "page-list"); - var navItems = navElement ? navElement.querySelectorAll("ol li") : []; - var length = navItems.length; - var i; - var toc = {}; - var list = []; - var item; - - if(!navItems || length === 0) return list; - - for (i = 0; i < length; ++i) { - item = this.pageListItem(navItems[i], spineIndexByURL, bookSpine); - list.push(item); - } - - return list; -}; - -EPUBJS.Parser.prototype.pageListItem = function(item, spineIndexByURL, bookSpine){ - var id = item.getAttribute('id') || false, - content = item.querySelector("a"), - href = content.getAttribute('href') || '', - text = content.textContent || "", - page = parseInt(text), - isCfi = href.indexOf("epubcfi"), - split, - packageUrl, - cfi; - - if(isCfi != -1) { - split = href.split("#"); - packageUrl = split[0]; - cfi = split.length > 1 ? split[1] : false; - return { - "cfi" : cfi, - "href" : href, - "packageUrl" : packageUrl, - "page" : page - }; - } else { - return { - "href" : href, - "page" : page - }; - } -}; - -EPUBJS.Render.Iframe = function() { - this.iframe = null; - this.document = null; - this.window = null; - this.docEl = null; - this.bodyEl = null; - - this.leftPos = 0; - this.pageWidth = 0; -}; - -//-- Build up any html needed -EPUBJS.Render.Iframe.prototype.create = function(){ - this.iframe = document.createElement('iframe'); - this.iframe.id = "epubjs-iframe:" + EPUBJS.core.uuid(); - this.iframe.scrolling = "no"; - this.iframe.seamless = "seamless"; - // Back up if seamless isn't supported - this.iframe.style.border = "none"; - - this.iframe.addEventListener("load", this.loaded.bind(this), false); - - this.isMobile = navigator.userAgent.match(/(iPad|iPhone|iPod|Mobile|Android)/g); - this.transform = EPUBJS.core.prefixed('transform'); - - return this.iframe; -}; - -/** -* Sets the source of the iframe with the given URL string -* Takes: Document Contents String -* Returns: promise with document element -*/ -EPUBJS.Render.Iframe.prototype.load = function(contents, url){ - var render = this, - deferred = new RSVP.defer(); - - if(this.window) { - this.unload(); - } - - this.iframe.onload = function(e) { - var title; - - render.document = render.iframe.contentDocument; - render.docEl = render.document.documentElement; - render.headEl = render.document.head; - render.bodyEl = render.document.body || render.document.querySelector("body"); - render.window = render.iframe.contentWindow; - - render.window.addEventListener("resize", render.resized.bind(render), false); - - // Reset the scroll position - render.leftPos = 0; - render.setLeft(0); - - //-- Clear Margins - if(render.bodyEl) { - render.bodyEl.style.margin = "0"; - } - - // HTML element must have direction set if RTL or columnns will - // not be in the correct direction in Firefox - // Firefox also need the html element to be position right - if(render.direction == "rtl" && render.docEl.dir != "rtl"){ - render.docEl.dir = "rtl"; - render.docEl.style.position = "absolute"; - render.docEl.style.right = "0"; - } - - deferred.resolve(render.docEl); - }; - - this.iframe.onerror = function(e) { - //console.error("Error Loading Contents", e); - deferred.reject({ - message : "Error Loading Contents: " + e, - stack : new Error().stack - }); - }; - - // this.iframe.contentWindow.location.replace(url); - this.document = this.iframe.contentDocument; - - if(!this.document) { - deferred.reject(new Error("No Document Available")); - return deferred; - } - - this.document.open(); - this.document.write(contents); - this.document.close(); - - return deferred.promise; -}; - - -EPUBJS.Render.Iframe.prototype.loaded = function(v){ - var url = this.iframe.contentWindow.location.href; - var baseEl, base; - - this.document = this.iframe.contentDocument; - this.docEl = this.document.documentElement; - this.headEl = this.document.head; - this.bodyEl = this.document.body || this.document.querySelector("body"); - this.window = this.iframe.contentWindow; - - if(url != "about:blank"){ - baseEl = this.iframe.contentDocument.querySelector("base"); - base = baseEl.getAttribute('href'); - this.trigger("render:loaded", base); - } -}; - -// Resize the iframe to the given width and height -EPUBJS.Render.Iframe.prototype.resize = function(width, height){ - var iframeBox; - - if(!this.iframe) return; - - this.iframe.height = height; - - if(!isNaN(width) && width % 2 !== 0){ - width += 1; //-- Prevent cutting off edges of text in columns - } - - this.iframe.width = width; - // Get the fractional height and width of the iframe - // Default to orginal if bounding rect is 0 - this.width = this.iframe.getBoundingClientRect().width || width; - this.height = this.iframe.getBoundingClientRect().height || height; -}; - - -EPUBJS.Render.Iframe.prototype.resized = function(e){ - // Get the fractional height and width of the iframe - this.width = this.iframe.getBoundingClientRect().width; - this.height = this.iframe.getBoundingClientRect().height; -}; - -EPUBJS.Render.Iframe.prototype.totalWidth = function(){ - return this.docEl.scrollWidth; -}; - -EPUBJS.Render.Iframe.prototype.totalHeight = function(){ - return this.docEl.scrollHeight; -}; - -EPUBJS.Render.Iframe.prototype.setPageDimensions = function(pageWidth, pageHeight){ - this.pageWidth = pageWidth; - this.pageHeight = pageHeight; - //-- Add a page to the width of the document to account an for odd number of pages - // this.docEl.style.width = this.docEl.scrollWidth + pageWidth + "px"; -}; - -EPUBJS.Render.Iframe.prototype.setDirection = function(direction){ - - this.direction = direction; - - // Undo previous changes if needed - if(this.docEl && this.docEl.dir == "rtl"){ - this.docEl.dir = "rtl"; - this.docEl.style.position = "static"; - this.docEl.style.right = "auto"; - } - -}; - -EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){ - // this.bodyEl.style.marginLeft = -leftPos + "px"; - // this.docEl.style.marginLeft = -leftPos + "px"; - // this.docEl.style[EPUBJS.Render.Iframe.transform] = 'translate('+ (-leftPos) + 'px, 0)'; - - if (this.isMobile) { - this.docEl.style[this.transform] = 'translate('+ (-leftPos) + 'px, 0)'; - } else { - this.document.defaultView.scrollTo(leftPos, 0); - } - -}; - -EPUBJS.Render.Iframe.prototype.setStyle = function(style, val, prefixed){ - if(prefixed) { - style = EPUBJS.core.prefixed(style); - } - - if(this.bodyEl) this.bodyEl.style[style] = val; -}; - -EPUBJS.Render.Iframe.prototype.removeStyle = function(style){ - - if(this.bodyEl) this.bodyEl.style[style] = ''; - -}; - -EPUBJS.Render.Iframe.prototype.addHeadTag = function(tag, attrs, _doc) { - var doc = _doc || this.document; - var tagEl = doc.createElement(tag); - var headEl = doc.head; - - for(var attr in attrs) { - tagEl.setAttribute(attr, attrs[attr]); - } - - if(headEl) headEl.insertBefore(tagEl, headEl.firstChild); -}; - -EPUBJS.Render.Iframe.prototype.page = function(pg){ - this.leftPos = this.pageWidth * (pg-1); //-- pages start at 1 - - // Reverse for rtl langs - if(this.direction === "rtl"){ - this.leftPos = this.leftPos * -1; - } - - this.setLeft(this.leftPos); -}; - -//-- Show the page containing an Element -EPUBJS.Render.Iframe.prototype.getPageNumberByElement = function(el){ - var left, pg; - if(!el) return; - - left = this.leftPos + el.getBoundingClientRect().left; //-- Calculate left offset compaired to scrolled position - - pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 - - return pg; -}; - -//-- Show the page containing an Element -EPUBJS.Render.Iframe.prototype.getPageNumberByRect = function(boundingClientRect){ - var left, pg; - - left = this.leftPos + boundingClientRect.left; //-- Calculate left offset compaired to scrolled position - pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 - - return pg; -}; - -// Return the root element of the content -EPUBJS.Render.Iframe.prototype.getBaseElement = function(){ - return this.bodyEl; -}; - -// Return the document element -EPUBJS.Render.Iframe.prototype.getDocumentElement = function(){ - return this.docEl; -}; - -// Checks if an element is on the screen -EPUBJS.Render.Iframe.prototype.isElementVisible = function(el){ - var rect; - var left; - - if(el && typeof el.getBoundingClientRect === 'function'){ - rect = el.getBoundingClientRect(); - left = rect.left; //+ rect.width; - if( rect.width !== 0 && - rect.height !== 0 && // Element not visible - left >= 0 && - left < this.pageWidth ) { - return true; - } - } - - return false; -}; - - -EPUBJS.Render.Iframe.prototype.scroll = function(bool){ - if(bool) { - this.iframe.scrolling = "yes"; - } else { - this.iframe.scrolling = "no"; - } -}; - -// Cleanup event listeners -EPUBJS.Render.Iframe.prototype.unload = function(){ - this.window.removeEventListener("resize", this.resized); - this.window.location.reload(); -}; - -//-- Enable binding events to Render -RSVP.EventTarget.mixin(EPUBJS.Render.Iframe.prototype); - -EPUBJS.Renderer = function(renderMethod, hidden) { - // Dom events to listen for - this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click"]; - this.upEvent = "mouseup"; - this.downEvent = "mousedown"; - if('ontouchstart' in document.documentElement) { - this.listenedEvents.push("touchstart", "touchend"); - this.upEvent = "touchend"; - this.downEvent = "touchstart"; - } - /** - * Setup a render method. - * Options are: Iframe - */ - if(renderMethod && typeof(EPUBJS.Render[renderMethod]) != "undefined"){ - this.render = new EPUBJS.Render[renderMethod](); - } else { - console.error("Not a Valid Rendering Method"); - } - - // Listen for load events - this.render.on("render:loaded", this.loaded.bind(this)); - - // Cached for replacement urls from storage - this.caches = {}; - - // Blank Cfi for Parsing - this.epubcfi = new EPUBJS.EpubCFI(); - - this.spreads = true; - this.isForcedSingle = false; - this.resized = this.onResized.bind(this); - - this.layoutSettings = {}; - - this.hidden = hidden || false; - //-- Adds Hook methods to the Book prototype - // Hooks will all return before triggering the callback. - EPUBJS.Hooks.mixin(this); - //-- Get pre-registered hooks for events - this.getHooks("beforeChapterDisplay"); - - //-- Queue up page changes if page map isn't ready - this._q = EPUBJS.core.queue(this); - - this._moving = false; - -}; - -//-- Renderer events for listening -EPUBJS.Renderer.prototype.Events = [ - "renderer:keydown", - "renderer:keyup", - "renderer:keypressed", - "renderer:mouseup", - "renderer:mousedown", - "renderer:click", - "renderer:touchstart", - "renderer:touchend", - "renderer:selected", - "renderer:chapterUnloaded", - "renderer:chapterDisplayed", - "renderer:locationChanged", - "renderer:visibleLocationChanged", - "renderer:resized", - "renderer:spreads" -]; - -/** -* Creates an element to render to. -* Resizes to passed width and height or to the elements size -*/ -EPUBJS.Renderer.prototype.initialize = function(element, width, height){ - this.container = element; - this.element = this.render.create(); - - this.initWidth = width; - this.initHeight = height; - - this.width = width || this.container.clientWidth; - this.height = height || this.container.clientHeight; - - this.container.appendChild(this.element); - - if(width && height){ - this.render.resize(this.width, this.height); - } else { - this.render.resize('100%', '100%'); - } - - document.addEventListener("orientationchange", this.onResized); -}; - -/** -* Display a chapter -* Takes: chapter object, global layout settings -* Returns: Promise with passed Renderer after pages has loaded -*/ -EPUBJS.Renderer.prototype.displayChapter = function(chapter, globalLayout){ - var store = false; - if(this._moving) { - console.error("Rendering In Progress"); - return; - } - this._moving = true; - // Get the url string from the chapter (may be from storage) - return chapter.render(). - then(function(contents) { - - // Unload the previous chapter listener - if(this.currentChapter) { - this.currentChapter.unload(); // Remove stored blobs - - if(this.render.window){ - this.render.window.removeEventListener("resize", this.resized); - } - - this.removeEventListeners(); - this.removeSelectionListeners(); - this.trigger("renderer:chapterUnloaded"); - this.contents = null; - this.doc = null; - this.pageMap = null; - } - - this.currentChapter = chapter; - - this.chapterPos = 1; - - this.currentChapterCfiBase = chapter.cfiBase; - - this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties); - - return this.load(contents, chapter.href); - - }.bind(this)); - -}; - -/** -* Loads a url (string) and renders it, -* attaching event listeners and triggering hooks. -* Returns: Promise with the rendered contents. -*/ - -EPUBJS.Renderer.prototype.load = function(contents, url){ - var deferred = new RSVP.defer(); - var loaded; - - // Switch to the required layout method for the settings - this.layoutMethod = this.determineLayout(this.layoutSettings); - this.layout = new EPUBJS.Layout[this.layoutMethod](); - - this.visible(false); - - render = this.render.load(contents, url); - - render.then(function(contents) { - - this.afterLoad(contents); - - //-- Trigger registered hooks before displaying - this.beforeDisplay(function(){ - - this.afterDisplay(); - - this.visible(true); - - - deferred.resolve(this); //-- why does this return the renderer? - - }.bind(this)); - - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Renderer.prototype.afterLoad = function(contents) { - var formated; - this.currentChapter.setDocument(this.render.document); - this.contents = contents; - this.doc = this.render.document; - - // Format the contents using the current layout method - this.formated = this.layout.format(contents, this.render.width, this.render.height, this.gap); - this.render.setPageDimensions(this.formated.pageWidth, this.formated.pageHeight); - - // window.addEventListener("orientationchange", this.onResized.bind(this), false); - if(!this.initWidth && !this.initHeight){ - this.render.window.addEventListener("resize", this.resized, false); - } - - this.addEventListeners(); - this.addSelectionListeners(); - -}; - -EPUBJS.Renderer.prototype.afterDisplay = function(contents) { - - var pages = this.layout.calculatePages(); - var msg = this.currentChapter; - var queued = this._q.length(); - this._moving = false; - - this.updatePages(pages); - - this.visibleRangeCfi = this.getVisibleRangeCfi(); - this.currentLocationCfi = this.visibleRangeCfi.start; - - if(queued === 0) { - this.trigger("renderer:locationChanged", this.currentLocationCfi); - this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); - } - - msg.cfi = this.currentLocationCfi; //TODO: why is this cfi passed to chapterDisplayed - this.trigger("renderer:chapterDisplayed", msg); - -}; - -EPUBJS.Renderer.prototype.loaded = function(url){ - this.trigger("render:loaded", url); - // var uri = EPUBJS.core.uri(url); - // var relative = uri.path.replace(book.bookUrl, ''); - // console.log(url, uri, relative); -}; - -/** -* Reconciles the current chapters layout properies with -* the global layout properities. -* Takes: global layout settings object, chapter properties string -* Returns: Object with layout properties -*/ -EPUBJS.Renderer.prototype.reconcileLayoutSettings = function(global, chapter){ - var settings = {}; - - //-- Get the global defaults - for (var attr in global) { - if (global.hasOwnProperty(attr)){ - settings[attr] = global[attr]; - } - } - //-- Get the chapter's display type - chapter.forEach(function(prop){ - var rendition = prop.replace("rendition:", ''); - var split = rendition.indexOf("-"); - var property, value; - - if(split != -1){ - property = rendition.slice(0, split); - value = rendition.slice(split+1); - - settings[property] = value; - } - }); - return settings; -}; - -/** -* Uses the settings to determine which Layout Method is needed -* Triggers events based on the method choosen -* Takes: Layout settings object -* Returns: String of appropriate for EPUBJS.Layout function -*/ -EPUBJS.Renderer.prototype.determineLayout = function(settings){ - // Default is layout: reflowable & spread: auto - var spreads = this.determineSpreads(this.minSpreadWidth); - var layoutMethod = spreads ? "ReflowableSpreads" : "Reflowable"; - var scroll = false; - - if(settings.layout === "pre-paginated") { - layoutMethod = "Fixed"; - scroll = true; - spreads = false; - } - - if(settings.layout === "reflowable" && settings.spread === "none") { - layoutMethod = "Reflowable"; - scroll = false; - spreads = false; - } - - if(settings.layout === "reflowable" && settings.spread === "both") { - layoutMethod = "ReflowableSpreads"; - scroll = false; - spreads = true; - } - - this.spreads = spreads; - this.render.scroll(scroll); - this.trigger("renderer:spreads", spreads); - return layoutMethod; -}; - -// Shortcut to trigger the hook before displaying the chapter -EPUBJS.Renderer.prototype.beforeDisplay = function(callback, renderer){ - this.triggerHooks("beforeChapterDisplay", callback, this); -}; - -// Update the renderer with the information passed by the layout -EPUBJS.Renderer.prototype.updatePages = function(layout){ - this.pageMap = this.mapPage(); - // this.displayedPages = layout.displayedPages; - - if (this.spreads) { - this.displayedPages = Math.ceil(this.pageMap.length / 2); - } else { - this.displayedPages = this.pageMap.length; - } - - this.currentChapter.pages = this.pageMap.length; - - this._q.flush(); -}; - -// Apply the layout again and jump back to the previous cfi position -EPUBJS.Renderer.prototype.reformat = function(){ - var renderer = this; - var formated, pages; - if(!this.contents) return; - - spreads = this.determineSpreads(this.minSpreadWidth); - - // Only re-layout if the spreads have switched - if(spreads != this.spreads){ - this.spreads = spreads; - this.layoutMethod = this.determineLayout(this.layoutSettings); - this.layout = new EPUBJS.Layout[this.layoutMethod](); - } - - // Reset pages - this.chapterPos = 1; - - this.render.page(this.chapterPos); - // Give the css styles time to update - // clearTimeout(this.timeoutTillCfi); - // this.timeoutTillCfi = setTimeout(function(){ - renderer.formated = renderer.layout.format(renderer.render.docEl, renderer.render.width, renderer.render.height, renderer.gap); - renderer.render.setPageDimensions(renderer.formated.pageWidth, renderer.formated.pageHeight); - - pages = renderer.layout.calculatePages(); - renderer.updatePages(pages); - - //-- Go to current page after formating - if(renderer.currentLocationCfi){ - renderer.gotoCfi(renderer.currentLocationCfi); - } - // renderer.timeoutTillCfi = null; - -}; - -// Hide and show the render's container . -EPUBJS.Renderer.prototype.visible = function(bool){ - if(typeof(bool) === "undefined") { - return this.element.style.visibility; - } - - if(bool === true && !this.hidden){ - this.element.style.visibility = "visible"; - }else if(bool === false){ - this.element.style.visibility = "hidden"; - } -}; - -// Remove the render element and clean up listeners -EPUBJS.Renderer.prototype.remove = function() { - if(this.render.window) { - this.render.unload(); - this.render.window.removeEventListener("resize", this.resized); - this.removeEventListeners(); - this.removeSelectionListeners(); - } - - this.container.removeChild(this.element); -}; - -//-- STYLES - -EPUBJS.Renderer.prototype.applyStyles = function(styles) { - for (var style in styles) { - this.render.setStyle(style, styles[style]); - } -}; - -EPUBJS.Renderer.prototype.setStyle = function(style, val, prefixed){ - this.render.setStyle(style, val, prefixed); -}; - -EPUBJS.Renderer.prototype.removeStyle = function(style){ - this.render.removeStyle(style); -}; - -//-- HEAD TAGS -EPUBJS.Renderer.prototype.applyHeadTags = function(headTags) { - for ( var headTag in headTags ) { - this.render.addHeadTag(headTag, headTags[headTag]); - } -}; - -//-- NAVIGATION - -EPUBJS.Renderer.prototype.page = function(pg){ - if(!this.pageMap) { - console.warn("pageMap not set, queuing"); - this._q.enqueue("page", arguments); - return true; - } - - if(pg >= 1 && pg <= this.displayedPages){ - this.chapterPos = pg; - - this.render.page(pg); - this.visibleRangeCfi = this.getVisibleRangeCfi(); - this.currentLocationCfi = this.visibleRangeCfi.start; - this.trigger("renderer:locationChanged", this.currentLocationCfi); - this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); - - return true; - } - //-- Return false if page is greater than the total - return false; -}; - -// Short cut to find next page's cfi starting at the last visible element -/* -EPUBJS.Renderer.prototype.nextPage = function(){ - var pg = this.chapterPos + 1; - if(pg <= this.displayedPages){ - this.chapterPos = pg; - - this.render.page(pg); - - this.currentLocationCfi = this.getPageCfi(this.visibileEl); - this.trigger("renderer:locationChanged", this.currentLocationCfi); - - return true; - } - //-- Return false if page is greater than the total - return false; -}; -*/ -EPUBJS.Renderer.prototype.nextPage = function(){ - return this.page(this.chapterPos + 1); -}; - -EPUBJS.Renderer.prototype.prevPage = function(){ - return this.page(this.chapterPos - 1); -}; - -//-- Show the page containing an Element -EPUBJS.Renderer.prototype.pageByElement = function(el){ - var pg; - if(!el) return; - - pg = this.render.getPageNumberByElement(el); - this.page(pg); -}; - -// Jump to the last page of the chapter -EPUBJS.Renderer.prototype.lastPage = function(){ - if(this._moving) { - return this._q.enqueue("lastPage", arguments); - } - - this.page(this.displayedPages); -}; - -// Jump to the first page of the chapter -EPUBJS.Renderer.prototype.firstPage = function(){ - if(this._moving) { - return this._q.enqueue("firstPage", arguments); - } - - this.page(1); -}; - -//-- Find a section by fragement id -EPUBJS.Renderer.prototype.section = function(fragment){ - var el = this.doc.getElementById(fragment), - left, pg; - - if(el){ - this.pageByElement(el); - } - -}; - -EPUBJS.Renderer.prototype.firstElementisTextNode = function(node) { - var children = node.childNodes; - var leng = children.length; - - if(leng && - children[0] && // First Child - children[0].nodeType === 3 && // This is a textNodes - children[0].textContent.trim().length) { // With non whitespace or return charecters - return true; - } - return false; -}; - -EPUBJS.Renderer.prototype.isGoodNode = function(node) { - var embeddedElements = ["audio", "canvas", "embed", "iframe", "img", "math", "object", "svg", "video"]; - if (embeddedElements.indexOf(node.tagName.toLowerCase()) !== -1) { - // Embedded elements usually do not have a text node as first element, but are also good nodes - return true; - } - return this.firstElementisTextNode(node); -}; - -// Walk the node tree from a start element to next visible element -EPUBJS.Renderer.prototype.walk = function(node, x, y) { - var r, children, leng, - startNode = node, - prevNode, - stack = [startNode]; - - var STOP = 10000, ITER=0; - - while(!r && stack.length) { - node = stack.shift(); - if( this.containsPoint(node, x, y) && this.isGoodNode(node)) { - r = node; - } - - if(!r && node && node.childElementCount > 0){ - children = node.children; - if (children && children.length) { - leng = children.length ? children.length : 0; - } else { - return r; - } - for (var i = leng-1; i >= 0; i--) { - if(children[i] != prevNode) stack.unshift(children[i]); - } - } - - if(!r && stack.length === 0 && startNode && startNode.parentNode !== null){ - stack.push(startNode.parentNode); - prevNode = startNode; - startNode = startNode.parentNode; - } - - - ITER++; - if(ITER > STOP) { - console.error("ENDLESS LOOP"); - break; - } - - } - - return r; -}; - -// Checks if an element is on the screen -EPUBJS.Renderer.prototype.containsPoint = function(el, x, y){ - var rect; - var left; - if(el && typeof el.getBoundingClientRect === 'function'){ - rect = el.getBoundingClientRect(); - // console.log(el, rect, x, y); - - if( rect.width !== 0 && - rect.height !== 0 && // Element not visible - rect.left >= x && - x <= rect.left + rect.width) { - return true; - } - } - - return false; -}; - -EPUBJS.Renderer.prototype.textSprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: function (node) { - if ( ! /^\s*$/.test(node.data) ) { - return NodeFilter.FILTER_ACCEPT; - } else { - return NodeFilter.FILTER_REJECT; - } - } - }, false); - var node; - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Renderer.prototype.sprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null, false); - var node; - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Renderer.prototype.mapPage = function(){ - var renderer = this; - var map = []; - var root = this.render.getBaseElement(); - var page = 1; - var width = this.layout.colWidth + this.layout.gap; - var offset = this.formated.pageWidth * (this.chapterPos-1); - var limit = (width * page) - offset;// (width * page) - offset; - var elLimit = 0; - var prevRange; - var cfi; - var lastChildren = null; - var prevElement; - var startRange, endRange; - var startCfi, endCfi; - var check = function(node) { - var elPos; - var elRange; - var found; - if (node.nodeType == Node.TEXT_NODE) { - - elRange = document.createRange(); - elRange.selectNodeContents(node); - elPos = elRange.getBoundingClientRect(); - - if(!elPos || (elPos.width === 0 && elPos.height === 0)) { - return; - } - - //-- Element starts new Col - if(elPos.left > elLimit) { - found = checkText(node); - } - - //-- Element Spans new Col - if(elPos.right > elLimit) { - found = checkText(node); - } - - prevElement = node; - - if (found) { - prevRange = null; - } - } - - }; - var checkText = function(node){ - var result; - var ranges = renderer.splitTextNodeIntoWordsRanges(node); - var prevRanges; - ranges.forEach(function(range){ - var pos = range.getBoundingClientRect(); - - if(!pos || (pos.width === 0 && pos.height === 0)) { - return; - } - if(pos.left + pos.width < limit) { - if(!map[page-1]){ - range.collapse(true); - cfi = renderer.currentChapter.cfiFromRange(range); - // map[page-1].start = cfi; - result = map.push({ start: cfi, end: null }); - } - } else { - // Previous Range is null since we already found our last map pair - // Use that last walked textNode - if(!prevRange && prevElement) { - prevRanges = renderer.splitTextNodeIntoWordsRanges(prevElement); - prevRange = prevRanges[prevRanges.length-1]; - } - - if(prevRange){ - prevRange.collapse(false); - cfi = renderer.currentChapter.cfiFromRange(prevRange); - map[map.length-1].end = cfi; - } - - range.collapse(true); - cfi = renderer.currentChapter.cfiFromRange(range); - result = map.push({ - start: cfi, - end: null - }); - - page += 1; - limit = (width * page) - offset; - elLimit = limit; - } - - prevRange = range; - }); - - return result; - }; - var docEl = this.render.getDocumentElement(); - var dir = docEl.dir; - - // Set back to ltr before sprinting to get correct order - if(dir == "rtl") { - docEl.dir = "ltr"; - docEl.style.position = "static"; - } - - this.textSprint(root, check); - - // Reset back to previous RTL settings - if(dir == "rtl") { - docEl.dir = dir; - docEl.style.left = "auto"; - docEl.style.right = "0"; - } - - // Check the remaining children that fit on this page - // to ensure the end is correctly calculated - if(!prevRange && prevElement) { - prevRanges = renderer.splitTextNodeIntoWordsRanges(prevElement); - prevRange = prevRanges[prevRanges.length-1]; - } - - if(prevRange){ - prevRange.collapse(false); - cfi = renderer.currentChapter.cfiFromRange(prevRange); - map[map.length-1].end = cfi; - } - - // Handle empty map - if(!map.length) { - startRange = this.doc.createRange(); - startRange.selectNodeContents(root); - startRange.collapse(true); - startCfi = renderer.currentChapter.cfiFromRange(startRange); - - endRange = this.doc.createRange(); - endRange.selectNodeContents(root); - endRange.collapse(false); - endCfi = renderer.currentChapter.cfiFromRange(endRange); - - - map.push({ start: startCfi, end: endCfi }); - - } - - // clean up - prevRange = null; - prevRanges = null; - ranges = null; - startRange = null; - endRange = null; - root = null; - - return map; -}; - - -EPUBJS.Renderer.prototype.indexOfBreakableChar = function (text, startPosition) { - var whiteCharacters = "\x2D\x20\t\r\n\b\f"; - // '-' \x2D - // ' ' \x20 - - if (! startPosition) { - startPosition = 0; - } - - for (var i = startPosition; i < text.length; i++) { - if (whiteCharacters.indexOf(text.charAt(i)) != -1) { - return i; - } - } - - return -1; -}; - - -EPUBJS.Renderer.prototype.splitTextNodeIntoWordsRanges = function(node){ - var ranges = []; - var text = node.textContent.trim(); - var range; - var rect; - var list; - - // Usage of indexOf() function for space character as word delimiter - // is not sufficient in case of other breakable characters like \r\n- etc - pos = this.indexOfBreakableChar(text); - - if(pos === -1) { - range = this.doc.createRange(); - range.selectNodeContents(node); - return [range]; - } - - range = this.doc.createRange(); - range.setStart(node, 0); - range.setEnd(node, pos); - ranges.push(range); - - // there was a word miss in case of one letter words - range = this.doc.createRange(); - range.setStart(node, pos+1); - - while ( pos != -1 ) { - - pos = this.indexOfBreakableChar(text, pos + 1); - if(pos > 0) { - - if(range) { - range.setEnd(node, pos); - ranges.push(range); - } - - range = this.doc.createRange(); - range.setStart(node, pos+1); - } - } - - if(range) { - range.setEnd(node, text.length); - ranges.push(range); - } - - return ranges; -}; - -EPUBJS.Renderer.prototype.rangePosition = function(range){ - var rect; - var list; - - list = range.getClientRects(); - - if(list.length) { - rect = list[0]; - return rect; - } - - return null; -}; - -/* -// Get the cfi of the current page -EPUBJS.Renderer.prototype.getPageCfi = function(prevEl){ - var range = this.doc.createRange(); - var position; - // TODO : this might need to take margin / padding into account? - var x = 1;//this.formated.pageWidth/2; - var y = 1;//;this.formated.pageHeight/2; - - range = this.getRange(x, y); - - // var test = this.doc.defaultView.getSelection(); - // var r = this.doc.createRange(); - // test.removeAllRanges(); - // r.setStart(range.startContainer, range.startOffset); - // r.setEnd(range.startContainer, range.startOffset + 1); - // test.addRange(r); - - return this.currentChapter.cfiFromRange(range); -}; -*/ - -// Get the cfi of the current page -EPUBJS.Renderer.prototype.getPageCfi = function(){ - var pg = (this.chapterPos * 2)-1; - return this.pageMap[pg].start; -}; - -EPUBJS.Renderer.prototype.getRange = function(x, y, forceElement){ - var range = this.doc.createRange(); - var position; - forceElement = true; // temp override - if(typeof document.caretPositionFromPoint !== "undefined" && !forceElement){ - position = this.doc.caretPositionFromPoint(x, y); - range.setStart(position.offsetNode, position.offset); - } else if(typeof document.caretRangeFromPoint !== "undefined" && !forceElement){ - range = this.doc.caretRangeFromPoint(x, y); - } else { - this.visibileEl = this.findElementAfter(x, y); - range.setStart(this.visibileEl, 1); - } - - // var test = this.doc.defaultView.getSelection(); - // var r = this.doc.createRange(); - // test.removeAllRanges(); - // r.setStart(range.startContainer, range.startOffset); - // r.setEnd(range.startContainer, range.startOffset + 1); - // test.addRange(r); - return range; -}; - -/* -EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(prevEl){ - var startX = 0; - var startY = 0; - var endX = this.width-1; - var endY = this.height-1; - var startRange = this.getRange(startX, startY); - var endRange = this.getRange(endX, endY); //fix if carret not avail - var startCfi = this.currentChapter.cfiFromRange(startRange); - var endCfi; - if(endRange) { - endCfi = this.currentChapter.cfiFromRange(endRange); - } - - return { - start: startCfi, - end: endCfi || false - }; -}; -*/ - -EPUBJS.Renderer.prototype.pagesInCurrentChapter = function() { - var pgs; - var length; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - length = this.pageMap.length; - - if(this.spreads){ - pgs = Math.ceil(length / 2); - } else { - pgs = length; - } - - return pgs; -}; - -EPUBJS.Renderer.prototype.currentRenderedPage = function(){ - var pg; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - if (this.spreads && this.pageMap.length > 1) { - pg = this.chapterPos*2; - } else { - pg = this.chapterPos; - } - - return pg; -}; - -EPUBJS.Renderer.prototype.getRenderedPagesLeft = function(){ - var pg; - var lastPage; - var pagesLeft; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - lastPage = this.pageMap.length; - - if (this.spreads) { - pg = this.chapterPos*2; - } else { - pg = this.chapterPos; - } - - pagesLeft = lastPage - pg; - return pagesLeft; - -}; - -EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(){ - var pg; - var startRange, endRange; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - if (this.spreads) { - pg = this.chapterPos*2; - startRange = this.pageMap[pg-2]; - endRange = startRange; - - if(this.pageMap.length > 1) { - endRange = this.pageMap[pg-1]; - } - } else { - pg = this.chapterPos; - startRange = this.pageMap[pg-1]; - endRange = startRange; - } - - if(!startRange) { - console.warn("page range miss:", pg, this.pageMap); - startRange = this.pageMap[this.pageMap.length-1]; - endRange = startRange; - } - - return { - start: startRange.start, - end: endRange.end - }; -}; - -// Goto a cfi position in the current chapter -EPUBJS.Renderer.prototype.gotoCfi = function(cfi){ - var pg; - var marker; - var range; - - if(this._moving){ - return this._q.enqueue("gotoCfi", arguments); - } - - if(EPUBJS.core.isString(cfi)){ - cfi = this.epubcfi.parse(cfi); - } - - if(typeof document.evaluate === 'undefined') { - marker = this.epubcfi.addMarker(cfi, this.doc); - if(marker) { - pg = this.render.getPageNumberByElement(marker); - // Must Clean up Marker before going to page - this.epubcfi.removeMarker(marker, this.doc); - this.page(pg); - } - } else { - range = this.epubcfi.generateRangeFromCfi(cfi, this.doc); - if(range) { - // jaroslaw.bielski@7bulls.com - // It seems that sometimes getBoundingClientRect() returns null for first page CFI in chapter. - // It is always reproductible if few consecutive chapters have only one page. - // NOTE: This is only workaround and the issue needs an deeper investigation. - // NOTE: Observed on Android 4.2.1 using WebView widget as HTML renderer (Asus TF300T). - var rect = range.getBoundingClientRect(); - if (rect) { - pg = this.render.getPageNumberByRect(rect); - - } else { - // Goto first page in chapter - pg = 1; - } - - this.page(pg); - - // Reset the current location cfi to requested cfi - this.currentLocationCfi = cfi.str; - } else { - // Failed to find a range, go to first page - this.page(1); - } - } -}; - -// Walk nodes until a visible element is found -EPUBJS.Renderer.prototype.findFirstVisible = function(startEl){ - var el = startEl || this.render.getBaseElement(); - var found; - // kgolunski@7bulls.com - // Looks like an old API usage - // Set x and y as 0 to fullfill walk method API. - found = this.walk(el, 0, 0); - - if(found) { - return found; - }else{ - return startEl; - } - -}; -// TODO: remove me - unsused -EPUBJS.Renderer.prototype.findElementAfter = function(x, y, startEl){ - var el = startEl || this.render.getBaseElement(); - var found; - found = this.walk(el, x, y); - if(found) { - return found; - }else{ - return el; - } - -}; - -/* -EPUBJS.Renderer.prototype.route = function(hash, callback){ - var location = window.location.hash.replace('#/', ''); - if(this.useHash && location.length && location != this.prevLocation){ - this.show(location, callback); - this.prevLocation = location; - return true; - } - return false; -} - -EPUBJS.Renderer.prototype.hideHashChanges = function(){ - this.useHash = false; -} - -*/ - -EPUBJS.Renderer.prototype.resize = function(width, height, setSize){ - var spreads; - - this.width = width; - this.height = height; - - if(setSize !== false) { - this.render.resize(this.width, this.height); - } - - - - if(this.contents){ - this.reformat(); - } - - this.trigger("renderer:resized", { - width: this.width, - height: this.height - }); -}; - -//-- Listeners for events in the frame - -EPUBJS.Renderer.prototype.onResized = function(e) { - var width = this.container.clientWidth; - var height = this.container.clientHeight; - - this.resize(width, height, false); -}; - -EPUBJS.Renderer.prototype.addEventListeners = function(){ - if(!this.render.document) { - return; - } - this.listenedEvents.forEach(function(eventName){ - this.render.document.addEventListener(eventName, this.triggerEvent.bind(this), false); - }, this); - -}; - -EPUBJS.Renderer.prototype.removeEventListeners = function(){ - if(!this.render.document) { - return; - } - this.listenedEvents.forEach(function(eventName){ - this.render.document.removeEventListener(eventName, this.triggerEvent, false); - }, this); - -}; - -// Pass browser events -EPUBJS.Renderer.prototype.triggerEvent = function(e){ - this.trigger("renderer:"+e.type, e); -}; - -EPUBJS.Renderer.prototype.addSelectionListeners = function(){ - this.render.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); -}; - -EPUBJS.Renderer.prototype.removeSelectionListeners = function(){ - if(!this.render.document) { - return; - } - this.doc.removeEventListener("selectionchange", this.onSelectionChange, false); -}; - -EPUBJS.Renderer.prototype.onSelectionChange = function(e){ - if (this.selectionEndTimeout) { - clearTimeout(this.selectionEndTimeout); - } - this.selectionEndTimeout = setTimeout(function() { - this.selectedRange = this.render.window.getSelection(); - this.trigger("renderer:selected", this.selectedRange); - }.bind(this), 500); -}; - - -//-- Spreads - -EPUBJS.Renderer.prototype.setMinSpreadWidth = function(width){ - this.minSpreadWidth = width; - this.spreads = this.determineSpreads(width); -}; - -EPUBJS.Renderer.prototype.determineSpreads = function(cutoff){ - if(this.isForcedSingle || !cutoff || this.width < cutoff) { - return false; //-- Single Page - }else{ - return true; //-- Double Page - } -}; - -EPUBJS.Renderer.prototype.forceSingle = function(bool){ - if(bool) { - this.isForcedSingle = true; - // this.spreads = false; - } else { - this.isForcedSingle = false; - // this.spreads = this.determineSpreads(this.minSpreadWidth); - } -}; - -EPUBJS.Renderer.prototype.setGap = function(gap){ - this.gap = gap; //-- False == auto gap -}; - -EPUBJS.Renderer.prototype.setDirection = function(direction){ - this.direction = direction; - this.render.setDirection(this.direction); -}; - -//-- Content Replacements - -EPUBJS.Renderer.prototype.replace = function(query, func, finished, progress){ - var items = this.contents.querySelectorAll(query), - resources = Array.prototype.slice.call(items), - count = resources.length; - - - if(count === 0) { - finished(false); - return; - } - resources.forEach(function(item){ - var called = false; - var after = function(result, full){ - if(called === false) { - count--; - if(progress) progress(result, full, count); - if(count <= 0 && finished) finished(true); - called = true; - } - }; - - func(item, after); - - }.bind(this)); - -}; - -//-- Enable binding events to Renderer -RSVP.EventTarget.mixin(EPUBJS.Renderer.prototype); - -var EPUBJS = EPUBJS || {}; -EPUBJS.replace = {}; - -//-- Replaces the relative links within the book to use our internal page changer -EPUBJS.replace.hrefs = function(callback, renderer){ - var book = this; - var replacments = function(link, done){ - var href = decodeURI(link.getAttribute("href")), - isRelative = href.search("://"), - directory, - relative, - location, - base, - uri, - url; - - if(isRelative != -1){ - - link.setAttribute("target", "_blank"); - - }else{ - // Links may need to be resolved, such as ../chp1.xhtml - base = renderer.render.docEl.querySelector('base'); - url = base.getAttribute("href"); - uri = EPUBJS.core.uri(url); - directory = uri.directory; - - if(directory) { - // We must ensure that the file:// protocol is preserved for - // local file links, as in certain contexts (such as under - // Titanium), file links without the file:// protocol will not - // work - if (uri.protocol === "file") { - relative = EPUBJS.core.resolveUrl(uri.base, href); - } else { - relative = EPUBJS.core.resolveUrl(directory, href); - } - } else { - relative = href; - } - - link.onclick = function(){ - book.goto(relative); - return false; - }; - - } - done(); - - }; - - renderer.replace("a[href]", replacments, callback); - -}; - -EPUBJS.replace.head = function(callback, renderer) { - - renderer.replaceWithStored("link[href]", "href", EPUBJS.replace.links, callback); - -}; - - -//-- Replaces assets src's to point to stored version if browser is offline -EPUBJS.replace.resources = function(callback, renderer){ - //srcs = this.doc.querySelectorAll('[src]'); - renderer.replaceWithStored("[src]", "src", EPUBJS.replace.srcs, callback); - -}; - -EPUBJS.replace.svg = function(callback, renderer) { - - renderer.replaceWithStored("svg image", "xlink:href", function(_store, full, done){ - _store.getUrl(full).then(done); - }, callback); - -}; - -EPUBJS.replace.srcs = function(_store, full, done){ - - _store.getUrl(full).then(done); - -}; - -//-- Replaces links in head, such as stylesheets - link[href] -EPUBJS.replace.links = function(_store, full, done, link){ - //-- Handle replacing urls in CSS - if(link.getAttribute("rel") === "stylesheet") { - EPUBJS.replace.stylesheets(_store, full).then(function(url, full){ - // done - done(url, full); - }, function(reason) { - // we were unable to replace the style sheets - done(null); - }); - }else{ - _store.getUrl(full).then(done, function(reason) { - // we were unable to get the url, signal to upper layer - done(null); - }); - } -}; - -EPUBJS.replace.stylesheets = function(_store, full) { - var deferred = new RSVP.defer(); - - if(!_store) return; - - _store.getText(full).then(function(text){ - var url; - - EPUBJS.replace.cssUrls(_store, full, text).then(function(newText){ - var _URL = window.URL || window.webkitURL || window.mozURL; - - var blob = new Blob([newText], { "type" : "text\/css" }), - url = _URL.createObjectURL(blob); - - deferred.resolve(url); - - }, function(reason) { - deferred.reject(reason); - }); - - }, function(reason) { - deferred.reject(reason); - }); - - return deferred.promise; -}; - -EPUBJS.replace.cssUrls = function(_store, base, text){ - var deferred = new RSVP.defer(), - promises = [], - matches = text.match(/url\(\'?\"?((?!data:)[^\'|^\"^\)]*)\'?\"?\)/g); - - if(!_store) return; - - if(!matches){ - deferred.resolve(text); - return deferred.promise; - } - - matches.forEach(function(str){ - var full = EPUBJS.core.resolveUrl(base, str.replace(/url\(|[|\)|\'|\"]|\?.*$/g, '')); - var replaced = _store.getUrl(full).then(function(url){ - text = text.replace(str, 'url("'+url+'")'); - }, function(reason) { - deferred.reject(reason); - }); - - promises.push(replaced); - }); - - RSVP.all(promises).then(function(){ - deferred.resolve(text); - }); - - return deferred.promise; -}; - - -EPUBJS.Storage = function(withCredentials){ - - this.checkRequirements(); - this.urlCache = {}; - this.withCredentials = withCredentials; - this.URL = window.URL || window.webkitURL || window.mozURL; - this.offline = false; -}; - -//-- Load the zip lib and set the workerScriptsPath -EPUBJS.Storage.prototype.checkRequirements = function(callback){ - if(typeof(localforage) == "undefined") console.error("localForage library not loaded"); -}; - -EPUBJS.Storage.prototype.put = function(assets, store) { - var deferred = new RSVP.defer(); - var count = assets.length; - var current = 0; - var next = function(deferred){ - var done = deferred || new RSVP.defer(); - var url; - var encodedUrl; - - if(current >= count) { - done.resolve(); - } else { - url = assets[current].url; - encodedUrl = window.encodeURIComponent(url); - - EPUBJS.core.request(url, "binary") - .then(function (data) { - return localforage.setItem(encodedUrl, data); - }) - .then(function(data){ - current++; - // Load up the next - setTimeout(function(){ - next(done); - }, 1); - - }); - } - return done.promise; - }.bind(this); - - if(!Array.isArray(assets)) { - assets = [assets]; - } - - next().then(function(){ - deferred.resolve(); - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Storage.prototype.token = function(url, value){ - var encodedUrl = window.encodeURIComponent(url); - return localforage.setItem(encodedUrl, value) - .then(function (result) { - if (result === null) { - return false; - } else { - return true; - } - }); -}; - -EPUBJS.Storage.prototype.isStored = function(url){ - var encodedUrl = window.encodeURIComponent(url); - return localforage.getItem(encodedUrl) - .then(function (result) { - if (result === null) { - return false; - } else { - return true; - } - }); -}; - -EPUBJS.Storage.prototype.getText = function(url){ - var encodedUrl = window.encodeURIComponent(url); - - return EPUBJS.core.request(url, 'arraybuffer', this.withCredentials) - .then(function(buffer){ - - if(this.offline){ - this.offline = false; - this.trigger("offline", false); - } - localforage.setItem(encodedUrl, buffer); - return buffer; - }.bind(this)) - .then(function(data) { - var deferred = new RSVP.defer(); - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - deferred.resolve(reader.result); - }); - reader.readAsText(blob, mimeType); - return deferred.promise; - }) - .catch(function() { - - var deferred = new RSVP.defer(); - var entry = localforage.getItem(encodedUrl); - - if(!this.offline){ - this.offline = true; - this.trigger("offline", true); - } - - if(!entry) { - deferred.reject({ - message : "File not found in the storage: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - entry.then(function(data) { - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - deferred.resolve(reader.result); - }); - reader.readAsText(blob, mimeType); - }); - - return deferred.promise; - }.bind(this)); -}; - -EPUBJS.Storage.prototype.getUrl = function(url){ - var encodedUrl = window.encodeURIComponent(url); - - return EPUBJS.core.request(url, 'arraybuffer', this.withCredentials) - .then(function(buffer){ - if(this.offline){ - this.offline = false; - this.trigger("offline", false); - } - localforage.setItem(encodedUrl, buffer); - return url; - }.bind(this)) - .catch(function() { - var deferred = new RSVP.defer(); - var entry; - var _URL = window.URL || window.webkitURL || window.mozURL; - var tempUrl; - - if(!this.offline){ - this.offline = true; - this.trigger("offline", true); - } - - if(encodedUrl in this.urlCache) { - deferred.resolve(this.urlCache[encodedUrl]); - return deferred.promise; - } - - entry = localforage.getItem(encodedUrl); - - if(!entry) { - deferred.reject({ - message : "File not found in the storage: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - entry.then(function(data) { - var blob = new Blob([data], {type : EPUBJS.core.getMimeType(url)}); - tempUrl = _URL.createObjectURL(blob); - deferred.resolve(tempUrl); - this.urlCache[encodedUrl] = tempUrl; - }.bind(this)); - - - return deferred.promise; - }.bind(this)); -}; - -EPUBJS.Storage.prototype.getXml = function(url){ - var encodedUrl = window.encodeURIComponent(url); - - return EPUBJS.core.request(url, 'arraybuffer', this.withCredentials) - .then(function(buffer){ - if(this.offline){ - this.offline = false; - this.trigger("offline", false); - } - localforage.setItem(encodedUrl, buffer); - return buffer; - }.bind(this)) - .then(function(data) { - var deferred = new RSVP.defer(); - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - var parser = new DOMParser(); - var doc = parser.parseFromString(reader.result, "text/xml"); - deferred.resolve(doc); - }); - reader.readAsText(blob, mimeType); - return deferred.promise; - }) - .catch(function() { - var deferred = new RSVP.defer(); - var entry = localforage.getItem(encodedUrl); - - if(!this.offline){ - this.offline = true; - this.trigger("offline", true); - } - - if(!entry) { - deferred.reject({ - message : "File not found in the storage: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - entry.then(function(data) { - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - var parser = new DOMParser(); - var doc = parser.parseFromString(reader.result, "text/xml"); - deferred.resolve(doc); - }); - reader.readAsText(blob, mimeType); - }); - - return deferred.promise; - }.bind(this)); -}; - -EPUBJS.Storage.prototype.revokeUrl = function(url){ - var _URL = window.URL || window.webkitURL || window.mozURL; - var fromCache = this.urlCache[url]; - if(fromCache) _URL.revokeObjectURL(fromCache); -}; - -EPUBJS.Storage.prototype.failed = function(error){ - console.error(error); -}; - -RSVP.EventTarget.mixin(EPUBJS.Storage.prototype); - -EPUBJS.Unarchiver = function(url){ - - this.checkRequirements(); - this.urlCache = {}; - -}; - -//-- Load the zip lib and set the workerScriptsPath -EPUBJS.Unarchiver.prototype.checkRequirements = function(callback){ - if(typeof(JSZip) == "undefined") console.error("JSZip lib not loaded"); -}; - -EPUBJS.Unarchiver.prototype.open = function(zipUrl, callback){ - if (zipUrl instanceof ArrayBuffer) { - this.zip = new JSZip(zipUrl); - var deferred = new RSVP.defer(); - deferred.resolve(); - return deferred.promise; - } else { - return EPUBJS.core.request(zipUrl, "binary").then(function(data){ - this.zip = new JSZip(data); - }.bind(this)); - } -}; - -EPUBJS.Unarchiver.prototype.getXml = function(url, encoding){ - var decodededUrl = window.decodeURIComponent(url); - return this.getText(decodededUrl, encoding). - then(function(text){ - var parser = new DOMParser(); - var mimeType = EPUBJS.core.getMimeType(url); - return parser.parseFromString(text, mimeType); - }); - -}; - -EPUBJS.Unarchiver.prototype.getUrl = function(url, mime){ - var unarchiver = this; - var deferred = new RSVP.defer(); - var decodededUrl = window.decodeURIComponent(url); - var entry = this.zip.file(decodededUrl); - var _URL = window.URL || window.webkitURL || window.mozURL; - var tempUrl; - var blob; - - if(!entry) { - deferred.reject({ - message : "File not found in the epub: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - if(url in this.urlCache) { - deferred.resolve(this.urlCache[url]); - return deferred.promise; - } - - blob = new Blob([entry.asUint8Array()], {type : EPUBJS.core.getMimeType(entry.name)}); - - tempUrl = _URL.createObjectURL(blob); - deferred.resolve(tempUrl); - unarchiver.urlCache[url] = tempUrl; - - return deferred.promise; -}; - -EPUBJS.Unarchiver.prototype.getText = function(url, encoding){ - var unarchiver = this; - var deferred = new RSVP.defer(); - var decodededUrl = window.decodeURIComponent(url); - var entry = this.zip.file(decodededUrl); - var text; - - if(!entry) { - deferred.reject({ - message : "File not found in the epub: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - text = entry.asText(); - deferred.resolve(text); - - return deferred.promise; -}; - -EPUBJS.Unarchiver.prototype.revokeUrl = function(url){ - var _URL = window.URL || window.webkitURL || window.mozURL; - var fromCache = this.urlCache[url]; - if(fromCache) _URL.revokeObjectURL(fromCache); -}; - -EPUBJS.Unarchiver.prototype.failed = function(error){ - console.error(error); -}; - -EPUBJS.Unarchiver.prototype.afterSaved = function(error){ - this.callback(); -}; - -EPUBJS.Unarchiver.prototype.toStorage = function(entries){ - var timeout = 0, - delay = 20, - that = this, - count = entries.length; - - function callback(){ - count--; - if(count === 0) that.afterSaved(); - } - - entries.forEach(function(entry){ - - setTimeout(function(entry){ - that.saveEntryFileToStorage(entry, callback); - }, timeout, entry); - - timeout += delay; - }); - - console.log("time", timeout); - - //entries.forEach(this.saveEntryFileToStorage.bind(this)); -}; - -// EPUBJS.Unarchiver.prototype.saveEntryFileToStorage = function(entry, callback){ -// var that = this; -// entry.getData(new zip.BlobWriter(), function(blob) { -// EPUBJS.storage.save(entry.filename, blob, callback); -// }); -// }; - -/* - From Zip.js, by Gildas Lormeau - */ - -(function() { - "use strict"; - var table = { - "application" : { - "ecmascript" : [ "es", "ecma" ], - "javascript" : "js", - "ogg" : "ogx", - "pdf" : "pdf", - "postscript" : [ "ps", "ai", "eps", "epsi", "epsf", "eps2", "eps3" ], - "rdf+xml" : "rdf", - "smil" : [ "smi", "smil" ], - "xhtml+xml" : [ "xhtml", "xht" ], - "xml" : [ "xml", "xsl", "xsd", "opf" ], - "zip" : "zip", - "x-httpd-eruby" : "rhtml", - "x-latex" : "latex", - "x-maker" : [ "frm", "maker", "frame", "fm", "fb", "book", "fbdoc" ], - "x-object" : "o", - "x-shockwave-flash" : [ "swf", "swfl" ], - "x-silverlight" : "scr", - "epub+zip" : "epub", - "font-tdpfr" : "pfr", - "inkml+xml" : [ "ink", "inkml" ], - "json" : "json", - "jsonml+json" : "jsonml", - "mathml+xml" : "mathml", - "metalink+xml" : "metalink", - "mp4" : "mp4s", - // "oebps-package+xml" : "opf", - "omdoc+xml" : "omdoc", - "oxps" : "oxps", - "vnd.amazon.ebook" : "azw", - "widget" : "wgt", - "x-dtbncx+xml" : "ncx", - "x-dtbook+xml" : "dtb", - "x-dtbresource+xml" : "res", - "x-font-bdf" : "bdf", - "x-font-ghostscript" : "gsf", - "x-font-linux-psf" : "psf", - "x-font-otf" : "otf", - "x-font-pcf" : "pcf", - "x-font-snf" : "snf", - "x-font-ttf" : [ "ttf", "ttc" ], - "x-font-type1" : [ "pfa", "pfb", "pfm", "afm" ], - "x-font-woff" : "woff", - "x-mobipocket-ebook" : [ "prc", "mobi" ], - "x-mspublisher" : "pub", - "x-nzb" : "nzb", - "x-tgif" : "obj", - "xaml+xml" : "xaml", - "xml-dtd" : "dtd", - "xproc+xml" : "xpl", - "xslt+xml" : "xslt", - "internet-property-stream" : "acx", - "x-compress" : "z", - "x-compressed" : "tgz", - "x-gzip" : "gz", - }, - "audio" : { - "flac" : "flac", - "midi" : [ "mid", "midi", "kar", "rmi" ], - "mpeg" : [ "mpga", "mpega", "mp2", "mp3", "m4a", "mp2a", "m2a", "m3a" ], - "mpegurl" : "m3u", - "ogg" : [ "oga", "ogg", "spx" ], - "x-aiff" : [ "aif", "aiff", "aifc" ], - "x-ms-wma" : "wma", - "x-wav" : "wav", - "adpcm" : "adp", - "mp4" : "mp4a", - "webm" : "weba", - "x-aac" : "aac", - "x-caf" : "caf", - "x-matroska" : "mka", - "x-pn-realaudio-plugin" : "rmp", - "xm" : "xm", - "mid" : [ "mid", "rmi" ] - }, - "image" : { - "gif" : "gif", - "ief" : "ief", - "jpeg" : [ "jpeg", "jpg", "jpe" ], - "pcx" : "pcx", - "png" : "png", - "svg+xml" : [ "svg", "svgz" ], - "tiff" : [ "tiff", "tif" ], - "x-icon" : "ico", - "bmp" : "bmp", - "webp" : "webp", - "x-pict" : [ "pic", "pct" ], - "x-tga" : "tga", - "cis-cod" : "cod", - }, - "message" : { - "rfc822" : [ "eml", "mime", "mht", "mhtml", "nws" ] - }, - "text" : { - "cache-manifest" : [ "manifest", "appcache" ], - "calendar" : [ "ics", "icz", "ifb" ], - "css" : "css", - "csv" : "csv", - "h323" : "323", - "html" : [ "html", "htm", "shtml", "stm" ], - "iuls" : "uls", - "mathml" : "mml", - "plain" : [ "txt", "text", "brf", "conf", "def", "list", "log", "in", "bas" ], - "richtext" : "rtx", - "tab-separated-values" : "tsv", - "x-bibtex" : "bib", - "x-dsrc" : "d", - "x-diff" : [ "diff", "patch" ], - "x-haskell" : "hs", - "x-java" : "java", - "x-literate-haskell" : "lhs", - "x-moc" : "moc", - "x-pascal" : [ "p", "pas" ], - "x-pcs-gcd" : "gcd", - "x-perl" : [ "pl", "pm" ], - "x-python" : "py", - "x-scala" : "scala", - "x-setext" : "etx", - "x-tcl" : [ "tcl", "tk" ], - "x-tex" : [ "tex", "ltx", "sty", "cls" ], - "x-vcard" : "vcf", - "sgml" : [ "sgml", "sgm" ], - "x-c" : [ "c", "cc", "cxx", "cpp", "h", "hh", "dic" ], - "x-fortran" : [ "f", "for", "f77", "f90" ], - "x-opml" : "opml", - "x-nfo" : "nfo", - "x-sfv" : "sfv", - "x-uuencode" : "uu", - "webviewhtml" : "htt" - }, - "video" : { - "mpeg" : [ "mpeg", "mpg", "mpe", "m1v", "m2v", "mp2", "mpa", "mpv2" ], - "mp4" : [ "mp4", "mp4v", "mpg4" ], - "quicktime" : [ "qt", "mov" ], - "ogg" : "ogv", - "vnd.mpegurl" : [ "mxu", "m4u" ], - "x-flv" : "flv", - "x-la-asf" : [ "lsf", "lsx" ], - "x-mng" : "mng", - "x-ms-asf" : [ "asf", "asx", "asr" ], - "x-ms-wm" : "wm", - "x-ms-wmv" : "wmv", - "x-ms-wmx" : "wmx", - "x-ms-wvx" : "wvx", - "x-msvideo" : "avi", - "x-sgi-movie" : "movie", - "x-matroska" : [ "mpv", "mkv", "mk3d", "mks" ], - "3gpp2" : "3g2", - "h261" : "h261", - "h263" : "h263", - "h264" : "h264", - "jpeg" : "jpgv", - "jpm" : [ "jpm", "jpgm" ], - "mj2" : [ "mj2", "mjp2" ], - "vnd.ms-playready.media.pyv" : "pyv", - "vnd.uvvu.mp4" : [ "uvu", "uvvu" ], - "vnd.vivo" : "viv", - "webm" : "webm", - "x-f4v" : "f4v", - "x-m4v" : "m4v", - "x-ms-vob" : "vob", - "x-smv" : "smv" - } - }; - - var mimeTypes = (function() { - var type, subtype, val, index, mimeTypes = {}; - for (type in table) { - if (table.hasOwnProperty(type)) { - for (subtype in table[type]) { - if (table[type].hasOwnProperty(subtype)) { - val = table[type][subtype]; - if (typeof val == "string") { - mimeTypes[val] = type + "/" + subtype; - } else { - for (index = 0; index < val.length; index++) { - mimeTypes[val[index]] = type + "/" + subtype; - } - } - } - } - } - } - return mimeTypes; - })(); - - EPUBJS.core.getMimeType = function(filename) { - var defaultValue = "text/plain";//"application/octet-stream"; - return filename && mimeTypes[filename.split(".").pop().toLowerCase()] || defaultValue; - }; - -})(); - -//# sourceMappingURL=epub.js.map \ No newline at end of file diff --git a/epub.js/epub.js.map b/epub.js/epub.js.map deleted file mode 100644 index bedb067..0000000 --- a/epub.js/epub.js.map +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": 3, - "file": "epub.js", - "sources": [ - "node_modules/rsvp/dist/rsvp.js", - "src/base.js", - "src/book.js", - "src/chapter.js", - "src/core.js", - "src/epubcfi.js", - "src/events.js", - "src/hooks.js", - "src/layout.js", - "src/locations.js", - "src/pagination.js", - "src/parser.js", - "src/render_iframe.js", - "src/renderer.js", - "src/replace.js", - "src/storage.js", - "src/unarchiver.js", - "libs/mime-types/mime-types.js" - ], - "names": [], - "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC5jDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC3yCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACpYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACvnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACtiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC5KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACxOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACvFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACpdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC7RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACztCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;AC7JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A" -} \ No newline at end of file diff --git a/epub.js/epub.min.js b/epub.js/epub.min.js deleted file mode 100644 index f1e3018..0000000 --- a/epub.js/epub.min.js +++ /dev/null @@ -1,12 +0,0 @@ -/*! - * @overview RSVP - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE - * @version 3.1.0 - */ -(function(){"use strict";function a(a){return"function"==typeof a||"object"==typeof a&&null!==a}function b(a){return"function"==typeof a}function c(a){return"object"==typeof a&&null!==a}function d(){}function e(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1}function f(a){var b=a._promiseCallbacks;return b||(b=a._promiseCallbacks={}),b}function g(a,b){return"onerror"===a?void va.on("error",b):2!==arguments.length?va[a]:void(va[a]=b)}function h(){setTimeout(function(){for(var a,b=0;bh;h++)u(e.resolve(a[h]),void 0,c,d);return f}function E(a,b){var c=this;if(a&&"object"==typeof a&&a.constructor===c)return a;var d=new c(k,b);return q(d,a),d}function F(a,b){var c=this,d=new c(k,b);return t(d,a),d}function G(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function H(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function I(a,c){var d=this;d._id=Ja++,d._label=c,d._state=void 0,d._result=void 0,d._subscribers=[],va.instrument&&xa("created",d),k!==a&&(b(a)||G(),d instanceof I||H(),z(d,a))}function J(a,b,c){this._superConstructor(a,b,!1,c)}function K(a,b){return new J(Ka,a,b).promise}function L(a,b){return Ka.all(a,b)}function M(a,b){Wa[Pa]=a,Wa[Pa+1]=b,Pa+=2,2===Pa&&Ma()}function N(){var a=process.nextTick,b=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);return Array.isArray(b)&&"0"===b[1]&&"10"===b[2]&&(a=setImmediate),function(){a(S)}}function O(){return function(){La(S)}}function P(){var a=0,b=new Ta(S),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function Q(){var a=new MessageChannel;return a.port1.onmessage=S,function(){a.port2.postMessage(0)}}function R(){return function(){setTimeout(S,1)}}function S(){for(var a=0;Pa>a;a+=2){var b=Wa[a],c=Wa[a+1];b(c),Wa[a]=void 0,Wa[a+1]=void 0}Pa=0}function T(){try{var a=require,b=a("vertx");return La=b.runOnLoop||b.runOnContext,O()}catch(c){return R()}}function U(a){var b={};return b.promise=new Ka(function(a,c){b.resolve=a,b.reject=c},a),b}function V(a,c,d){return Ka.all(a,d).then(function(a){if(!b(c))throw new TypeError("You must pass a function as filter's second argument.");for(var e=a.length,f=new Array(e),g=0;e>g;g++)f[g]=c(a[g]);return Ka.all(f,d).then(function(b){for(var c=new Array(e),d=0,f=0;e>f;f++)b[f]&&(c[d]=a[f],d++);return c.length=d,c})})}function W(a,b,c){this._superConstructor(a,b,!0,c)}function X(a,b,c){this._superConstructor(a,b,!1,c)}function Y(a,b){return new X(Ka,a,b).promise}function Z(a,b){return new Za(Ka,a,b).promise}function $(a,c,d){return Ka.all(a,d).then(function(a){if(!b(c))throw new TypeError("You must pass a function as map's second argument.");for(var e=a.length,f=new Array(e),g=0;e>g;g++)f[g]=c(a[g]);return Ka.all(f,d)})}function _(){this.value=void 0}function aa(a){try{return a.then}catch(b){return cb.value=b,cb}}function ba(a,b,c){try{a.apply(b,c)}catch(d){return cb.value=d,cb}}function ca(a,b){for(var c,d,e={},f=a.length,g=new Array(f),h=0;f>h;h++)g[h]=a[h];for(d=0;dd;d++)c[d-1]=a[d];return c}function ea(a,b){return{then:function(c,d){return a.call(b,c,d)}}}function fa(a,b){var c=function(){for(var c,d=this,e=arguments.length,f=new Array(e+1),g=!1,h=0;e>h;++h){if(c=arguments[h],!g){if(g=ia(c),g===db){var i=new Ka(k);return t(i,db.value),i}g&&g!==!0&&(c=ea(g,c))}f[h]=c}var j=new Ka(k);return f[e]=function(a,c){a?t(j,a):void 0===b?q(j,c):b===!0?q(j,da(arguments)):ra(b)?q(j,ca(arguments,b)):q(j,c)},g?ha(j,f,a,d):ga(j,f,a,d)};return c.__proto__=a,c}function ga(a,b,c,d){var e=ba(c,d,b);return e===cb&&t(a,e.value),a}function ha(a,b,c,d){return Ka.all(b).then(function(b){var e=ba(c,d,b);return e===cb&&t(a,e.value),a})}function ia(a){return a&&"object"==typeof a?a.constructor===Ka?!0:aa(a):!1}function ja(a,b){return Ka.race(a,b)}function ka(a,b){return Ka.reject(a,b)}function la(a,b){return Ka.resolve(a,b)}function ma(a){throw setTimeout(function(){throw a}),a}function na(a,b){va.async(a,b)}function oa(){va.on.apply(va,arguments)}function pa(){va.off.apply(va,arguments)}var qa;qa=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)};var ra=qa,sa=Date.now||function(){return(new Date).getTime()},ta=Object.create||function(a){if(arguments.length>1)throw new Error("Second argument not supported");if("object"!=typeof a)throw new TypeError("Argument must be an object");return d.prototype=a,new d},ua={mixin:function(a){return a.on=this.on,a.off=this.off,a.trigger=this.trigger,a._promiseCallbacks=void 0,a},on:function(a,b){if("function"!=typeof b)throw new TypeError("Callback must be a function");var c,d=f(this);c=d[a],c||(c=d[a]=[]),-1===e(c,b)&&c.push(b)},off:function(a,b){var c,d,g=f(this);return b?(c=g[a],d=e(c,b),void(-1!==d&&c.splice(d,1))):void(g[a]=[])},trigger:function(a,b,c){var d,e,g=f(this);if(d=g[a])for(var h=0;he;e++)a._eachEntry(d[e],e)},B.prototype._eachEntry=function(a,b){var d=this,e=d._instanceConstructor;c(a)?a.constructor===e&&a._state!==ya?(a._onError=null,d._settledAt(a._state,b,a._result)):d._willSettleAt(e.resolve(a),b):(d._remaining--,d._result[b]=d._makeResult(za,b,a))},B.prototype._settledAt=function(a,b,c){var d=this,e=d.promise;e._state===ya&&(d._remaining--,d._abortOnReject&&a===Aa?t(e,c):d._result[b]=d._makeResult(a,b,c)),0===d._remaining&&s(e,d._result)},B.prototype._makeResult=function(a,b,c){return c},B.prototype._willSettleAt=function(a,b){var c=this;u(a,void 0,function(a){c._settledAt(za,b,a)},function(a){c._settledAt(Aa,b,a)})};var Ea=C,Fa=D,Ga=E,Ha=F,Ia="rsvp_"+sa()+"-",Ja=0,Ka=I;I.cast=Ga,I.all=Ea,I.race=Fa,I.resolve=Ga,I.reject=Ha,I.prototype={constructor:I,_guidKey:Ia,_onError:function(a){var b=this;va.after(function(){b._onError&&va.trigger("error",a,b._label)})},then:function(a,b,c){var d=this,e=d._state;if(e===za&&!a||e===Aa&&!b)return va.instrument&&xa("chained",d,d),d;d._onError=null;var f=new d.constructor(k,c),g=d._result;if(va.instrument&&xa("chained",d,f),e){var h=arguments[e-1];va.async(function(){y(e,f,h,g)})}else u(d,f,a,b);return f},"catch":function(a,b){return this.then(void 0,a,b)},"finally":function(a,b){var c=this,d=c.constructor;return c.then(function(b){return d.resolve(a()).then(function(){return b})},function(b){return d.resolve(a()).then(function(){throw b})},b)}},J.prototype=ta(Da.prototype),J.prototype._superConstructor=Da,J.prototype._makeResult=A,J.prototype._validationError=function(){return new Error("allSettled must be called with an array")};var La,Ma,Na=K,Oa=L,Pa=0,Qa=({}.toString,M),Ra="undefined"!=typeof window?window:void 0,Sa=Ra||{},Ta=Sa.MutationObserver||Sa.WebKitMutationObserver,Ua="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Va="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,Wa=new Array(1e3);Ma=Ua?N():Ta?P():Va?Q():void 0===Ra&&"function"==typeof require?T():R();var Xa=U,Ya=V,Za=W;W.prototype=ta(Da.prototype),W.prototype._superConstructor=Da,W.prototype._init=function(){this._result={}},W.prototype._validateInput=function(a){return a&&"object"==typeof a},W.prototype._validationError=function(){return new Error("Promise.hash must be called with an object")},W.prototype._enumerate=function(){var a=this,b=a.promise,c=a._input,d=[];for(var e in c)b._state===ya&&Object.prototype.hasOwnProperty.call(c,e)&&d.push({position:e,entry:c[e]});var f=d.length;a._remaining=f;for(var g,h=0;b._state===ya&&f>h;h++)g=d[h],a._eachEntry(g.entry,g.position)},X.prototype=ta(Za.prototype),X.prototype._superConstructor=Da,X.prototype._makeResult=A,X.prototype._validationError=function(){return new Error("hashSettled must be called with an object")};var $a,_a=Y,ab=Z,bb=$,cb=new _,db=new _,eb=fa;if("object"==typeof self)$a=self;else{if("object"!=typeof global)throw new Error("no global: `self` or `global` found");$a=global}var fb=$a,gb=ja,hb=ka,ib=la,jb=ma;va.async=Qa,va.after=function(a){setTimeout(a,0)};if("undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var kb=window.__PROMISE_INSTRUMENTATION__;g("instrument",!0);for(var lb in kb)kb.hasOwnProperty(lb)&&oa(lb,kb[lb])}var mb={race:gb,Promise:Ka,allSettled:Na,hash:ab,hashSettled:_a,denodeify:eb,on:oa,off:pa,map:bb,filter:Ya,resolve:ib,reject:hb,all:Oa,rethrow:jb,defer:Xa,EventTarget:ua,configure:g,async:na};"function"==typeof define&&define.amd?define(function(){return mb}):"undefined"!=typeof module&&module.exports?module.exports=mb:"undefined"!=typeof fb&&(fb.RSVP=mb)}).call(this);var EPUBJS=EPUBJS||{};EPUBJS.VERSION="0.2.12",EPUBJS.plugins=EPUBJS.plugins||{},EPUBJS.filePath=EPUBJS.filePath||"/epubjs/",EPUBJS.Render={},function(a){var b=(a.ePub||{},a.ePub=function(){var a,b;return"undefined"!=typeof arguments[0]&&("string"==typeof arguments[0]||arguments[0]instanceof ArrayBuffer)&&(a=arguments[0],arguments[1]&&"object"==typeof arguments[1]?(b=arguments[1],b.bookPath=a):b={bookPath:a}),!arguments[0]||"object"!=typeof arguments[0]||arguments[0]instanceof ArrayBuffer||(b=arguments[0]),new EPUBJS.Book(b)});"function"==typeof define&&define.amd?define(["rsvp"],function(){return b}):"undefined"!=typeof module&&module.exports&&(module.exports=b)}(window),EPUBJS.Book=function(a){this.settings=EPUBJS.core.defaults(a||{},{bookPath:void 0,bookKey:void 0,packageUrl:void 0,storage:!1,fromStorage:!1,saved:!1,online:!0,contained:!1,width:void 0,height:void 0,layoutOveride:void 0,orientation:void 0,minSpreadWidth:768,gap:"auto",version:1,restore:!1,reload:!1,"goto":!1,styles:{},headTags:{},withCredentials:!1,render_method:"Iframe"}),this.settings.EPUBJSVERSION=EPUBJS.VERSION,this.spinePos=0,this.stored=!1,this.online=this.settings.online||navigator.onLine,this.networkListeners(),this.ready={manifest:new RSVP.defer,spine:new RSVP.defer,metadata:new RSVP.defer,cover:new RSVP.defer,toc:new RSVP.defer,pageList:new RSVP.defer},this.readyPromises=[this.ready.manifest.promise,this.ready.spine.promise,this.ready.metadata.promise,this.ready.cover.promise,this.ready.toc.promise],this.pageList=[],this.pagination=new EPUBJS.Pagination,this.pageListReady=this.ready.pageList.promise,this.ready.all=RSVP.all(this.readyPromises),this.ready.all.then(this._ready.bind(this)),this.isRendered=!1,this._q=EPUBJS.core.queue(this),this._rendering=!1,this._displayQ=EPUBJS.core.queue(this),this._moving=!1,this._gotoQ=EPUBJS.core.queue(this),this.renderer=new EPUBJS.Renderer(this.settings.render_method),this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth),this.renderer.setGap(this.settings.gap),this.listenToRenderer(this.renderer),this.defer_opened=new RSVP.defer,this.opened=this.defer_opened.promise,this.store=!1,this.settings.storage!==!1&&this.fromStorage(!0),("string"==typeof this.settings.bookPath||this.settings.bookPath instanceof ArrayBuffer)&&this.open(this.settings.bookPath,this.settings.reload),window.addEventListener("beforeunload",this.unload.bind(this),!1)},EPUBJS.Book.prototype.open=function(a,b){var c,d=this,e=new RSVP.defer;return this.settings.bookPath=a,this.settings.contained||this.isContained(a)?(this.settings.contained=this.contained=!0,this.bookUrl="",c=this.unarchive(a).then(function(){return d.loadPackage()})):(this.bookUrl=this.urlFrom(a),c=this.loadPackage()),this.settings.restore&&!b&&localStorage?c.then(function(a){var b=d.packageIdentifier(a),c=d.restore(b);c||d.unpack(a),e.resolve(),d.defer_opened.resolve()}):c.then(function(a){d.unpack(a),e.resolve(),d.defer_opened.resolve()}),this._registerReplacements(this.renderer),e.promise},EPUBJS.Book.prototype.loadPackage=function(a){var b,c=this,d=new EPUBJS.Parser,e=a||"META-INF/container.xml";return b=this.settings.packageUrl?c.loadXml(c.settings.packageUrl):c.loadXml(c.bookUrl+e).then(function(a){return d.container(a)}).then(function(a){return c.settings.contentsPath=c.bookUrl+a.basePath,c.settings.packageUrl=c.bookUrl+a.packagePath,c.settings.encoding=a.encoding,c.loadXml(c.settings.packageUrl)}),b["catch"](function(a){console.error("Could not load book at: "+e),c.trigger("book:loadFailed",e)}),b},EPUBJS.Book.prototype.packageIdentifier=function(a){var b=new EPUBJS.Parser;return b.identifier(a)},EPUBJS.Book.prototype.unpack=function(a){var b=this,c=new EPUBJS.Parser;b.contents=c.packageContents(a,b.settings.contentsPath),b.manifest=b.contents.manifest,b.spine=b.contents.spine,b.spineIndexByURL=b.contents.spineIndexByURL,b.metadata=b.contents.metadata,b.settings.bookKey||(b.settings.bookKey=b.generateBookKey(b.metadata.identifier)),b.globalLayoutProperties=b.parseLayoutProperties(b.metadata),b.contents.coverPath&&(b.cover=b.contents.cover=b.settings.contentsPath+b.contents.coverPath),b.spineNodeIndex=b.contents.spineNodeIndex,b.ready.manifest.resolve(b.contents.manifest),b.ready.spine.resolve(b.contents.spine),b.ready.metadata.resolve(b.contents.metadata),b.ready.cover.resolve(b.contents.cover),b.locations=new EPUBJS.Locations(b.spine,b.store,b.settings.withCredentials),b.contents.navPath?(b.settings.navUrl=b.settings.contentsPath+b.contents.navPath,b.loadXml(b.settings.navUrl).then(function(a){return c.nav(a,b.spineIndexByURL,b.spine)}).then(function(a){b.toc=b.contents.toc=a,b.ready.toc.resolve(b.contents.toc)},function(a){b.ready.toc.resolve(!1)}),b.loadXml(b.settings.navUrl).then(function(a){return c.pageList(a,b.spineIndexByURL,b.spine)}).then(function(a){var c=new EPUBJS.EpubCFI,d=0;0!==a.length&&(b.pageList=b.contents.pageList=a,b.pageList.forEach(function(a){a.cfi||(d+=1,c.generateCfiFromHref(a.href,b).then(function(c){a.cfi=c,a.packageUrl=b.settings.packageUrl,d-=1,0===d&&(b.pagination.process(b.pageList),b.ready.pageList.resolve(b.pageList))}))}),d||(b.pagination.process(b.pageList),b.ready.pageList.resolve(b.pageList)))},function(a){b.ready.pageList.resolve([])})):b.contents.tocPath?(b.settings.tocUrl=b.settings.contentsPath+b.contents.tocPath,b.loadXml(b.settings.tocUrl).then(function(a){return c.toc(a,b.spineIndexByURL,b.spine)}).then(function(a){b.toc=b.contents.toc=a,b.ready.toc.resolve(b.contents.toc)},function(a){b.ready.toc.resolve(!1)})):b.ready.toc.resolve(!1)},EPUBJS.Book.prototype.createHiddenRender=function(a,b,c){var d,e,f=this.element.getBoundingClientRect(),g=b||this.settings.width||f.width,h=c||this.settings.height||f.height;return a.setMinSpreadWidth(this.settings.minSpreadWidth),a.setGap(this.settings.gap),this._registerReplacements(a),this.settings.forceSingle&&a.forceSingle(!0),d=document.createElement("div"),d.style.visibility="hidden",d.style.overflow="hidden",d.style.width="0",d.style.height="0",this.element.appendChild(d),e=document.createElement("div"),e.style.visibility="hidden",e.style.overflow="hidden",e.style.width=g+"px",e.style.height=h+"px",d.appendChild(e),a.initialize(e),d},EPUBJS.Book.prototype.generatePageList=function(a,b){var c=[],d=new EPUBJS.Renderer(this.settings.render_method,!1),e=this.createHiddenRender(d,a,b),f=new RSVP.defer,g=-1,h=this.spine.length,i=0,j=function(a){var b,e=g+1,f=a||new RSVP.defer;return e>=h?f.resolve():(g=e,b=new EPUBJS.Chapter(this.spine[g],this.store),d.displayChapter(b,this.globalLayoutProperties).then(function(a){d.pageMap.forEach(function(a){i+=1,c.push({cfi:a.start,page:i})}),d.pageMap.length%2>0&&d.spreads&&(i+=1,c.push({cfi:d.pageMap[d.pageMap.length-1].end,page:i})),setTimeout(function(){j(f)},1)})),f.promise}.bind(this);j().then(function(){d.remove(),this.element.removeChild(e),f.resolve(c)}.bind(this));return f.promise},EPUBJS.Book.prototype.generatePagination=function(a,b){var c=this,d=new RSVP.defer;return this.ready.spine.promise.then(function(){c.generatePageList(a,b).then(function(a){c.pageList=c.contents.pageList=a,c.pagination.process(a),c.ready.pageList.resolve(c.pageList),d.resolve(c.pageList)})}),d.promise},EPUBJS.Book.prototype.loadPagination=function(a){var b=JSON.parse(a);return b&&b.length&&(this.pageList=b,this.pagination.process(this.pageList),this.ready.pageList.resolve(this.pageList)),this.pageList},EPUBJS.Book.prototype.getPageList=function(){return this.ready.pageList.promise},EPUBJS.Book.prototype.getMetadata=function(){return this.ready.metadata.promise},EPUBJS.Book.prototype.getToc=function(){return this.ready.toc.promise},EPUBJS.Book.prototype.networkListeners=function(){var a=this;window.addEventListener("offline",function(b){a.online=!1,a.settings.storage&&a.fromStorage(!0),a.trigger("book:offline")},!1),window.addEventListener("online",function(b){a.online=!0,a.settings.storage&&a.fromStorage(!1),a.trigger("book:online")},!1)},EPUBJS.Book.prototype.listenToRenderer=function(a){var b=this;a.Events.forEach(function(c){a.on(c,function(a){b.trigger(c,a)})}),a.on("renderer:visibleRangeChanged",function(a){var b,c,d,e=[];this.pageList.length>0&&(b=this.pagination.pageFromCfi(a.start),d=this.pagination.percentageFromPage(b),e.push(b),a.end&&(c=this.pagination.pageFromCfi(a.end),e.push(c)),this.trigger("book:pageChanged",{anchorPage:b,percentage:d,pageRange:e}))}.bind(this)),a.on("render:loaded",this.loadChange.bind(this))},EPUBJS.Book.prototype.loadChange=function(a){var b,c,d=EPUBJS.core.uri(a),e=EPUBJS.core.uri(this.currentChapter.absolute);d.path!=e.path?(console.warn("Miss Match",d.path,this.currentChapter.absolute),b=this.spineIndexByURL[d.filename],c=new EPUBJS.Chapter(this.spine[b],this.store),this.currentChapter=c,this.renderer.currentChapter=c,this.renderer.afterLoad(this.renderer.render.docEl),this.renderer.beforeDisplay(function(){this.renderer.afterDisplay()}.bind(this))):this._rendering||this.renderer.reformat()},EPUBJS.Book.prototype.unlistenToRenderer=function(a){a.Events.forEach(function(b){a.off(b)})},EPUBJS.Book.prototype.loadXml=function(a){return this.settings.fromStorage?this.store.getXml(a,this.settings.encoding):this.settings.contained?this.zip.getXml(a,this.settings.encoding):EPUBJS.core.request(a,"xml",this.settings.withCredentials)},EPUBJS.Book.prototype.urlFrom=function(a){var b,c=EPUBJS.core.uri(a),d=c.protocol,e="/"==c.path[0],f=window.location,g=f.origin||f.protocol+"//"+f.host,h=document.getElementsByTagName("base");return h.length&&(b=h[0].href),c.protocol?c.origin+c.path:!d&&e?(b||g)+c.path:d||e?void 0:EPUBJS.core.resolveUrl(b||f.pathname,c.path)},EPUBJS.Book.prototype.unarchive=function(a){return this.zip=new EPUBJS.Unarchiver,this.store=this.zip,this.zip.open(a)},EPUBJS.Book.prototype.isContained=function(a){if(a instanceof ArrayBuffer)return!0;var b=EPUBJS.core.uri(a);return!b.extension||"epub"!=b.extension&&"zip"!=b.extension?!1:!0},EPUBJS.Book.prototype.isSaved=function(a){var b;return localStorage?(b=localStorage.getItem(a),localStorage&&null!==b?!0:!1):!1},EPUBJS.Book.prototype.generateBookKey=function(a){return"epubjs:"+EPUBJS.VERSION+":"+window.location.host+":"+a},EPUBJS.Book.prototype.saveContents=function(){return localStorage?void localStorage.setItem(this.settings.bookKey,JSON.stringify(this.contents)):!1},EPUBJS.Book.prototype.removeSavedContents=function(){return localStorage?void localStorage.removeItem(this.settings.bookKey):!1},EPUBJS.Book.prototype.renderTo=function(a){var b,c=this;if(EPUBJS.core.isElement(a))this.element=a;else{if("string"!=typeof a)return void console.error("Not an Element");this.element=EPUBJS.core.getEl(a)}return b=this.opened.then(function(){return c.renderer.initialize(c.element,c.settings.width,c.settings.height),c.metadata.direction&&c.renderer.setDirection(c.metadata.direction),c._rendered(),c.startDisplay()})},EPUBJS.Book.prototype.startDisplay=function(){var a;return a=this.settings["goto"]?this["goto"](this.settings["goto"]):this.settings.previousLocationCfi?this.gotoCfi(this.settings.previousLocationCfi):this.displayChapter(this.spinePos)},EPUBJS.Book.prototype.restore=function(a){var b,c=this,d=["manifest","spine","metadata","cover","toc","spineNodeIndex","spineIndexByURL","globalLayoutProperties"],e=!1,f=this.generateBookKey(a),g=localStorage.getItem(f),h=d.length;if(this.settings.clearSaved&&(e=!0),!e&&"undefined"!=g&&null!==g)for(c.contents=JSON.parse(g),b=0;h>b;b++){var i=d[b];if(!c.contents[i]){e=!0;break}c[i]=c.contents[i]}return!e&&g&&this.contents&&this.settings.contentsPath?(this.settings.bookKey=f,this.ready.manifest.resolve(this.manifest),this.ready.spine.resolve(this.spine),this.ready.metadata.resolve(this.metadata),this.ready.cover.resolve(this.cover),this.ready.toc.resolve(this.toc),!0):!1},EPUBJS.Book.prototype.displayChapter=function(a,b,c){var d,e,f,g,h=this,i=c||new RSVP.defer;return this.isRendered?this._rendering||this._rendering?(this._displayQ.enqueue("displayChapter",[a,b,i]),i.promise):(EPUBJS.core.isNumber(a)?f=a:(e=new EPUBJS.EpubCFI(a),f=e.spinePos),(0>f||f>=this.spine.length)&&(console.warn("Not A Valid Location"),f=0,b=!1,e=!1),g=new EPUBJS.Chapter(this.spine[f],this.store),this._rendering=!0,this._needsAssetReplacement()&&g.registerHook("beforeChapterRender",[EPUBJS.replace.head,EPUBJS.replace.resources,EPUBJS.replace.svg],!0),h.currentChapter=g,d=h.renderer.displayChapter(g,this.globalLayoutProperties),e?h.renderer.gotoCfi(e):b&&h.renderer.lastPage(),d.then(function(a){h.spinePos=f,i.resolve(h.renderer),h.settings.fromStorage===!1&&h.settings.contained===!1&&h.preloadNextChapter(),h._rendering=!1,h._displayQ.dequeue(),0===h._displayQ.length()&&h._gotoQ.dequeue()},function(a){console.error("Could not load Chapter: "+g.absolute,a),h.trigger("book:chapterLoadFailed",g.absolute),h._rendering=!1,i.reject(a)}),i.promise):(this._q.enqueue("displayChapter",arguments),i.reject({message:"Rendering",stack:(new Error).stack}),i.promise)},EPUBJS.Book.prototype.nextPage=function(){var a;return this.isRendered?(a=this.renderer.nextPage(),a?void 0:this.nextChapter()):this._q.enqueue("nextPage",arguments)},EPUBJS.Book.prototype.prevPage=function(){var a;return this.isRendered?(a=this.renderer.prevPage(),a?void 0:this.prevChapter()):this._q.enqueue("prevPage",arguments)},EPUBJS.Book.prototype.nextChapter=function(){var a;if(this.spinePos0){for(a=this.spinePos-1;this.spine[a]&&this.spine[a].linear&&"no"==this.spine[a].linear;)a--;if(a>=0)return this.displayChapter(a,!0);this.trigger("book:atStart")}else this.trigger("book:atStart")},EPUBJS.Book.prototype.getCurrentLocationCfi=function(){return this.isRendered?this.renderer.currentLocationCfi:!1},EPUBJS.Book.prototype["goto"]=function(a){return 0===a.indexOf("epubcfi(")?this.gotoCfi(a):a.indexOf("%")===a.length-1?this.gotoPercentage(parseInt(a.substring(0,a.length-1))/100):"number"==typeof a||isNaN(a)===!1?this.gotoPage(a):this.gotoHref(a)},EPUBJS.Book.prototype.gotoCfi=function(a,b){var c,d,e,f=b||new RSVP.defer;return this.isRendered?this._moving||this._rendering?(console.warn("Renderer is moving"),this._gotoQ.enqueue("gotoCfi",[a,f]),!1):(c=new EPUBJS.EpubCFI(a),d=c.spinePos,-1==d?!1:(e=this.spine[d],promise=f.promise,this._moving=!0,this.currentChapter&&this.spinePos===d?(this.renderer.gotoCfi(c),this._moving=!1,f.resolve(this.renderer.currentLocationCfi)):(e&&-1!=d||(d=0,e=this.spine[d]),this.currentChapter=new EPUBJS.Chapter(e,this.store),this.currentChapter&&(this.spinePos=d,render=this.renderer.displayChapter(this.currentChapter,this.globalLayoutProperties),this.renderer.gotoCfi(c),render.then(function(a){this._moving=!1,f.resolve(a.currentLocationCfi)}.bind(this)))),promise.then(function(){this._gotoQ.dequeue()}.bind(this)),promise)):(console.warn("Not yet Rendered"),this.settings.previousLocationCfi=a,!1)},EPUBJS.Book.prototype.gotoHref=function(a,b){var c,d,e,f,g,h=b||new RSVP.defer;return this.isRendered?this._moving||this._rendering?(this._gotoQ.enqueue("gotoHref",[a,h]),!1):(c=a.split("#"),d=c[0],e=c[1]||!1,f=-1==d.search("://")?d.replace(EPUBJS.core.uri(this.settings.contentsPath).path,""):d.replace(this.settings.contentsPath,""),g=this.spineIndexByURL[f],d||(g=this.currentChapter?this.currentChapter.spinePos:0),"number"!=typeof g?!1:this.currentChapter&&g==this.currentChapter.spinePos?(e?this.renderer.section(e):this.renderer.firstPage(),h.resolve(this.renderer.currentLocationCfi),h.promise.then(function(){this._gotoQ.dequeue()}.bind(this)),h.promise):this.displayChapter(g).then(function(){e&&this.renderer.section(e),h.resolve(this.renderer.currentLocationCfi)}.bind(this))):(this.settings["goto"]=a,!1)},EPUBJS.Book.prototype.gotoPage=function(a){var b=this.pagination.cfiFromPage(a);return this.gotoCfi(b)},EPUBJS.Book.prototype.gotoPercentage=function(a){var b=this.pagination.pageFromPercentage(a);return this.gotoPage(b)},EPUBJS.Book.prototype.preloadNextChapter=function(){var a,b=this.spinePos+1;return b>=this.spine.length?!1:(a=new EPUBJS.Chapter(this.spine[b]),void(a&&EPUBJS.core.request(a.absolute)))},EPUBJS.Book.prototype.storeOffline=function(){var a=this,b=EPUBJS.core.values(this.manifest);return this.store.put(b).then(function(){a.settings.stored=!0,a.trigger("book:stored")})},EPUBJS.Book.prototype.availableOffline=function(){return this.settings.stored>0?!0:!1},EPUBJS.Book.prototype.toStorage=function(){var a=this.settings.bookKey;this.store.isStored(a).then(function(b){return b===!0?(this.settings.stored=!0,!0):this.storeOffline().then(function(){this.store.token(a,!0)}.bind(this))}.bind(this))},EPUBJS.Book.prototype.fromStorage=function(a){[EPUBJS.replace.head,EPUBJS.replace.resources,EPUBJS.replace.svg];this.contained||this.settings.contained||(this.online&&this.opened.then(this.toStorage.bind(this)),this.store&&this.settings.fromStorage&&a===!1?(this.settings.fromStorage=!1,this.store.off("offline"),this.store=!1):this.settings.fromStorage||(this.store=new EPUBJS.Storage(this.settings.credentials),this.store.on("offline",function(a){a?(this.offline=!0,this.settings.fromStorage=!0,this.trigger("book:offline")):(this.offline=!1,this.settings.fromStorage=!1,this.trigger("book:online"))}.bind(this))))},EPUBJS.Book.prototype.setStyle=function(a,b,c){var d=["color","background","background-color"];return this.isRendered?(this.settings.styles[a]=b,this.renderer.setStyle(a,b,c),void(-1===d.indexOf(a)&&this.renderer.reformat())):this._q.enqueue("setStyle",arguments)},EPUBJS.Book.prototype.removeStyle=function(a){return this.isRendered?(this.renderer.removeStyle(a),this.renderer.reformat(),void delete this.settings.styles[a]):this._q.enqueue("removeStyle",arguments)},EPUBJS.Book.prototype.addHeadTag=function(a,b){return this.isRendered?void(this.settings.headTags[a]=b):this._q.enqueue("addHeadTag",arguments)},EPUBJS.Book.prototype.useSpreads=function(a){console.warn("useSpreads is deprecated, use forceSingle or set a layoutOveride instead"),a===!1?this.forceSingle(!0):this.forceSingle(!1)},EPUBJS.Book.prototype.forceSingle=function(a){var b="undefined"==typeof a?!0:a;this.renderer.forceSingle(b),this.settings.forceSingle=b,this.isRendered&&this.renderer.reformat()},EPUBJS.Book.prototype.setMinSpreadWidth=function(a){this.settings.minSpreadWidth=a,this.isRendered&&(this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth),this.renderer.reformat())},EPUBJS.Book.prototype.setGap=function(a){this.settings.gap=a,this.isRendered&&(this.renderer.setGap(this.settings.gap),this.renderer.reformat())},EPUBJS.Book.prototype.chapter=function(a){var b,c,d=this.spineIndexByURL[a];return d&&(b=this.spine[d],c=new EPUBJS.Chapter(b,this.store,this.settings.withCredentials),c.load()),c},EPUBJS.Book.prototype.unload=function(){this.settings.restore&&localStorage&&this.saveContents(),this.unlistenToRenderer(this.renderer),this.trigger("book:unload")},EPUBJS.Book.prototype.destroy=function(){window.removeEventListener("beforeunload",this.unload),this.currentChapter&&this.currentChapter.unload(),this.unload(),this.renderer&&this.renderer.remove()},EPUBJS.Book.prototype._ready=function(){this.trigger("book:ready")},EPUBJS.Book.prototype._rendered=function(a){this.isRendered=!0,this.trigger("book:rendered"),this._q.flush()},EPUBJS.Book.prototype.applyStyles=function(a,b){a.applyStyles(this.settings.styles),b()},EPUBJS.Book.prototype.applyHeadTags=function(a,b){a.applyHeadTags(this.settings.headTags),b()},EPUBJS.Book.prototype._registerReplacements=function(a){a.registerHook("beforeChapterDisplay",this.applyStyles.bind(this,a),!0),a.registerHook("beforeChapterDisplay",this.applyHeadTags.bind(this,a),!0),a.registerHook("beforeChapterDisplay",EPUBJS.replace.hrefs.bind(this),!0)},EPUBJS.Book.prototype._needsAssetReplacement=function(){return this.settings.fromStorage?!0:this.settings.contained?!0:!1; -},EPUBJS.Book.prototype.parseLayoutProperties=function(a){var b=this.settings.layoutOveride&&this.settings.layoutOveride.layout||a.layout||"reflowable",c=this.settings.layoutOveride&&this.settings.layoutOveride.spread||a.spread||"auto",d=this.settings.layoutOveride&&this.settings.layoutOveride.orientation||a.orientation||"auto";return{layout:b,spread:c,orientation:d}},RSVP.EventTarget.mixin(EPUBJS.Book.prototype),RSVP.on("error",function(a){}),RSVP.configure("instrument",!1),EPUBJS.Chapter=function(a,b,c){this.href=a.href,this.absolute=a.url,this.id=a.id,this.spinePos=a.index,this.cfiBase=a.cfiBase,this.properties=a.properties,this.manifestProperties=a.manifestProperties,this.linear=a.linear,this.pages=1,this.store=b,this.credentials=c,this.epubcfi=new EPUBJS.EpubCFI,this.deferred=new RSVP.defer,this.loaded=this.deferred.promise,EPUBJS.Hooks.mixin(this),this.getHooks("beforeChapterRender"),this.caches={}},EPUBJS.Chapter.prototype.load=function(a,b){var c,d=a||this.store,e=b||this.credentials;return c=d?d.getXml(this.absolute):EPUBJS.core.request(this.absolute,!1,e),c.then(function(a){this.setDocument(a),this.deferred.resolve(this)}.bind(this)),c},EPUBJS.Chapter.prototype.render=function(a){return this.load().then(function(a){var b=a.querySelector("head"),c=a.createElement("base");return c.setAttribute("href",this.absolute),b.insertBefore(c,b.firstChild),this.contents=a,new RSVP.Promise(function(b,c){this.triggerHooks("beforeChapterRender",function(){b(a)}.bind(this),this)}.bind(this))}.bind(this)).then(function(a){var b=new XMLSerializer,c=b.serializeToString(a);return c}.bind(this))},EPUBJS.Chapter.prototype.url=function(a){var b,c=new RSVP.defer,d=a||this.store,e=this;return d?this.tempUrl?(b=this.tempUrl,c.resolve(b)):d.getUrl(this.absolute).then(function(a){e.tempUrl=a,c.resolve(a)}):(b=this.absolute,c.resolve(b)),c.promise},EPUBJS.Chapter.prototype.setPages=function(a){this.pages=a},EPUBJS.Chapter.prototype.getPages=function(a){return this.pages},EPUBJS.Chapter.prototype.getID=function(){return this.ID},EPUBJS.Chapter.prototype.unload=function(a){this.document=null,this.tempUrl&&a&&(a.revokeUrl(this.tempUrl),this.tempUrl=!1)},EPUBJS.Chapter.prototype.setDocument=function(a){var b=a.namespaceURI;a.doctype;this.document=a.implementation.createDocument(b,null,null),this.contents=this.document.importNode(a.documentElement,!0),this.document.appendChild(this.contents),!this.document.evaluate&&document.evaluate&&(this.document.evaluate=document.evaluate)},EPUBJS.Chapter.prototype.cfiFromRange=function(a){var b,c,d,e,f,g;if(this.document){if("undefined"!=typeof document.evaluate){if(c=EPUBJS.core.getElementXPath(a.startContainer),d=EPUBJS.core.getElementXPath(a.endContainer),e=this.document.evaluate(c,this.document,EPUBJS.core.nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue,a.collapsed||(f=this.document.evaluate(d,this.document,EPUBJS.core.nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue),b=this.document.createRange(),e)try{b.setStart(e,a.startOffset),!a.collapsed&&f&&b.setEnd(f,a.endOffset)}catch(h){console.log("missed"),e=!1}e||(console.log("not found, try fuzzy match"),cleanStartTextContent=EPUBJS.core.cleanStringForXpath(a.startContainer.textContent),c="//text()[contains(.,"+cleanStartTextContent+")]",e=this.document.evaluate(c,this.document,EPUBJS.core.nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue,e&&(b.setStart(e,a.startOffset),a.collapsed||(g=EPUBJS.core.cleanStringForXpath(a.endContainer.textContent),d="//text()[contains(.,"+g+")]",f=this.document.evaluate(d,this.document,EPUBJS.core.nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue,f&&b.setEnd(f,a.endOffset))))}else b=a;return this.epubcfi.generateCfiFromRange(b,this.cfiBase)}},EPUBJS.Chapter.prototype.find=function(a){var b=this,c=[],d=a.toLowerCase(),e=function(a){for(var e,f,g,h=a.textContent.toLowerCase(),i=b.document.createRange(),j=-1,k=150;-1!=f;)f=h.indexOf(d,j+1),-1!=f&&(i=b.document.createRange(),i.setStart(a,f),i.setEnd(a,f+d.length),e=b.cfiFromRange(i),a.textContent.length=g&&c&&c(!0),e=!0)};b(a,f)}.bind(this))},EPUBJS.Chapter.prototype.replaceWithStored=function(a,b,c,d){var e,f={},g=this.store,h=this.caches[a],i=EPUBJS.core.uri(this.absolute),j=i.base,k=b,l=5,m=function(a,b,c){f[b]=a},n=function(a){d&&d(),EPUBJS.core.values(e).forEach(function(a){g.revokeUrl(a)}),h=f};g&&(h||(h={}),e=EPUBJS.core.clone(h),this.replace(a,function(b,d){var h=b.getAttribute(k),i=EPUBJS.core.resolveUrl(j,h),m=function(c){var e;b.onload=function(){clearTimeout(e),d(c,i)},b.onerror=function(a){clearTimeout(e),d(c,i),console.error(a)},"svg image"==a&&b.setAttribute("externalResourcesRequired","true"),"link[href]"==a&&"stylesheet"!==b.getAttribute("rel")?d(c,i):e=setTimeout(function(){d(c,i)},l),c&&b.setAttribute(k,c)};i in e?(m(e[i]),f[i]=e[i],delete e[i]):c(g,i,m,b)},n,m))};var EPUBJS=EPUBJS||{};EPUBJS.core={},EPUBJS.core.getEl=function(a){return document.getElementById(a)},EPUBJS.core.getEls=function(a){return document.getElementsByClassName(a)},EPUBJS.core.request=function(a,b,c){var d,e=window.URL,f=e?"blob":"arraybuffer",g=new RSVP.defer,h=new XMLHttpRequest,i=XMLHttpRequest.prototype,j=function(){var a;this.readyState==this.DONE&&(200===this.status||0===this.status&&this.response?(a="xml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xml"):"xhtml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xhtml+xml"):"html"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"text/html"):"json"==b?JSON.parse(this.response):"blob"==b?e?this.response:new Blob([this.response]):this.response,g.resolve(a)):g.reject({message:this.response,stack:(new Error).stack}))};return"overrideMimeType"in i||Object.defineProperty(i,"overrideMimeType",{value:function(a){}}),h.open("GET",a,!0),h.onreadystatechange=j,c&&(h.withCredentials=!0),b||(d=EPUBJS.core.uri(a),b=d.extension,b={htm:"html"}[b]||b),"blob"==b&&(h.responseType=f),"json"==b&&h.setRequestHeader("Accept","application/json"),"xml"==b&&(h.responseType="document",h.overrideMimeType("text/xml")),"xhtml"==b&&(h.responseType="document"),"html"==b&&(h.responseType="document"),"binary"==b&&(h.responseType="arraybuffer"),h.send(),g.promise},EPUBJS.core.toArray=function(a){var b=[];for(var c in a){var d;a.hasOwnProperty(c)&&(d=a[c],d.ident=c,b.push(d))}return b},EPUBJS.core.uri=function(a){var b,c,d,e={protocol:"",host:"",path:"",origin:"",directory:"",base:"",filename:"",extension:"",fragment:"",href:a},f=a.indexOf("blob:"),g=a.indexOf("://"),h=a.indexOf("?"),i=a.indexOf("#");return 0===f?(e.protocol="blob",e.base=a.indexOf(0,i),e):(-1!=i&&(e.fragment=a.slice(i+1),a=a.slice(0,i)),-1!=h&&(e.search=a.slice(h+1),a=a.slice(0,h),href=a),-1!=g?(e.protocol=a.slice(0,g),b=a.slice(g+3),d=b.indexOf("/"),-1===d?(e.host=e.path,e.path=""):(e.host=b.slice(0,d),e.path=b.slice(d)),e.origin=e.protocol+"://"+e.host,e.directory=EPUBJS.core.folder(e.path),e.base=e.origin+e.directory):(e.path=a,e.directory=EPUBJS.core.folder(a),e.base=e.directory),e.filename=a.replace(e.base,""),c=e.filename.lastIndexOf("."),-1!=c&&(e.extension=e.filename.slice(c+1)),e)},EPUBJS.core.folder=function(a){var b=a.lastIndexOf("/");if(-1==b)var c="";return c=a.slice(0,b+1)},EPUBJS.core.dataURLToBlob=function(a){var b,c,d,e,f,g=";base64,";if(-1==a.indexOf(g))return b=a.split(","),c=b[0].split(":")[1],d=b[1],new Blob([d],{type:c});b=a.split(g),c=b[0].split(":")[1],d=window.atob(b[1]),e=d.length,f=new Uint8Array(e);for(var h=0;e>h;++h)f[h]=d.charCodeAt(h);return new Blob([f],{type:c})},EPUBJS.core.addScript=function(a,b,c){var d,e;e=!1,d=document.createElement("script"),d.type="text/javascript",d.async=!1,d.src=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.addScripts=function(a,b,c){var d=a.length,e=0,f=function(){e++,d==e?b&&b():EPUBJS.core.addScript(a[e],f,c)};EPUBJS.core.addScript(a[e],f,c)},EPUBJS.core.addCss=function(a,b,c){var d,e;e=!1,d=document.createElement("link"),d.type="text/css",d.rel="stylesheet",d.href=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.prefixed=function(a){var b=["Webkit","Moz","O","ms"],c=a[0].toUpperCase()+a.slice(1),d=b.length;if("undefined"!=typeof document.documentElement.style[a])return a;for(var e=0;d>e;e++)if("undefined"!=typeof document.documentElement.style[b[e]+c])return b[e]+c;return a},EPUBJS.core.resolveUrl=function(a,b){var c,d,e=[],f=EPUBJS.core.uri(b),g=a.split("/");return f.host?b:(g.pop(),d=b.split("/"),d.forEach(function(a){".."===a?g.pop():e.push(a)}),c=g.concat(e),c.join("/"))},EPUBJS.core.uuid=function(){var a=(new Date).getTime(),b="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(b){var c=(a+16*Math.random())%16|0;return a=Math.floor(a/16),("x"==b?c:7&c|8).toString(16)});return b},EPUBJS.core.insert=function(a,b,c){var d=EPUBJS.core.locationOf(a,b,c);return b.splice(d,0,a),d},EPUBJS.core.locationOf=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:b>a?-1:(a=b)?0:void 0}),0>=h-g?i:(f=c(b[i],a),h-g===1?f>0?i:i+1:0===f?i:-1===f?EPUBJS.core.locationOf(a,b,c,i,h):EPUBJS.core.locationOf(a,b,c,g,i))},EPUBJS.core.indexOfSorted=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:b>a?-1:(a=b)?0:void 0}),0>=h-g?-1:(f=c(b[i],a),h-g===1?0===f?i:-1:0===f?i:-1===f?EPUBJS.core.indexOfSorted(a,b,c,i,h):EPUBJS.core.indexOfSorted(a,b,c,g,i))},EPUBJS.core.queue=function(a){var b=[],c=a,d=function(a,c,d){return b.push({funcName:a,args:c,context:d}),b},e=function(){var a;b.length&&(a=b.shift(),c[a.funcName].apply(a.context||c,a.args))},f=function(){for(;b.length;)e()},g=function(){b=[]},h=function(){return b.length};return{enqueue:d,dequeue:e,flush:f,clear:g,length:h}},EPUBJS.core.getElementXPath=function(a){return a&&a.id?'//*[@id="'+a.id+'"]':EPUBJS.core.getElementTreeXPath(a)},EPUBJS.core.getElementTreeXPath=function(a){var b,c,d,e,f=[],g="http://www.w3.org/1999/xhtml"===a.ownerDocument.documentElement.getAttribute("xmlns");for(a.nodeType===Node.TEXT_NODE&&(b=EPUBJS.core.indexOfTextNode(a)+1,f.push("text()["+b+"]"),a=a.parentNode);a&&1==a.nodeType;a=a.parentNode){b=0;for(var h=a.previousSibling;h;h=h.previousSibling)h.nodeType!=Node.DOCUMENT_TYPE_NODE&&h.nodeName==a.nodeName&&++b;c=a.nodeName.toLowerCase(),d=g?"xhtml:"+c:c,e=b?"["+(b+1)+"]":"",f.splice(0,0,d+e)}return f.length?"./"+f.join("/"):null},EPUBJS.core.nsResolver=function(a){var b={xhtml:"http://www.w3.org/1999/xhtml",epub:"http://www.idpf.org/2007/ops"};return b[a]||null},EPUBJS.core.cleanStringForXpath=function(a){var b=a.match(/[^'"]+|['"]/g);return b=b.map(function(a){return"'"===a?'"\'"':'"'===a?"'\"'":"'"+a+"'"}),"concat('',"+b.join(",")+")"},EPUBJS.core.indexOfTextNode=function(a){for(var b,c=a.parentNode,d=c.childNodes,e=-1,f=0;fb;b++){var d=arguments[b];for(var e in d)void 0===a[e]&&(a[e]=d[e])}return a},EPUBJS.core.extend=function(a){var b=[].slice.call(arguments,1);return b.forEach(function(b){b&&Object.getOwnPropertyNames(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))})}),a},EPUBJS.core.clone=function(a){return EPUBJS.core.isArray(a)?a.slice():EPUBJS.core.extend({},a)},EPUBJS.core.isElement=function(a){return!(!a||1!=a.nodeType)},EPUBJS.core.isNumber=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},EPUBJS.core.isString=function(a){return"string"==typeof a||a instanceof String},EPUBJS.core.isArray=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},EPUBJS.core.values=function(a){var b,c,d,e=-1;if(!a)return[];for(b=Object.keys(a),c=b.length,d=Array(c);++e0;){if(c=d.shift(),"text"===c.type?(e=g.childNodes[c.index],g=e.parentNode||g):g=c.id?f.getElementById(c.id):h[c.index],"undefined"==typeof g)return console.error("No Element For",c,a.str),!1;h=Array.prototype.slice.call(g.children)}return g},EPUBJS.EpubCFI.prototype.compare=function(a,b){if("string"==typeof a&&(a=new EPUBJS.EpubCFI(a)),"string"==typeof b&&(b=new EPUBJS.EpubCFI(b)),a.spinePos>b.spinePos)return 1;if(a.spinePosb.steps[c].index)return 1;if(a.steps[c].indexb.characterOffset?1:a.characterOffset")},EPUBJS.EpubCFI.prototype.generateRangeFromCfi=function(a,b){var c,d,e,f,g,h,i=b||document,j=i.createRange();return"string"==typeof a&&(a=this.parse(a)),-1===a.spinePos?!1:(c=a.steps[a.steps.length-1],"undefined"!=typeof document.evaluate?(d=this.generateXpathFromSteps(a.steps),e=i.evaluate(d,i,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue):(g=this.generateQueryFromSteps(a.steps),h=i.querySelector(g),h&&"text"==c.type&&(e=h.childNodes[c.index])),e?(e&&a.characterOffset>=0?(f=e.length,a.characterOffset-1&&this.hooks[a].splice(c,1)):Array.isArray(b)&&b.forEach(function(b){c=this.hooks[a].indexOf(b),c>-1&&this.hooks[a].splice(c,1)},this))},a.prototype.triggerHooks=function(a,b,c){function d(){f--,0>=f&&b&&b()}var e,f;return"undefined"==typeof this.hooks[a]?!1:(e=this.hooks[a],f=e.length,0===f&&b&&b(),void e.forEach(function(a){a(d,c)}))},{register:function(a){if(void 0===EPUBJS.hooks[a]&&(EPUBJS.hooks[a]={}),"object"!=typeof EPUBJS.hooks[a])throw"Already registered: "+a;return EPUBJS.hooks[a]},mixin:function(b){for(var c in a.prototype)b[c]=a.prototype[c]}}}(),EPUBJS.Layout=EPUBJS.Layout||{},EPUBJS.Layout.Reflowable=function(){this.documentElement=null,this.spreadWidth=null},EPUBJS.Layout.Reflowable.prototype.format=function(a,b,c,d){var e=EPUBJS.core.prefixed("columnAxis"),f=EPUBJS.core.prefixed("columnGap"),g=EPUBJS.core.prefixed("columnWidth"),h=EPUBJS.core.prefixed("columnFill"),i=Math.floor(b),j=Math.floor(i/8),k=d>=0?d:j%2===0?j:j-1;return this.documentElement=a,this.spreadWidth=i+k,a.style.overflow="hidden",a.style.width=i+"px",a.style.height=c+"px",a.style[e]="horizontal",a.style[h]="auto",a.style[g]=i+"px",a.style[f]=k+"px",this.colWidth=i,this.gap=k,{pageWidth:this.spreadWidth,pageHeight:c}},EPUBJS.Layout.Reflowable.prototype.calculatePages=function(){var a,b;return this.documentElement.style.width="auto",a=this.documentElement.scrollWidth,b=Math.ceil(a/this.spreadWidth),{displayedPages:b,pageCount:b}},EPUBJS.Layout.ReflowableSpreads=function(){this.documentElement=null,this.spreadWidth=null},EPUBJS.Layout.ReflowableSpreads.prototype.format=function(a,b,c,d){var e=EPUBJS.core.prefixed("columnAxis"),f=EPUBJS.core.prefixed("columnGap"),g=EPUBJS.core.prefixed("columnWidth"),h=EPUBJS.core.prefixed("columnFill"),i=2,j=Math.floor(b),k=j%2===0?j:j-1,l=Math.floor(k/8),m=d>=0?d:l%2===0?l:l-1,n=Math.floor((k-m)/i);return this.documentElement=a,this.spreadWidth=(n+m)*i,a.style.overflow="hidden",a.style.width=k+"px",a.style.height=c+"px",a.style[e]="horizontal",a.style[h]="auto",a.style[f]=m+"px",a.style[g]=n+"px",this.colWidth=n,this.gap=m,{pageWidth:this.spreadWidth,pageHeight:c}},EPUBJS.Layout.ReflowableSpreads.prototype.calculatePages=function(){var a=this.documentElement.scrollWidth,b=Math.ceil(a/this.spreadWidth);return this.documentElement.style.width=b*this.spreadWidth-this.gap+"px",{displayedPages:b,pageCount:2*b}},EPUBJS.Layout.Fixed=function(){this.documentElement=null},EPUBJS.Layout.Fixed.prototype.format=function(a,b,c,d){var e,f,g,h,i=EPUBJS.core.prefixed("columnWidth"),j=a.querySelector("[name=viewport]");return this.documentElement=a,j&&j.hasAttribute("content")&&(e=j.getAttribute("content"),f=e.split(","),f[0]&&(g=f[0].replace("width=","")),f[1]&&(h=f[1].replace("height=",""))),a.style.width=g+"px"||"auto",a.style.height=h+"px"||"auto",a.style[i]="auto",a.style.overflow="auto",this.colWidth=g,this.gap=0,{pageWidth:g,pageHeight:h}},EPUBJS.Layout.Fixed.prototype.calculatePages=function(){return{displayedPages:1,pageCount:1}},EPUBJS.Locations=function(a,b,c){this.spine=a,this.store=b,this.credentials=c,this.epubcfi=new EPUBJS.EpubCFI,this._locations=[],this.total=0,this["break"]=150,this._current=0},EPUBJS.Locations.prototype.generate=function(a){var b,c=new RSVP.defer,d=-1,e=this.spine.length,f=function(a){var b,c=d+1,g=a||new RSVP.defer;return c>=e?g.resolve():(d=c,b=new EPUBJS.Chapter(this.spine[d],this.store,this.credentials),this.process(b).then(function(){setTimeout(function(){f(g)},1)})),g.promise}.bind(this);return"number"==typeof a&&(this["break"]=a),b=f().then(function(){this.total=this._locations.length-1,this._currentCfi&&(this.currentLocation=this._currentCfi),c.resolve(this._locations)}.bind(this)),c.promise},EPUBJS.Locations.prototype.process=function(a){return a.load().then(function(b){var c,d,e=b,f=e.documentElement.querySelector("body"),g=0;this.sprint(f,function(b){var f,h=b.length,i=0;for(0===g&&(c=e.createRange(),c.setStart(b,0)),f=this["break"]-g,f>h&&(g+=h,i=h);h>i;)g=this["break"],i+=this["break"],i>=h?g=h-(i-this["break"]):(c.setEnd(b,i),cfi=a.cfiFromRange(c),this._locations.push(cfi),g=0,i+=1,c=e.createRange(),c.setStart(b,i));d=b}.bind(this)),c&&(c.setEnd(d,d.length),cfi=a.cfiFromRange(c),this._locations.push(cfi),g=0)}.bind(this))},EPUBJS.Locations.prototype.sprint=function(a,b){for(var c=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,null,!1);node=c.nextNode();)b(node)},EPUBJS.Locations.prototype.locationFromCfi=function(a){return 0===this._locations.length?-1:EPUBJS.core.locationOf(a,this._locations,this.epubcfi.compare)},EPUBJS.Locations.prototype.percentageFromCfi=function(a){var b=this.locationFromCfi(a);return this.percentageFromLocation(b)},EPUBJS.Locations.prototype.percentageFromLocation=function(a){return a&&this.total?a/this.total:0},EPUBJS.Locations.prototype.cfiFromLocation=function(a){var b=-1;return"number"!=typeof a&&(a=parseInt(a)),a>=0&&a1?a/100:a,c=Math.ceil(this.total*b);return this.cfiFromLocation(c)},EPUBJS.Locations.prototype.load=function(a){return this._locations=JSON.parse(a),this.total=this._locations.length-1,this._locations},EPUBJS.Locations.prototype.save=function(a){return JSON.stringify(this._locations)},EPUBJS.Locations.prototype.getCurrent=function(a){return this._current},EPUBJS.Locations.prototype.setCurrent=function(a){var b;if("string"==typeof a)this._currentCfi=a;else{if("number"!=typeof a)return;this._current=a}0!==this._locations.length&&("string"==typeof a?(b=this.locationFromCfi(a),this._current=b):b=a,this.trigger("changed",{percentage:this.percentageFromLocation(b)}))},Object.defineProperty(EPUBJS.Locations.prototype,"currentLocation",{get:function(){return this._current},set:function(a){this.setCurrent(a)}}),RSVP.EventTarget.mixin(EPUBJS.Locations.prototype),EPUBJS.Pagination=function(a){this.pages=[],this.locations=[],this.epubcfi=new EPUBJS.EpubCFI,a&&a.length&&this.process(a)},EPUBJS.Pagination.prototype.process=function(a){a.forEach(function(a){this.pages.push(a.page),this.locations.push(a.cfi)},this),this.pageList=a,this.firstPage=parseInt(this.pages[0]),this.lastPage=parseInt(this.pages[this.pages.length-1]),this.totalPages=this.lastPage-this.firstPage},EPUBJS.Pagination.prototype.pageFromCfi=function(a){var b=-1;if(0===this.locations.length)return-1;var c=EPUBJS.core.indexOfSorted(a,this.locations,this.epubcfi.compare);return-1!=c&&c=0?this.pages[c-1]:this.pages[0],void 0!==b||(b=-1)),b},EPUBJS.Pagination.prototype.cfiFromPage=function(a){var b=-1;"number"!=typeof a&&(a=parseInt(a));var c=this.pages.indexOf(a);return-1!=c&&(b=this.locations[c]),b},EPUBJS.Pagination.prototype.pageFromPercentage=function(a){var b=Math.round(this.totalPages*a);return b},EPUBJS.Pagination.prototype.percentageFromPage=function(a){var b=(a-this.firstPage)/this.totalPages;return Math.round(1e3*b)/1e3},EPUBJS.Pagination.prototype.percentageFromCfi=function(a){var b=this.pageFromCfi(a),c=this.percentageFromPage(b);return c},EPUBJS.Parser=function(a){this.baseUrl=a||""},EPUBJS.Parser.prototype.container=function(a){var b,c,d,e;return a?(b=a.querySelector("rootfile"))?(c=b.getAttribute("full-path"),d=EPUBJS.core.uri(c).directory,e=a.xmlEncoding,{packagePath:c,basePath:d,encoding:e}):void console.error("No RootFile Found"):void console.error("Container File Not Found")},EPUBJS.Parser.prototype.identifier=function(a){var b;return a?(b=a.querySelector("metadata"),b?this.getElementText(b,"identifier"):void console.error("No Metadata Found")):void console.error("Package File Not Found")},EPUBJS.Parser.prototype.packageContents=function(a,b){var c,d,e,f,g,h,i,j,k,l,m,n=this;return b&&(this.baseUrl=b),a?(c=a.querySelector("metadata"))?(d=a.querySelector("manifest"))?(e=a.querySelector("spine"))?(f=n.manifest(d),g=n.findNavPath(d),h=n.findTocPath(d,e),i=n.findCoverPath(a),j=Array.prototype.indexOf.call(e.parentNode.childNodes,e),k=n.spine(e,f),l={},k.forEach(function(a){l[a.href]=a.index}),m=n.metadata(c),m.direction=e.getAttribute("page-progression-direction"),{metadata:m,spine:k,manifest:f,navPath:g,tocPath:h,coverPath:i,spineNodeIndex:j,spineIndexByURL:l}):void console.error("No Spine Found"):void console.error("No Manifest Found"):void console.error("No Metadata Found"):void console.error("Package File Not Found")},EPUBJS.Parser.prototype.findNavPath=function(a){var b=a.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']");return b?b.getAttribute("href"):!1},EPUBJS.Parser.prototype.findTocPath=function(a,b){var c,d=a.querySelector("item[media-type='application/x-dtbncx+xml']");return d||(c=b.getAttribute("toc"),c&&(d=a.querySelector("item[id='"+c+"']"))),d?d.getAttribute("href"):!1},EPUBJS.Parser.prototype.metadata=function(a){var b={},c=this;return b.bookTitle=c.getElementText(a,"title"),b.creator=c.getElementText(a,"creator"),b.description=c.getElementText(a,"description"),b.pubdate=c.getElementText(a,"date"),b.publisher=c.getElementText(a,"publisher"),b.identifier=c.getElementText(a,"identifier"),b.language=c.getElementText(a,"language"),b.rights=c.getElementText(a,"rights"),b.modified_date=c.querySelectorText(a,"meta[property='dcterms:modified']"),b.layout=c.querySelectorText(a,"meta[property='rendition:layout']"),b.orientation=c.querySelectorText(a,"meta[property='rendition:orientation']"),b.spread=c.querySelectorText(a,"meta[property='rendition:spread']"),b},EPUBJS.Parser.prototype.findCoverPath=function(a){var b=a.querySelector("package").getAttribute("version");if("2.0"===b){var c=a.querySelector('meta[name="cover"]');if(c){var d=c.getAttribute("content"),e=a.querySelector("item[id='"+d+"']");return e?e.getAttribute("href"):!1}return!1}var f=a.querySelector("item[properties='cover-image']");return f?f.getAttribute("href"):!1},EPUBJS.Parser.prototype.getElementText=function(a,b){var c,d=a.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/",b);return d&&0!==d.length?(c=d[0],c.childNodes.length?c.childNodes[0].nodeValue:""):""},EPUBJS.Parser.prototype.querySelectorText=function(a,b){var c=a.querySelector(b);return c&&c.childNodes.length?c.childNodes[0].nodeValue:""},EPUBJS.Parser.prototype.manifest=function(a){var b=this.baseUrl,c={},d=a.querySelectorAll("item"),e=Array.prototype.slice.call(d);return e.forEach(function(a){var d=a.getAttribute("id"),e=a.getAttribute("href")||"",f=a.getAttribute("media-type")||"",g=a.getAttribute("properties")||"";c[d]={href:e,url:b+e,type:f,properties:g}}),c},EPUBJS.Parser.prototype.spine=function(a,b){var c=[],d=a.getElementsByTagName("itemref"),e=Array.prototype.slice.call(d),f=Array.prototype.indexOf.call(a.parentNode.childNodes,a),g=new EPUBJS.EpubCFI; -return e.forEach(function(a,d){var e=a.getAttribute("idref"),h=g.generateChapterComponent(f,d,e),i=a.getAttribute("properties")||"",j=i.length?i.split(" "):[],k=b[e].properties,l=k.length?k.split(" "):[],m={id:e,linear:a.getAttribute("linear")||"",properties:j,manifestProperties:l,href:b[e].href,url:b[e].url,index:d,cfiBase:h,cfi:"epubcfi("+h+")"};c.push(m)}),c},EPUBJS.Parser.prototype.querySelectorByType=function(a,b,c){var d=a.querySelector(b+'[*|type="'+c+'"]');if(null!==d&&0!==d.length)return d;d=a.querySelectorAll(b);for(var e=0;ed;++d)e=this.navItem(h[d],b,c),j[e.id]=e,e.parent?(f=j[e.parent],f.subitems.push(e)):k.push(e);return k},EPUBJS.Parser.prototype.navItem=function(a,b,c){var d,e=a.getAttribute("id")||!1,f=a.querySelector("a, span"),g=f.getAttribute("href")||"",h=f.textContent||"",i=g.split("#"),j=i[0],k=b[j],l=c[k],m=[],n=a.parentNode,o=l?l.cfi:"";return n&&"navPoint"===n.nodeName&&(d=n.getAttribute("id")),e||(k?(l=c[k],e=l.id,o=l.cfi):(e="epubjs-autogen-toc-id-"+EPUBJS.core.uuid(),a.setAttribute("id",e))),{id:e,href:g,label:h,spinePos:k,subitems:m,parent:d,cfi:o}},EPUBJS.Parser.prototype.toc=function(a,b,c){var d,e,f,g=a.querySelectorAll("navMap navPoint"),h=g.length,i={},j=[];if(!g||0===h)return j;for(d=0;h>d;++d)e=this.tocItem(g[d],b,c),i[e.id]=e,e.parent?(f=i[e.parent],f.subitems.push(e)):j.push(e);return j},EPUBJS.Parser.prototype.tocItem=function(a,b,c){var d,e=a.getAttribute("id")||!1,f=a.querySelector("content"),g=f.getAttribute("src"),h=a.querySelector("navLabel"),i=h.textContent?h.textContent:"",j=g.split("#"),k=j[0],l=b[k],m=c[l],n=[],o=a.parentNode,p=m?m.cfi:"";return o&&"navPoint"===o.nodeName&&(d=o.getAttribute("id")),e||(l?(m=c[l],e=m.id,p=m.cfi):(e="epubjs-autogen-toc-id-"+EPUBJS.core.uuid(),a.setAttribute("id",e))),{id:e,href:g,label:i,spinePos:l,subitems:n,parent:d,cfi:p}},EPUBJS.Parser.prototype.pageList=function(a,b,c){var d,e,f=this.querySelectorByType(a,"nav","page-list"),g=f?f.querySelectorAll("ol li"):[],h=g.length,i=[];if(!g||0===h)return i;for(d=0;h>d;++d)e=this.pageListItem(g[d],b,c),i.push(e);return i},EPUBJS.Parser.prototype.pageListItem=function(a,b,c){var d,e,f,g=(a.getAttribute("id")||!1,a.querySelector("a")),h=g.getAttribute("href")||"",i=g.textContent||"",j=parseInt(i),k=h.indexOf("epubcfi");return-1!=k?(d=h.split("#"),e=d[0],f=d.length>1?d[1]:!1,{cfi:f,href:h,packageUrl:e,page:j}):{href:h,page:j}},EPUBJS.Render.Iframe=function(){this.iframe=null,this.document=null,this.window=null,this.docEl=null,this.bodyEl=null,this.leftPos=0,this.pageWidth=0},EPUBJS.Render.Iframe.prototype.create=function(){return this.iframe=document.createElement("iframe"),this.iframe.id="epubjs-iframe:"+EPUBJS.core.uuid(),this.iframe.scrolling="no",this.iframe.seamless="seamless",this.iframe.style.border="none",this.iframe.addEventListener("load",this.loaded.bind(this),!1),this.isMobile=navigator.userAgent.match(/(iPad|iPhone|iPod|Mobile|Android)/g),this.transform=EPUBJS.core.prefixed("transform"),this.iframe},EPUBJS.Render.Iframe.prototype.load=function(a,b){var c=this,d=new RSVP.defer;return this.window&&this.unload(),this.iframe.onload=function(a){c.document=c.iframe.contentDocument,c.docEl=c.document.documentElement,c.headEl=c.document.head,c.bodyEl=c.document.body||c.document.querySelector("body"),c.window=c.iframe.contentWindow,c.window.addEventListener("resize",c.resized.bind(c),!1),c.leftPos=0,c.setLeft(0),c.bodyEl&&(c.bodyEl.style.margin="0"),"rtl"==c.direction&&"rtl"!=c.docEl.dir&&(c.docEl.dir="rtl",c.docEl.style.position="absolute",c.docEl.style.right="0"),d.resolve(c.docEl)},this.iframe.onerror=function(a){d.reject({message:"Error Loading Contents: "+a,stack:(new Error).stack})},this.document=this.iframe.contentDocument,this.document?(this.document.open(),this.document.write(a),this.document.close(),d.promise):(d.reject(new Error("No Document Available")),d)},EPUBJS.Render.Iframe.prototype.loaded=function(a){var b,c,d=this.iframe.contentWindow.location.href;this.document=this.iframe.contentDocument,this.docEl=this.document.documentElement,this.headEl=this.document.head,this.bodyEl=this.document.body||this.document.querySelector("body"),this.window=this.iframe.contentWindow,"about:blank"!=d&&(b=this.iframe.contentDocument.querySelector("base"),c=b.getAttribute("href"),this.trigger("render:loaded",c))},EPUBJS.Render.Iframe.prototype.resize=function(a,b){this.iframe&&(this.iframe.height=b,isNaN(a)||a%2===0||(a+=1),this.iframe.width=a,this.width=this.iframe.getBoundingClientRect().width||a,this.height=this.iframe.getBoundingClientRect().height||b)},EPUBJS.Render.Iframe.prototype.resized=function(a){this.width=this.iframe.getBoundingClientRect().width,this.height=this.iframe.getBoundingClientRect().height},EPUBJS.Render.Iframe.prototype.totalWidth=function(){return this.docEl.scrollWidth},EPUBJS.Render.Iframe.prototype.totalHeight=function(){return this.docEl.scrollHeight},EPUBJS.Render.Iframe.prototype.setPageDimensions=function(a,b){this.pageWidth=a,this.pageHeight=b},EPUBJS.Render.Iframe.prototype.setDirection=function(a){this.direction=a,this.docEl&&"rtl"==this.docEl.dir&&(this.docEl.dir="rtl",this.docEl.style.position="static",this.docEl.style.right="auto")},EPUBJS.Render.Iframe.prototype.setLeft=function(a){this.isMobile?this.docEl.style[this.transform]="translate("+-a+"px, 0)":this.document.defaultView.scrollTo(a,0)},EPUBJS.Render.Iframe.prototype.setStyle=function(a,b,c){c&&(a=EPUBJS.core.prefixed(a)),this.bodyEl&&(this.bodyEl.style[a]=b)},EPUBJS.Render.Iframe.prototype.removeStyle=function(a){this.bodyEl&&(this.bodyEl.style[a]="")},EPUBJS.Render.Iframe.prototype.addHeadTag=function(a,b,c){var d=c||this.document,e=d.createElement(a),f=d.head;for(var g in b)e.setAttribute(g,b[g]);f&&f.insertBefore(e,f.firstChild)},EPUBJS.Render.Iframe.prototype.page=function(a){this.leftPos=this.pageWidth*(a-1),"rtl"===this.direction&&(this.leftPos=-1*this.leftPos),this.setLeft(this.leftPos)},EPUBJS.Render.Iframe.prototype.getPageNumberByElement=function(a){var b,c;if(a)return b=this.leftPos+a.getBoundingClientRect().left,c=Math.floor(b/this.pageWidth)+1},EPUBJS.Render.Iframe.prototype.getPageNumberByRect=function(a){var b,c;return b=this.leftPos+a.left,c=Math.floor(b/this.pageWidth)+1},EPUBJS.Render.Iframe.prototype.getBaseElement=function(){return this.bodyEl},EPUBJS.Render.Iframe.prototype.getDocumentElement=function(){return this.docEl},EPUBJS.Render.Iframe.prototype.isElementVisible=function(a){var b,c;return a&&"function"==typeof a.getBoundingClientRect&&(b=a.getBoundingClientRect(),c=b.left,0!==b.width&&0!==b.height&&c>=0&&c=1&&a<=this.displayedPages?(this.chapterPos=a,this.render.page(a),this.visibleRangeCfi=this.getVisibleRangeCfi(),this.currentLocationCfi=this.visibleRangeCfi.start,this.trigger("renderer:locationChanged",this.currentLocationCfi),this.trigger("renderer:visibleRangeChanged",this.visibleRangeCfi),!0):!1:(console.warn("pageMap not set, queuing"),this._q.enqueue("page",arguments),!0)},EPUBJS.Renderer.prototype.nextPage=function(){return this.page(this.chapterPos+1)},EPUBJS.Renderer.prototype.prevPage=function(){return this.page(this.chapterPos-1)},EPUBJS.Renderer.prototype.pageByElement=function(a){var b;a&&(b=this.render.getPageNumberByElement(a),this.page(b))},EPUBJS.Renderer.prototype.lastPage=function(){return this._moving?this._q.enqueue("lastPage",arguments):void this.page(this.displayedPages)},EPUBJS.Renderer.prototype.firstPage=function(){return this._moving?this._q.enqueue("firstPage",arguments):void this.page(1)},EPUBJS.Renderer.prototype.section=function(a){var b=this.doc.getElementById(a);b&&this.pageByElement(b)},EPUBJS.Renderer.prototype.firstElementisTextNode=function(a){var b=a.childNodes,c=b.length;return c&&b[0]&&3===b[0].nodeType&&b[0].textContent.trim().length?!0:!1},EPUBJS.Renderer.prototype.isGoodNode=function(a){var b=["audio","canvas","embed","iframe","img","math","object","svg","video"];return-1!==b.indexOf(a.tagName.toLowerCase())?!0:this.firstElementisTextNode(a)},EPUBJS.Renderer.prototype.walk=function(a,b,c){for(var d,e,f,g,h=a,i=[h],j=1e4,k=0;!d&&i.length;){if(a=i.shift(),this.containsPoint(a,b,c)&&this.isGoodNode(a)&&(d=a),!d&&a&&a.childElementCount>0){if(e=a.children,!e||!e.length)return d;f=e.length?e.length:0;for(var l=f-1;l>=0;l--)e[l]!=g&&i.unshift(e[l])}if(!d&&0===i.length&&h&&null!==h.parentNode&&(i.push(h.parentNode),g=h,h=h.parentNode),k++,k>j){console.error("ENDLESS LOOP");break}}return d},EPUBJS.Renderer.prototype.containsPoint=function(a,b,c){var d;return a&&"function"==typeof a.getBoundingClientRect&&(d=a.getBoundingClientRect(),0!==d.width&&0!==d.height&&d.left>=b&&b<=d.left+d.width)?!0:!1},EPUBJS.Renderer.prototype.textSprint=function(a,b){for(var c,d=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,{acceptNode:function(a){return/^\s*$/.test(a.data)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}},!1);c=d.nextNode();)b(c)},EPUBJS.Renderer.prototype.sprint=function(a,b){for(var c,d=document.createTreeWalker(a,NodeFilter.SHOW_ELEMENT,null,!1);c=d.nextNode();)b(c)},EPUBJS.Renderer.prototype.mapPage=function(){var a,b,c,d,e,f,g,h=this,i=[],j=this.render.getBaseElement(),k=1,l=this.layout.colWidth+this.layout.gap,m=this.formated.pageWidth*(this.chapterPos-1),n=l*k-m,o=0,p=function(b){var d,e,f;if(b.nodeType==Node.TEXT_NODE){if(e=document.createRange(),e.selectNodeContents(b),d=e.getBoundingClientRect(),!d||0===d.width&&0===d.height)return;d.left>o&&(f=q(b)),d.right>o&&(f=q(b)),c=b,f&&(a=null)}},q=function(d){var e,f,g=h.splitTextNodeIntoWordsRanges(d);return g.forEach(function(d){var g=d.getBoundingClientRect();!g||0===g.width&&0===g.height||(g.left+g.width0&&(b&&(b.setEnd(a,pos),c.push(b)),b=this.doc.createRange(),b.setStart(a,pos+1));return b&&(b.setEnd(a,d.length),c.push(b)),c},EPUBJS.Renderer.prototype.rangePosition=function(a){var b,c;return c=a.getClientRects(),c.length?b=c[0]:null},EPUBJS.Renderer.prototype.getPageCfi=function(){var a=2*this.chapterPos-1;return this.pageMap[a].start},EPUBJS.Renderer.prototype.getRange=function(a,b,c){var d,e=this.doc.createRange();return c=!0,"undefined"==typeof document.caretPositionFromPoint||c?"undefined"==typeof document.caretRangeFromPoint||c?(this.visibileEl=this.findElementAfter(a,b),e.setStart(this.visibileEl,1)):e=this.doc.caretRangeFromPoint(a,b):(d=this.doc.caretPositionFromPoint(a,b),e.setStart(d.offsetNode,d.offset)),e},EPUBJS.Renderer.prototype.pagesInCurrentChapter=function(){var a,b;return this.pageMap?(b=this.pageMap.length,a=this.spreads?Math.ceil(b/2):b):(console.warn("page map not loaded"),!1)},EPUBJS.Renderer.prototype.currentRenderedPage=function(){var a;return this.pageMap?a=this.spreads&&this.pageMap.length>1?2*this.chapterPos:this.chapterPos:(console.warn("page map not loaded"),!1)},EPUBJS.Renderer.prototype.getRenderedPagesLeft=function(){var a,b,c;return this.pageMap?(b=this.pageMap.length,a=this.spreads?2*this.chapterPos:this.chapterPos,c=b-a):(console.warn("page map not loaded"),!1)},EPUBJS.Renderer.prototype.getVisibleRangeCfi=function(){var a,b,c;return this.pageMap?(this.spreads?(a=2*this.chapterPos,b=this.pageMap[a-2],c=b,this.pageMap.length>1&&(c=this.pageMap[a-1])):(a=this.chapterPos,b=this.pageMap[a-1],c=b),b||(console.warn("page range miss:",a,this.pageMap),b=this.pageMap[this.pageMap.length-1],c=b),{start:b.start,end:c.end}):(console.warn("page map not loaded"),!1)},EPUBJS.Renderer.prototype.gotoCfi=function(a){var b,c,d;if(this._moving)return this._q.enqueue("gotoCfi",arguments);if(EPUBJS.core.isString(a)&&(a=this.epubcfi.parse(a)),"undefined"==typeof document.evaluate)c=this.epubcfi.addMarker(a,this.doc),c&&(b=this.render.getPageNumberByElement(c),this.epubcfi.removeMarker(c,this.doc),this.page(b));else if(d=this.epubcfi.generateRangeFromCfi(a,this.doc)){var e=d.getBoundingClientRect();b=e?this.render.getPageNumberByRect(e):1,this.page(b),this.currentLocationCfi=a.str}else this.page(1)},EPUBJS.Renderer.prototype.findFirstVisible=function(a){var b,c=a||this.render.getBaseElement();return b=this.walk(c,0,0),b?b:a},EPUBJS.Renderer.prototype.findElementAfter=function(a,b,c){var d,e=c||this.render.getBaseElement();return d=this.walk(e,a,b),d?d:e},EPUBJS.Renderer.prototype.resize=function(a,b,c){this.width=a,this.height=b,c!==!1&&this.render.resize(this.width,this.height),this.contents&&this.reformat(),this.trigger("renderer:resized",{width:this.width,height:this.height})},EPUBJS.Renderer.prototype.onResized=function(a){var b=this.container.clientWidth,c=this.container.clientHeight;this.resize(b,c,!1)},EPUBJS.Renderer.prototype.addEventListeners=function(){this.render.document&&this.listenedEvents.forEach(function(a){this.render.document.addEventListener(a,this.triggerEvent.bind(this),!1)},this)},EPUBJS.Renderer.prototype.removeEventListeners=function(){this.render.document&&this.listenedEvents.forEach(function(a){this.render.document.removeEventListener(a,this.triggerEvent,!1)},this)},EPUBJS.Renderer.prototype.triggerEvent=function(a){this.trigger("renderer:"+a.type,a)},EPUBJS.Renderer.prototype.addSelectionListeners=function(){this.render.document.addEventListener("selectionchange",this.onSelectionChange.bind(this),!1)},EPUBJS.Renderer.prototype.removeSelectionListeners=function(){this.render.document&&this.doc.removeEventListener("selectionchange",this.onSelectionChange,!1)},EPUBJS.Renderer.prototype.onSelectionChange=function(a){this.selectionEndTimeout&&clearTimeout(this.selectionEndTimeout),this.selectionEndTimeout=setTimeout(function(){this.selectedRange=this.render.window.getSelection(),this.trigger("renderer:selected",this.selectedRange)}.bind(this),500)},EPUBJS.Renderer.prototype.setMinSpreadWidth=function(a){this.minSpreadWidth=a,this.spreads=this.determineSpreads(a)},EPUBJS.Renderer.prototype.determineSpreads=function(a){return this.isForcedSingle||!a||this.width=g&&c&&c(!0),e=!0)};b(a,f)}.bind(this))},RSVP.EventTarget.mixin(EPUBJS.Renderer.prototype);var EPUBJS=EPUBJS||{};EPUBJS.replace={},EPUBJS.replace.hrefs=function(a,b){var c=this,d=function(a,d){var e,f,g,h,i,j=decodeURI(a.getAttribute("href")),k=j.search("://");-1!=k?a.setAttribute("target","_blank"):(g=b.render.docEl.querySelector("base"),i=g.getAttribute("href"),h=EPUBJS.core.uri(i),e=h.directory,f=e?"file"===h.protocol?EPUBJS.core.resolveUrl(h.base,j):EPUBJS.core.resolveUrl(e,j):j,a.onclick=function(){return c["goto"](f),!1}),d()};b.replace("a[href]",d,a)},EPUBJS.replace.head=function(a,b){b.replaceWithStored("link[href]","href",EPUBJS.replace.links,a)},EPUBJS.replace.resources=function(a,b){b.replaceWithStored("[src]","src",EPUBJS.replace.srcs,a)},EPUBJS.replace.svg=function(a,b){b.replaceWithStored("svg image","xlink:href",function(a,b,c){a.getUrl(b).then(c)},a)},EPUBJS.replace.srcs=function(a,b,c){a.getUrl(b).then(c)},EPUBJS.replace.links=function(a,b,c,d){"stylesheet"===d.getAttribute("rel")?EPUBJS.replace.stylesheets(a,b).then(function(a,b){c(a,b)},function(a){c(null)}):a.getUrl(b).then(c,function(a){c(null)})},EPUBJS.replace.stylesheets=function(a,b){var c=new RSVP.defer;if(a)return a.getText(b).then(function(d){EPUBJS.replace.cssUrls(a,b,d).then(function(a){var b=window.URL||window.webkitURL||window.mozURL,d=new Blob([a],{type:"text/css"}),e=b.createObjectURL(d);c.resolve(e)},function(a){c.reject(a)})},function(a){c.reject(a)}),c.promise},EPUBJS.replace.cssUrls=function(a,b,c){var d=new RSVP.defer,e=[],f=c.match(/url\(\'?\"?((?!data:)[^\'|^\"^\)]*)\'?\"?\)/g);if(a)return f?(f.forEach(function(f){var g=EPUBJS.core.resolveUrl(b,f.replace(/url\(|[|\)|\'|\"]|\?.*$/g,"")),h=a.getUrl(g).then(function(a){c=c.replace(f,'url("'+a+'")')},function(a){d.reject(a)});e.push(h)}),RSVP.all(e).then(function(){d.resolve(c)}),d.promise):(d.resolve(c),d.promise)},EPUBJS.Storage=function(a){this.checkRequirements(),this.urlCache={},this.withCredentials=a,this.URL=window.URL||window.webkitURL||window.mozURL,this.offline=!1},EPUBJS.Storage.prototype.checkRequirements=function(a){"undefined"==typeof localforage&&console.error("localForage library not loaded")},EPUBJS.Storage.prototype.put=function(a,b){var c=new RSVP.defer,d=a.length,e=0,f=function(b){var c,g,h=b||new RSVP.defer;return e>=d?h.resolve():(c=a[e].url,g=window.encodeURIComponent(c),EPUBJS.core.request(c,"binary").then(function(a){return localforage.setItem(g,a)}).then(function(a){e++,setTimeout(function(){f(h)},1)})),h.promise}.bind(this);return Array.isArray(a)||(a=[a]),f().then(function(){c.resolve()}.bind(this)),c.promise},EPUBJS.Storage.prototype.token=function(a,b){var c=window.encodeURIComponent(a);return localforage.setItem(c,b).then(function(a){return null===a?!1:!0})},EPUBJS.Storage.prototype.isStored=function(a){var b=window.encodeURIComponent(a);return localforage.getItem(b).then(function(a){return null===a?!1:!0})},EPUBJS.Storage.prototype.getText=function(a){var b=window.encodeURIComponent(a);return EPUBJS.core.request(a,"arraybuffer",this.withCredentials).then(function(a){return this.offline&&(this.offline=!1,this.trigger("offline",!1)),localforage.setItem(b,a),a}.bind(this)).then(function(b){var c=new RSVP.defer,d=EPUBJS.core.getMimeType(a),e=new Blob([b],{type:d}),f=new FileReader;return f.addEventListener("loadend",function(){c.resolve(f.result)}),f.readAsText(e,d),c.promise})["catch"](function(){var c=new RSVP.defer,d=localforage.getItem(b);return this.offline||(this.offline=!0,this.trigger("offline",!0)),d?(d.then(function(b){var d=EPUBJS.core.getMimeType(a),e=new Blob([b],{type:d}),f=new FileReader;f.addEventListener("loadend",function(){c.resolve(f.result)}),f.readAsText(e,d)}),c.promise):(c.reject({message:"File not found in the storage: "+a,stack:(new Error).stack}),c.promise)}.bind(this))},EPUBJS.Storage.prototype.getUrl=function(a){var b=window.encodeURIComponent(a);return EPUBJS.core.request(a,"arraybuffer",this.withCredentials).then(function(c){return this.offline&&(this.offline=!1,this.trigger("offline",!1)),localforage.setItem(b,c),a}.bind(this))["catch"](function(){var c,d,e=new RSVP.defer,f=window.URL||window.webkitURL||window.mozURL;return this.offline||(this.offline=!0,this.trigger("offline",!0)),b in this.urlCache?(e.resolve(this.urlCache[b]),e.promise):(c=localforage.getItem(b))?(c.then(function(c){var g=new Blob([c],{type:EPUBJS.core.getMimeType(a)});d=f.createObjectURL(g),e.resolve(d),this.urlCache[b]=d}.bind(this)),e.promise):(e.reject({message:"File not found in the storage: "+a,stack:(new Error).stack}),e.promise)}.bind(this))},EPUBJS.Storage.prototype.getXml=function(a){var b=window.encodeURIComponent(a);return EPUBJS.core.request(a,"arraybuffer",this.withCredentials).then(function(a){return this.offline&&(this.offline=!1,this.trigger("offline",!1)),localforage.setItem(b,a),a}.bind(this)).then(function(b){var c=new RSVP.defer,d=EPUBJS.core.getMimeType(a),e=new Blob([b],{type:d}),f=new FileReader;return f.addEventListener("loadend",function(){var a=new DOMParser,b=a.parseFromString(f.result,"text/xml");c.resolve(b)}),f.readAsText(e,d),c.promise})["catch"](function(){var c=new RSVP.defer,d=localforage.getItem(b);return this.offline||(this.offline=!0,this.trigger("offline",!0)),d?(d.then(function(b){var d=EPUBJS.core.getMimeType(a),e=new Blob([b],{type:d}),f=new FileReader;f.addEventListener("loadend",function(){var a=new DOMParser,b=a.parseFromString(f.result,"text/xml");c.resolve(b)}),f.readAsText(e,d)}),c.promise):(c.reject({message:"File not found in the storage: "+a,stack:(new Error).stack}),c.promise)}.bind(this))},EPUBJS.Storage.prototype.revokeUrl=function(a){var b=window.URL||window.webkitURL||window.mozURL,c=this.urlCache[a];c&&b.revokeObjectURL(c)},EPUBJS.Storage.prototype.failed=function(a){console.error(a)},RSVP.EventTarget.mixin(EPUBJS.Storage.prototype),EPUBJS.Unarchiver=function(a){this.checkRequirements(),this.urlCache={}},EPUBJS.Unarchiver.prototype.checkRequirements=function(a){"undefined"==typeof JSZip&&console.error("JSZip lib not loaded")},EPUBJS.Unarchiver.prototype.open=function(a,b){if(a instanceof ArrayBuffer){this.zip=new JSZip(a);var c=new RSVP.defer;return c.resolve(),c.promise}return EPUBJS.core.request(a,"binary").then(function(a){this.zip=new JSZip(a)}.bind(this))},EPUBJS.Unarchiver.prototype.getXml=function(a,b){var c=window.decodeURIComponent(a);return this.getText(c,b).then(function(b){var c=new DOMParser,d=EPUBJS.core.getMimeType(a);return c.parseFromString(b,d)})},EPUBJS.Unarchiver.prototype.getUrl=function(a,b){var c,d,e=this,f=new RSVP.defer,g=window.decodeURIComponent(a),h=this.zip.file(g),i=window.URL||window.webkitURL||window.mozURL;return h?a in this.urlCache?(f.resolve(this.urlCache[a]),f.promise):(d=new Blob([h.asUint8Array()],{type:EPUBJS.core.getMimeType(h.name)}),c=i.createObjectURL(d),f.resolve(c),e.urlCache[a]=c,f.promise):(f.reject({message:"File not found in the epub: "+a,stack:(new Error).stack}),f.promise)},EPUBJS.Unarchiver.prototype.getText=function(a,b){var c,d=new RSVP.defer,e=window.decodeURIComponent(a),f=this.zip.file(e);return f?(c=f.asText(),d.resolve(c),d.promise):(d.reject({message:"File not found in the epub: "+a,stack:(new Error).stack}),d.promise)},EPUBJS.Unarchiver.prototype.revokeUrl=function(a){var b=window.URL||window.webkitURL||window.mozURL,c=this.urlCache[a];c&&b.revokeObjectURL(c)},EPUBJS.Unarchiver.prototype.failed=function(a){console.error(a)},EPUBJS.Unarchiver.prototype.afterSaved=function(a){this.callback()},EPUBJS.Unarchiver.prototype.toStorage=function(a){function b(){f--,0===f&&e.afterSaved()}var c=0,d=20,e=this,f=a.length;a.forEach(function(a){setTimeout(function(a){e.saveEntryFileToStorage(a,b)},c,a),c+=d}),console.log("time",c)},function(){"use strict";var a={application:{ecmascript:["es","ecma"],javascript:"js",ogg:"ogx",pdf:"pdf",postscript:["ps","ai","eps","epsi","epsf","eps2","eps3"],"rdf+xml":"rdf",smil:["smi","smil"],"xhtml+xml":["xhtml","xht"],xml:["xml","xsl","xsd","opf"],zip:"zip","x-httpd-eruby":"rhtml","x-latex":"latex","x-maker":["frm","maker","frame","fm","fb","book","fbdoc"],"x-object":"o","x-shockwave-flash":["swf","swfl"],"x-silverlight":"scr","epub+zip":"epub","font-tdpfr":"pfr","inkml+xml":["ink","inkml"],json:"json","jsonml+json":"jsonml","mathml+xml":"mathml","metalink+xml":"metalink",mp4:"mp4s","omdoc+xml":"omdoc",oxps:"oxps","vnd.amazon.ebook":"azw",widget:"wgt","x-dtbncx+xml":"ncx","x-dtbook+xml":"dtb","x-dtbresource+xml":"res","x-font-bdf":"bdf","x-font-ghostscript":"gsf","x-font-linux-psf":"psf","x-font-otf":"otf","x-font-pcf":"pcf","x-font-snf":"snf","x-font-ttf":["ttf","ttc"],"x-font-type1":["pfa","pfb","pfm","afm"],"x-font-woff":"woff","x-mobipocket-ebook":["prc","mobi"],"x-mspublisher":"pub","x-nzb":"nzb","x-tgif":"obj","xaml+xml":"xaml","xml-dtd":"dtd","xproc+xml":"xpl","xslt+xml":"xslt","internet-property-stream":"acx","x-compress":"z","x-compressed":"tgz","x-gzip":"gz"},audio:{flac:"flac",midi:["mid","midi","kar","rmi"],mpeg:["mpga","mpega","mp2","mp3","m4a","mp2a","m2a","m3a"],mpegurl:"m3u",ogg:["oga","ogg","spx"],"x-aiff":["aif","aiff","aifc"],"x-ms-wma":"wma","x-wav":"wav",adpcm:"adp",mp4:"mp4a",webm:"weba","x-aac":"aac","x-caf":"caf","x-matroska":"mka","x-pn-realaudio-plugin":"rmp",xm:"xm",mid:["mid","rmi"]},image:{gif:"gif",ief:"ief",jpeg:["jpeg","jpg","jpe"],pcx:"pcx",png:"png","svg+xml":["svg","svgz"],tiff:["tiff","tif"],"x-icon":"ico",bmp:"bmp",webp:"webp","x-pict":["pic","pct"],"x-tga":"tga","cis-cod":"cod"},message:{ -rfc822:["eml","mime","mht","mhtml","nws"]},text:{"cache-manifest":["manifest","appcache"],calendar:["ics","icz","ifb"],css:"css",csv:"csv",h323:"323",html:["html","htm","shtml","stm"],iuls:"uls",mathml:"mml",plain:["txt","text","brf","conf","def","list","log","in","bas"],richtext:"rtx","tab-separated-values":"tsv","x-bibtex":"bib","x-dsrc":"d","x-diff":["diff","patch"],"x-haskell":"hs","x-java":"java","x-literate-haskell":"lhs","x-moc":"moc","x-pascal":["p","pas"],"x-pcs-gcd":"gcd","x-perl":["pl","pm"],"x-python":"py","x-scala":"scala","x-setext":"etx","x-tcl":["tcl","tk"],"x-tex":["tex","ltx","sty","cls"],"x-vcard":"vcf",sgml:["sgml","sgm"],"x-c":["c","cc","cxx","cpp","h","hh","dic"],"x-fortran":["f","for","f77","f90"],"x-opml":"opml","x-nfo":"nfo","x-sfv":"sfv","x-uuencode":"uu",webviewhtml:"htt"},video:{mpeg:["mpeg","mpg","mpe","m1v","m2v","mp2","mpa","mpv2"],mp4:["mp4","mp4v","mpg4"],quicktime:["qt","mov"],ogg:"ogv","vnd.mpegurl":["mxu","m4u"],"x-flv":"flv","x-la-asf":["lsf","lsx"],"x-mng":"mng","x-ms-asf":["asf","asx","asr"],"x-ms-wm":"wm","x-ms-wmv":"wmv","x-ms-wmx":"wmx","x-ms-wvx":"wvx","x-msvideo":"avi","x-sgi-movie":"movie","x-matroska":["mpv","mkv","mk3d","mks"],"3gpp2":"3g2",h261:"h261",h263:"h263",h264:"h264",jpeg:"jpgv",jpm:["jpm","jpgm"],mj2:["mj2","mjp2"],"vnd.ms-playready.media.pyv":"pyv","vnd.uvvu.mp4":["uvu","uvvu"],"vnd.vivo":"viv",webm:"webm","x-f4v":"f4v","x-m4v":"m4v","x-ms-vob":"vob","x-smv":"smv"}},b=function(){var b,c,d,e,f={};for(b in a)if(a.hasOwnProperty(b))for(c in a[b])if(a[b].hasOwnProperty(c))if(d=a[b][c],"string"==typeof d)f[d]=b+"/"+c;else for(e=0;e 1; - }; - - RSVP.filter(promises, filterFn).then(function(result){ - // result is [ 2, 3 ] - }); - ``` - - If any of the `promises` given to `RSVP.filter` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - var filterFn = function(item){ - return item > 1; - }; - - RSVP.filter(promises, filterFn).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === "2" - }); - ``` - - `RSVP.filter` will also wait for any promises returned from `filterFn`. - For instance, you may want to fetch a list of users then return a subset - of those users based on some asynchronous operation: - - ```javascript - - var alice = { name: 'alice' }; - var bob = { name: 'bob' }; - var users = [ alice, bob ]; - - var promises = users.map(function(user){ - return RSVP.resolve(user); - }); - - var filterFn = function(user){ - // Here, Alice has permissions to create a blog post, but Bob does not. - return getPrivilegesForUser(user).then(function(privs){ - return privs.can_create_blog_post === true; - }); - }; - RSVP.filter(promises, filterFn).then(function(users){ - // true, because the server told us only Alice can create a blog post. - users.length === 1; - // false, because Alice is the only user present in `users` - users[0] === bob; - }); - ``` - - @method filter - @for RSVP - @param {Array} promises - @param {Function} filterFn - function to be called on each resolved value to - filter the final results. - @param {String} label optional string describing the promise. Useful for - tooling. - @return {Promise} - */ - function filter(promises, filterFn, label) { - if (!isArray(promises)) { - throw new TypeError('You must pass an array to filter.'); - } - - if (!isFunction(filterFn)){ - throw new TypeError("You must pass a function to filter's second argument."); - } - - return all(promises, label).then(function(values){ - return map(promises, filterFn, label).then(function(filterResults){ - var i, - valuesLen = values.length, - filtered = []; - - for (i = 0; i < valuesLen; i++){ - if(filterResults[i]) filtered.push(values[i]); - } - return filtered; - }); - }); - } - - __exports__["default"] = filter; - }); -define("rsvp/hash", - ["./promise","./utils","exports"], - function(__dependency1__, __dependency2__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - var isNonThenable = __dependency2__.isNonThenable; - var keysOf = __dependency2__.keysOf; - - /** - `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array - for its `promises` argument. - - Returns a promise that is fulfilled when all the given promises have been - fulfilled, or rejected if any of them become rejected. The returned promise - is fulfilled with a hash that has the same key names as the `promises` object - argument. If any of the values in the object are not promises, they will - simply be copied over to the fulfilled object. - - Example: - - ```javascript - var promises = { - myPromise: RSVP.resolve(1), - yourPromise: RSVP.resolve(2), - theirPromise: RSVP.resolve(3), - notAPromise: 4 - }; - - RSVP.hash(promises).then(function(hash){ - // hash here is an object that looks like: - // { - // myPromise: 1, - // yourPromise: 2, - // theirPromise: 3, - // notAPromise: 4 - // } - }); - ```` - - If any of the `promises` given to `RSVP.hash` are rejected, the first promise - that is rejected will be given as as the first argument, or as the reason to - the rejection handler. For example: - - ```javascript - var promises = { - myPromise: RSVP.resolve(1), - rejectedPromise: RSVP.reject(new Error("rejectedPromise")), - anotherRejectedPromise: RSVP.reject(new Error("anotherRejectedPromise")), - }; - - RSVP.hash(promises).then(function(hash){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === "rejectedPromise" - }); - ``` - - An important note: `RSVP.hash` is intended for plain JavaScript objects that - are just a set of keys and values. `RSVP.hash` will NOT preserve prototype - chains. - - Example: - - ```javascript - function MyConstructor(){ - this.example = RSVP.resolve("Example"); - } - - MyConstructor.prototype = { - protoProperty: RSVP.resolve("Proto Property") - }; - - var myObject = new MyConstructor(); - - RSVP.hash(myObject).then(function(hash){ - // protoProperty will not be present, instead you will just have an - // object that looks like: - // { - // example: "Example" - // } - // - // hash.hasOwnProperty('protoProperty'); // false - // 'undefined' === typeof hash.protoProperty - }); - ``` - - @method hash - @for RSVP - @param {Object} promises - @param {String} label - optional string that describes the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all properties of `promises` - have been fulfilled, or rejected if any of them become rejected. - */ - __exports__["default"] = function hash(object, label) { - return new Promise(function(resolve, reject){ - var results = {}; - var keys = keysOf(object); - var remaining = keys.length; - var entry, property; - - if (remaining === 0) { - resolve(results); - return; - } - - function fulfilledTo(property) { - return function(value) { - results[property] = value; - if (--remaining === 0) { - resolve(results); - } - }; - } - - function onRejection(reason) { - remaining = 0; - reject(reason); - } - - for (var i = 0; i < keys.length; i++) { - property = keys[i]; - entry = object[property]; - - if (isNonThenable(entry)) { - results[property] = entry; - if (--remaining === 0) { - resolve(results); - } - } else { - Promise.cast(entry).then(fulfilledTo(property), onRejection); - } - } - }); - }; - }); -define("rsvp/instrument", - ["./config","./utils","exports"], - function(__dependency1__, __dependency2__, __exports__) { - "use strict"; - var config = __dependency1__.config; - var now = __dependency2__.now; - - __exports__["default"] = function instrument(eventName, promise, child) { - // instrumentation should not disrupt normal usage. - try { - config.trigger(eventName, { - guid: promise._guidKey + promise._id, - eventName: eventName, - detail: promise._detail, - childGuid: child && promise._guidKey + child._id, - label: promise._label, - timeStamp: now(), - stack: new Error(promise._label).stack - }); - } catch(error) { - setTimeout(function(){ - throw error; - }, 0); - } - }; - }); -define("rsvp/map", - ["./promise","./all","./utils","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - var all = __dependency2__["default"]; - var isArray = __dependency3__.isArray; - var isFunction = __dependency3__.isFunction; - - /** - - `RSVP.map` is similar to JavaScript's native `map` method, except that it - waits for all promises to become fulfilled before running the `mapFn` on - each item in given to `promises`. `RSVP.map` returns a promise that will - become fulfilled with the result of running `mapFn` on the values the promises - become fulfilled with. - - For example: - - ```javascript - - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - var mapFn = function(item){ - return item + 1; - }; - - RSVP.map(promises, mapFn).then(function(result){ - // result is [ 2, 3, 4 ] - }); - ``` - - If any of the `promises` given to `RSVP.map` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - var mapFn = function(item){ - return item + 1; - }; - - RSVP.map(promises, mapFn).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === "2" - }); - ``` - - `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, - say you want to get all comments from a set of blog posts, but you need - the blog posts first becuase they contain a url to those comments. - - ```javscript - - var mapFn = function(blogPost){ - // getComments does some ajax and returns an RSVP.Promise that is fulfilled - // with some comments data - return getComments(blogPost.comments_url); - }; - - // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled - // with some blog post data - RSVP.map(getBlogPosts(), mapFn).then(function(comments){ - // comments is the result of asking the server for the comments - // of all blog posts returned from getBlogPosts() - }); - ``` - - @method map - @for RSVP - @param {Array} promises - @param {Function} mapFn function to be called on each fulfilled promise. - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled with the result of calling - `mapFn` on each fulfilled promise or value when they become fulfilled. - The promise will be rejected if any of the given `promises` become rejected. - */ - __exports__["default"] = function map(promises, mapFn, label) { - - if (!isArray(promises)) { - throw new TypeError('You must pass an array to map.'); - } - - if (!isFunction(mapFn)){ - throw new TypeError("You must pass a function to map's second argument."); - } - - return all(promises, label).then(function(results){ - var resultLen = results.length, - mappedResults = [], - i; - - for (i = 0; i < resultLen; i++){ - mappedResults.push(mapFn(results[i])); - } - - return all(mappedResults, label); - }); - }; - }); -define("rsvp/node", - ["./promise","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - - var slice = Array.prototype.slice; - - function makeNodeCallbackFor(resolve, reject) { - return function (error, value) { - if (error) { - reject(error); - } else if (arguments.length > 2) { - resolve(slice.call(arguments, 1)); - } else { - resolve(value); - } - }; - } - - /** - `RSVP.denodeify` takes a "node-style" function and returns a function that - will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the - browser when you'd prefer to use promises over using callbacks. For example, - `denodeify` transforms the following: - - ```javascript - var fs = require('fs'); - - fs.readFile('myfile.txt', function(err, data){ - if (err) return handleError(err); - handleData(data); - }); - ``` - - into: - - ```javascript - var fs = require('fs'); - - var readFile = RSVP.denodeify(fs.readFile); - - readFile('myfile.txt').then(handleData, handleError); - ``` - - Using `denodeify` makes it easier to compose asynchronous operations instead - of using callbacks. For example, instead of: - - ```javascript - var fs = require('fs'); - var log = require('some-async-logger'); - - fs.readFile('myfile.txt', function(err, data){ - if (err) return handleError(err); - fs.writeFile('myfile2.txt', data, function(err){ - if (err) throw err; - log('success', function(err) { - if (err) throw err; - }); - }); - }); - ``` - - You can chain the operations together using `then` from the returned promise: - - ```javascript - var fs = require('fs'); - var denodeify = RSVP.denodeify; - var readFile = denodeify(fs.readFile); - var writeFile = denodeify(fs.writeFile); - var log = denodeify(require('some-async-logger')); - - readFile('myfile.txt').then(function(data){ - return writeFile('myfile2.txt', data); - }).then(function(){ - return log('SUCCESS'); - }).then(function(){ - // success handler - }, function(reason){ - // rejection handler - }); - ``` - - @method denodeify - @for RSVP - @param {Function} nodeFunc a "node-style" function that takes a callback as - its last argument. The callback expects an error to be passed as its first - argument (if an error occurred, otherwise null), and the value from the - operation as its second argument ("function(err, value){ }"). - @param {Any} binding optional argument for binding the "this" value when - calling the `nodeFunc` function. - @return {Function} a function that wraps `nodeFunc` to return an - `RSVP.Promise` - */ - __exports__["default"] = function denodeify(nodeFunc, binding) { - return function() { - var nodeArgs = slice.call(arguments), resolve, reject; - var thisArg = this || binding; - - return new Promise(function(resolve, reject) { - Promise.all(nodeArgs).then(function(nodeArgs) { - try { - nodeArgs.push(makeNodeCallbackFor(resolve, reject)); - nodeFunc.apply(thisArg, nodeArgs); - } catch(e) { - reject(e); - } - }); - }); - }; - }; - }); -define("rsvp/promise", - ["./config","./events","./instrument","./utils","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __exports__) { - "use strict"; - var config = __dependency1__.config; - var EventTarget = __dependency2__["default"]; - var instrument = __dependency3__["default"]; - var objectOrFunction = __dependency4__.objectOrFunction; - var isFunction = __dependency4__.isFunction; - var now = __dependency4__.now; - var cast = __dependency5__["default"]; - var all = __dependency6__["default"]; - var race = __dependency7__["default"]; - var Resolve = __dependency8__["default"]; - var Reject = __dependency9__["default"]; - - var guidKey = 'rsvp_' + now() + '-'; - var counter = 0; - - function noop() {} - - __exports__["default"] = Promise; - - - /** - - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]"); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} - @param {String} label optional string for labeling the promise. - Useful for tooling. - @constructor - */ - function Promise(resolver, label) { - if (!isFunction(resolver)) { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - if (!(this instanceof Promise)) { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - this._id = counter++; - this._label = label; - this._subscribers = []; - - if (config.instrument) { - instrument('created', this); - } - - if (noop !== resolver) { - invokeResolver(resolver, this); - } - } - - function invokeResolver(resolver, promise) { - function resolvePromise(value) { - resolve(promise, value); - } - - function rejectPromise(reason) { - reject(promise, reason); - } - - try { - resolver(resolvePromise, rejectPromise); - } catch(e) { - rejectPromise(e); - } - } - - Promise.cast = cast; - Promise.all = all; - Promise.race = race; - Promise.resolve = Resolve; - Promise.reject = Reject; - - var PENDING = void 0; - var SEALED = 0; - var FULFILLED = 1; - var REJECTED = 2; - - function subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - subscribers[length] = child; - subscribers[length + FULFILLED] = onFulfillment; - subscribers[length + REJECTED] = onRejection; - } - - function publish(promise, settled) { - var child, callback, subscribers = promise._subscribers, detail = promise._detail; - - if (config.instrument) { - instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); - } - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - invokeCallback(settled, child, callback, detail); - } - - promise._subscribers = null; - } - - Promise.prototype = { - /** - @property constructor - */ - constructor: Promise, - - _id: undefined, - _guidKey: guidKey, - _label: undefined, - - _state: undefined, - _detail: undefined, - _subscribers: undefined, - - _onerror: function (reason) { - config.trigger('error', reason); - }, - - /** - - A promise represents the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, "downstream" - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return "default name"; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `"default name"` - }); - - findUser().then(function (user) { - throw "Found user, but still unhappy"; - }, function (reason) { - throw "`findUser` rejected and we're unhappy"; - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be "Found user, but still unhappy". - // If `findUser` rejected, `reason` will be "`findUser` rejected and we're unhappy". - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException("Upstream error"); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javacsript - findResult().then(function(result){ - - }, function(reason){ - - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javacsript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong; - }); - ``` - - @method then - @param {Function} onFulfillment - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection, label) { - var promise = this; - this._onerror = null; - - var thenPromise = new this.constructor(noop, label); - - if (this._state) { - var callbacks = arguments; - config.async(function invokePromiseCallback() { - invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); - }); - } else { - subscribe(this, thenPromise, onFulfillment, onRejection); - } - - if (config.instrument) { - instrument('chained', promise, thenPromise); - } - - return thenPromise; - }, - - /** - `catch` is simply sugar for `then(null, onRejection)` which makes it the same - as the catch block, of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error("couldn't find that author"); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong; - }); - ``` - - @method catch - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection, label) { - return this.then(null, onRejection, label); - }, - - /** - `finally` will be invoked regardless of the promise's fate just as native - try/catch/finally behaves - - ```js - findAuthor() { - if (Math.random() > 0.5) { - throw new Error(); - } - return new Author(); - } - - try { - return findAuthor(); // succeed or fail - } catch(error) { - return findOtherAuther(); - } finally { - // always runs - // doesn't effect the return value - } - - findAuthor().finally(function(){ - // author was either found, or not - }); - ``` - - @method finally - @param {Function} callback - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - 'finally': function(callback, label) { - var constructor = this.constructor; - - return this.then(function(value) { - return constructor.cast(callback()).then(function(){ - return value; - }); - }, function(reason) { - return constructor.cast(callback()).then(function(){ - throw reason; - }); - }, label); - } - }; - - function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - try { - value = callback(detail); - succeeded = true; - } catch(e) { - failed = true; - error = e; - } - } else { - value = detail; - succeeded = true; - } - - if (handleThenable(promise, value)) { - return; - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - resolve(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } - } - - function handleThenable(promise, value) { - var then = null, - resolved; - - try { - if (promise === value) { - throw new TypeError("A promises callback cannot return that same promise."); - } - - if (objectOrFunction(value)) { - then = value.then; - - if (isFunction(then)) { - then.call(value, function(val) { - if (resolved) { return true; } - resolved = true; - - if (value !== val) { - resolve(promise, val); - } else { - fulfill(promise, val); - } - }, function(val) { - if (resolved) { return true; } - resolved = true; - - reject(promise, val); - }, 'derived from: ' + (promise._label || ' unknown promise')); - - return true; - } - } - } catch (error) { - if (resolved) { return true; } - reject(promise, error); - return true; - } - - return false; - } - - function resolve(promise, value) { - if (promise === value) { - fulfill(promise, value); - } else if (!handleThenable(promise, value)) { - fulfill(promise, value); - } - } - - function fulfill(promise, value) { - if (promise._state !== PENDING) { return; } - promise._state = SEALED; - promise._detail = value; - - config.async(publishFulfillment, promise); - } - - function reject(promise, reason) { - if (promise._state !== PENDING) { return; } - promise._state = SEALED; - promise._detail = reason; - - config.async(publishRejection, promise); - } - - function publishFulfillment(promise) { - publish(promise, promise._state = FULFILLED); - } - - function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._detail); - } - - publish(promise, promise._state = REJECTED); - } - }); -define("rsvp/promise/all", - ["../utils","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var isArray = __dependency1__.isArray; - var isNonThenable = __dependency1__.isNonThenable; - - /** - - `RSVP.Promise.all` returns a new promise which is fulfilled with an array of - fulfillment values for the passed promises, or rejects with the reason of the - first passed promise that rejects. It casts all elements of the passed iterable - to promises as it runs this algorithm. - - Example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `RSVP.all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @for RSVP.Promise - @param {Array} promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - */ - __exports__["default"] = function all(entries, label) { - - /*jshint validthis:true */ - var Constructor = this; - - return new Constructor(function(resolve, reject) { - if (!isArray(entries)) { - throw new TypeError('You must pass an array to all.'); - } - - var remaining = entries.length; - var results = new Array(remaining); - var entry, pending = true; - - if (remaining === 0) { - resolve(results); - return; - } - - function fulfillmentAt(index) { - return function(value) { - results[index] = value; - if (--remaining === 0) { - resolve(results); - } - }; - } - - function onRejection(reason) { - remaining = 0; - reject(reason); - } - - for (var index = 0; index < entries.length; index++) { - entry = entries[index]; - if (isNonThenable(entry)) { - results[index] = entry; - if (--remaining === 0) { - resolve(results); - } - } else { - Constructor.cast(entry).then(fulfillmentAt(index), onRejection); - } - } - }, label); - }; - }); -define("rsvp/promise/cast", - ["exports"], - function(__exports__) { - "use strict"; - /** - - `RSVP.Promise.cast` cast coerces its argument to a promise, or returns the - argument if it is already a promise which shares a constructor with the caster; - - Example: - - ```javascript - var promise = RSVP.Promise.resolve(1); - var casted = RSVP.Promise.cast(promise); - - console.log(promise === casted); // true - ``` - - In the case of a promise whose constructor does not match, it is assimilated. - The resulting promise will fulfill or reject based on the outcome of the - promise being casted. - - In the case of a non-promise, a promise which will fulfill with that value is - returned. - - Example: - - ```javascript - var value = 1; // could be a number, boolean, string, undefined... - var casted = RSVP.Promise.cast(value); - - console.log(value === casted); // false - console.log(casted instanceof RSVP.Promise) // true - - casted.then(function(val) { - val === value // => true - }); - ``` - - `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the - following ways: - - * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you - have something that could either be a promise or a value. RSVP.resolve - will have the same effect but will create a new promise wrapper if the - argument is a promise. - * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to - promises of the exact class specified, so that the resulting object's `then` is - ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). - - @method cast - @for RSVP.Promise - @param {Object} object to be casted - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise - */ - - __exports__["default"] = function cast(object, label) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - return new Constructor(function(resolve) { - resolve(object); - }, label); - }; - }); -define("rsvp/promise/race", - ["../utils","exports"], - function(__dependency1__, __exports__) { - "use strict"; - /* global toString */ - - var isArray = __dependency1__.isArray; - var isFunction = __dependency1__.isFunction; - var isNonThenable = __dependency1__.isNonThenable; - - /** - `RSVP.Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - var promise1 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve("promise 1"); - }, 200); - }); - - var promise2 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve("promise 2"); - }, 100); - }); - - RSVP.Promise.race([promise1, promise2]).then(function(result){ - // result === "promise 2" because it was resolved before promise1 - // was resolved. - }); - ``` - - `RSVP.Promise.race` is deterministic in that only the state of the first - completed promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first completed promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - var promise1 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve("promise 1"); - }, 200); - }); - - var promise2 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error("promise 2")); - }, 100); - }); - - RSVP.Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs because there are rejected promises! - }, function(reason){ - // reason.message === "promise2" because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - @method race - @for RSVP.Promise - @param {Array} promises array of promises to observe - @param {String} label optional string for describing the promise returned. - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. - */ - __exports__["default"] = function race(entries, label) { - /*jshint validthis:true */ - var Constructor = this, entry; - - return new Constructor(function(resolve, reject) { - if (!isArray(entries)) { - throw new TypeError('You must pass an array to race.'); - } - - var pending = true; - - function onFulfillment(value) { if (pending) { pending = false; resolve(value); } } - function onRejection(reason) { if (pending) { pending = false; reject(reason); } } - - for (var i = 0; i < entries.length; i++) { - entry = entries[i]; - if (isNonThenable(entry)) { - pending = false; - resolve(entry); - return; - } else { - Constructor.cast(entry).then(onFulfillment, onRejection); - } - } - }, label); - }; - }); -define("rsvp/promise/reject", - ["exports"], - function(__exports__) { - "use strict"; - /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. - It is essentially shorthand for the following: - - ```javascript - var promise = new RSVP.Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = RSVP.Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @for RSVP.Promise - @param {Any} reason value that the returned promise will be rejected with. - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. - */ - __exports__["default"] = function reject(reason, label) { - /*jshint validthis:true */ - var Constructor = this; - - return new Constructor(function (resolve, reject) { - reject(reason); - }, label); - }; - }); -define("rsvp/promise/resolve", - ["exports"], - function(__exports__) { - "use strict"; - /** - `RSVP.Promise.resolve` returns a promise that will become fulfilled with the passed - `value`. It is essentially shorthand for the following: - - ```javascript - var promise = new RSVP.Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = RSVP.Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @for RSVP.Promise - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - __exports__["default"] = function resolve(value, label) { - /*jshint validthis:true */ - var Constructor = this; - - return new Constructor(function(resolve, reject) { - resolve(value); - }, label); - }; - }); -define("rsvp/race", - ["./promise","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - - __exports__["default"] = function race(array, label) { - return Promise.race(array, label); - }; - }); -define("rsvp/reject", - ["./promise","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - - __exports__["default"] = function reject(reason, label) { - return Promise.reject(reason, label); - }; - }); -define("rsvp/resolve", - ["./promise","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - - __exports__["default"] = function resolve(value, label) { - return Promise.resolve(value, label); - }; - }); -define("rsvp/rethrow", - ["exports"], - function(__exports__) { - "use strict"; - /** - `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event - loop in order to aid debugging. - - Promises A+ specifies that any exceptions that occur with a promise must be - caught by the promises implementation and bubbled to the last handler. For - this reason, it is recommended that you always specify a second rejection - handler function to `then`. However, `RSVP.rethrow` will throw the exception - outside of the promise, so it bubbles up to your console if in the browser, - or domain/cause uncaught exception in Node. `rethrow` will throw the error - again so the error can be handled by the promise. - - ```javascript - function throws(){ - throw new Error('Whoops!'); - } - - var promise = new RSVP.Promise(function(resolve, reject){ - throws(); - }); - - promise.catch(RSVP.rethrow).then(function(){ - // Code here doesn't run because the promise became rejected due to an - // error! - }, function (err){ - // handle the error here - }); - ``` - - The 'Whoops' error will be thrown on the next turn of the event loop - and you can watch for it in your console. You can also handle it using a - rejection handler given to `.then` or `.catch` on the returned promise. - - @method rethrow - @for RSVP - @param {Error} reason reason the promise became rejected. - @throws Error - */ - __exports__["default"] = function rethrow(reason) { - setTimeout(function() { - throw reason; - }); - throw reason; - }; - }); -define("rsvp/utils", - ["exports"], - function(__exports__) { - "use strict"; - function objectOrFunction(x) { - return typeof x === "function" || (typeof x === "object" && x !== null); - } - - __exports__.objectOrFunction = objectOrFunction;function isFunction(x) { - return typeof x === "function"; - } - - __exports__.isFunction = isFunction;function isNonThenable(x) { - return !objectOrFunction(x); - } - - __exports__.isNonThenable = isNonThenable;function isArray(x) { - return Object.prototype.toString.call(x) === "[object Array]"; - } - - __exports__.isArray = isArray;// Date.now is not available in browsers < IE9 - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility - var now = Date.now || function() { return new Date().getTime(); }; - __exports__.now = now; - var keysOf = Object.keys || function(object) { - var result = []; - - for (var prop in object) { - result.push(prop); - } - - return result; - }; - __exports__.keysOf = keysOf; - }); -define("rsvp", - ["./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all_settled","./rsvp/race","./rsvp/hash","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/asap","./rsvp/filter","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __exports__) { - "use strict"; - var Promise = __dependency1__["default"]; - var EventTarget = __dependency2__["default"]; - var denodeify = __dependency3__["default"]; - var all = __dependency4__["default"]; - var allSettled = __dependency5__["default"]; - var race = __dependency6__["default"]; - var hash = __dependency7__["default"]; - var rethrow = __dependency8__["default"]; - var defer = __dependency9__["default"]; - var config = __dependency10__.config; - var configure = __dependency10__.configure; - var map = __dependency11__["default"]; - var resolve = __dependency12__["default"]; - var reject = __dependency13__["default"]; - var asap = __dependency14__["default"]; - var filter = __dependency15__["default"]; - - config.async = asap; // default async is asap; - - function async(callback, arg) { - config.async(callback, arg); - } - - function on() { - config.on.apply(config, arguments); - } - - function off() { - config.off.apply(config, arguments); - } - - // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` - if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') { - var callbacks = window.__PROMISE_INSTRUMENTATION__; - configure('instrument', true); - for (var eventName in callbacks) { - if (callbacks.hasOwnProperty(eventName)) { - on(eventName, callbacks[eventName]); - } - } - } - - __exports__.Promise = Promise; - __exports__.EventTarget = EventTarget; - __exports__.all = all; - __exports__.allSettled = allSettled; - __exports__.race = race; - __exports__.hash = hash; - __exports__.rethrow = rethrow; - __exports__.defer = defer; - __exports__.denodeify = denodeify; - __exports__.configure = configure; - __exports__.on = on; - __exports__.off = off; - __exports__.resolve = resolve; - __exports__.reject = reject; - __exports__.async = async; - __exports__.map = map; - __exports__.filter = filter; - }); -global.RSVP = requireModule('rsvp'); -}(window)); -'use strict'; - -var EPUBJS = EPUBJS || {}; -EPUBJS.VERSION = "0.2.7"; - -EPUBJS.plugins = EPUBJS.plugins || {}; - -EPUBJS.filePath = EPUBJS.filePath || "/epubjs/"; - -EPUBJS.Render = {}; - -(function(root) { - - var previousEpub = root.ePub || {}; - - var ePub = root.ePub = function() { - var bookPath, options; - - //-- var book = ePub("path/to/book.epub", { restore: true }) - if(typeof(arguments[0]) != 'undefined' && - typeof arguments[0] === 'string') { - - bookPath = arguments[0]; - - if( arguments[1] && typeof arguments[1] === 'object' ) { - options = arguments[1]; - options.bookPath = bookPath; - } else { - options = { 'bookPath' : bookPath }; - } - - } - - /* - * var book = ePub({ bookPath: "path/to/book.epub", restore: true }); - * - * - OR - - * - * var book = ePub({ restore: true }); - * book.open("path/to/book.epub"); - */ - - if( arguments[0] && typeof arguments[0] === 'object' ) { - options = arguments[0]; - } - - - return new EPUBJS.Book(options); - }; - - EPUBJS.core.extend(ePub, { - noConflict : function() { - root.ePub = previousEpub; - return this; - } - }); - - //exports to multiple environments - if (typeof define === 'function' && define.amd) - //AMD - define(function(){ return ePub; }); - else if (typeof module != "undefined" && module.exports) - //Node - module.exports = ePub; - -})(window); - -EPUBJS.Book = function(options){ - - var book = this; - - this.settings = EPUBJS.core.defaults(options || {}, { - bookPath : null, - bookKey : null, - packageUrl : null, - storage: false, //-- true (auto) or false (none) | override: 'ram', 'websqldatabase', 'indexeddb', 'filesystem' - fromStorage : false, - saved : false, - online : true, - contained : false, - width : null, - height: null, - layoutOveride : null, // Default: { spread: 'reflowable', layout: 'auto', orientation: 'auto'} - orientation : null, - minSpreadWidth: 800, //-- overridden by spread: none (never) / both (always) - gap: "auto", //-- "auto" or int - version: 1, - restore: false, - reload : false, - goto : false, - styles : {}, - headTags : {}, - withCredentials: false, - render_method: "Iframe" - }); - - this.settings.EPUBJSVERSION = EPUBJS.VERSION; - - this.spinePos = 0; - this.stored = false; - - //-- All Book events for listening - /* - book:ready - book:stored - book:online - book:offline - book:pageChanged - book:loadFailed - book:loadChapterFailed - */ - - //-- Adds Hook methods to the Book prototype - // Hooks will all return before triggering the callback. - // EPUBJS.Hooks.mixin(this); - //-- Get pre-registered hooks for events - // this.getHooks("beforeChapterDisplay"); - - this.online = this.settings.online || navigator.onLine; - this.networkListeners(); - - this.ready = { - manifest: new RSVP.defer(), - spine: new RSVP.defer(), - metadata: new RSVP.defer(), - cover: new RSVP.defer(), - toc: new RSVP.defer(), - pageList: new RSVP.defer() - }; - - this.readyPromises = [ - this.ready.manifest.promise, - this.ready.spine.promise, - this.ready.metadata.promise, - this.ready.cover.promise, - this.ready.toc.promise - ]; - - this.pageList = []; - this.pagination = new EPUBJS.Pagination(); - this.pageListReady = this.ready.pageList.promise; - - this.ready.all = RSVP.all(this.readyPromises); - - this.ready.all.then(this._ready.bind(this)); - - // Queue for methods used before rendering - this.isRendered = false; - this._q = EPUBJS.core.queue(this); - // Queue for rendering - this._rendering = false; - this._displayQ = EPUBJS.core.queue(this); - // Queue for going to another location - this._moving = false; - this._gotoQ = EPUBJS.core.queue(this); - - /** - * Creates a new renderer. - * The renderer will handle displaying the content using the method provided in the settings - */ - this.renderer = new EPUBJS.Renderer(this.settings.render_method); - //-- Set the width at which to switch from spreads to single pages - this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); - this.renderer.setGap(this.settings.gap); - //-- Pass through the renderer events - this.listenToRenderer(this.renderer); - - this.defer_opened = new RSVP.defer(); - this.opened = this.defer_opened.promise; - - this.store = false; //-- False if not using storage; - - //-- Determine storage method - //-- Override options: none | ram | websqldatabase | indexeddb | filesystem - if(this.settings.storage !== false){ - // this.storage = new fileStorage.storage(this.settings.storage); - this.fromStorage(true); - } - - // BookUrl is optional, but if present start loading process - if(typeof this.settings.bookPath === 'string') { - this.open(this.settings.bookPath, this.settings.reload); - } - - window.addEventListener("beforeunload", this.unload.bind(this), false); - - //-- Listen for these promises: - //-- book.opened.then() - //-- book.rendered.then() -}; - -//-- Check bookUrl and start parsing book Assets or load them from storage -EPUBJS.Book.prototype.open = function(bookPath, forceReload){ - var book = this, - epubpackage, - opened = new RSVP.defer(); - - this.settings.bookPath = bookPath; - - //-- Get a absolute URL from the book path - this.bookUrl = this.urlFrom(bookPath); - - if(this.settings.contained || this.isContained(bookPath)){ - - this.settings.contained = this.contained = true; - - this.bookUrl = ''; - - epubpackage = this.unarchive(bookPath). - then(function(){ - return book.loadPackage(); - }); - - } else { - epubpackage = this.loadPackage(); - } - - if(this.settings.restore && !forceReload && localStorage){ - //-- Will load previous package json, or re-unpack if error - epubpackage.then(function(packageXml) { - var identifier = book.packageIdentifier(packageXml); - var restored = book.restore(identifier); - - if(!restored) { - book.unpack(packageXml); - } - opened.resolve(); - book.defer_opened.resolve(); - }); - - }else{ - - //-- Get package information from epub opf - epubpackage.then(function(packageXml) { - book.unpack(packageXml); - opened.resolve(); - book.defer_opened.resolve(); - }); - } - - this._registerReplacements(this.renderer); - - return opened.promise; - -}; - -EPUBJS.Book.prototype.loadPackage = function(_containerPath){ - var book = this, - parse = new EPUBJS.Parser(), - containerPath = _containerPath || "META-INF/container.xml", - containerXml, - packageXml; - - if(!this.settings.packageUrl) { //-- provide the packageUrl to skip this step - packageXml = book.loadXml(book.bookUrl + containerPath). - then(function(containerXml){ - return parse.container(containerXml); // Container has path to content - }). - then(function(paths){ - book.settings.contentsPath = book.bookUrl + paths.basePath; - book.settings.packageUrl = book.bookUrl + paths.packagePath; - book.settings.encoding = paths.encoding; - return book.loadXml(book.settings.packageUrl); // Containes manifest, spine and metadata - }); - } else { - packageXml = book.loadXml(book.settings.packageUrl); - } - - packageXml.catch(function(error) { - // handle errors in either of the two requests - console.error("Could not load book at: "+ containerPath); - book.trigger("book:loadFailed", containerPath); - }); - return packageXml; -}; - -EPUBJS.Book.prototype.packageIdentifier = function(packageXml){ - var book = this, - parse = new EPUBJS.Parser(); - - return parse.identifier(packageXml); -}; - -EPUBJS.Book.prototype.unpack = function(packageXml){ - var book = this, - parse = new EPUBJS.Parser(); - - book.contents = parse.packageContents(packageXml, book.settings.contentsPath); // Extract info from contents - - book.manifest = book.contents.manifest; - book.spine = book.contents.spine; - book.spineIndexByURL = book.contents.spineIndexByURL; - book.metadata = book.contents.metadata; - if(!book.settings.bookKey) { - book.settings.bookKey = book.generateBookKey(book.metadata.identifier); - } - - //-- Set Globbal Layout setting based on metadata - book.globalLayoutProperties = book.parseLayoutProperties(book.metadata); - - if(book.contents.coverPath) { - book.cover = book.contents.cover = book.settings.contentsPath + book.contents.coverPath; - } - - book.spineNodeIndex = book.contents.spineNodeIndex; - - book.ready.manifest.resolve(book.contents.manifest); - book.ready.spine.resolve(book.contents.spine); - book.ready.metadata.resolve(book.contents.metadata); - book.ready.cover.resolve(book.contents.cover); - - book.locations = new EPUBJS.Locations(book.spine); - - //-- Load the TOC, optional; either the EPUB3 XHTML Navigation file or the EPUB2 NCX file - if(book.contents.navPath) { - book.settings.navUrl = book.settings.contentsPath + book.contents.navPath; - - book.loadXml(book.settings.navUrl). - then(function(navHtml){ - return parse.nav(navHtml, book.spineIndexByURL, book.spine); // Grab Table of Contents - }).then(function(toc){ - book.toc = book.contents.toc = toc; - book.ready.toc.resolve(book.contents.toc); - }, function(error) { - book.ready.toc.resolve(false); - }); - - // Load the optional pageList - book.loadXml(book.settings.navUrl). - then(function(navHtml){ - return parse.pageList(navHtml, book.spineIndexByURL, book.spine); - }).then(function(pageList){ - var epubcfi = new EPUBJS.EpubCFI(); - var wait = 0; // need to generate a cfi - - // No pageList found - if(pageList.length === 0) { - return; - } - - book.pageList = book.contents.pageList = pageList; - - // Replace HREFs with CFI - book.pageList.forEach(function(pg){ - if(!pg.cfi) { - wait += 1; - epubcfi.generateCfiFromHref(pg.href, book).then(function(cfi){ - pg.cfi = cfi; - pg.packageUrl = book.settings.packageUrl; - - wait -= 1; - if(wait === 0) { - book.pagination.process(book.pageList); - book.ready.pageList.resolve(book.pageList); - } - }); - } - }); - - if(!wait) { - book.pagination.process(book.pageList); - book.ready.pageList.resolve(book.pageList); - } - - }, function(error) { - book.ready.pageList.resolve([]); - }); - } else if(book.contents.tocPath) { - book.settings.tocUrl = book.settings.contentsPath + book.contents.tocPath; - - book.loadXml(book.settings.tocUrl). - then(function(tocXml){ - return parse.toc(tocXml, book.spineIndexByURL, book.spine); // Grab Table of Contents - }).then(function(toc){ - book.toc = book.contents.toc = toc; - book.ready.toc.resolve(book.contents.toc); - }, function(error) { - book.ready.toc.resolve(false); - }); - - } else { - book.ready.toc.resolve(false); - } - -}; - -EPUBJS.Book.prototype.createHiddenRender = function(renderer, _width, _height) { - var box = this.element.getBoundingClientRect(); - var width = _width || this.settings.width || box.width; - var height = _height || this.settings.height || box.height; - var hiddenContainer; - var hiddenEl; - renderer.setMinSpreadWidth(this.settings.minSpreadWidth); - renderer.setGap(this.settings.gap); - - this._registerReplacements(renderer); - if(this.settings.forceSingle) { - renderer.forceSingle(true); - } - - hiddenContainer = document.createElement("div"); - hiddenContainer.style.visibility = "hidden"; - hiddenContainer.style.overflow = "hidden"; - hiddenContainer.style.width = "0"; - hiddenContainer.style.height = "0"; - this.element.appendChild(hiddenContainer); - - hiddenEl = document.createElement("div"); - hiddenEl.style.visibility = "hidden"; - hiddenEl.style.overflow = "hidden"; - hiddenEl.style.width = width + "px";//"0"; - hiddenEl.style.height = height +"px"; //"0"; - hiddenContainer.appendChild(hiddenEl); - - renderer.initialize(hiddenEl); - return hiddenContainer; -}; - -// Generates the pageList array by loading every chapter and paging through them -EPUBJS.Book.prototype.generatePageList = function(width, height){ - var pageList = []; - var pager = new EPUBJS.Renderer(this.settings.render_method, false); //hidden - var hiddenContainer = this.createHiddenRender(pager, width, height); - var deferred = new RSVP.defer(); - var spinePos = -1; - var spineLength = this.spine.length; - var totalPages = 0; - var currentPage = 0; - var nextChapter = function(deferred){ - var chapter; - var next = spinePos + 1; - var done = deferred || new RSVP.defer(); - var loaded; - if(next >= spineLength) { - done.resolve(); - } else { - spinePos = next; - chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); - pager.displayChapter(chapter, this.globalLayoutProperties).then(function(chap){ - pager.pageMap.forEach(function(item){ - currentPage += 1; - pageList.push({ - "cfi" : item.start, - "page" : currentPage - }); - - }); - - if(pager.pageMap.length % 2 > 0 && - pager.spreads) { - currentPage += 1; // Handle Spreads - pageList.push({ - "cfi" : pager.pageMap[pager.pageMap.length - 1].end, - "page" : currentPage - }); - } - - // Load up the next chapter - setTimeout(function(){ - nextChapter(done); - }, 1); - }); - } - return done.promise; - }.bind(this); - - var finished = nextChapter().then(function(){ - pager.remove(); - this.element.removeChild(hiddenContainer); - deferred.resolve(pageList); - }.bind(this)); - - return deferred.promise; -}; - -// Render out entire book and generate the pagination -// Width and Height are optional and will default to the current dimensions -EPUBJS.Book.prototype.generatePagination = function(width, height) { - var book = this; - var defered = new RSVP.defer(); - - this.ready.spine.promise.then(function(){ - book.generatePageList(width, height).then(function(pageList){ - book.pageList = book.contents.pageList = pageList; - book.pagination.process(pageList); - book.ready.pageList.resolve(book.pageList); - defered.resolve(book.pageList); - }); - }); - - return defered.promise; -}; - -// Process the pagination from a JSON array containing the pagelist -EPUBJS.Book.prototype.loadPagination = function(pagelistJSON) { - var pageList = JSON.parse(pagelistJSON); - - if(pageList && pageList.length) { - this.pageList = pageList; - this.pagination.process(this.pageList); - this.ready.pageList.resolve(this.pageList); - } - return this.pageList; -}; - -EPUBJS.Book.prototype.getPageList = function() { - return this.ready.pageList.promise; -}; - -EPUBJS.Book.prototype.getMetadata = function() { - return this.ready.metadata.promise; -}; - -EPUBJS.Book.prototype.getToc = function() { - return this.ready.toc.promise; -}; - -/* Private Helpers */ - -//-- Listeners for browser events -EPUBJS.Book.prototype.networkListeners = function(){ - var book = this; - window.addEventListener("offline", function(e) { - book.online = false; - if (book.settings.storage) { - book.fromStorage(true); - } - book.trigger("book:offline"); - }, false); - - window.addEventListener("online", function(e) { - book.online = true; - if (book.settings.storage) { - book.fromStorage(false); - } - book.trigger("book:online"); - }, false); - -}; - -// Listen to all events the renderer triggers and pass them as book events -EPUBJS.Book.prototype.listenToRenderer = function(renderer){ - var book = this; - renderer.Events.forEach(function(eventName){ - renderer.on(eventName, function(e){ - book.trigger(eventName, e); - }); - }); - - renderer.on("renderer:visibleRangeChanged", function(range) { - var startPage, endPage, percent; - var pageRange = []; - - if(this.pageList.length > 0) { - startPage = this.pagination.pageFromCfi(range.start); - percent = this.pagination.percentageFromPage(startPage); - pageRange.push(startPage); - - if(range.end) { - endPage = this.pagination.pageFromCfi(range.end); - //if(startPage != endPage) { - pageRange.push(endPage); - //} - } - this.trigger("book:pageChanged", { - "anchorPage": startPage, - "percentage": percent, - "pageRange" : pageRange - }); - - // TODO: Add event for first and last page. - // (though last is going to be hard, since it could be several reflowed pages long) - } - }.bind(this)); - - renderer.on("render:loaded", this.loadChange.bind(this)); -}; - -// Listens for load events from the Renderer and checks against the current chapter -// Prevents the Render from loading a different chapter when back button is pressed -EPUBJS.Book.prototype.loadChange = function(url){ - var uri = EPUBJS.core.uri(url); - var chapterUri = EPUBJS.core.uri(this.currentChapter.absolute); - var spinePos, chapter; - - if(uri.path != chapterUri.path){ - console.warn("Miss Match", uri.path, this.currentChapter.absolute); - // this.goto(uri.filename); - - // Set the current chapter to what is being displayed - spinePos = this.spineIndexByURL[uri.filename]; - chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); - this.currentChapter = chapter; - - // setup the renderer with the displayed chapter - this.renderer.currentChapter = chapter; - this.renderer.afterLoad(this.renderer.render.docEl); - this.renderer.beforeDisplay(function () { - this.renderer.afterDisplay(); - }.bind(this)); - - } else if(!this._rendering) { - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.unlistenToRenderer = function(renderer){ - renderer.Events.forEach(function(eventName){ - renderer.off(eventName); - } ); -}; - -//-- Choose between a request from store or a request from network -EPUBJS.Book.prototype.loadXml = function(url){ - if(this.settings.fromStorage) { - return this.store.getXml(url, this.settings.encoding); - } else if(this.settings.contained) { - return this.zip.getXml(url, this.settings.encoding); - }else{ - return EPUBJS.core.request(url, 'xml', this.settings.withCredentials); - } -}; - -//-- Turns a url into a absolute url -EPUBJS.Book.prototype.urlFrom = function(bookPath){ - var uri = EPUBJS.core.uri(bookPath), - absolute = uri.protocol, - fromRoot = uri.path[0] == "/", - location = window.location, - //-- Get URL orgin, try for native or combine - origin = location.origin || location.protocol + "//" + location.host, - baseTag = document.getElementsByTagName('base'), - base; - - - //-- Check is Base tag is set - - if(baseTag.length) { - base = baseTag[0].href; - } - - //-- 1. Check if url is absolute - if(uri.protocol){ - return uri.origin + uri.path; - } - - //-- 2. Check if url starts with /, add base url - if(!absolute && fromRoot){ - return (base || origin) + uri.path; - } - - //-- 3. Or find full path to url and add that - if(!absolute && !fromRoot){ - return EPUBJS.core.resolveUrl(base || location.pathname, uri.path); - } - -}; - - -EPUBJS.Book.prototype.unarchive = function(bookPath){ - var book = this, - unarchived; - - //-- Must use storage - // if(this.settings.storage == false ){ - // this.settings.storage = true; - // this.storage = new fileStorage.storage(); - // } - - this.zip = new EPUBJS.Unarchiver(); - this.store = this.zip; // Use zip storaged in ram - return this.zip.open(bookPath); -}; - -//-- Checks if url has a .epub or .zip extension -EPUBJS.Book.prototype.isContained = function(bookUrl){ - var uri = EPUBJS.core.uri(bookUrl); - - if(uri.extension && (uri.extension == "epub" || uri.extension == "zip")){ - return true; - } - - return false; -}; - -//-- Checks if the book can be retrieved from localStorage -EPUBJS.Book.prototype.isSaved = function(bookKey) { - var storedSettings; - - if(!localStorage) { - return false; - } - - storedSettings = localStorage.getItem(bookKey); - - if( !localStorage || - storedSettings === null) { - return false; - } else { - return true; - } -}; - -// Generates the Book Key using the identifer in the manifest or other string provided -EPUBJS.Book.prototype.generateBookKey = function(identifier){ - return "epubjs:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; -}; - -EPUBJS.Book.prototype.saveContents = function(){ - if(!localStorage) { - return false; - } - localStorage.setItem(this.settings.bookKey, JSON.stringify(this.contents)); -}; - -EPUBJS.Book.prototype.removeSavedContents = function() { - if(!localStorage) { - return false; - } - localStorage.removeItem(this.settings.bookKey); -}; - - - -//-- Takes a string or a element -EPUBJS.Book.prototype.renderTo = function(elem){ - var book = this, - rendered; - - if(EPUBJS.core.isElement(elem)) { - this.element = elem; - } else if (typeof elem == "string") { - this.element = EPUBJS.core.getEl(elem); - } else { - console.error("Not an Element"); - return; - } - - rendered = this.opened. - then(function(){ - // book.render = new EPUBJS.Renderer[this.settings.renderer](book); - book.renderer.initialize(book.element, book.settings.width, book.settings.height); - - if(book.metadata.direction) { - book.renderer.setDirection(book.metadata.direction); - } - - book._rendered(); - return book.startDisplay(); - }); - - // rendered.then(null, function(error) { console.error(error); }); - - return rendered; -}; - -EPUBJS.Book.prototype.startDisplay = function(){ - var display; - - if(this.settings.goto) { - display = this.goto(this.settings.goto); - }else if(this.settings.previousLocationCfi) { - display = this.gotoCfi(this.settings.previousLocationCfi); - }else{ - display = this.displayChapter(this.spinePos); - } - - return display; -}; - -EPUBJS.Book.prototype.restore = function(identifier){ - - var book = this, - fetch = ['manifest', 'spine', 'metadata', 'cover', 'toc', 'spineNodeIndex', 'spineIndexByURL', 'globalLayoutProperties'], - reject = false, - bookKey = this.generateBookKey(identifier), - fromStore = localStorage.getItem(bookKey), - len = fetch.length, - i; - - if(this.settings.clearSaved) reject = true; - - if(!reject && fromStore != 'undefined' && fromStore !== null){ - book.contents = JSON.parse(fromStore); - - for(i = 0; i < len; i++) { - var item = fetch[i]; - - if(!book.contents[item]) { - reject = true; - break; - } - book[item] = book.contents[item]; - } - } - - if(reject || !fromStore || !this.contents || !this.settings.contentsPath){ - return false; - }else{ - this.settings.bookKey = bookKey; - this.ready.manifest.resolve(this.manifest); - this.ready.spine.resolve(this.spine); - this.ready.metadata.resolve(this.metadata); - this.ready.cover.resolve(this.cover); - this.ready.toc.resolve(this.toc); - return true; - } - -}; - -EPUBJS.Book.prototype.displayChapter = function(chap, end, deferred){ - var book = this, - render, - cfi, - pos, - store, - defer = deferred || new RSVP.defer(); - - var chapter; - - if(!this.isRendered) { - this._q.enqueue("displayChapter", arguments); - // Reject for now. TODO: pass promise to queue - defer.reject({ - message : "Rendering", - stack : new Error().stack - }); - return defer.promise; - } - - - if(this._rendering || this._rendering) { - // Pass along the current defer - this._displayQ.enqueue("displayChapter", [chap, end, defer]); - return defer.promise; - } - - if(EPUBJS.core.isNumber(chap)){ - pos = chap; - }else{ - cfi = new EPUBJS.EpubCFI(chap); - pos = cfi.spinePos; - } - - if(pos < 0 || pos >= this.spine.length){ - console.warn("Not A Valid Location"); - pos = 0; - end = false; - cfi = false; - } - - //-- Create a new chapter - chapter = new EPUBJS.Chapter(this.spine[pos], this.store); - - this._rendering = true; - - if(this._needsAssetReplacement()) { - - chapter.registerHook("beforeChapterRender", [ - EPUBJS.replace.head, - EPUBJS.replace.resources, - EPUBJS.replace.svg - ], true); - - } - - book.currentChapter = chapter; - - render = book.renderer.displayChapter(chapter, this.globalLayoutProperties); - if(cfi) { - book.renderer.gotoCfi(cfi); - } else if(end) { - book.renderer.lastPage(); - } - //-- Success, Clear render queue - render.then(function(rendered){ - // var inwait; - //-- Set the book's spine position - book.spinePos = pos; - - defer.resolve(book.renderer); - - if(book.settings.fromStorage === false && - book.settings.contained === false) { - book.preloadNextChapter(); - } - - book._rendering = false; - book._displayQ.dequeue(); - if(book._displayQ.length() === 0) { - book._gotoQ.dequeue(); - } - - }, function(error) { - // handle errors in either of the two requests - console.error("Could not load Chapter: "+ chapter.absolute, error); - book.trigger("book:chapterLoadFailed", chapter.absolute); - book._rendering = false; - defer.reject(error); - }); - - return defer.promise; -}; - -EPUBJS.Book.prototype.nextPage = function(){ - var next; - - if(!this.isRendered) return this._q.enqueue("nextPage", arguments); - - next = this.renderer.nextPage(); - - if(!next){ - return this.nextChapter(); - } -}; - -EPUBJS.Book.prototype.prevPage = function() { - var prev; - - if(!this.isRendered) return this._q.enqueue("prevPage", arguments); - - prev = this.renderer.prevPage(); - - if(!prev){ - return this.prevChapter(); - } -}; - -EPUBJS.Book.prototype.nextChapter = function() { - var next; - if (this.spinePos < this.spine.length - 1) { - next = this.spinePos + 1; - // Skip non linear chapters - while (this.spine[next] && this.spine[next].linear && this.spine[next].linear == 'no') { - next++; - } - if (next < this.spine.length) { - return this.displayChapter(next); - } else { - this.trigger("book:atEnd"); - } - - } else { - this.trigger("book:atEnd"); - } -}; - -EPUBJS.Book.prototype.prevChapter = function() { - var prev; - if (this.spinePos > 0) { - prev = this.spinePos - 1; - while (this.spine[prev] && this.spine[prev].linear && this.spine[prev].linear == 'no') { - prev--; - } - if (prev >= 0) { - return this.displayChapter(prev, true); - } else { - this.trigger("book:atStart"); - } - - } else { - this.trigger("book:atStart"); - } -}; - -EPUBJS.Book.prototype.getCurrentLocationCfi = function() { - if(!this.isRendered) return false; - return this.renderer.currentLocationCfi; -}; - -EPUBJS.Book.prototype.goto = function(target){ - - if(target.indexOf("epubcfi(") === 0) { - return this.gotoCfi(target); - } else if(target.indexOf("%") === target.length-1) { - return this.gotoPercentage(parseInt(target.substring(0, target.length-1))/100); - } else if(typeof target === "number" || isNaN(target) === false){ - return this.gotoPage(target); - } else { - return this.gotoHref(target); - } - -}; - -EPUBJS.Book.prototype.gotoCfi = function(cfiString, defer){ - var cfi, - spinePos, - spineItem, - rendered, - deferred = defer || new RSVP.defer(); - - if(!this.isRendered) { - console.warn("Not yet Rendered"); - this.settings.previousLocationCfi = cfiString; - return false; - } - - // Currently going to a chapter - if(this._moving || this._rendering) { - console.warn("Renderer is moving"); - this._gotoQ.enqueue("gotoCfi", [cfiString, deferred]); - return false; - } - - cfi = new EPUBJS.EpubCFI(cfiString); - spinePos = cfi.spinePos; - - if(spinePos == -1) { - return false; - } - - spineItem = this.spine[spinePos]; - promise = deferred.promise; - this._moving = true; - //-- If same chapter only stay on current chapter - if(this.currentChapter && this.spinePos === spinePos){ - this.renderer.gotoCfi(cfi); - this._moving = false; - deferred.resolve(this.renderer.currentLocationCfi); - } else { - - if(!spineItem || spinePos == -1) { - spinePos = 0; - spineItem = this.spine[spinePos]; - } - - this.currentChapter = new EPUBJS.Chapter(spineItem, this.store); - - if(this.currentChapter) { - this.spinePos = spinePos; - render = this.renderer.displayChapter(this.currentChapter, this.globalLayoutProperties); - - this.renderer.gotoCfi(cfi); - render.then(function(rendered){ - this._moving = false; - deferred.resolve(rendered.currentLocationCfi); - }.bind(this)); - } - } - - promise.then(function(){ - this._gotoQ.dequeue(); - }.bind(this)); - - return promise; -}; - -EPUBJS.Book.prototype.gotoHref = function(url, defer){ - var split, chapter, section, relativeURL, spinePos; - var deferred = defer || new RSVP.defer(); - - if(!this.isRendered) { - this.settings.goto = url; - return false; - } - - // Currently going to a chapter - if(this._moving || this._rendering) { - this._gotoQ.enqueue("gotoHref", [url, deferred]); - return false; - } - - split = url.split("#"); - chapter = split[0]; - section = split[1] || false; - // absoluteURL = (chapter.search("://") === -1) ? (this.settings.contentsPath + chapter) : chapter; - relativeURL = chapter.replace(this.settings.contentsPath, ''); - spinePos = this.spineIndexByURL[relativeURL]; - - //-- If link fragment only stay on current chapter - if(!chapter){ - spinePos = this.currentChapter ? this.currentChapter.spinePos : 0; - } - - //-- Check that URL is present in the index, or stop - if(typeof(spinePos) != "number") return false; - - if(!this.currentChapter || spinePos != this.currentChapter.spinePos){ - //-- Load new chapter if different than current - return this.displayChapter(spinePos).then(function(){ - if(section){ - this.renderer.section(section); - } - deferred.resolve(this.renderer.currentLocationCfi); - }.bind(this)); - }else{ - //-- Goto section - if(section) { - this.renderer.section(section); - } else { - // Or jump to the start - this.renderer.firstPage(); - } - deferred.resolve(this.renderer.currentLocationCfi); - } - - deferred.promise.then(function(){ - this._gotoQ.dequeue(); - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Book.prototype.gotoPage = function(pg){ - var cfi = this.pagination.cfiFromPage(pg); - return this.gotoCfi(cfi); -}; - -EPUBJS.Book.prototype.gotoPercentage = function(percent){ - var pg = this.pagination.pageFromPercentage(percent); - return this.gotoPage(pg); -}; - -EPUBJS.Book.prototype.preloadNextChapter = function() { - var next; - var chap = this.spinePos + 1; - - if(chap >= this.spine.length){ - return false; - } - - next = new EPUBJS.Chapter(this.spine[chap]); - if(next) { - EPUBJS.core.request(next.absolute); - } -}; - -EPUBJS.Book.prototype.storeOffline = function() { - var book = this, - assets = EPUBJS.core.values(this.manifest); - - //-- Creates a queue of all items to load - return this.store.put(assets). - then(function(){ - book.settings.stored = true; - book.trigger("book:stored"); - }); -}; - -EPUBJS.Book.prototype.availableOffline = function() { - return this.settings.stored > 0 ? true : false; -}; - -EPUBJS.Book.prototype.toStorage = function () { - var key = this.settings.bookKey; - this.store.isStored(key).then(function(stored) { - - if (stored === true) { - this.settings.stored = true; - return true; - } - - return this.storeOffline() - .then(function() { - this.store.token(key, true); - }.bind(this)); - - }.bind(this)); - -}; -EPUBJS.Book.prototype.fromStorage = function(stored) { - var hooks = [ - EPUBJS.replace.head, - EPUBJS.replace.resources, - EPUBJS.replace.svg - ]; - - if(this.contained || this.settings.contained) return; - - //-- If there is network connection, store the books contents - if(this.online){ - this.opened.then(this.toStorage.bind(this)); - } - - if(this.store && this.settings.fromStorage && stored === false){ - this.settings.fromStorage = false; - this.store.off("offline"); - // this.renderer.removeHook("beforeChapterRender", hooks, true); - this.store = false; - }else if(!this.settings.fromStorage){ - - this.store = new EPUBJS.Storage(this.settings.credentials); - this.store.on("offline", function (offline) { - if (!offline) { - // Online - this.offline = false; - this.settings.fromStorage = false; - // this.renderer.removeHook("beforeChapterRender", hooks, true); - this.trigger("book:online"); - } else { - // Offline - this.offline = true; - this.settings.fromStorage = true; - // this.renderer.registerHook("beforeChapterRender", hooks, true); - this.trigger("book:offline"); - } - }.bind(this)); - - } - -}; - -EPUBJS.Book.prototype.setStyle = function(style, val, prefixed) { - var noreflow = ["color", "background", "background-color"]; - - if(!this.isRendered) return this._q.enqueue("setStyle", arguments); - - this.settings.styles[style] = val; - - this.renderer.setStyle(style, val, prefixed); - - if(noreflow.indexOf(style) === -1) { - // clearTimeout(this.reformatTimeout); - // this.reformatTimeout = setTimeout(function(){ - this.renderer.reformat(); - // }.bind(this), 10); - } -}; - -EPUBJS.Book.prototype.removeStyle = function(style) { - if(!this.isRendered) return this._q.enqueue("removeStyle", arguments); - this.renderer.removeStyle(style); - this.renderer.reformat(); - delete this.settings.styles[style]; -}; - -EPUBJS.Book.prototype.addHeadTag = function(tag, attrs) { - if(!this.isRendered) return this._q.enqueue("addHeadTag", arguments); - this.settings.headTags[tag] = attrs; -}; - -EPUBJS.Book.prototype.useSpreads = function(use) { - console.warn("useSpreads is deprecated, use forceSingle or set a layoutOveride instead"); - if(use === false) { - this.forceSingle(true); - } else { - this.forceSingle(false); - } -}; - -EPUBJS.Book.prototype.forceSingle = function(_use) { - var force = typeof _use === "undefined" ? true : _use; - - this.renderer.forceSingle(force); - this.settings.forceSingle = force; - if(this.isRendered) { - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.setMinSpreadWidth = function(width) { - this.settings.minSpreadWidth = width; - if(this.isRendered) { - this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.setGap = function(gap) { - this.settings.gap = gap; - if(this.isRendered) { - this.renderer.setGap(this.settings.gap); - this.renderer.reformat(); - } -}; - -EPUBJS.Book.prototype.chapter = function(path) { - var spinePos = this.spineIndexByURL[path]; - var spineItem; - var chapter; - - if(spinePos){ - spineItem = this.spine[spinePos]; - chapter = new EPUBJS.Chapter(spineItem, this.store); - chapter.load(); - } - return chapter; -}; - -EPUBJS.Book.prototype.unload = function(){ - - if(this.settings.restore && localStorage) { - this.saveContents(); - } - - this.unlistenToRenderer(this.renderer); - - this.trigger("book:unload"); -}; - -EPUBJS.Book.prototype.destroy = function() { - - window.removeEventListener("beforeunload", this.unload); - - if(this.currentChapter) this.currentChapter.unload(); - - this.unload(); - - if(this.renderer) this.renderer.remove(); - -}; - -EPUBJS.Book.prototype._ready = function() { - - this.trigger("book:ready"); - -}; - -EPUBJS.Book.prototype._rendered = function(err) { - var book = this; - - this.isRendered = true; - this.trigger("book:rendered"); - - this._q.flush(); -}; - - -EPUBJS.Book.prototype.applyStyles = function(renderer, callback){ - // if(!this.isRendered) return this._q.enqueue("applyStyles", arguments); - renderer.applyStyles(this.settings.styles); - callback(); -}; - -EPUBJS.Book.prototype.applyHeadTags = function(renderer, callback){ - // if(!this.isRendered) return this._q.enqueue("applyHeadTags", arguments); - renderer.applyHeadTags(this.settings.headTags); - callback(); -}; - -EPUBJS.Book.prototype._registerReplacements = function(renderer){ - renderer.registerHook("beforeChapterDisplay", this.applyStyles.bind(this, renderer), true); - renderer.registerHook("beforeChapterDisplay", this.applyHeadTags.bind(this, renderer), true); - renderer.registerHook("beforeChapterDisplay", EPUBJS.replace.hrefs.bind(this), true); -}; - -EPUBJS.Book.prototype._needsAssetReplacement = function(){ - if(this.settings.fromStorage) { - - //-- Filesystem api links are relative, so no need to replace them - // if(this.storage.getStorageType() == "filesystem") { - // return false; - // } - - return true; - - } else if(this.settings.contained) { - - return true; - - } else { - - return false; - - } -}; - - -//-- http://www.idpf.org/epub/fxl/ -EPUBJS.Book.prototype.parseLayoutProperties = function(metadata){ - var layout = (this.layoutOveride && this.layoutOveride.layout) || metadata.layout || "reflowable"; - var spread = (this.layoutOveride && this.layoutOveride.spread) || metadata.spread || "auto"; - var orientation = (this.layoutOveride && this.layoutOveride.orientation) || metadata.orientation || "auto"; - return { - layout : layout, - spread : spread, - orientation : orientation - }; -}; - -//-- Enable binding events to book -RSVP.EventTarget.mixin(EPUBJS.Book.prototype); - -//-- Handle RSVP Errors -RSVP.on('error', function(event) { - //console.error(event, event.detail); -}); - -RSVP.configure('instrument', false); //-- true | will logging out all RSVP rejections -// RSVP.on('created', listener); -// RSVP.on('chained', listener); -// RSVP.on('fulfilled', listener); -// RSVP.on('rejected', function(event){ -// console.error(event.detail.message, event.detail.stack); -// }); - -EPUBJS.Chapter = function(spineObject, store){ - this.href = spineObject.href; - this.absolute = spineObject.url; - this.id = spineObject.id; - this.spinePos = spineObject.index; - this.cfiBase = spineObject.cfiBase; - this.properties = spineObject.properties; - this.manifestProperties = spineObject.manifestProperties; - this.linear = spineObject.linear; - this.pages = 1; - this.store = store; - this.epubcfi = new EPUBJS.EpubCFI(); - this.deferred = new RSVP.defer(); - this.loaded = this.deferred.promise; - - EPUBJS.Hooks.mixin(this); - //-- Get pre-registered hooks for events - this.getHooks("beforeChapterRender"); - - // Cached for replacement urls from storage - this.caches = {}; -}; - - -EPUBJS.Chapter.prototype.load = function(_store){ - var store = _store || this.store; - var promise; - // if(this.store && (!this.book.online || this.book.contained)) - if(store){ - promise = store.getXml(this.absolute); - }else{ - promise = EPUBJS.core.request(this.absolute, 'xml'); - } - - promise.then(function(xml){ - this.setDocument(xml); - this.deferred.resolve(this); - }.bind(this)); - - return promise; -}; - -EPUBJS.Chapter.prototype.render = function(_store){ - - return this.load().then(function(doc){ - - var head = doc.querySelector('head'); - var base = doc.createElement("base"); - - base.setAttribute("href", this.absolute); - head.insertBefore(base, head.firstChild); - - this.contents = doc; - - return new RSVP.Promise(function (resolve, reject) { - this.triggerHooks("beforeChapterRender", function () { - resolve(doc); - }.bind(this), this); - }.bind(this)); - - }.bind(this)) - .then(function(doc) { - var serializer = new XMLSerializer(); - var contents = serializer.serializeToString(doc); - return contents; - }.bind(this)); -}; - -EPUBJS.Chapter.prototype.url = function(_store){ - var deferred = new RSVP.defer(); - var store = _store || this.store; - var loaded; - var chapter = this; - var url; - - if(store){ - if(!this.tempUrl) { - store.getUrl(this.absolute).then(function(url){ - chapter.tempUrl = url; - deferred.resolve(url); - }); - } else { - url = this.tempUrl; - deferred.resolve(url); - } - }else{ - url = this.absolute; - deferred.resolve(url); - } - /* - loaded = EPUBJS.core.request(url, 'xml', false); - loaded.then(function(contents){ - chapter.contents = contents; - deferred.resolve(chapter.absolute); - }, function(error){ - deferred.reject(error); - }); - */ - - return deferred.promise; -}; - -EPUBJS.Chapter.prototype.setPages = function(num){ - this.pages = num; -}; - -EPUBJS.Chapter.prototype.getPages = function(num){ - return this.pages; -}; - -EPUBJS.Chapter.prototype.getID = function(){ - return this.ID; -}; - -EPUBJS.Chapter.prototype.unload = function(store){ - this.document = null; - if(this.tempUrl && store) { - store.revokeUrl(this.tempUrl); - this.tempUrl = false; - } -}; - -EPUBJS.Chapter.prototype.setDocument = function(_document){ - var uri = _document.namespaceURI; - var doctype = _document.doctype; - - // Creates an empty document - this.document = _document.implementation.createDocument( - uri, - null, - null - ); - this.contents = this.document.importNode( - _document.documentElement, //node to import - true //clone its descendants - ); - - this.document.appendChild(this.contents); - - // Fix to apply wgxpath to new document in IE - if(!this.document.evaluate && document.evaluate) { - this.document.evaluate = document.evaluate; - } - - // this.deferred.resolve(this.contents); -}; - -EPUBJS.Chapter.prototype.cfiFromRange = function(_range) { - var range; - var startXpath, endXpath; - var startContainer, endContainer; - var cleanTextContent, cleanEndTextContent; - - // Check for Contents - if(!this.document) return; - - if(typeof document.evaluate != 'undefined') { - - startXpath = EPUBJS.core.getElementXPath(_range.startContainer); - // console.log(startContainer) - endXpath = EPUBJS.core.getElementXPath(_range.endContainer); - - startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - - if(!_range.collapsed) { - endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - } - - range = this.document.createRange(); - // Find Exact Range in original document - if(startContainer) { - try { - range.setStart(startContainer, _range.startOffset); - if(!_range.collapsed && endContainer) { - range.setEnd(endContainer, _range.endOffset); - } - } catch (e) { - console.log("missed"); - startContainer = false; - } - - } - - // Fuzzy Match - if(!startContainer) { - console.log("not found, try fuzzy match"); - cleanStartTextContent = EPUBJS.core.cleanStringForXpath(_range.startContainer.textContent); - startXpath = "//text()[contains(.," + cleanStartTextContent + ")]"; - - startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - - if(startContainer){ - // console.log("Found with Fuzzy"); - range.setStart(startContainer, _range.startOffset); - - if(!_range.collapsed) { - cleanEndTextContent = EPUBJS.core.cleanStringForXpath(_range.endContainer.textContent); - endXpath = "//text()[contains(.," + cleanEndTextContent + ")]"; - endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - if(endContainer) { - range.setEnd(endContainer, _range.endOffset); - } - } - - } - } - } else { - range = _range; // Just evaluate the current documents range - } - - // Generate the Cfi - return this.epubcfi.generateCfiFromRange(range, this.cfiBase); -}; - -EPUBJS.Chapter.prototype.find = function(_query){ - var chapter = this; - var matches = []; - var query = _query.toLowerCase(); - //var xpath = this.document.evaluate(".//text()[contains(translate(., '"+query.toUpperCase()+"', '"+query+"'),'"+query+"')]", this.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); - var find = function(node){ - // Search String - var text = node.textContent.toLowerCase(); - var range = chapter.document.createRange(); - var cfi; - var pos; - var last = -1; - var excerpt; - var limit = 150; - - while (pos != -1) { - pos = text.indexOf(query, last + 1); - - if(pos != -1) { - // If Found, Create Range - range = chapter.document.createRange(); - range.setStart(node, pos); - range.setEnd(node, pos + query.length); - - //Generate CFI - cfi = chapter.cfiFromRange(range); - - // Generate Excerpt - if(node.textContent.length < limit) { - excerpt = node.textContent; - } else { - excerpt = node.textContent.substring(pos-limit/2,pos+limit/2); - excerpt = "..." + excerpt + "..."; - } - - //Add CFI to list - matches.push({ - cfi: cfi, - excerpt: excerpt - }); - } - - last = pos; - } - - }; - - // Grab text nodes - - /* - for ( var i=0 ; i < xpath.snapshotLength; i++ ) { - find(xpath.snapshotItem(i)); - } - */ - - this.textSprint(this.document, function(node){ - find(node); - }); - - - // Return List of CFIs - return matches; -}; - - -EPUBJS.Chapter.prototype.textSprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: function (node) { - if (node.data && ! /^\s*$/.test(node.data) ) { - return NodeFilter.FILTER_ACCEPT; - } else { - return NodeFilter.FILTER_REJECT; - } - } - }, false); - var node; - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Chapter.prototype.replace = function(query, func, finished, progress){ - var items = this.contents.querySelectorAll(query), - resources = Array.prototype.slice.call(items), - count = resources.length; - - - if(count === 0) { - finished(false); - return; - } - resources.forEach(function(item){ - var called = false; - var after = function(result, full){ - if(called === false) { - count--; - if(progress) progress(result, full, count); - if(count <= 0 && finished) finished(true); - called = true; - } - }; - - func(item, after); - - }.bind(this)); - -}; - -EPUBJS.Chapter.prototype.replaceWithStored = function(query, attr, func, callback) { - var _oldUrls, - _newUrls = {}, - _store = this.store, - _cache = this.caches[query], - _uri = EPUBJS.core.uri(this.absolute), - _chapterBase = _uri.base, - _attr = attr, - _wait = 5, - progress = function(url, full, count) { - _newUrls[full] = url; - }, - finished = function(notempty) { - if(callback) callback(); - - _oldUrls.forEach(function(url){ - _store.revokeUrl(url); - }); - - _cache = _newUrls; - }; - - if(!_store) return; - - if(!_cache) _cache = {}; - _oldUrls = EPUBJS.core.clone(_cache); - - this.replace(query, function(link, done){ - var src = link.getAttribute(_attr), - full = EPUBJS.core.resolveUrl(_chapterBase, src); - - var replaceUrl = function(url) { - var timeout; - link.onload = function(){ - clearTimeout(timeout); - done(url, full); - }; - - link.onerror = function(e){ - clearTimeout(timeout); - done(url, full); - console.error(e); - }; - - if(query == "image") { - //-- SVG needs this to trigger a load event - link.setAttribute("externalResourcesRequired", "true"); - } - - if(query == "link[href]" && link.getAttribute("rel") !== "stylesheet") { - //-- Only Stylesheet links seem to have a load events, just continue others - done(url, full); - } else { - timeout = setTimeout(function(){ - done(url, full); - }, _wait); - } - - link.setAttribute(_attr, url); - - - - }; - - if(full in _oldUrls){ - replaceUrl(_oldUrls[full]); - _newUrls[full] = _oldUrls[full]; - delete _oldUrls[full]; - }else{ - func(_store, full, replaceUrl, link); - } - - }, finished, progress); -}; - -var EPUBJS = EPUBJS || {}; -EPUBJS.core = {}; - -//-- Get a element for an id -EPUBJS.core.getEl = function(elem) { - return document.getElementById(elem); -}; - -//-- Get all elements for a class -EPUBJS.core.getEls = function(classes) { - return document.getElementsByClassName(classes); -}; - -EPUBJS.core.request = function(url, type, withCredentials) { - var supportsURL = window.URL; - var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; - - var deferred = new RSVP.defer(); - - var xhr = new XMLHttpRequest(); - - //-- Check from PDF.js: - // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js - var xhrPrototype = XMLHttpRequest.prototype; - - if (!('overrideMimeType' in xhrPrototype)) { - // IE10 might have response, but not overrideMimeType - Object.defineProperty(xhrPrototype, 'overrideMimeType', { - value: function xmlHttpRequestOverrideMimeType(mimeType) {} - }); - } - if(withCredentials) { - xhr.withCredentials = true; - } - xhr.open("GET", url, true); - xhr.onreadystatechange = handler; - - if(type == 'blob'){ - xhr.responseType = BLOB_RESPONSE; - } - - if(type == "json") { - xhr.setRequestHeader("Accept", "application/json"); - } - - if(type == 'xml') { - xhr.overrideMimeType('text/xml'); - } - - if(type == "binary") { - xhr.responseType = "arraybuffer"; - } - - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200 || (this.status === 0 && this.response) ) { // Android & Firefox reporting 0 for local & blob urls - var r; - - if(type == 'xml'){ - r = this.responseXML; - }else - if(type == 'json'){ - r = JSON.parse(this.response); - }else - if(type == 'blob'){ - - if(supportsURL) { - r = this.response; - } else { - //-- Safari doesn't support responseType blob, so create a blob from arraybuffer - r = new Blob([this.response]); - } - - }else{ - r = this.response; - } - - deferred.resolve(r); - } else { - deferred.reject({ - message : this.response, - stack : new Error().stack - }); - } - } - } - - return deferred.promise; -}; - -EPUBJS.core.toArray = function(obj) { - var arr = []; - - for (var member in obj) { - var newitm; - if ( obj.hasOwnProperty(member) ) { - newitm = obj[member]; - newitm.ident = member; - arr.push(newitm); - } - } - - return arr; -}; - -//-- Parse the different parts of a url, returning a object -EPUBJS.core.uri = function(url){ - var uri = { - protocol : '', - host : '', - path : '', - origin : '', - directory : '', - base : '', - filename : '', - extension : '', - fragment : '', - href : url - }, - blob = url.indexOf('blob:'), - doubleSlash = url.indexOf('://'), - search = url.indexOf('?'), - fragment = url.indexOf("#"), - withoutProtocol, - dot, - firstSlash; - - if(blob === 0) { - uri.protocol = "blob"; - uri.base = url.indexOf(0, fragment); - return uri; - } - - if(fragment != -1) { - uri.fragment = url.slice(fragment + 1); - url = url.slice(0, fragment); - } - - if(search != -1) { - uri.search = url.slice(search + 1); - url = url.slice(0, search); - href = url; - } - - if(doubleSlash != -1) { - uri.protocol = url.slice(0, doubleSlash); - withoutProtocol = url.slice(doubleSlash+3); - firstSlash = withoutProtocol.indexOf('/'); - - if(firstSlash === -1) { - uri.host = uri.path; - uri.path = ""; - } else { - uri.host = withoutProtocol.slice(0, firstSlash); - uri.path = withoutProtocol.slice(firstSlash); - } - - - uri.origin = uri.protocol + "://" + uri.host; - - uri.directory = EPUBJS.core.folder(uri.path); - - uri.base = uri.origin + uri.directory; - // return origin; - } else { - uri.path = url; - uri.directory = EPUBJS.core.folder(url); - uri.base = uri.directory; - } - - //-- Filename - uri.filename = url.replace(uri.base, ''); - dot = uri.filename.lastIndexOf('.'); - if(dot != -1) { - uri.extension = uri.filename.slice(dot+1); - } - return uri; -}; - -//-- Parse out the folder, will return everything before the last slash - -EPUBJS.core.folder = function(url){ - - var lastSlash = url.lastIndexOf('/'); - - if(lastSlash == -1) var folder = ''; - - folder = url.slice(0, lastSlash + 1); - - return folder; - -}; - -//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 -EPUBJS.core.dataURLToBlob = function(dataURL) { - var BASE64_MARKER = ';base64,', - parts, contentType, raw, rawLength, uInt8Array; - - if (dataURL.indexOf(BASE64_MARKER) == -1) { - parts = dataURL.split(','); - contentType = parts[0].split(':')[1]; - raw = parts[1]; - - return new Blob([raw], {type: contentType}); - } - - parts = dataURL.split(BASE64_MARKER); - contentType = parts[0].split(':')[1]; - raw = window.atob(parts[1]); - rawLength = raw.length; - - uInt8Array = new Uint8Array(rawLength); - - for (var i = 0; i < rawLength; ++i) { - uInt8Array[i] = raw.charCodeAt(i); - } - - return new Blob([uInt8Array], {type: contentType}); -}; - -//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously -EPUBJS.core.addScript = function(src, callback, target) { - var s, r; - r = false; - s = document.createElement('script'); - s.type = 'text/javascript'; - s.async = false; - s.src = src; - s.onload = s.onreadystatechange = function() { - if ( !r && (!this.readyState || this.readyState == 'complete') ) { - r = true; - if(callback) callback(); - } - }; - target = target || document.body; - target.appendChild(s); -}; - -EPUBJS.core.addScripts = function(srcArr, callback, target) { - var total = srcArr.length, - curr = 0, - cb = function(){ - curr++; - if(total == curr){ - if(callback) callback(); - }else{ - EPUBJS.core.addScript(srcArr[curr], cb, target); - } - }; - - EPUBJS.core.addScript(srcArr[curr], cb, target); -}; - -EPUBJS.core.addCss = function(src, callback, target) { - var s, r; - r = false; - s = document.createElement('link'); - s.type = 'text/css'; - s.rel = "stylesheet"; - s.href = src; - s.onload = s.onreadystatechange = function() { - if ( !r && (!this.readyState || this.readyState == 'complete') ) { - r = true; - if(callback) callback(); - } - }; - target = target || document.body; - target.appendChild(s); -}; - -EPUBJS.core.prefixed = function(unprefixed) { - var vendors = ["Webkit", "Moz", "O", "ms" ], - prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], - upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), - length = vendors.length; - - if (typeof(document.documentElement.style[unprefixed]) != 'undefined') { - return unprefixed; - } - - for ( var i=0; i < length; i++ ) { - if (typeof(document.documentElement.style[vendors[i] + upper]) != 'undefined') { - return vendors[i] + upper; - } - } - - return unprefixed; -}; - -EPUBJS.core.resolveUrl = function(base, path) { - var url, - segments = [], - uri = EPUBJS.core.uri(path), - folders = base.split("/"), - paths; - - if(uri.host) { - return path; - } - - folders.pop(); - - paths = path.split("/"); - paths.forEach(function(p){ - if(p === ".."){ - folders.pop(); - }else{ - segments.push(p); - } - }); - - url = folders.concat(segments); - - return url.join("/"); -}; - -// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript -EPUBJS.core.uuid = function() { - var d = new Date().getTime(); - var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = (d + Math.random()*16)%16 | 0; - d = Math.floor(d/16); - return (c=='x' ? r : (r&0x7|0x8)).toString(16); - }); - return uuid; -}; - -// Fast quicksort insert for sorted array -- based on: -// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers -EPUBJS.core.insert = function(item, array, compareFunction) { - var location = EPUBJS.core.locationOf(item, array, compareFunction); - array.splice(location, 0, item); - - return location; -}; - -EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { - var start = _start || 0; - var end = _end || array.length; - var pivot = parseInt(start + (end - start) / 2); - var compared; - if(!compareFunction){ - compareFunction = function(a, b) { - if(a > b) return 1; - if(a < b) return -1; - if(a = b) return 0; - }; - } - if(end-start <= 0) { - return pivot; - } - - compared = compareFunction(array[pivot], item); - if(end-start === 1) { - return compared > 0 ? pivot : pivot + 1; - } - - if(compared === 0) { - return pivot; - } - if(compared === -1) { - return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); - } else{ - return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); - } -}; - -EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { - var start = _start || 0; - var end = _end || array.length; - var pivot = parseInt(start + (end - start) / 2); - var compared; - if(!compareFunction){ - compareFunction = function(a, b) { - if(a > b) return 1; - if(a < b) return -1; - if(a = b) return 0; - }; - } - if(end-start <= 0) { - return -1; // Not found - } - - compared = compareFunction(array[pivot], item); - if(end-start === 1) { - return compared === 0 ? pivot : -1; - } - if(compared === 0) { - return pivot; // Found - } - if(compared === -1) { - return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); - } else{ - return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); - } -}; - - -EPUBJS.core.queue = function(_scope){ - var _q = []; - var scope = _scope; - // Add an item to the queue - var enqueue = function(funcName, args, context) { - _q.push({ - "funcName" : funcName, - "args" : args, - "context" : context - }); - return _q; - }; - // Run one item - var dequeue = function(){ - var inwait; - if(_q.length) { - inwait = _q.shift(); - // Defer to any current tasks - // setTimeout(function(){ - scope[inwait.funcName].apply(inwait.context || scope, inwait.args); - // }, 0); - } - }; - - // Run All - var flush = function(){ - while(_q.length) { - dequeue(); - } - }; - // Clear all items in wait - var clear = function(){ - _q = []; - }; - - var length = function(){ - return _q.length; - }; - - return { - "enqueue" : enqueue, - "dequeue" : dequeue, - "flush" : flush, - "clear" : clear, - "length" : length - }; -}; - -// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js -/** - * Gets an XPath for an element which describes its hierarchical location. - */ -EPUBJS.core.getElementXPath = function(element) { - if (element && element.id) { - return '//*[@id="' + element.id + '"]'; - } else { - return EPUBJS.core.getElementTreeXPath(element); - } -}; - -EPUBJS.core.getElementTreeXPath = function(element) { - var paths = []; - var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); - var index, nodeName, tagName, pathIndex; - - if(element.nodeType === Node.TEXT_NODE){ - // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; - index = EPUBJS.core.indexOfTextNode(element) + 1; - - paths.push("text()["+index+"]"); - element = element.parentNode; - } - - // Use nodeName (instead of localName) so namespace prefix is included (if any). - for (; element && element.nodeType == 1; element = element.parentNode) - { - index = 0; - for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) - { - // Ignore document type declaration. - if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { - continue; - } - if (sibling.nodeName == element.nodeName) { - ++index; - } - } - nodeName = element.nodeName.toLowerCase(); - tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); - pathIndex = (index ? "[" + (index+1) + "]" : ""); - paths.splice(0, 0, tagName + pathIndex); - } - - return paths.length ? "./" + paths.join("/") : null; -}; - -EPUBJS.core.nsResolver = function(prefix) { - var ns = { - 'xhtml' : 'http://www.w3.org/1999/xhtml', - 'epub': 'http://www.idpf.org/2007/ops' - }; - return ns[prefix] || null; -}; - -//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 -EPUBJS.core.cleanStringForXpath = function(str) { - var parts = str.match(/[^'"]+|['"]/g); - parts = parts.map(function(part){ - if (part === "'") { - return '\"\'\"'; // output "'" - } - - if (part === '"') { - return "\'\"\'"; // output '"' - } - return "\'" + part + "\'"; - }); - return "concat(\'\'," + parts.join(",") + ")"; -}; - -EPUBJS.core.indexOfTextNode = function(textNode){ - var parent = textNode.parentNode; - var children = parent.childNodes; - var sib; - var index = -1; - for (var i = 0; i < children.length; i++) { - sib = children[i]; - if(sib.nodeType === Node.TEXT_NODE){ - index++; - } - if(sib == textNode) break; - } - - return index; -}; - -// Underscore -EPUBJS.core.defaults = function(obj) { - for (var i = 1, length = arguments.length; i < length; i++) { - var source = arguments[i]; - for (var prop in source) { - if (obj[prop] === void 0) obj[prop] = source[prop]; - } - } - return obj; -}; - -EPUBJS.core.extend = function(target) { - var sources = [].slice.call(arguments, 1); - sources.forEach(function (source) { - if(!source) return; - Object.getOwnPropertyNames(source).forEach(function(propName) { - Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); - }); - }); - return target; -}; - -EPUBJS.core.clone = function(obj) { - return EPUBJS.core.isArray(obj) ? obj.slice() : EPUBJS.core.extend({}, obj); -}; - -EPUBJS.core.isElement = function(obj) { - return !!(obj && obj.nodeType == 1); -}; - -EPUBJS.core.isNumber = function(n) { - return !isNaN(parseFloat(n)) && isFinite(n); -}; - -EPUBJS.core.isString = function(str) { - return (typeof str === 'string' || str instanceof String); -}; - -EPUBJS.core.isArray = Array.isArray || function(obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; -}; - -// Lodash -EPUBJS.core.values = function(object) { - var index = -1, - props = Object.keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; -}; -EPUBJS.EpubCFI = function(cfiStr){ - if(cfiStr) return this.parse(cfiStr); -}; - -EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) { - var pos = parseInt(_pos), - spineNodeIndex = _spineNodeIndex + 1, - cfi = '/'+spineNodeIndex+'/'; - - cfi += (pos + 1) * 2; - - if(id) cfi += "[" + id + "]"; - - //cfi += "!"; - - return cfi; -}; - -EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) { - var parts = []; - - steps.forEach(function(part){ - var segment = ''; - segment += (part.index + 1) * 2; - - if(part.id) { - segment += "[" + part.id + "]"; - } - - parts.push(segment); - }); - - return parts.join('/'); -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) { - var steps = this.pathTo(element); - var path = this.generatePathComponent(steps); - if(!path.length) { - // Start of Chapter - return "epubcfi(" + chapter + "!/4/)"; - } else { - // First Text Node - return "epubcfi(" + chapter + "!" + path + "/1:0)"; - } -}; - -EPUBJS.EpubCFI.prototype.pathTo = function(node) { - var stack = [], - children; - - while(node && node.parentNode !== null && node.parentNode.nodeType != 9) { - children = node.parentNode.children; - - stack.unshift({ - 'id' : node.id, - // 'classList' : node.classList, - 'tagName' : node.tagName, - 'index' : children ? Array.prototype.indexOf.call(children, node) : 0 - }); - - node = node.parentNode; - } - - return stack; -}; - -EPUBJS.EpubCFI.prototype.getChapterComponent = function(cfiStr) { - - var splitStr = cfiStr.split("!"); - - return splitStr[0]; -}; - -EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) { - - var splitStr = cfiStr.split("!"); - var pathComponent = splitStr[1] ? splitStr[1].split(":") : ''; - - return pathComponent[0]; -}; - -EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) { - var splitStr = cfiStr.split(":"); - return splitStr[1] || ''; -}; - - -EPUBJS.EpubCFI.prototype.parse = function(cfiStr) { - var cfi = {}, - chapSegment, - chapterComponent, - pathComponent, - charecterOffsetComponent, - assertion, - chapId, - path, - end, - endInt, - text, - parseStep = function(part){ - var type, index, has_brackets, id; - - type = "element"; - index = parseInt(part) / 2 - 1; - has_brackets = part.match(/\[(.*)\]/); - if(has_brackets && has_brackets[1]){ - id = has_brackets[1]; - } - - return { - "type" : type, - 'index' : index, - 'id' : id || false - }; - }; - - if(typeof cfiStr !== "string") { - return {spinePos: -1}; - } - - cfi.str = cfiStr; - - if(cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length-1] === ")") { - // Remove intial epubcfi( and ending ) - cfiStr = cfiStr.slice(8, cfiStr.length-1); - } - - chapterComponent = this.getChapterComponent(cfiStr); - pathComponent = this.getPathComponent(cfiStr) || ''; - charecterOffsetComponent = this.getCharecterOffsetComponent(cfiStr); - // Make sure this is a valid cfi or return - if(!chapterComponent) { - return {spinePos: -1}; - } - - // Chapter segment is always the second one - chapSegment = chapterComponent.split("/")[2] || ''; - if(!chapSegment) return {spinePos:-1}; - - cfi.spinePos = (parseInt(chapSegment) / 2 - 1 ) || 0; - - chapId = chapSegment.match(/\[(.*)\]/); - - cfi.spineId = chapId ? chapId[1] : false; - - if(pathComponent.indexOf(',') != -1) { - // Handle ranges -- not supported yet - console.warn("CFI Ranges are not supported"); - } - - path = pathComponent.split('/'); - end = path.pop(); - - cfi.steps = []; - - path.forEach(function(part){ - var step; - - if(part) { - step = parseStep(part); - cfi.steps.push(step); - } - }); - - //-- Check if END is a text node or element - endInt = parseInt(end); - if(!isNaN(endInt)) { - - if(endInt % 2 === 0) { // Even = is an element - cfi.steps.push(parseStep(end)); - } else { - cfi.steps.push({ - "type" : "text", - 'index' : (endInt - 1 ) / 2 - }); - } - - } - - assertion = charecterOffsetComponent.match(/\[(.*)\]/); - if(assertion && assertion[1]){ - cfi.characterOffset = parseInt(charecterOffsetComponent.split('[')[0]); - // We arent handling these assertions yet - cfi.textLocationAssertion = assertion[1]; - } else { - cfi.characterOffset = parseInt(charecterOffsetComponent); - } - - return cfi; -}; - -EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) { - var doc = _doc || document; - var marker = _marker || this.createMarker(doc); - var parent; - var lastStep; - var text; - var split; - - if(typeof cfi === 'string') { - cfi = this.parse(cfi); - } - // Get the terminal step - lastStep = cfi.steps[cfi.steps.length-1]; - - // check spinePos - if(cfi.spinePos === -1) { - // Not a valid CFI - return false; - } - - // Find the CFI elements parent - parent = this.findParent(cfi, doc); - - if(!parent) { - // CFI didn't return an element - // Maybe it isnt in the current chapter? - return false; - } - - if(lastStep && lastStep.type === "text") { - text = parent.childNodes[lastStep.index]; - if(cfi.characterOffset){ - split = text.splitText(cfi.characterOffset); - marker.classList.add("EPUBJS-CFI-SPLIT"); - parent.insertBefore(marker, split); - } else { - parent.insertBefore(marker, text); - } - } else { - parent.insertBefore(marker, parent.firstChild); - } - - return marker; -}; - -EPUBJS.EpubCFI.prototype.createMarker = function(_doc) { - var doc = _doc || document; - var element = doc.createElement('span'); - element.id = "EPUBJS-CFI-MARKER:"+ EPUBJS.core.uuid(); - element.classList.add("EPUBJS-CFI-MARKER"); - - return element; -}; - -EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) { - var doc = _doc || document; - // var id = marker.id; - - // Cleanup textnodes if they were split - if(marker.classList.contains("EPUBJS-CFI-SPLIT")){ - nextSib = marker.nextSibling; - prevSib = marker.previousSibling; - if(nextSib && - prevSib && - nextSib.nodeType === 3 && - prevSib.nodeType === 3){ - - prevSib.textContent += nextSib.textContent; - marker.parentNode.removeChild(nextSib); - } - marker.parentNode.removeChild(marker); - } else if(marker.classList.contains("EPUBJS-CFI-MARKER")) { - // Remove only elements added as markers - marker.parentNode.removeChild(marker); - } - -}; - -EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) { - var doc = _doc || document, - element = doc.getElementsByTagName('html')[0], - children = Array.prototype.slice.call(element.children), - num, index, part, sections, - text, textBegin, textEnd; - - if(typeof cfi === 'string') { - cfi = this.parse(cfi); - } - - sections = cfi.steps.slice(0); // Clone steps array - if(!sections.length) { - return doc.getElementsByTagName('body')[0]; - } - - while(sections && sections.length > 0) { - part = sections.shift(); - // Find textNodes Parent - if(part.type === "text") { - text = element.childNodes[part.index]; - element = text.parentNode || element; - // Find element by id if present - } else if(part.id){ - element = doc.getElementById(part.id); - // Find element in parent - }else{ - element = children[part.index]; - } - // Element can't be found - if(typeof element === "undefined") { - console.error("No Element For", part, cfi.str); - return false; - } - // Get current element children and continue through steps - children = Array.prototype.slice.call(element.children); - } - - return element; -}; - -EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) { - if(typeof cfiOne === 'string') { - cfiOne = new EPUBJS.EpubCFI(cfiOne); - } - if(typeof cfiTwo === 'string') { - cfiTwo = new EPUBJS.EpubCFI(cfiTwo); - } - // Compare Spine Positions - if(cfiOne.spinePos > cfiTwo.spinePos) { - return 1; - } - if(cfiOne.spinePos < cfiTwo.spinePos) { - return -1; - } - - - // Compare Each Step in the First item - for (var i = 0; i < cfiOne.steps.length; i++) { - if(!cfiTwo.steps[i]) { - return 1; - } - if(cfiOne.steps[i].index > cfiTwo.steps[i].index) { - return 1; - } - if(cfiOne.steps[i].index < cfiTwo.steps[i].index) { - return -1; - } - // Otherwise continue checking - } - - // All steps in First present in Second - if(cfiOne.steps.length < cfiTwo.steps.length) { - return -1; - } - - // Compare the charecter offset of the text node - if(cfiOne.characterOffset > cfiTwo.characterOffset) { - return 1; - } - if(cfiOne.characterOffset < cfiTwo.characterOffset) { - return -1; - } - - // CFI's are equal - return 0; -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) { - var uri = EPUBJS.core.uri(href); - var path = uri.path; - var fragment = uri.fragment; - var spinePos = book.spineIndexByURL[path]; - var loaded; - var deferred = new RSVP.defer(); - var epubcfi = new EPUBJS.EpubCFI(); - var spineItem; - - if(typeof spinePos !== "undefined"){ - spineItem = book.spine[spinePos]; - loaded = book.loadXml(spineItem.url); - loaded.then(function(doc){ - var element = doc.getElementById(fragment); - var cfi; - cfi = epubcfi.generateCfiFromElement(element, spineItem.cfiBase); - deferred.resolve(cfi); - }); - } - - return deferred.promise; -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) { - var parent = anchor.parentNode; - var steps = this.pathTo(parent); - var path = this.generatePathComponent(steps); - var index = 1 + (2 * Array.prototype.indexOf.call(parent.childNodes, anchor)); - return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")"; -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) { - var anchor = range.anchorNode; - var offset = range.anchorOffset; - return this.generateCfiFromTextNode(anchor, offset, base); -}; - -EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) { - var start, startElement, startSteps, startPath, startOffset, startIndex; - var end, endElement, endSteps, endPath, endOffset, endIndex; - - start = range.startContainer; - - if(start.nodeType === 3) { // text node - startElement = start.parentNode; - //startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start)); - startIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(start)); - startSteps = this.pathTo(startElement); - } else if(range.collapsed) { - return this.generateCfiFromElement(start, base); // single element - } else { - startSteps = this.pathTo(start); - } - - startPath = this.generatePathComponent(startSteps); - startOffset = range.startOffset; - - if(!range.collapsed) { - end = range.endContainer; - - if(end.nodeType === 3) { // text node - endElement = end.parentNode; - // endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end)); - endIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(end)); - - endSteps = this.pathTo(endElement); - } else { - endSteps = this.pathTo(end); - } - - endPath = this.generatePathComponent(endSteps); - endOffset = range.endOffset; - - // Remove steps present in startPath - endPath = endPath.replace(startPath, ''); - - if (endPath.length) { - endPath = endPath + "/"; - } - - return "epubcfi(" + base + "!" + startPath + "/" + startIndex + ":" + startOffset + "," + endPath + endIndex + ":" + endOffset + ")"; - - } else { - return "epubcfi(" + base + "!" + startPath + "/"+ startIndex +":"+ startOffset +")"; - } -}; - -EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) { - var xpath = [".", "*"]; - - steps.forEach(function(step){ - var position = step.index + 1; - - if(step.id){ - xpath.push("*[position()=" + position + " and @id='" + step.id + "']"); - } else if(step.type === "text") { - xpath.push("text()[" + position + "]"); - } else { - xpath.push("*[" + position + "]"); - } - }); - - return xpath.join("/"); -}; - -EPUBJS.EpubCFI.prototype.generateQueryFromSteps = function(steps) { - var query = ["html"]; - - steps.forEach(function(step){ - var position = step.index + 1; - - if(step.id){ - query.push("#" + step.id); - } else if(step.type === "text") { - // unsupported in querySelector - // query.push("text()[" + position + "]"); - } else { - query.push("*:nth-child(" + position + ")"); - } - }); - - return query.join(">"); -}; - - -EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) { - var doc = _doc || document; - var range = doc.createRange(); - var lastStep; - var xpath; - var startContainer; - var textLength; - var query; - var startContainerParent; - - if(typeof cfi === 'string') { - cfi = this.parse(cfi); - } - - // check spinePos - if(cfi.spinePos === -1) { - // Not a valid CFI - return false; - } - - // Get the terminal step - lastStep = cfi.steps[cfi.steps.length-1]; - - if(typeof document.evaluate != 'undefined') { - xpath = this.generateXpathFromSteps(cfi.steps); - startContainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - } else { - // Get the query string - query = this.generateQueryFromSteps(cfi.steps); - // Find the containing element - startContainerParent = doc.querySelector(query); - // Find the text node within that element - if(startContainerParent && lastStep.type == "text") { - startContainer = startContainerParent.childNodes[lastStep.index]; - } - } - - if(!startContainer) { - return null; - } - - if(startContainer && cfi.characterOffset >= 0) { - textLength = startContainer.length; - - if(cfi.characterOffset < textLength) { - range.setStart(startContainer, cfi.characterOffset); - range.setEnd(startContainer, textLength ); - } else { - console.debug("offset greater than length:", cfi.characterOffset, textLength); - range.setStart(startContainer, textLength - 1 ); - range.setEnd(startContainer, textLength ); - } - } else if(startContainer) { - range.selectNode(startContainer); - } - // doc.defaultView.getSelection().addRange(range); - return range; -}; - -EPUBJS.EpubCFI.prototype.isCfiString = function(target) { - if(typeof target === "string" && - target.indexOf("epubcfi(") === 0) { - return true; - } - - return false; -}; - -EPUBJS.Events = function(obj, el){ - - this.events = {}; - - if(!el){ - this.el = document.createElement('div'); - }else{ - this.el = el; - } - - obj.createEvent = this.createEvent; - obj.tell = this.tell; - obj.listen = this.listen; - obj.deafen = this.deafen; - obj.listenUntil = this.listenUntil; - - return this; -}; - -EPUBJS.Events.prototype.createEvent = function(evt){ - var e = new CustomEvent(evt); - this.events[evt] = e; - return e; -}; - -EPUBJS.Events.prototype.tell = function(evt, msg){ - var e; - - if(!this.events[evt]){ - console.warn("No event:", evt, "defined yet, creating."); - e = this.createEvent(evt); - }else{ - e = this.events[evt]; - } - - if(msg) e.msg = msg; - this.el.dispatchEvent(e); - -}; - -EPUBJS.Events.prototype.listen = function(evt, func, bindto){ - if(!this.events[evt]){ - console.warn("No event:", evt, "defined yet, creating."); - this.createEvent(evt); - return; - } - - if(bindto){ - this.el.addEventListener(evt, func.bind(bindto), false); - }else{ - this.el.addEventListener(evt, func, false); - } - -}; - -EPUBJS.Events.prototype.deafen = function(evt, func){ - this.el.removeEventListener(evt, func, false); -}; - -EPUBJS.Events.prototype.listenUntil = function(OnEvt, OffEvt, func, bindto){ - this.listen(OnEvt, func, bindto); - - function unlisten(){ - this.deafen(OnEvt, func); - this.deafen(OffEvt, unlisten); - } - - this.listen(OffEvt, unlisten, this); -}; -EPUBJS.hooks = {}; -EPUBJS.Hooks = (function(){ - function hooks(){} - - //-- Get pre-registered hooks - hooks.prototype.getHooks = function(){ - var plugs; - this.hooks = {}; - Array.prototype.slice.call(arguments).forEach(function(arg){ - this.hooks[arg] = []; - }, this); - - for (var plugType in this.hooks) { - plugs = EPUBJS.core.values(EPUBJS.hooks[plugType]); - - plugs.forEach(function(hook){ - this.registerHook(plugType, hook); - }, this); - } - }; - - //-- Hooks allow for injecting async functions that must all complete before continuing - // Functions must have a callback as their first argument. - hooks.prototype.registerHook = function(type, toAdd, toFront){ - - if(typeof(this.hooks[type]) != "undefined"){ - - if(typeof(toAdd) === "function"){ - if(toFront) { - this.hooks[type].unshift(toAdd); - }else{ - this.hooks[type].push(toAdd); - } - }else if(Array.isArray(toAdd)){ - toAdd.forEach(function(hook){ - if(toFront) { - this.hooks[type].unshift(hook); - }else{ - this.hooks[type].push(hook); - } - }, this); - } - }else{ - //-- Allows for undefined hooks - this.hooks[type] = [toAdd]; - - if(typeof(toAdd) === "function"){ - this.hooks[type] = [toAdd]; - }else if(Array.isArray(toAdd)){ - this.hooks[type] = []; - toAdd.forEach(function(hook){ - this.hooks[type].push(hook); - }, this); - } - - } - }; - - hooks.prototype.removeHook = function(type, toRemove){ - var index; - - if(typeof(this.hooks[type]) != "undefined"){ - - if(typeof(toRemove) === "function"){ - index = this.hooks[type].indexOf(toRemove); - if (index > -1) { - this.hooks[type].splice(index, 1); - } - }else if(Array.isArray(toRemove)){ - toRemove.forEach(function(hook){ - index = this.hooks[type].indexOf(hook); - if (index > -1) { - this.hooks[type].splice(index, 1); - } - }, this); - } - } - }; - - hooks.prototype.triggerHooks = function(type, callback, passed){ - var hooks, count; - - if(typeof(this.hooks[type]) == "undefined") return false; - - hooks = this.hooks[type]; - - count = hooks.length; - if(count === 0 && callback) { - callback(); - } - - function countdown(){ - count--; - if(count <= 0 && callback) callback(); - } - - hooks.forEach(function(hook){ - hook(countdown, passed); - }); - }; - - return { - register: function(name) { - if(EPUBJS.hooks[name] === undefined) { EPUBJS.hooks[name] = {}; } - if(typeof EPUBJS.hooks[name] !== 'object') { throw "Already registered: "+name; } - return EPUBJS.hooks[name]; - }, - mixin: function(object) { - for (var prop in hooks.prototype) { - object[prop] = hooks.prototype[prop]; - } - } - }; -})(); - -EPUBJS.Layout = EPUBJS.Layout || {}; - -EPUBJS.Layout.Reflowable = function(){ - this.documentElement = null; - this.spreadWidth = null; -}; - -EPUBJS.Layout.Reflowable.prototype.format = function(documentElement, _width, _height, _gap){ - // Get the prefixed CSS commands - var columnAxis = EPUBJS.core.prefixed('columnAxis'); - var columnGap = EPUBJS.core.prefixed('columnGap'); - var columnWidth = EPUBJS.core.prefixed('columnWidth'); - var columnFill = EPUBJS.core.prefixed('columnFill'); - - //-- Check the width and create even width columns - var width = Math.floor(_width); - // var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 0; // Not needed for single - var section = Math.floor(width / 8); - var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); - this.documentElement = documentElement; - //-- Single Page - this.spreadWidth = (width + gap); - - - documentElement.style.overflow = "hidden"; - - // Must be set to the new calculated width or the columns will be off - documentElement.style.width = width + "px"; - - //-- Adjust height - documentElement.style.height = _height + "px"; - - //-- Add columns - documentElement.style[columnAxis] = "horizontal"; - documentElement.style[columnFill] = "auto"; - documentElement.style[columnWidth] = width+"px"; - documentElement.style[columnGap] = gap+"px"; - this.colWidth = width; - this.gap = gap; - - return { - pageWidth : this.spreadWidth, - pageHeight : _height - }; -}; - -EPUBJS.Layout.Reflowable.prototype.calculatePages = function() { - var totalWidth, displayedPages; - this.documentElement.style.width = "auto"; //-- reset width for calculations - totalWidth = this.documentElement.scrollWidth; - displayedPages = Math.ceil(totalWidth / this.spreadWidth); - - return { - displayedPages : displayedPages, - pageCount : displayedPages - }; -}; - -EPUBJS.Layout.ReflowableSpreads = function(){ - this.documentElement = null; - this.spreadWidth = null; -}; - -EPUBJS.Layout.ReflowableSpreads.prototype.format = function(documentElement, _width, _height, _gap){ - var columnAxis = EPUBJS.core.prefixed('columnAxis'); - var columnGap = EPUBJS.core.prefixed('columnGap'); - var columnWidth = EPUBJS.core.prefixed('columnWidth'); - var columnFill = EPUBJS.core.prefixed('columnFill'); - - var divisor = 2, - cutoff = 800; - - //-- Check the width and create even width columns - var fullWidth = Math.floor(_width); - var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 1; - - var section = Math.floor(width / 8); - var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); - - //-- Double Page - var colWidth = Math.floor((width - gap) / divisor); - - this.documentElement = documentElement; - this.spreadWidth = (colWidth + gap) * divisor; - - - documentElement.style.overflow = "hidden"; - - // Must be set to the new calculated width or the columns will be off - documentElement.style.width = width + "px"; - - //-- Adjust height - documentElement.style.height = _height + "px"; - - //-- Add columns - documentElement.style[columnAxis] = "horizontal"; - documentElement.style[columnFill] = "auto"; - documentElement.style[columnGap] = gap+"px"; - documentElement.style[columnWidth] = colWidth+"px"; - - this.colWidth = colWidth; - this.gap = gap; - return { - pageWidth : this.spreadWidth, - pageHeight : _height - }; -}; - -EPUBJS.Layout.ReflowableSpreads.prototype.calculatePages = function() { - var totalWidth = this.documentElement.scrollWidth; - var displayedPages = Math.ceil(totalWidth / this.spreadWidth); - - //-- Add a page to the width of the document to account an for odd number of pages - this.documentElement.style.width = ((displayedPages * this.spreadWidth) - this.gap) + "px"; - - return { - displayedPages : displayedPages, - pageCount : displayedPages * 2 - }; -}; - -EPUBJS.Layout.Fixed = function(){ - this.documentElement = null; -}; - -EPUBJS.Layout.Fixed.prototype.format = function(documentElement, _width, _height, _gap){ - var columnWidth = EPUBJS.core.prefixed('columnWidth'); - var viewport = documentElement.querySelector("[name=viewport]"); - var content; - var contents; - var width, height; - this.documentElement = documentElement; - /** - * check for the viewport size - * - */ - if(viewport && viewport.hasAttribute("content")) { - content = viewport.getAttribute("content"); - contents = content.split(','); - if(contents[0]){ - width = contents[0].replace("width=", ''); - } - if(contents[1]){ - height = contents[1].replace("height=", ''); - } - } - - //-- Adjust width and height - documentElement.style.width = width + "px" || "auto"; - documentElement.style.height = height + "px" || "auto"; - - //-- Remove columns - documentElement.style[columnWidth] = "auto"; - - //-- Scroll - documentElement.style.overflow = "auto"; - - this.colWidth = width; - this.gap = 0; - - return { - pageWidth : width, - pageHeight : height - }; - -}; - -EPUBJS.Layout.Fixed.prototype.calculatePages = function(){ - return { - displayedPages : 1, - pageCount : 1 - }; -}; - -EPUBJS.Locations = function(spine, store) { - this.spine = spine; - this.store = store; - - this.epubcfi = new EPUBJS.EpubCFI(); - - this._locations = []; - this.total = 0; - - this.break = 150; - - this._current = 0; - -}; - -EPUBJS.Locations.prototype.generate = function(chars) { - var deferred = new RSVP.defer(); - var spinePos = -1; - var spineLength = this.spine.length; - var nextChapter = function(deferred){ - var chapter; - var next = spinePos + 1; - var done = deferred || new RSVP.defer(); - var loaded; - if(next >= spineLength) { - done.resolve(); - } else { - spinePos = next; - chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); - - this.process(chapter).then(function() { - // Load up the next chapter - setTimeout(function(){ - nextChapter(done); - }, 1); - - }); - } - return done.promise; - }.bind(this); - - var finished = nextChapter().then(function(){ - this.total = this._locations.length-1; - - if (this._currentCfi) { - this.currentLocation = this._currentCfi; - } - deferred.resolve(this._locations); - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Locations.prototype.process = function(chapter) { - return chapter.load(this.request) - .then(function(_doc) { - - var range; - var doc = _doc; - var contents = doc.documentElement.querySelector("body"); - var counter = 0; - var prev; - - this.sprint(contents, function(node) { - var len = node.length; - var dist; - var pos = 0; - - // Start range - if (counter === 0) { - range = doc.createRange(); - range.setStart(node, 0); - } - - dist = this.break - counter; - - // Node is smaller than a break - if(dist > len){ - counter += len; - pos = len; - } - - while (pos < len) { - counter = this.break; - pos += this.break; - - // Gone over - if(pos >= len){ - // Continue counter for next node - counter = len - (pos - this.break); - - // At End - } else { - // End the previous range - range.setEnd(node, pos); - cfi = chapter.cfiFromRange(range); - this._locations.push(cfi); - counter = 0; - - // Start new range - pos += 1; - range = doc.createRange(); - range.setStart(node, pos); - } - - } - - prev = node; - - }.bind(this)); - - // Close remaining - if (range) { - range.setEnd(prev, prev.length); - cfi = chapter.cfiFromRange(range); - this._locations.push(cfi); - counter = 0; - } - - }.bind(this)); - -}; - -EPUBJS.Locations.prototype.sprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false); - - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Locations.prototype.locationFromCfi = function(cfi){ - // Check if the location has not been set yet - if(this._locations.length === 0) { - return -1; - } - - return EPUBJS.core.locationOf(cfi, this._locations, this.epubcfi.compare); -}; - -EPUBJS.Locations.prototype.percentageFromCfi = function(cfi) { - // Find closest cfi - var loc = this.locationFromCfi(cfi); - // Get percentage in total - return this.percentageFromLocation(loc); -}; - -EPUBJS.Locations.prototype.percentageFromLocation = function(loc) { - if (!loc || !this.total) { - return 0; - } - return (loc / this.total); -}; - -EPUBJS.Locations.prototype.cfiFromLocation = function(loc){ - var cfi = -1; - // check that pg is an int - if(typeof loc != "number"){ - loc = parseInt(loc); - } - - if(loc >= 0 && loc < this._locations.length) { - cfi = this._locations[loc]; - } - - return cfi; -}; - -EPUBJS.Locations.prototype.cfiFromPercentage = function(value){ - var percentage = (value > 1) ? value / 100 : value; // Normalize value to 0-1 - var loc = Math.ceil(this.total * percentage); - - return this.cfiFromLocation(loc); -}; - -EPUBJS.Locations.prototype.load = function(locations){ - this._locations = JSON.parse(locations); - this.total = this._locations.length-1; - return this._locations; -}; - -EPUBJS.Locations.prototype.save = function(json){ - return JSON.stringify(this._locations); -}; - -EPUBJS.Locations.prototype.getCurrent = function(json){ - return this._current; -}; - -EPUBJS.Locations.prototype.setCurrent = function(curr){ - var loc; - - if(typeof curr == "string"){ - this._currentCfi = curr; - } else if (typeof curr == "number") { - this._current = curr; - } else { - return; - } - - if(this._locations.length === 0) { - return; - } - - if(typeof curr == "string"){ - loc = this.locationFromCfi(curr); - this._current = loc; - } else { - loc = curr; - } - - this.trigger("changed", { - percentage: this.percentageFromLocation(loc) - }); -}; - -Object.defineProperty(EPUBJS.Locations.prototype, 'currentLocation', { - get: function () { - return this._current; - }, - set: function (curr) { - this.setCurrent(curr); - } -}); - -RSVP.EventTarget.mixin(EPUBJS.Locations.prototype); - -EPUBJS.Pagination = function(pageList) { - this.pages = []; - this.locations = []; - this.epubcfi = new EPUBJS.EpubCFI(); - if(pageList && pageList.length) { - this.process(pageList); - } -}; - -EPUBJS.Pagination.prototype.process = function(pageList){ - pageList.forEach(function(item){ - this.pages.push(item.page); - this.locations.push(item.cfi); - }, this); - - this.pageList = pageList; - this.firstPage = parseInt(this.pages[0]); - this.lastPage = parseInt(this.pages[this.pages.length-1]); - this.totalPages = this.lastPage - this.firstPage; -}; - -EPUBJS.Pagination.prototype.pageFromCfi = function(cfi){ - var pg = -1; - - // Check if the pageList has not been set yet - if(this.locations.length === 0) { - return -1; - } - - // TODO: check if CFI is valid? - - // check if the cfi is in the location list - // var index = this.locations.indexOf(cfi); - var index = EPUBJS.core.indexOfSorted(cfi, this.locations, this.epubcfi.compare); - if(index != -1 && index < (this.pages.length-1) ) { - pg = this.pages[index]; - } else { - // Otherwise add it to the list of locations - // Insert it in the correct position in the locations page - //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare); - index = EPUBJS.core.locationOf(cfi, this.locations, this.epubcfi.compare); - // Get the page at the location just before the new one, or return the first - pg = index-1 >= 0 ? this.pages[index-1] : this.pages[0]; - if(pg !== undefined) { - // Add the new page in so that the locations and page array match up - //this.pages.splice(index, 0, pg); - } else { - pg = -1; - } - - } - return pg; -}; - -EPUBJS.Pagination.prototype.cfiFromPage = function(pg){ - var cfi = -1; - // check that pg is an int - if(typeof pg != "number"){ - pg = parseInt(pg); - } - - // check if the cfi is in the page list - // Pages could be unsorted. - var index = this.pages.indexOf(pg); - if(index != -1) { - cfi = this.locations[index]; - } - // TODO: handle pages not in the list - return cfi; -}; - -EPUBJS.Pagination.prototype.pageFromPercentage = function(percent){ - var pg = Math.round(this.totalPages * percent); - return pg; -}; - -// Returns a value between 0 - 1 corresponding to the location of a page -EPUBJS.Pagination.prototype.percentageFromPage = function(pg){ - var percentage = (pg - this.firstPage) / this.totalPages; - return Math.round(percentage * 1000) / 1000; -}; - -// Returns a value between 0 - 1 corresponding to the location of a cfi -EPUBJS.Pagination.prototype.percentageFromCfi = function(cfi){ - var pg = this.pageFromCfi(cfi); - var percentage = this.percentageFromPage(pg); - return percentage; -}; -EPUBJS.Parser = function(baseUrl){ - this.baseUrl = baseUrl || ''; -}; - -EPUBJS.Parser.prototype.container = function(containerXml){ - //-- - var rootfile, fullpath, folder, encoding; - - if(!containerXml) { - console.error("Container File Not Found"); - return; - } - - rootfile = containerXml.querySelector("rootfile"); - - if(!rootfile) { - console.error("No RootFile Found"); - return; - } - - fullpath = rootfile.getAttribute('full-path'); - folder = EPUBJS.core.uri(fullpath).directory; - encoding = containerXml.xmlEncoding; - - //-- Now that we have the path we can parse the contents - return { - 'packagePath' : fullpath, - 'basePath' : folder, - 'encoding' : encoding - }; -}; - -EPUBJS.Parser.prototype.identifier = function(packageXml){ - var metadataNode; - - if(!packageXml) { - console.error("Package File Not Found"); - return; - } - - metadataNode = packageXml.querySelector("metadata"); - - if(!metadataNode) { - console.error("No Metadata Found"); - return; - } - - return this.getElementText(metadataNode, "identifier"); -}; - -EPUBJS.Parser.prototype.packageContents = function(packageXml, baseUrl){ - var parse = this; - var metadataNode, manifestNode, spineNode; - var manifest, navPath, tocPath, coverPath; - var spineNodeIndex; - var spine; - var spineIndexByURL; - var metadata; - - if(baseUrl) this.baseUrl = baseUrl; - - if(!packageXml) { - console.error("Package File Not Found"); - return; - } - - metadataNode = packageXml.querySelector("metadata"); - if(!metadataNode) { - console.error("No Metadata Found"); - return; - } - - manifestNode = packageXml.querySelector("manifest"); - if(!manifestNode) { - console.error("No Manifest Found"); - return; - } - - spineNode = packageXml.querySelector("spine"); - if(!spineNode) { - console.error("No Spine Found"); - return; - } - - manifest = parse.manifest(manifestNode); - navPath = parse.findNavPath(manifestNode); - tocPath = parse.findTocPath(manifestNode, spineNode); - coverPath = parse.findCoverPath(manifestNode); - - spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); - - spine = parse.spine(spineNode, manifest); - - spineIndexByURL = {}; - spine.forEach(function(item){ - spineIndexByURL[item.href] = item.index; - }); - - metadata = parse.metadata(metadataNode); - - metadata.direction = spineNode.getAttribute("page-progression-direction"); - - return { - 'metadata' : metadata, - 'spine' : spine, - 'manifest' : manifest, - 'navPath' : navPath, - 'tocPath' : tocPath, - 'coverPath': coverPath, - 'spineNodeIndex' : spineNodeIndex, - 'spineIndexByURL' : spineIndexByURL - }; -}; - -//-- Find TOC NAV -EPUBJS.Parser.prototype.findNavPath = function(manifestNode){ - // Find item with property 'nav' - // Should catch nav irregardless of order - var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); - return node ? node.getAttribute('href') : false; -}; - -//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" -EPUBJS.Parser.prototype.findTocPath = function(manifestNode, spineNode){ - var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); - var tocId; - - // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as - // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2, - // "The item that describes the NCX must be referenced by the spine toc attribute." - if (!node) { - tocId = spineNode.getAttribute("toc"); - if(tocId) { - node = manifestNode.querySelector("item[id='" + tocId + "']"); - } - } - - return node ? node.getAttribute('href') : false; -}; - -//-- Find Cover: -EPUBJS.Parser.prototype.findCoverPath = function(manifestNode){ - var node = manifestNode.querySelector("item[properties='cover-image']"); - return node ? node.getAttribute('href') : false; -}; - -//-- Expanded to match Readium web components -EPUBJS.Parser.prototype.metadata = function(xml){ - var metadata = {}, - p = this; - - metadata.bookTitle = p.getElementText(xml, 'title'); - metadata.creator = p.getElementText(xml, 'creator'); - metadata.description = p.getElementText(xml, 'description'); - - metadata.pubdate = p.getElementText(xml, 'date'); - - metadata.publisher = p.getElementText(xml, 'publisher'); - - metadata.identifier = p.getElementText(xml, "identifier"); - metadata.language = p.getElementText(xml, "language"); - metadata.rights = p.getElementText(xml, "rights"); - - metadata.modified_date = p.querySelectorText(xml, "meta[property='dcterms:modified']"); - metadata.layout = p.querySelectorText(xml, "meta[property='rendition:layout']"); - metadata.orientation = p.querySelectorText(xml, "meta[property='rendition:orientation']"); - metadata.spread = p.querySelectorText(xml, "meta[property='rendition:spread']"); - - return metadata; -}; - -EPUBJS.Parser.prototype.getElementText = function(xml, tag){ - var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), - el; - - if(!found || found.length === 0) return ''; - - el = found[0]; - - if(el.childNodes.length){ - return el.childNodes[0].nodeValue; - } - - return ''; - -}; - -EPUBJS.Parser.prototype.querySelectorText = function(xml, q){ - var el = xml.querySelector(q); - - if(el && el.childNodes.length){ - return el.childNodes[0].nodeValue; - } - - return ''; -}; - -EPUBJS.Parser.prototype.manifest = function(manifestXml){ - var baseUrl = this.baseUrl, - manifest = {}; - - //-- Turn items into an array - var selected = manifestXml.querySelectorAll("item"), - items = Array.prototype.slice.call(selected); - - //-- Create an object with the id as key - items.forEach(function(item){ - var id = item.getAttribute('id'), - href = item.getAttribute('href') || '', - type = item.getAttribute('media-type') || '', - properties = item.getAttribute('properties') || ''; - - manifest[id] = { - 'href' : href, - 'url' : baseUrl + href, //-- Absolute URL for loading with a web worker - 'type' : type, - 'properties' : properties - }; - - }); - - return manifest; - -}; - -EPUBJS.Parser.prototype.spine = function(spineXml, manifest){ - var spine = []; - - var selected = spineXml.getElementsByTagName("itemref"), - items = Array.prototype.slice.call(selected); - - var spineNodeIndex = Array.prototype.indexOf.call(spineXml.parentNode.childNodes, spineXml); - - var epubcfi = new EPUBJS.EpubCFI(); - - //-- Add to array to mantain ordering and cross reference with manifest - items.forEach(function(item, index){ - var Id = item.getAttribute('idref'); - var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); - var props = item.getAttribute('properties') || ''; - var propArray = props.length ? props.split(' ') : []; - var manifestProps = manifest[Id].properties; - var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : []; - var vert = { - 'id' : Id, - 'linear' : item.getAttribute('linear') || '', - 'properties' : propArray, - 'manifestProperties' : manifestPropArray, - 'href' : manifest[Id].href, - 'url' : manifest[Id].url, - 'index' : index, - 'cfiBase' : cfiBase, - 'cfi' : "epub(" + cfiBase + ")" - }; - spine.push(vert); - }); - - return spine; -}; - -EPUBJS.Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ - var navEl = navHtml.querySelector('nav[*|type="toc"]'), //-- [*|type="toc"] * Doesn't seem to work - idCounter = 0; - - if(!navEl) return []; - - // Implements `> ol > li` - function findListItems(parent){ - var items = []; - - Array.prototype.slice.call(parent.childNodes).forEach(function(node){ - if('ol' == node.tagName){ - Array.prototype.slice.call(node.childNodes).forEach(function(item){ - if('li' == item.tagName){ - items.push(item); - } - }); - } - }); - - return items; - - } - - // Implements `> a, > span` - function findAnchorOrSpan(parent){ - var item = null; - - Array.prototype.slice.call(parent.childNodes).forEach(function(node){ - if('a' == node.tagName || 'span' == node.tagName){ - item = node; - } - }); - - return item; - } - - function getTOC(parent){ - var list = [], - nodes = findListItems(parent), - items = Array.prototype.slice.call(nodes), - length = items.length, - node; - - if(length === 0) return false; - - items.forEach(function(item){ - var id = item.getAttribute('id') || false, - content = findAnchorOrSpan(item), - href = content.getAttribute('href') || '', - text = content.textContent || "", - split = href.split("#"), - baseUrl = split[0], - subitems = getTOC(item), - spinePos = spineIndexByURL[baseUrl], - spineItem = bookSpine[spinePos], - cfi = spineItem ? spineItem.cfi : ''; - - if(!id) { - if(spinePos) { - spineItem = bookSpine[spinePos]; - id = spineItem.id; - cfi = spineItem.cfi; - } else { - id = 'epubjs-autogen-toc-id-' + (idCounter++); - } - } - - item.setAttribute('id', id); // Ensure all elements have an id - list.push({ - "id": id, - "href": href, - "label": text, - "subitems" : subitems, - "parent" : parent ? parent.getAttribute('id') : null, - "cfi" : cfi - }); - - }); - - return list; - } - - return getTOC(navEl); -}; - -EPUBJS.Parser.prototype.toc = function(tocXml, spineIndexByURL, bookSpine){ - var navMap = tocXml.querySelector("navMap"); - if(!navMap) return []; - - function getTOC(parent){ - var list = [], - snapshot = tocXml.evaluate("*[local-name()='navPoint']", parent, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null), - length = snapshot.snapshotLength; - - if(length === 0) return []; - - for ( var i=length-1 ; i >= 0; i-- ) { - var item = snapshot.snapshotItem(i); - - var id = item.getAttribute('id') || false, - content = item.querySelector("content"), - src = content.getAttribute('src'), - navLabel = item.querySelector("navLabel"), - text = navLabel.textContent ? navLabel.textContent : "", - split = src.split("#"), - baseUrl = split[0], - spinePos = spineIndexByURL[baseUrl], - spineItem = bookSpine[spinePos], - subitems = getTOC(item), - cfi = spineItem ? spineItem.cfi : ''; - - if(!id) { - if(spinePos) { - spineItem = bookSpine[spinePos]; - id = spineItem.id; - cfi = spineItem.cfi; - } else { - id = 'epubjs-autogen-toc-id-' + (idCounter++); - } - } - - list.unshift({ - "id": id, - "href": src, - "label": text, - "spinePos": spinePos, - "subitems" : subitems, - "parent" : parent ? parent.getAttribute('id') : null, - "cfi" : cfi - }); - - } - - return list; - } - - return getTOC(navMap); -}; - -EPUBJS.Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ - var navEl = navHtml.querySelector('nav[*|type="page-list"]'), - idCounter = 0; - - if(!navEl) return []; - - // Implements `> ol > li` - function findListItems(parent){ - var items = []; - - Array.prototype.slice.call(parent.childNodes).forEach(function(node){ - if('ol' == node.tagName){ - Array.prototype.slice.call(node.childNodes).forEach(function(item){ - if('li' == item.tagName){ - items.push(item); - } - }); - } - }); - - return items; - - } - - // Implements `> a, > span` - function findAnchorOrSpan(parent){ - var item = null; - - Array.prototype.slice.call(parent.childNodes).forEach(function(node){ - if('a' == node.tagName || 'span' == node.tagName){ - item = node; - } - }); - - return item; - } - - function getPages(parent){ - var list = [], - nodes = findListItems(parent), - items = Array.prototype.slice.call(nodes), - length = items.length, - node; - - if(length === 0) return false; - - items.forEach(function(item){ - var id = item.getAttribute('id') || false, - content = findAnchorOrSpan(item), - href = content.getAttribute('href') || '', - text = content.textContent || "", - page = parseInt(text), - isCfi = href.indexOf("epubcfi"), - split, - packageUrl, - cfi; - - if(isCfi != -1) { - split = href.split("#"); - packageUrl = split[0]; - cfi = split.length > 1 ? split[1] : false; - list.push({ - "cfi" : cfi, - "href" : href, - "packageUrl" : packageUrl, - "page" : page - }); - } else { - list.push({ - "href" : href, - "page" : page - }); - } - - }); - - return list; - } - - return getPages(navEl); -}; - -EPUBJS.Render.Iframe = function() { - this.iframe = null; - this.document = null; - this.window = null; - this.docEl = null; - this.bodyEl = null; - - this.leftPos = 0; - this.pageWidth = 0; - - this.isMobile = navigator.userAgent.match(/(iPad|iPhone|iPod|Mobile|Android)/g); - this.transform = EPUBJS.core.prefixed('transform'); -}; - -//-- Build up any html needed -EPUBJS.Render.Iframe.prototype.create = function(){ - this.iframe = document.createElement('iframe'); - this.iframe.id = "epubjs-iframe:" + EPUBJS.core.uuid(); - this.iframe.scrolling = "no"; - this.iframe.seamless = "seamless"; - // Back up if seamless isn't supported - this.iframe.style.border = "none"; - - this.iframe.addEventListener("load", this.loaded.bind(this), false); - return this.iframe; -}; - -/** -* Sets the source of the iframe with the given URL string -* Takes: Document Contents String -* Returns: promise with document element -*/ -EPUBJS.Render.Iframe.prototype.load = function(contents, url){ - var render = this, - deferred = new RSVP.defer(); - - if(this.window) { - this.unload(); - } - - this.iframe.onload = function(e) { - var title; - - render.document = render.iframe.contentDocument; - render.docEl = render.document.documentElement; - render.headEl = render.document.head; - render.bodyEl = render.document.body || render.document.querySelector("body"); - render.window = render.iframe.contentWindow; - - render.window.addEventListener("resize", render.resized.bind(render), false); - - // Reset the scroll position - render.leftPos = 0; - render.setLeft(0); - - //-- Clear Margins - if(render.bodyEl) { - render.bodyEl.style.margin = "0"; - } - - // HTML element must have direction set if RTL or columnns will - // not be in the correct direction in Firefox - // Firefox also need the html element to be position right - if(render.direction == "rtl" && render.docEl.dir != "rtl"){ - render.docEl.dir = "rtl"; - render.docEl.style.position = "absolute"; - render.docEl.style.right = "0"; - } - - deferred.resolve(render.docEl); - }; - - this.iframe.onerror = function(e) { - //console.error("Error Loading Contents", e); - deferred.reject({ - message : "Error Loading Contents: " + e, - stack : new Error().stack - }); - }; - - // this.iframe.contentWindow.location.replace(url); - this.document = this.iframe.contentDocument; - - if(!this.document) { - deferred.reject(new Error("No Document Available")); - return deferred; - } - - this.document.open(); - this.document.write(contents); - this.document.close(); - - return deferred.promise; -}; - - -EPUBJS.Render.Iframe.prototype.loaded = function(v){ - var url = this.iframe.contentWindow.location.href; - var baseEl, base; - - this.document = this.iframe.contentDocument; - this.docEl = this.document.documentElement; - this.headEl = this.document.head; - this.bodyEl = this.document.body || this.document.querySelector("body"); - this.window = this.iframe.contentWindow; - - if(url != "about:blank"){ - baseEl = this.iframe.contentDocument.querySelector("base"); - base = baseEl.getAttribute('href'); - this.trigger("render:loaded", base); - } -}; - -// Resize the iframe to the given width and height -EPUBJS.Render.Iframe.prototype.resize = function(width, height){ - var iframeBox; - - if(!this.iframe) return; - - this.iframe.height = height; - - if(!isNaN(width) && width % 2 !== 0){ - width += 1; //-- Prevent cutting off edges of text in columns - } - - this.iframe.width = width; - // Get the fractional height and width of the iframe - // Default to orginal if bounding rect is 0 - this.width = this.iframe.getBoundingClientRect().width || width; - this.height = this.iframe.getBoundingClientRect().height || height; -}; - - -EPUBJS.Render.Iframe.prototype.resized = function(e){ - // Get the fractional height and width of the iframe - this.width = this.iframe.getBoundingClientRect().width; - this.height = this.iframe.getBoundingClientRect().height; -}; - -EPUBJS.Render.Iframe.prototype.totalWidth = function(){ - return this.docEl.scrollWidth; -}; - -EPUBJS.Render.Iframe.prototype.totalHeight = function(){ - return this.docEl.scrollHeight; -}; - -EPUBJS.Render.Iframe.prototype.setPageDimensions = function(pageWidth, pageHeight){ - this.pageWidth = pageWidth; - this.pageHeight = pageHeight; - //-- Add a page to the width of the document to account an for odd number of pages - // this.docEl.style.width = this.docEl.scrollWidth + pageWidth + "px"; -}; - -EPUBJS.Render.Iframe.prototype.setDirection = function(direction){ - - this.direction = direction; - - // Undo previous changes if needed - if(this.docEl && this.docEl.dir == "rtl"){ - this.docEl.dir = "rtl"; - this.docEl.style.position = "static"; - this.docEl.style.right = "auto"; - } - -}; - -EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){ - // this.bodyEl.style.marginLeft = -leftPos + "px"; - // this.docEl.style.marginLeft = -leftPos + "px"; - // this.docEl.style[EPUBJS.Render.Iframe.transform] = 'translate('+ (-leftPos) + 'px, 0)'; - - if (this.isMobile) { - this.docEl.style[this.transform] = 'translate('+ (-leftPos) + 'px, 0)'; - } else { - this.document.defaultView.scrollTo(leftPos, 0); - } - -}; - -EPUBJS.Render.Iframe.prototype.setStyle = function(style, val, prefixed){ - if(prefixed) { - style = EPUBJS.core.prefixed(style); - } - - if(this.bodyEl) this.bodyEl.style[style] = val; -}; - -EPUBJS.Render.Iframe.prototype.removeStyle = function(style){ - - if(this.bodyEl) this.bodyEl.style[style] = ''; - -}; - -EPUBJS.Render.Iframe.prototype.addHeadTag = function(tag, attrs, _doc) { - var doc = _doc || this.document; - var tagEl = doc.createElement(tag); - var headEl = doc.head; - - for(var attr in attrs) { - tagEl.setAttribute(attr, attrs[attr]); - } - - if(headEl) headEl.insertBefore(tagEl, headEl.firstChild); -}; - -EPUBJS.Render.Iframe.prototype.page = function(pg){ - this.leftPos = this.pageWidth * (pg-1); //-- pages start at 1 - - // Reverse for rtl langs - if(this.direction === "rtl"){ - this.leftPos = this.leftPos * -1; - } - - this.setLeft(this.leftPos); -}; - -//-- Show the page containing an Element -EPUBJS.Render.Iframe.prototype.getPageNumberByElement = function(el){ - var left, pg; - if(!el) return; - - left = this.leftPos + el.getBoundingClientRect().left; //-- Calculate left offset compaired to scrolled position - - pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 - - return pg; -}; - -//-- Show the page containing an Element -EPUBJS.Render.Iframe.prototype.getPageNumberByRect = function(boundingClientRect){ - var left, pg; - - left = this.leftPos + boundingClientRect.left; //-- Calculate left offset compaired to scrolled position - pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 - - return pg; -}; - -// Return the root element of the content -EPUBJS.Render.Iframe.prototype.getBaseElement = function(){ - return this.bodyEl; -}; - -// Return the document element -EPUBJS.Render.Iframe.prototype.getDocumentElement = function(){ - return this.docEl; -}; - -// Checks if an element is on the screen -EPUBJS.Render.Iframe.prototype.isElementVisible = function(el){ - var rect; - var left; - - if(el && typeof el.getBoundingClientRect === 'function'){ - rect = el.getBoundingClientRect(); - left = rect.left; //+ rect.width; - if( rect.width !== 0 && - rect.height !== 0 && // Element not visible - left >= 0 && - left < this.pageWidth ) { - return true; - } - } - - return false; -}; - - -EPUBJS.Render.Iframe.prototype.scroll = function(bool){ - if(bool) { - this.iframe.scrolling = "yes"; - } else { - this.iframe.scrolling = "no"; - } -}; - -// Cleanup event listeners -EPUBJS.Render.Iframe.prototype.unload = function(){ - this.window.removeEventListener("resize", this.resized); -}; - -//-- Enable binding events to Render -RSVP.EventTarget.mixin(EPUBJS.Render.Iframe.prototype); - -EPUBJS.Renderer = function(renderMethod, hidden) { - // Dom events to listen for - this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click"]; - this.upEvent = "mouseup"; - this.downEvent = "mousedown"; - if('ontouchstart' in document.documentElement) { - this.listenedEvents.push("touchstart", "touchend"); - this.upEvent = "touchend"; - this.downEvent = "touchstart"; - } - /** - * Setup a render method. - * Options are: Iframe - */ - if(renderMethod && typeof(EPUBJS.Render[renderMethod]) != "undefined"){ - this.render = new EPUBJS.Render[renderMethod](); - } else { - console.error("Not a Valid Rendering Method"); - } - - // Listen for load events - this.render.on("render:loaded", this.loaded.bind(this)); - - // Cached for replacement urls from storage - this.caches = {}; - - // Blank Cfi for Parsing - this.epubcfi = new EPUBJS.EpubCFI(); - - this.spreads = true; - this.isForcedSingle = false; - this.resized = this.onResized.bind(this); - - this.layoutSettings = {}; - - this.hidden = hidden || false; - //-- Adds Hook methods to the Book prototype - // Hooks will all return before triggering the callback. - EPUBJS.Hooks.mixin(this); - //-- Get pre-registered hooks for events - this.getHooks("beforeChapterDisplay"); - - //-- Queue up page changes if page map isn't ready - this._q = EPUBJS.core.queue(this); - - this._moving = false; - -}; - -//-- Renderer events for listening -EPUBJS.Renderer.prototype.Events = [ - "renderer:keydown", - "renderer:keyup", - "renderer:keypressed", - "renderer:mouseup", - "renderer:mousedown", - "renderer:click", - "renderer:touchstart", - "renderer:touchend", - "renderer:selected", - "renderer:chapterUnloaded", - "renderer:chapterDisplayed", - "renderer:locationChanged", - "renderer:visibleLocationChanged", - "renderer:resized", - "renderer:spreads" -]; - -/** -* Creates an element to render to. -* Resizes to passed width and height or to the elements size -*/ -EPUBJS.Renderer.prototype.initialize = function(element, width, height){ - this.container = element; - this.element = this.render.create(); - - this.initWidth = width; - this.initHeight = height; - - this.width = width || this.container.clientWidth; - this.height = height || this.container.clientHeight; - - this.container.appendChild(this.element); - - if(width && height){ - this.render.resize(this.width, this.height); - } else { - this.render.resize('100%', '100%'); - } - - document.addEventListener("orientationchange", this.onResized); -}; - -/** -* Display a chapter -* Takes: chapter object, global layout settings -* Returns: Promise with passed Renderer after pages has loaded -*/ -EPUBJS.Renderer.prototype.displayChapter = function(chapter, globalLayout){ - var store = false; - if(this._moving) { - console.error("Rendering In Progress"); - return; - } - this._moving = true; - // Get the url string from the chapter (may be from storage) - return chapter.render(). - then(function(contents) { - - // Unload the previous chapter listener - if(this.currentChapter) { - this.currentChapter.unload(); // Remove stored blobs - - if(this.render.window){ - this.render.window.removeEventListener("resize", this.resized); - } - - this.removeEventListeners(); - this.removeSelectionListeners(); - this.trigger("renderer:chapterUnloaded"); - this.contents = null; - this.doc = null; - this.pageMap = null; - } - - this.currentChapter = chapter; - - this.chapterPos = 1; - - this.currentChapterCfiBase = chapter.cfiBase; - - this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties); - - return this.load(contents, chapter.href); - - }.bind(this)); - -}; - -/** -* Loads a url (string) and renders it, -* attaching event listeners and triggering hooks. -* Returns: Promise with the rendered contents. -*/ - -EPUBJS.Renderer.prototype.load = function(contents, url){ - var deferred = new RSVP.defer(); - var loaded; - - // Switch to the required layout method for the settings - this.layoutMethod = this.determineLayout(this.layoutSettings); - this.layout = new EPUBJS.Layout[this.layoutMethod](); - - this.visible(false); - - render = this.render.load(contents, url); - - render.then(function(contents) { - - this.afterLoad(contents); - - //-- Trigger registered hooks before displaying - this.beforeDisplay(function(){ - - this.afterDisplay(); - - this.visible(true); - - - deferred.resolve(this); //-- why does this return the renderer? - - }.bind(this)); - - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Renderer.prototype.afterLoad = function(contents) { - var formated; - this.currentChapter.setDocument(this.render.document); - this.contents = contents; - this.doc = this.render.document; - - // Format the contents using the current layout method - this.formated = this.layout.format(contents, this.render.width, this.render.height, this.gap); - this.render.setPageDimensions(this.formated.pageWidth, this.formated.pageHeight); - - // window.addEventListener("orientationchange", this.onResized.bind(this), false); - if(!this.initWidth && !this.initHeight){ - this.render.window.addEventListener("resize", this.resized, false); - } - - this.addEventListeners(); - this.addSelectionListeners(); - -}; - -EPUBJS.Renderer.prototype.afterDisplay = function(contents) { - - var pages = this.layout.calculatePages(); - var msg = this.currentChapter; - var queued = this._q.length(); - this._moving = false; - - this.updatePages(pages); - - this.visibleRangeCfi = this.getVisibleRangeCfi(); - this.currentLocationCfi = this.visibleRangeCfi.start; - - if(queued === 0) { - this.trigger("renderer:locationChanged", this.currentLocationCfi); - this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); - } - - msg.cfi = this.currentLocationCfi; //TODO: why is this cfi passed to chapterDisplayed - this.trigger("renderer:chapterDisplayed", msg); - -}; - -EPUBJS.Renderer.prototype.loaded = function(url){ - this.trigger("render:loaded", url); - // var uri = EPUBJS.core.uri(url); - // var relative = uri.path.replace(book.bookUrl, ''); - // console.log(url, uri, relative); -}; - -/** -* Reconciles the current chapters layout properies with -* the global layout properities. -* Takes: global layout settings object, chapter properties string -* Returns: Object with layout properties -*/ -EPUBJS.Renderer.prototype.reconcileLayoutSettings = function(global, chapter){ - var settings = {}; - - //-- Get the global defaults - for (var attr in global) { - if (global.hasOwnProperty(attr)){ - settings[attr] = global[attr]; - } - } - //-- Get the chapter's display type - chapter.forEach(function(prop){ - var rendition = prop.replace("rendition:", ''); - var split = rendition.indexOf("-"); - var property, value; - - if(split != -1){ - property = rendition.slice(0, split); - value = rendition.slice(split+1); - - settings[property] = value; - } - }); - return settings; -}; - -/** -* Uses the settings to determine which Layout Method is needed -* Triggers events based on the method choosen -* Takes: Layout settings object -* Returns: String of appropriate for EPUBJS.Layout function -*/ -EPUBJS.Renderer.prototype.determineLayout = function(settings){ - // Default is layout: reflowable & spread: auto - var spreads = this.determineSpreads(this.minSpreadWidth); - var layoutMethod = spreads ? "ReflowableSpreads" : "Reflowable"; - var scroll = false; - - if(settings.layout === "pre-paginated") { - layoutMethod = "Fixed"; - scroll = true; - spreads = false; - } - - if(settings.layout === "reflowable" && settings.spread === "none") { - layoutMethod = "Reflowable"; - scroll = false; - spreads = false; - } - - if(settings.layout === "reflowable" && settings.spread === "both") { - layoutMethod = "ReflowableSpreads"; - scroll = false; - spreads = true; - } - - this.spreads = spreads; - this.render.scroll(scroll); - this.trigger("renderer:spreads", spreads); - return layoutMethod; -}; - -// Shortcut to trigger the hook before displaying the chapter -EPUBJS.Renderer.prototype.beforeDisplay = function(callback, renderer){ - this.triggerHooks("beforeChapterDisplay", callback, this); -}; - -// Update the renderer with the information passed by the layout -EPUBJS.Renderer.prototype.updatePages = function(layout){ - this.pageMap = this.mapPage(); - // this.displayedPages = layout.displayedPages; - - if (this.spreads) { - this.displayedPages = Math.ceil(this.pageMap.length / 2); - } else { - this.displayedPages = this.pageMap.length; - } - - // this.currentChapter.pages = layout.pageCount; - this.currentChapter.pages = this.pageMap.length; - - this._q.flush(); -}; - -// Apply the layout again and jump back to the previous cfi position -EPUBJS.Renderer.prototype.reformat = function(){ - var renderer = this; - var formated, pages; - if(!this.contents) return; - - spreads = this.determineSpreads(this.minSpreadWidth); - - // Only re-layout if the spreads have switched - if(spreads != this.spreads){ - this.spreads = spreads; - this.layoutMethod = this.determineLayout(this.layoutSettings); - this.layout = new EPUBJS.Layout[this.layoutMethod](); - } - - // Reset pages - this.chapterPos = 1; - - this.render.page(this.chapterPos); - // Give the css styles time to update - // clearTimeout(this.timeoutTillCfi); - // this.timeoutTillCfi = setTimeout(function(){ - renderer.formated = renderer.layout.format(renderer.render.docEl, renderer.render.width, renderer.render.height, renderer.gap); - renderer.render.setPageDimensions(renderer.formated.pageWidth, renderer.formated.pageHeight); - - pages = renderer.layout.calculatePages(); - renderer.updatePages(pages); - - //-- Go to current page after formating - if(renderer.currentLocationCfi){ - renderer.gotoCfi(renderer.currentLocationCfi); - } - // renderer.timeoutTillCfi = null; - -}; - -// Hide and show the render's container . -EPUBJS.Renderer.prototype.visible = function(bool){ - if(typeof(bool) === "undefined") { - return this.element.style.visibility; - } - - if(bool === true && !this.hidden){ - this.element.style.visibility = "visible"; - }else if(bool === false){ - this.element.style.visibility = "hidden"; - } -}; - -// Remove the render element and clean up listeners -EPUBJS.Renderer.prototype.remove = function() { - if(this.render.window) { - this.render.unload(); - this.render.window.removeEventListener("resize", this.resized); - this.removeEventListeners(); - this.removeSelectionListeners(); - } - - this.container.removeChild(this.element); -}; - -//-- STYLES - -EPUBJS.Renderer.prototype.applyStyles = function(styles) { - for (var style in styles) { - this.render.setStyle(style, styles[style]); - } -}; - -EPUBJS.Renderer.prototype.setStyle = function(style, val, prefixed){ - this.render.setStyle(style, val, prefixed); -}; - -EPUBJS.Renderer.prototype.removeStyle = function(style){ - this.render.removeStyle(style); -}; - -//-- HEAD TAGS -EPUBJS.Renderer.prototype.applyHeadTags = function(headTags) { - for ( var headTag in headTags ) { - this.render.addHeadTag(headTag, headTags[headTag]); - } -}; - -//-- NAVIGATION - -EPUBJS.Renderer.prototype.page = function(pg){ - if(!this.pageMap) { - console.warn("pageMap not set, queuing"); - this._q.enqueue("page", arguments); - return true; - } - - if(pg >= 1 && pg <= this.displayedPages){ - this.chapterPos = pg; - - this.render.page(pg); - this.visibleRangeCfi = this.getVisibleRangeCfi(); - this.currentLocationCfi = this.visibleRangeCfi.start; - this.trigger("renderer:locationChanged", this.currentLocationCfi); - this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); - - return true; - } - //-- Return false if page is greater than the total - return false; -}; - -// Short cut to find next page's cfi starting at the last visible element -/* -EPUBJS.Renderer.prototype.nextPage = function(){ - var pg = this.chapterPos + 1; - if(pg <= this.displayedPages){ - this.chapterPos = pg; - - this.render.page(pg); - - this.currentLocationCfi = this.getPageCfi(this.visibileEl); - this.trigger("renderer:locationChanged", this.currentLocationCfi); - - return true; - } - //-- Return false if page is greater than the total - return false; -}; -*/ -EPUBJS.Renderer.prototype.nextPage = function(){ - return this.page(this.chapterPos + 1); -}; - -EPUBJS.Renderer.prototype.prevPage = function(){ - return this.page(this.chapterPos - 1); -}; - -//-- Show the page containing an Element -EPUBJS.Renderer.prototype.pageByElement = function(el){ - var pg; - if(!el) return; - - pg = this.render.getPageNumberByElement(el); - this.page(pg); -}; - -// Jump to the last page of the chapter -EPUBJS.Renderer.prototype.lastPage = function(){ - if(this._moving) { - return this._q.enqueue("lastPage", arguments); - } - - this.page(this.displayedPages); -}; - -// Jump to the first page of the chapter -EPUBJS.Renderer.prototype.firstPage = function(){ - if(this._moving) { - return this._q.enqueue("firstPage", arguments); - } - - this.page(1); -}; - -//-- Find a section by fragement id -EPUBJS.Renderer.prototype.section = function(fragment){ - var el = this.doc.getElementById(fragment), - left, pg; - - if(el){ - this.pageByElement(el); - } - -}; - -EPUBJS.Renderer.prototype.firstElementisTextNode = function(node) { - var children = node.childNodes; - var leng = children.length; - - if(leng && - children[0] && // First Child - children[0].nodeType === 3 && // This is a textNodes - children[0].textContent.trim().length) { // With non whitespace or return charecters - return true; - } - return false; -}; - -EPUBJS.Renderer.prototype.isGoodNode = function(node) { - var embeddedElements = ["audio", "canvas", "embed", "iframe", "img", "math", "object", "svg", "video"]; - if (embeddedElements.indexOf(node.tagName.toLowerCase()) !== -1) { - // Embedded elements usually do not have a text node as first element, but are also good nodes - return true; - } - return this.firstElementisTextNode(node); -}; - -// Walk the node tree from a start element to next visible element -EPUBJS.Renderer.prototype.walk = function(node, x, y) { - var r, children, leng, - startNode = node, - prevNode, - stack = [startNode]; - - var STOP = 10000, ITER=0; - - while(!r && stack.length) { - node = stack.shift(); - if( this.containsPoint(node, x, y) && this.isGoodNode(node)) { - r = node; - } - - if(!r && node && node.childElementCount > 0){ - children = node.children; - if (children && children.length) { - leng = children.length ? children.length : 0; - } else { - return r; - } - for (var i = leng-1; i >= 0; i--) { - if(children[i] != prevNode) stack.unshift(children[i]); - } - } - - if(!r && stack.length === 0 && startNode && startNode.parentNode !== null){ - stack.push(startNode.parentNode); - prevNode = startNode; - startNode = startNode.parentNode; - } - - - ITER++; - if(ITER > STOP) { - console.error("ENDLESS LOOP"); - break; - } - - } - - return r; -}; - -// Checks if an element is on the screen -EPUBJS.Renderer.prototype.containsPoint = function(el, x, y){ - var rect; - var left; - if(el && typeof el.getBoundingClientRect === 'function'){ - rect = el.getBoundingClientRect(); - // console.log(el, rect, x, y); - - if( rect.width !== 0 && - rect.height !== 0 && // Element not visible - rect.left >= x && - x <= rect.left + rect.width) { - return true; - } - } - - return false; -}; - -EPUBJS.Renderer.prototype.textSprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: function (node) { - if ( ! /^\s*$/.test(node.data) ) { - return NodeFilter.FILTER_ACCEPT; - } else { - return NodeFilter.FILTER_REJECT; - } - } - }, false); - var node; - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Renderer.prototype.sprint = function(root, func) { - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null, false); - var node; - while ((node = treeWalker.nextNode())) { - func(node); - } - -}; - -EPUBJS.Renderer.prototype.mapPage = function(){ - var renderer = this; - var map = []; - var root = this.render.getBaseElement(); - var page = 1; - var width = this.layout.colWidth + this.layout.gap; - var offset = this.formated.pageWidth * (this.chapterPos-1); - var limit = (width * page) - offset;// (width * page) - offset; - var elLimit = 0; - var prevRange; - var cfi; - var check = function(node) { - var elPos; - var elRange; - var children = Array.prototype.slice.call(node.childNodes); - if (node.nodeType == Node.ELEMENT_NODE) { - // elPos = node.getBoundingClientRect(); - elRange = document.createRange(); - elRange.selectNodeContents(node); - elPos = elRange.getBoundingClientRect(); - - if(!elPos || (elPos.width === 0 && elPos.height === 0)) { - return; - } - - //-- Element starts new Col - if(elPos.left > elLimit) { - children.forEach(function(node){ - if(node.nodeType == Node.TEXT_NODE && - node.textContent.trim().length) { - checkText(node); - } - }); - } - - //-- Element Spans new Col - if(elPos.right > elLimit) { - children.forEach(function(node){ - if(node.nodeType == Node.TEXT_NODE && - node.textContent.trim().length) { - checkText(node); - } - }); - } - } - - }; - var checkText = function(node){ - var ranges = renderer.splitTextNodeIntoWordsRanges(node); - ranges.forEach(function(range){ - var pos = range.getBoundingClientRect(); - - if(!pos || (pos.width === 0 && pos.height === 0)) { - return; - } - if(pos.left + pos.width < limit) { - if(!map[page-1]){ - range.collapse(true); - cfi = renderer.currentChapter.cfiFromRange(range); - // map[page-1].start = cfi; - map.push({ start: cfi, end: null }); - } - } else { - if(prevRange){ - prevRange.collapse(true); - cfi = renderer.currentChapter.cfiFromRange(prevRange); - map[map.length-1].end = cfi; - } - - range.collapse(true); - cfi = renderer.currentChapter.cfiFromRange(range); - map.push({ - start: cfi, - end: null - }); - - page += 1; - limit = (width * page) - offset; - elLimit = limit; - } - - prevRange = range; - }); - - - }; - var docEl = this.render.getDocumentElement(); - var dir = docEl.dir; - - // Set back to ltr before sprinting to get correct order - if(dir == "rtl") { - docEl.dir = "ltr"; - docEl.style.position = "static"; - } - - this.sprint(root, check); - - // Reset back to previous RTL settings - if(dir == "rtl") { - docEl.dir = dir; - docEl.style.left = "auto"; - docEl.style.right = "0"; - } - - // this.textSprint(root, checkText); - - if(prevRange){ - prevRange.collapse(true); - - cfi = renderer.currentChapter.cfiFromRange(prevRange); - map[map.length-1].end = cfi; - } - - // Handle empty map - if(!map.length) { - range = this.doc.createRange(); - range.selectNodeContents(root); - range.collapse(true); - - cfi = renderer.currentChapter.cfiFromRange(range); - - map.push({ start: cfi, end: cfi }); - - } - - // clean up - prevRange = null; - ranges = null; - range = null; - root = null; - - return map; -}; - - -EPUBJS.Renderer.prototype.indexOfBreakableChar = function (text, startPosition) { - var whiteCharacters = "\x2D\x20\t\r\n\b\f"; - // '-' \x2D - // ' ' \x20 - - if (! startPosition) { - startPosition = 0; - } - - for (var i = startPosition; i < text.length; i++) { - if (whiteCharacters.indexOf(text.charAt(i)) != -1) { - return i; - } - } - - return -1; -}; - - -EPUBJS.Renderer.prototype.splitTextNodeIntoWordsRanges = function(node){ - var ranges = []; - var text = node.textContent.trim(); - var range; - var rect; - var list; - // jaroslaw.bielski@7bulls.com - // Usage of indexOf() function for space character as word delimiter - // is not sufficient in case of other breakable characters like \r\n- etc - pos = this.indexOfBreakableChar(text); - - if(pos === -1) { - range = this.doc.createRange(); - range.selectNodeContents(node); - return [range]; - } - - range = this.doc.createRange(); - range.setStart(node, 0); - range.setEnd(node, pos); - ranges.push(range); - - // jaroslaw.bielski@7bulls.com - // there was a word miss in case of one letter words - range = this.doc.createRange(); - range.setStart(node, pos+1); - - while ( pos != -1 ) { - - pos = this.indexOfBreakableChar(text, pos + 1); - if(pos > 0) { - - if(range) { - range.setEnd(node, pos); - ranges.push(range); - } - - range = this.doc.createRange(); - range.setStart(node, pos+1); - } - } - - if(range) { - range.setEnd(node, text.length); - ranges.push(range); - } - - return ranges; -}; - -EPUBJS.Renderer.prototype.rangePosition = function(range){ - var rect; - var list; - - list = range.getClientRects(); - - if(list.length) { - rect = list[0]; - return rect; - } - - return null; -}; - -/* -// Get the cfi of the current page -EPUBJS.Renderer.prototype.getPageCfi = function(prevEl){ - var range = this.doc.createRange(); - var position; - // TODO : this might need to take margin / padding into account? - var x = 1;//this.formated.pageWidth/2; - var y = 1;//;this.formated.pageHeight/2; - - range = this.getRange(x, y); - - // var test = this.doc.defaultView.getSelection(); - // var r = this.doc.createRange(); - // test.removeAllRanges(); - // r.setStart(range.startContainer, range.startOffset); - // r.setEnd(range.startContainer, range.startOffset + 1); - // test.addRange(r); - - return this.currentChapter.cfiFromRange(range); -}; -*/ - -// Get the cfi of the current page -EPUBJS.Renderer.prototype.getPageCfi = function(){ - var pg; - if (this.spreads) { - pg = this.chapterPos*2; - startRange = this.pageMap[pg-2]; - } else { - pg = this.chapterPos; - startRange = this.pageMap[pg-1]; - } - return this.pageMap[(this.chapterPos * 2) -1].start; -}; - -EPUBJS.Renderer.prototype.getRange = function(x, y, forceElement){ - var range = this.doc.createRange(); - var position; - forceElement = true; // temp override - if(typeof document.caretPositionFromPoint !== "undefined" && !forceElement){ - position = this.doc.caretPositionFromPoint(x, y); - range.setStart(position.offsetNode, position.offset); - } else if(typeof document.caretRangeFromPoint !== "undefined" && !forceElement){ - range = this.doc.caretRangeFromPoint(x, y); - } else { - this.visibileEl = this.findElementAfter(x, y); - range.setStart(this.visibileEl, 1); - } - - // var test = this.doc.defaultView.getSelection(); - // var r = this.doc.createRange(); - // test.removeAllRanges(); - // r.setStart(range.startContainer, range.startOffset); - // r.setEnd(range.startContainer, range.startOffset + 1); - // test.addRange(r); - return range; -}; - -/* -EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(prevEl){ - var startX = 0; - var startY = 0; - var endX = this.width-1; - var endY = this.height-1; - var startRange = this.getRange(startX, startY); - var endRange = this.getRange(endX, endY); //fix if carret not avail - var startCfi = this.currentChapter.cfiFromRange(startRange); - var endCfi; - if(endRange) { - endCfi = this.currentChapter.cfiFromRange(endRange); - } - - return { - start: startCfi, - end: endCfi || false - }; -}; -*/ - -EPUBJS.Renderer.prototype.pagesInCurrentChapter = function() { - var pgs; - var length; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - length = this.pageMap.length; - - if(this.spreads){ - pgs = Math.ceil(length / 2); - } else { - pgs = length; - } - - return pgs; -}; - -EPUBJS.Renderer.prototype.currentRenderedPage = function(){ - var pg; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - if (this.spreads && this.layout.pageCount > 1) { - pg = this.chapterPos*2; - } else { - pg = this.chapterPos; - } - - return pg; -}; - -EPUBJS.Renderer.prototype.getRenderedPagesLeft = function(){ - var pg; - var lastPage; - var pagesLeft; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - lastPage = this.pageMap.length; - - if (this.spreads) { - pg = this.chapterPos*2; - } else { - pg = this.chapterPos; - } - - pagesLeft = lastPage - pg; - return pagesLeft; - -}; - -EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(){ - var pg; - var startRange, endRange; - - if(!this.pageMap) { - console.warn("page map not loaded"); - return false; - } - - if (this.spreads) { - pg = this.chapterPos*2; - startRange = this.pageMap[pg-2]; - endRange = startRange; - - if(this.layout.pageCount > 1) { - endRange = this.pageMap[pg-1]; - } - } else { - pg = this.chapterPos; - startRange = this.pageMap[pg-1]; - endRange = startRange; - } - - if(!startRange) { - console.warn("page range miss:", pg, this.pageMap); - startRange = this.pageMap[this.pageMap.length-1]; - endRange = startRange; - } - - return { - start: startRange.start, - end: endRange.end - }; -}; - -// Goto a cfi position in the current chapter -EPUBJS.Renderer.prototype.gotoCfi = function(cfi){ - var pg; - var marker; - var range; - - if(this._moving){ - return this._q.enqueue("gotoCfi", arguments); - } - - if(EPUBJS.core.isString(cfi)){ - cfi = this.epubcfi.parse(cfi); - } - - if(typeof document.evaluate === 'undefined') { - marker = this.epubcfi.addMarker(cfi, this.doc); - if(marker) { - pg = this.render.getPageNumberByElement(marker); - // Must Clean up Marker before going to page - this.epubcfi.removeMarker(marker, this.doc); - this.page(pg); - } - } else { - range = this.epubcfi.generateRangeFromCfi(cfi, this.doc); - if(range) { - // jaroslaw.bielski@7bulls.com - // It seems that sometimes getBoundingClientRect() returns null for first page CFI in chapter. - // It is always reproductible if few consecutive chapters have only one page. - // NOTE: This is only workaround and the issue needs an deeper investigation. - // NOTE: Observed on Android 4.2.1 using WebView widget as HTML renderer (Asus TF300T). - var rect = range.getBoundingClientRect(); - if (rect) { - pg = this.render.getPageNumberByRect(rect); - - } else { - // Goto first page in chapter - pg = 1; - } - - this.page(pg); - - // Reset the current location cfi to requested cfi - this.currentLocationCfi = cfi.str; - } else { - // Failed to find a range, go to first page - this.page(1); - } - } -}; - -// Walk nodes until a visible element is found -EPUBJS.Renderer.prototype.findFirstVisible = function(startEl){ - var el = startEl || this.render.getBaseElement(); - var found; - // kgolunski@7bulls.com - // Looks like an old API usage - // Set x and y as 0 to fullfill walk method API. - found = this.walk(el, 0, 0); - - if(found) { - return found; - }else{ - return startEl; - } - -}; -// TODO: remove me - unsused -EPUBJS.Renderer.prototype.findElementAfter = function(x, y, startEl){ - var el = startEl || this.render.getBaseElement(); - var found; - found = this.walk(el, x, y); - if(found) { - return found; - }else{ - return el; - } - -}; - -/* -EPUBJS.Renderer.prototype.route = function(hash, callback){ - var location = window.location.hash.replace('#/', ''); - if(this.useHash && location.length && location != this.prevLocation){ - this.show(location, callback); - this.prevLocation = location; - return true; - } - return false; -} - -EPUBJS.Renderer.prototype.hideHashChanges = function(){ - this.useHash = false; -} - -*/ - -EPUBJS.Renderer.prototype.resize = function(width, height, setSize){ - var spreads; - - this.width = width; - this.height = height; - - if(setSize !== false) { - this.render.resize(this.width, this.height); - } - - - - if(this.contents){ - this.reformat(); - } - - this.trigger("renderer:resized", { - width: this.width, - height: this.height - }); -}; - -//-- Listeners for events in the frame - -EPUBJS.Renderer.prototype.onResized = function(e) { - var width = this.container.clientWidth; - var height = this.container.clientHeight; - - this.resize(width, height, false); -}; - -EPUBJS.Renderer.prototype.addEventListeners = function(){ - if(!this.render.document) { - return; - } - this.listenedEvents.forEach(function(eventName){ - this.render.document.addEventListener(eventName, this.triggerEvent.bind(this), false); - }, this); - -}; - -EPUBJS.Renderer.prototype.removeEventListeners = function(){ - if(!this.render.document) { - return; - } - this.listenedEvents.forEach(function(eventName){ - this.render.document.removeEventListener(eventName, this.triggerEvent, false); - }, this); - -}; - -// Pass browser events -EPUBJS.Renderer.prototype.triggerEvent = function(e){ - this.trigger("renderer:"+e.type, e); -}; - -EPUBJS.Renderer.prototype.addSelectionListeners = function(){ - this.render.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); -}; - -EPUBJS.Renderer.prototype.removeSelectionListeners = function(){ - if(!this.render.document) { - return; - } - this.doc.removeEventListener("selectionchange", this.onSelectionChange, false); -}; - -EPUBJS.Renderer.prototype.onSelectionChange = function(e){ - if (this.selectionEndTimeout) { - clearTimeout(this.selectionEndTimeout); - } - this.selectionEndTimeout = setTimeout(function() { - this.selectedRange = this.render.window.getSelection(); - this.trigger("renderer:selected", this.selectedRange); - }.bind(this), 500); -}; - - -//-- Spreads - -EPUBJS.Renderer.prototype.setMinSpreadWidth = function(width){ - this.minSpreadWidth = width; - this.spreads = this.determineSpreads(width); -}; - -EPUBJS.Renderer.prototype.determineSpreads = function(cutoff){ - if(this.isForcedSingle || !cutoff || this.width < cutoff) { - return false; //-- Single Page - }else{ - return true; //-- Double Page - } -}; - -EPUBJS.Renderer.prototype.forceSingle = function(bool){ - if(bool) { - this.isForcedSingle = true; - // this.spreads = false; - } else { - this.isForcedSingle = false; - // this.spreads = this.determineSpreads(this.minSpreadWidth); - } -}; - -EPUBJS.Renderer.prototype.setGap = function(gap){ - this.gap = gap; //-- False == auto gap -}; - -EPUBJS.Renderer.prototype.setDirection = function(direction){ - this.direction = direction; - this.render.setDirection(this.direction); -}; - -//-- Content Replacements - -EPUBJS.Renderer.prototype.replace = function(query, func, finished, progress){ - var items = this.contents.querySelectorAll(query), - resources = Array.prototype.slice.call(items), - count = resources.length; - - - if(count === 0) { - finished(false); - return; - } - resources.forEach(function(item){ - var called = false; - var after = function(result, full){ - if(called === false) { - count--; - if(progress) progress(result, full, count); - if(count <= 0 && finished) finished(true); - called = true; - } - }; - - func(item, after); - - }.bind(this)); - -}; - -//-- Enable binding events to Renderer -RSVP.EventTarget.mixin(EPUBJS.Renderer.prototype); - -var EPUBJS = EPUBJS || {}; -EPUBJS.replace = {}; - -//-- Replaces the relative links within the book to use our internal page changer -EPUBJS.replace.hrefs = function(callback, renderer){ - var book = this; - var replacments = function(link, done){ - var href = link.getAttribute("href"), - isRelative = href.search("://"), - directory, - relative, - location; - - if(isRelative != -1){ - - link.setAttribute("target", "_blank"); - - }else{ - // Links may need to be resolved, such as ../chp1.xhtml - var uri = EPUBJS.core.uri(renderer.render.window.location.href); - - directory = uri.directory; - - if(directory) { - // We must ensure that the file:// protocol is preserved for - // local file links, as in certain contexts (such as under - // Titanium), file links without the file:// protocol will not - // work - if (uri.protocol === "file") { - relative = EPUBJS.core.resolveUrl(uri.base, href); - } else { - relative = EPUBJS.core.resolveUrl(directory, href); - } - } else { - relative = href; - } - - link.onclick = function(){ - book.goto(relative); - return false; - }; - - } - done(); - - }; - - renderer.replace("a[href]", replacments, callback); - -}; - -EPUBJS.replace.head = function(callback, renderer) { - - renderer.replaceWithStored("link[href]", "href", EPUBJS.replace.links, callback); - -}; - - -//-- Replaces assets src's to point to stored version if browser is offline -EPUBJS.replace.resources = function(callback, renderer){ - //srcs = this.doc.querySelectorAll('[src]'); - renderer.replaceWithStored("[src]", "src", EPUBJS.replace.srcs, callback); - -}; - -EPUBJS.replace.svg = function(callback, renderer) { - - renderer.replaceWithStored("image", "xlink:href", function(_store, full, done){ - _store.getUrl(full).then(done); - }, callback); - -}; - -EPUBJS.replace.srcs = function(_store, full, done){ - - _store.getUrl(full).then(done); - -}; - -//-- Replaces links in head, such as stylesheets - link[href] -EPUBJS.replace.links = function(_store, full, done, link){ - //-- Handle replacing urls in CSS - if(link.getAttribute("rel") === "stylesheet") { - EPUBJS.replace.stylesheets(_store, full).then(function(url, full){ - // done - done(url, full); - }, function(reason) { - // we were unable to replace the style sheets - done(null); - }); - }else{ - _store.getUrl(full).then(done, function(reason) { - // we were unable to get the url, signal to upper layer - done(null); - }); - } -}; - -EPUBJS.replace.stylesheets = function(_store, full) { - var deferred = new RSVP.defer(); - - if(!_store) return; - - _store.getText(full).then(function(text){ - var url; - - EPUBJS.replace.cssUrls(_store, full, text).then(function(newText){ - var _URL = window.URL || window.webkitURL || window.mozURL; - - var blob = new Blob([newText], { "type" : "text\/css" }), - url = _URL.createObjectURL(blob); - - deferred.resolve(url); - - }, function(reason) { - deferred.reject(reason); - }); - - }, function(reason) { - deferred.reject(reason); - }); - - return deferred.promise; -}; - -EPUBJS.replace.cssUrls = function(_store, base, text){ - var deferred = new RSVP.defer(), - promises = [], - matches = text.match(/url\(\'?\"?([^\'|^\"^\)]*)\'?\"?\)/g); - - if(!_store) return; - - if(!matches){ - deferred.resolve(text); - return deferred.promise; - } - - matches.forEach(function(str){ - var full = EPUBJS.core.resolveUrl(base, str.replace(/url\(|[|\)|\'|\"]/g, '')); - var replaced = _store.getUrl(full).then(function(url){ - text = text.replace(str, 'url("'+url+'")'); - }, function(reason) { - deferred.reject(reason); - }); - - promises.push(replaced); - }); - - RSVP.all(promises).then(function(){ - deferred.resolve(text); - }); - - return deferred.promise; -}; - - -EPUBJS.Storage = function(withCredentials){ - - this.checkRequirements(); - this.urlCache = {}; - this.withCredentials = withCredentials; - this.URL = window.URL || window.webkitURL || window.mozURL; - this.offline = false; -}; - -//-- Load the zip lib and set the workerScriptsPath -EPUBJS.Storage.prototype.checkRequirements = function(callback){ - if(typeof(localforage) == "undefined") console.error("localForage library not loaded"); -}; - -EPUBJS.Storage.prototype.put = function(assets, store) { - var deferred = new RSVP.defer(); - var count = assets.length; - var current = 0; - var next = function(deferred){ - var done = deferred || new RSVP.defer(); - var url; - var encodedUrl; - - if(current >= count) { - done.resolve(); - } else { - url = assets[current].url; - encodedUrl = window.encodeURIComponent(url); - - EPUBJS.core.request(url, "binary") - .then(function (data) { - return localforage.setItem(encodedUrl, data); - }) - .then(function(data){ - current++; - // Load up the next - setTimeout(function(){ - next(done); - }, 1); - - }); - } - return done.promise; - }.bind(this); - - if(!Array.isArray(assets)) { - assets = [assets]; - } - - next().then(function(){ - deferred.resolve(); - }.bind(this)); - - return deferred.promise; -}; - -EPUBJS.Storage.prototype.token = function(url, value){ - var encodedUrl = window.encodeURIComponent(url); - return localforage.setItem(encodedUrl, value) - .then(function (result) { - if (result === null) { - return false; - } else { - return true; - } - }); -}; - -EPUBJS.Storage.prototype.isStored = function(url){ - var encodedUrl = window.encodeURIComponent(url); - return localforage.getItem(encodedUrl) - .then(function (result) { - if (result === null) { - return false; - } else { - return true; - } - }); -}; - -EPUBJS.Storage.prototype.getText = function(url){ - var encodedUrl = window.encodeURIComponent(url); - - return EPUBJS.core.request(url, 'arraybuffer', this.withCredentials) - .then(function(buffer){ - - if(this.offline){ - this.offline = false; - this.trigger("offline", false); - } - localforage.setItem(encodedUrl, buffer); - return buffer; - }.bind(this)) - .then(function(data) { - var deferred = new RSVP.defer(); - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - deferred.resolve(reader.result); - }); - reader.readAsText(blob, mimeType); - return deferred.promise; - }) - .catch(function() { - - var deferred = new RSVP.defer(); - var entry = localforage.getItem(encodedUrl); - - if(!this.offline){ - this.offline = true; - this.trigger("offline", true); - } - - if(!entry) { - deferred.reject({ - message : "File not found in the storage: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - entry.then(function(data) { - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - deferred.resolve(reader.result); - }); - reader.readAsText(blob, mimeType); - }); - - return deferred.promise; - }.bind(this)); -}; - -EPUBJS.Storage.prototype.getUrl = function(url){ - var encodedUrl = window.encodeURIComponent(url); - - return EPUBJS.core.request(url, 'arraybuffer', this.withCredentials) - .then(function(buffer){ - if(this.offline){ - this.offline = false; - this.trigger("offline", false); - } - localforage.setItem(encodedUrl, buffer); - return url; - }.bind(this)) - .catch(function() { - var deferred = new RSVP.defer(); - var entry; - var _URL = window.URL || window.webkitURL || window.mozURL; - var tempUrl; - - if(!this.offline){ - this.offline = true; - this.trigger("offline", true); - } - - if(encodedUrl in this.urlCache) { - deferred.resolve(this.urlCache[encodedUrl]); - return deferred.promise; - } - - entry = localforage.getItem(encodedUrl); - - if(!entry) { - deferred.reject({ - message : "File not found in the storage: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - entry.then(function(data) { - var blob = new Blob([data], {type : EPUBJS.core.getMimeType(url)}); - tempUrl = _URL.createObjectURL(blob); - deferred.resolve(tempUrl); - this.urlCache[encodedUrl] = tempUrl; - }.bind(this)); - - - return deferred.promise; - }.bind(this)); -}; - -EPUBJS.Storage.prototype.getXml = function(url){ - var encodedUrl = window.encodeURIComponent(url); - - return EPUBJS.core.request(url, 'arraybuffer', this.withCredentials) - .then(function(buffer){ - if(this.offline){ - this.offline = false; - this.trigger("offline", false); - } - localforage.setItem(encodedUrl, buffer); - return buffer; - }.bind(this)) - .then(function(data) { - var deferred = new RSVP.defer(); - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - var parser = new DOMParser(); - var doc = parser.parseFromString(reader.result, "text/xml"); - deferred.resolve(doc); - }); - reader.readAsText(blob, mimeType); - return deferred.promise; - }) - .catch(function() { - var deferred = new RSVP.defer(); - var entry = localforage.getItem(encodedUrl); - - if(!this.offline){ - this.offline = true; - this.trigger("offline", true); - } - - if(!entry) { - deferred.reject({ - message : "File not found in the storage: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - entry.then(function(data) { - var mimeType = EPUBJS.core.getMimeType(url); - var blob = new Blob([data], {type : mimeType}); - var reader = new FileReader(); - reader.addEventListener("loadend", function() { - var parser = new DOMParser(); - var doc = parser.parseFromString(reader.result, "text/xml"); - deferred.resolve(doc); - }); - reader.readAsText(blob, mimeType); - }); - - return deferred.promise; - }.bind(this)); -}; - -EPUBJS.Storage.prototype.revokeUrl = function(url){ - var _URL = window.URL || window.webkitURL || window.mozURL; - var fromCache = this.urlCache[url]; - if(fromCache) _URL.revokeObjectURL(fromCache); -}; - -EPUBJS.Storage.prototype.failed = function(error){ - console.error(error); -}; - -RSVP.EventTarget.mixin(EPUBJS.Storage.prototype); - -EPUBJS.Unarchiver = function(url){ - - this.checkRequirements(); - this.urlCache = {}; - -}; - -//-- Load the zip lib and set the workerScriptsPath -EPUBJS.Unarchiver.prototype.checkRequirements = function(callback){ - if(typeof(JSZip) == "undefined") console.error("JSZip lib not loaded"); -}; - -EPUBJS.Unarchiver.prototype.open = function(zipUrl, callback){ - var deferred = new RSVP.defer(); - - return EPUBJS.core.request(zipUrl, "binary").then(function(data){ - this.zip = new JSZip(data); - }.bind(this)); -}; - -EPUBJS.Unarchiver.prototype.getXml = function(url, encoding){ - var decodededUrl = window.decodeURIComponent(url); - return this.getText(decodededUrl, encoding). - then(function(text){ - var parser = new DOMParser(); - return parser.parseFromString(text, "text/xml"); - }); - -}; - -EPUBJS.Unarchiver.prototype.getUrl = function(url, mime){ - var unarchiver = this; - var deferred = new RSVP.defer(); - var decodededUrl = window.decodeURIComponent(url); - var entry = this.zip.file(decodededUrl); - var _URL = window.URL || window.webkitURL || window.mozURL; - var tempUrl; - var blob; - - if(!entry) { - deferred.reject({ - message : "File not found in the epub: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - if(url in this.urlCache) { - deferred.resolve(this.urlCache[url]); - return deferred.promise; - } - - blob = new Blob([entry.asUint8Array()], {type : EPUBJS.core.getMimeType(entry.name)}); - - tempUrl = _URL.createObjectURL(blob); - deferred.resolve(tempUrl); - unarchiver.urlCache[url] = tempUrl; - - return deferred.promise; -}; - -EPUBJS.Unarchiver.prototype.getText = function(url, encoding){ - var unarchiver = this; - var deferred = new RSVP.defer(); - var decodededUrl = window.decodeURIComponent(url); - var entry = this.zip.file(decodededUrl); - var text; - - if(!entry) { - deferred.reject({ - message : "File not found in the epub: " + url, - stack : new Error().stack - }); - return deferred.promise; - } - - text = entry.asText(); - deferred.resolve(text); - - return deferred.promise; -}; - -EPUBJS.Unarchiver.prototype.revokeUrl = function(url){ - var _URL = window.URL || window.webkitURL || window.mozURL; - var fromCache = this.urlCache[url]; - if(fromCache) _URL.revokeObjectURL(fromCache); -}; - -EPUBJS.Unarchiver.prototype.failed = function(error){ - console.error(error); -}; - -EPUBJS.Unarchiver.prototype.afterSaved = function(error){ - this.callback(); -}; - -EPUBJS.Unarchiver.prototype.toStorage = function(entries){ - var timeout = 0, - delay = 20, - that = this, - count = entries.length; - - function callback(){ - count--; - if(count === 0) that.afterSaved(); - } - - entries.forEach(function(entry){ - - setTimeout(function(entry){ - that.saveEntryFileToStorage(entry, callback); - }, timeout, entry); - - timeout += delay; - }); - - console.log("time", timeout); - - //entries.forEach(this.saveEntryFileToStorage.bind(this)); -}; - -// EPUBJS.Unarchiver.prototype.saveEntryFileToStorage = function(entry, callback){ -// var that = this; -// entry.getData(new zip.BlobWriter(), function(blob) { -// EPUBJS.storage.save(entry.filename, blob, callback); -// }); -// }; - -/* - From Zip.js, by Gildas Lormeau - */ - -(function() { - "use strict"; - var table = { - "application" : { - "ecmascript" : [ "es", "ecma" ], - "javascript" : "js", - "ogg" : "ogx", - "pdf" : "pdf", - "postscript" : [ "ps", "ai", "eps", "epsi", "epsf", "eps2", "eps3" ], - "rdf+xml" : "rdf", - "smil" : [ "smi", "smil" ], - "xhtml+xml" : [ "xhtml", "xht" ], - "xml" : [ "xml", "xsl", "xsd" ], - "zip" : "zip", - "x-httpd-eruby" : "rhtml", - "x-latex" : "latex", - "x-maker" : [ "frm", "maker", "frame", "fm", "fb", "book", "fbdoc" ], - "x-object" : "o", - "x-shockwave-flash" : [ "swf", "swfl" ], - "x-silverlight" : "scr", - "epub+zip" : "epub", - "font-tdpfr" : "pfr", - "inkml+xml" : [ "ink", "inkml" ], - "json" : "json", - "jsonml+json" : "jsonml", - "mathml+xml" : "mathml", - "metalink+xml" : "metalink", - "mp4" : "mp4s", - "oebps-package+xml" : "opf", - "omdoc+xml" : "omdoc", - "oxps" : "oxps", - "vnd.amazon.ebook" : "azw", - "widget" : "wgt", - "x-dtbncx+xml" : "ncx", - "x-dtbook+xml" : "dtb", - "x-dtbresource+xml" : "res", - "x-font-bdf" : "bdf", - "x-font-ghostscript" : "gsf", - "x-font-linux-psf" : "psf", - "x-font-otf" : "otf", - "x-font-pcf" : "pcf", - "x-font-snf" : "snf", - "x-font-ttf" : [ "ttf", "ttc" ], - "x-font-type1" : [ "pfa", "pfb", "pfm", "afm" ], - "x-font-woff" : "woff", - "x-mobipocket-ebook" : [ "prc", "mobi" ], - "x-mspublisher" : "pub", - "x-nzb" : "nzb", - "x-tgif" : "obj", - "xaml+xml" : "xaml", - "xml-dtd" : "dtd", - "xproc+xml" : "xpl", - "xslt+xml" : "xslt", - "internet-property-stream" : "acx", - "x-compress" : "z", - "x-compressed" : "tgz", - "x-gzip" : "gz", - }, - "audio" : { - "flac" : "flac", - "midi" : [ "mid", "midi", "kar", "rmi" ], - "mpeg" : [ "mpga", "mpega", "mp2", "mp3", "m4a", "mp2a", "m2a", "m3a" ], - "mpegurl" : "m3u", - "ogg" : [ "oga", "ogg", "spx" ], - "x-aiff" : [ "aif", "aiff", "aifc" ], - "x-ms-wma" : "wma", - "x-wav" : "wav", - "adpcm" : "adp", - "mp4" : "mp4a", - "webm" : "weba", - "x-aac" : "aac", - "x-caf" : "caf", - "x-matroska" : "mka", - "x-pn-realaudio-plugin" : "rmp", - "xm" : "xm", - "mid" : [ "mid", "rmi" ] - }, - "image" : { - "gif" : "gif", - "ief" : "ief", - "jpeg" : [ "jpeg", "jpg", "jpe" ], - "pcx" : "pcx", - "png" : "png", - "svg+xml" : [ "svg", "svgz" ], - "tiff" : [ "tiff", "tif" ], - "x-icon" : "ico", - "bmp" : "bmp", - "webp" : "webp", - "x-pict" : [ "pic", "pct" ], - "x-tga" : "tga", - "cis-cod" : "cod", - }, - "message" : { - "rfc822" : [ "eml", "mime", "mht", "mhtml", "nws" ] - }, - "text" : { - "cache-manifest" : [ "manifest", "appcache" ], - "calendar" : [ "ics", "icz", "ifb" ], - "css" : "css", - "csv" : "csv", - "h323" : "323", - "html" : [ "html", "htm", "shtml", "stm" ], - "iuls" : "uls", - "mathml" : "mml", - "plain" : [ "txt", "text", "brf", "conf", "def", "list", "log", "in", "bas" ], - "richtext" : "rtx", - "tab-separated-values" : "tsv", - "x-bibtex" : "bib", - "x-dsrc" : "d", - "x-diff" : [ "diff", "patch" ], - "x-haskell" : "hs", - "x-java" : "java", - "x-literate-haskell" : "lhs", - "x-moc" : "moc", - "x-pascal" : [ "p", "pas" ], - "x-pcs-gcd" : "gcd", - "x-perl" : [ "pl", "pm" ], - "x-python" : "py", - "x-scala" : "scala", - "x-setext" : "etx", - "x-tcl" : [ "tcl", "tk" ], - "x-tex" : [ "tex", "ltx", "sty", "cls" ], - "x-vcard" : "vcf", - "sgml" : [ "sgml", "sgm" ], - "x-c" : [ "c", "cc", "cxx", "cpp", "h", "hh", "dic" ], - "x-fortran" : [ "f", "for", "f77", "f90" ], - "x-opml" : "opml", - "x-nfo" : "nfo", - "x-sfv" : "sfv", - "x-uuencode" : "uu", - "webviewhtml" : "htt" - }, - "video" : { - "mpeg" : [ "mpeg", "mpg", "mpe", "m1v", "m2v", "mp2", "mpa", "mpv2" ], - "mp4" : [ "mp4", "mp4v", "mpg4" ], - "quicktime" : [ "qt", "mov" ], - "ogg" : "ogv", - "vnd.mpegurl" : [ "mxu", "m4u" ], - "x-flv" : "flv", - "x-la-asf" : [ "lsf", "lsx" ], - "x-mng" : "mng", - "x-ms-asf" : [ "asf", "asx", "asr" ], - "x-ms-wm" : "wm", - "x-ms-wmv" : "wmv", - "x-ms-wmx" : "wmx", - "x-ms-wvx" : "wvx", - "x-msvideo" : "avi", - "x-sgi-movie" : "movie", - "x-matroska" : [ "mpv", "mkv", "mk3d", "mks" ], - "3gpp2" : "3g2", - "h261" : "h261", - "h263" : "h263", - "h264" : "h264", - "jpeg" : "jpgv", - "jpm" : [ "jpm", "jpgm" ], - "mj2" : [ "mj2", "mjp2" ], - "vnd.ms-playready.media.pyv" : "pyv", - "vnd.uvvu.mp4" : [ "uvu", "uvvu" ], - "vnd.vivo" : "viv", - "webm" : "webm", - "x-f4v" : "f4v", - "x-m4v" : "m4v", - "x-ms-vob" : "vob", - "x-smv" : "smv" - } - }; - - var mimeTypes = (function() { - var type, subtype, val, index, mimeTypes = {}; - for (type in table) { - if (table.hasOwnProperty(type)) { - for (subtype in table[type]) { - if (table[type].hasOwnProperty(subtype)) { - val = table[type][subtype]; - if (typeof val == "string") { - mimeTypes[val] = type + "/" + subtype; - } else { - for (index = 0; index < val.length; index++) { - mimeTypes[val[index]] = type + "/" + subtype; - } - } - } - } - } - } - return mimeTypes; - })(); - - EPUBJS.core.getMimeType = function(filename) { - var defaultValue = "text/plain";//"application/octet-stream"; - return filename && mimeTypes[filename.split(".").pop().toLowerCase()] || defaultValue; - }; - -})(); -//# sourceMappingURL=epub_no_underscore.js.map \ No newline at end of file diff --git a/epub.js/epub_no_underscore.js.map b/epub.js/epub_no_underscore.js.map deleted file mode 100644 index a94c021..0000000 --- a/epub.js/epub_no_underscore.js.map +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": 3, - "file": "epub_no_underscore.js", - "sources": [ - "libs/rsvp/rsvp.js", - "src/base.js", - "src/book.js", - "src/chapter.js", - "src/core.js", - "src/epubcfi.js", - "src/events.js", - "src/hooks.js", - "src/layout.js", - "src/locations.js", - "src/pagination.js", - "src/parser.js", - "src/render_iframe.js", - "src/renderer.js", - "src/replace.js", - "src/storage.js", - "src/unarchiver.js", - "libs/mime-types/mime-types.js" - ], - "names": [], - "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,Y;ACtoEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACryCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC5YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;AC7kBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACtiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC5KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AClOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACvFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACheA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC3RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC9sCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;;ACzJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,K" -} \ No newline at end of file diff --git a/epub.js/hooks.js b/epub.js/hooks.js deleted file mode 100644 index 0d62b7e..0000000 --- a/epub.js/hooks.js +++ /dev/null @@ -1,318 +0,0 @@ -EPUBJS.Hooks.register("beforeChapterDisplay").endnotes = function(callback, renderer){ - - var notes = renderer.contents.querySelectorAll('a[href]'), - items = Array.prototype.slice.call(notes), //[].slice.call() - attr = "epub:type", - type = "noteref", - folder = EPUBJS.core.folder(location.pathname), - cssPath = (folder + EPUBJS.cssPath) || folder, - popups = {}; - - EPUBJS.core.addCss(EPUBJS.cssPath + "popup.css", false, renderer.render.document.head); - - - items.forEach(function(item){ - var epubType = item.getAttribute(attr), - href, - id, - el, - pop, - pos, - left, - top, - txt; - - if(epubType != type) return; - - href = item.getAttribute("href"); - id = href.replace("#", ''); - el = renderer.render.document.getElementById(id); - - - item.addEventListener("mouseover", showPop, false); - item.addEventListener("mouseout", hidePop, false); - - function showPop(){ - var poppos, - iheight = renderer.height, - iwidth = renderer.width, - tip, - pop, - maxHeight = 225, - itemRect; - - if(!txt) { - pop = el.cloneNode(true); - txt = pop.querySelector("p"); - } - - // chapter.replaceLinks.bind(this) //TODO:Fred - update? - //-- create a popup with endnote inside of it - if(!popups[id]) { - popups[id] = document.createElement("div"); - popups[id].setAttribute("class", "popup"); - - pop_content = document.createElement("div"); - - popups[id].appendChild(pop_content); - - pop_content.appendChild(txt); - pop_content.setAttribute("class", "pop_content"); - - renderer.render.document.body.appendChild(popups[id]); - - //-- TODO: will these leak memory? - Fred - popups[id].addEventListener("mouseover", onPop, false); - popups[id].addEventListener("mouseout", offPop, false); - - //-- Add hide on page change - // chapter.book.listenUntil("book:pageChanged", "book:chapterDestroy", hidePop); - // chapter.book.listenUntil("book:pageChanged", "book:chapterDestroy", offPop); - renderer.on("renderer:pageChanged", hidePop, this); - renderer.on("renderer:pageChanged", offPop, this); - // chapter.book.on("renderer:chapterDestroy", hidePop, this); - } - - pop = popups[id]; - - - //-- get location of item - itemRect = item.getBoundingClientRect(); - left = itemRect.left; - top = itemRect.top; - - //-- show the popup - pop.classList.add("show"); - - //-- locations of popup - popRect = pop.getBoundingClientRect(); - - //-- position the popup - pop.style.left = left - popRect.width / 2 + "px"; - pop.style.top = top + "px"; - - - //-- Adjust max height - if(maxHeight > iheight / 2.5) { - maxHeight = iheight / 2.5; - pop_content.style.maxHeight = maxHeight + "px"; - } - - //-- switch above / below - if(popRect.height + top >= iheight - 25) { - pop.style.top = top - popRect.height + "px"; - pop.classList.add("above"); - }else{ - pop.classList.remove("above"); - } - - //-- switch left - if(left - popRect.width <= 0) { - pop.style.left = left + "px"; - pop.classList.add("left"); - }else{ - pop.classList.remove("left"); - } - - //-- switch right - if(left + popRect.width / 2 >= iwidth) { - //-- TEMP MOVE: 300 - pop.style.left = left - 300 + "px"; - - popRect = pop.getBoundingClientRect(); - pop.style.left = left - popRect.width + "px"; - //-- switch above / below again - if(popRect.height + top >= iheight - 25) { - pop.style.top = top - popRect.height + "px"; - pop.classList.add("above"); - }else{ - pop.classList.remove("above"); - } - - pop.classList.add("right"); - }else{ - pop.classList.remove("right"); - } - - - } - - function onPop(){ - popups[id].classList.add("on"); - } - - function offPop(){ - popups[id].classList.remove("on"); - } - - function hidePop(){ - setTimeout(function(){ - popups[id].classList.remove("show"); - }, 100); - } - - }); - - - if(callback) callback(); - -} - -EPUBJS.Hooks.register("beforeChapterDisplay").mathml = function(callback, renderer){ - - // check of currentChapter properties contains 'mathml' - if(renderer.currentChapter.manifestProperties.indexOf("mathml") !== -1 ){ - - // Assign callback to be inside iframe window - renderer.render.iframe.contentWindow.mathmlCallback = callback; - - // add MathJax config script tag to the renderer body - var s = document.createElement("script"); - s.type = 'text/x-mathjax-config'; - s.innerHTML = '\ - MathJax.Hub.Register.StartupHook("End",function () { \ - window.mathmlCallback(); \ - });\ - MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); \ - '; - renderer.doc.body.appendChild(s); - // add MathJax.js to renderer head - EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML", null, renderer.doc.head); - - } else { - if(callback) callback(); - } -} - -EPUBJS.Hooks.register("beforeChapterDisplay").smartimages = function(callback, renderer){ - var images = renderer.contents.querySelectorAll('img'), - items = Array.prototype.slice.call(images), - iheight = renderer.height,//chapter.bodyEl.clientHeight,//chapter.doc.body.getBoundingClientRect().height, - oheight; - - if(renderer.layoutSettings.layout != "reflowable") { - callback(); - return; //-- Only adjust images for reflowable text - } - - items.forEach(function(item){ - - function size() { - var itemRect = item.getBoundingClientRect(), - rectHeight = itemRect.height, - top = itemRect.top, - oHeight = item.getAttribute('data-height'), - height = oHeight || rectHeight, - newHeight, - fontSize = Number(getComputedStyle(item, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]), - fontAdjust = fontSize ? fontSize / 2 : 0; - - iheight = renderer.contents.clientHeight; - if(top < 0) top = 0; - - if(height + top >= iheight) { - - if(top < iheight/2) { - // Remove top and half font-size from height to keep container from overflowing - newHeight = iheight - top - fontAdjust; - item.style.maxHeight = newHeight + "px"; - item.style.width= "auto"; - }else{ - if(height > iheight) { - item.style.maxHeight = iheight + "px"; - item.style.width= "auto"; - itemRect = item.getBoundingClientRect(); - height = itemRect.height; - } - item.style.display = "block"; - item.style["WebkitColumnBreakBefore"] = "always"; - item.style["breakBefore"] = "column"; - - } - - item.setAttribute('data-height', newHeight); - - }else{ - item.style.removeProperty('max-height'); - item.style.removeProperty('margin-top'); - } - } - - item.addEventListener('load', size, false); - - renderer.on("renderer:resized", size); - - renderer.on("renderer:chapterUnloaded", function(){ - item.removeEventListener('load', size); - renderer.off("renderer:resized", size); - }); - - size(); - - }); - - if(callback) callback(); - -} - -EPUBJS.Hooks.register("beforeChapterDisplay").transculsions = function(callback, renderer){ - /* - - */ - - var trans = renderer.contents.querySelectorAll('[transclusion]'), - items = Array.prototype.slice.call(trans); - - items.forEach(function(item){ - var src = item.getAttribute("ref"), - iframe = document.createElement('iframe'), - orginal_width = item.getAttribute("width"), - orginal_height = item.getAttribute("height"), - parent = item.parentNode, - width = orginal_width, - height = orginal_height, - ratio; - - - function size() { - width = orginal_width; - height = orginal_height; - - if(width > chapter.colWidth){ - ratio = chapter.colWidth / width; - - width = chapter.colWidth; - height = height * ratio; - } - - iframe.width = width; - iframe.height = height; - } - - - size(); - - //-- resize event - - - renderer.listenUntil("renderer:resized", "renderer:chapterUnloaded", size); - - iframe.src = src; - - // - parent.replaceChild(iframe, item); - - - }); - - - - - if(callback) callback(); - - -} - -//# sourceMappingURL=hooks.js.map \ No newline at end of file diff --git a/epub.js/hooks.js.map b/epub.js/hooks.js.map deleted file mode 100644 index 2858e23..0000000 --- a/epub.js/hooks.js.map +++ /dev/null @@ -1,12 +0,0 @@ -{ - "version": 3, - "file": "hooks.js", - "sources": [ - "hooks/default/endnotes.js", - "hooks/default/mathml.js", - "hooks/default/smartimages.js", - "hooks/default/transculsions.js" - ], - "names": [], - "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC9JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A" -} \ No newline at end of file diff --git a/epub.js/hooks.min.js b/epub.js/hooks.min.js deleted file mode 100644 index 5e8c36f..0000000 --- a/epub.js/hooks.min.js +++ /dev/null @@ -1,2 +0,0 @@ -EPUBJS.Hooks.register("beforeChapterDisplay").endnotes=function(a,b){var c=b.contents.querySelectorAll("a[href]"),d=Array.prototype.slice.call(c),e="epub:type",f="noteref",g=EPUBJS.core.folder(location.pathname),h=(g+EPUBJS.cssPath||g,{});EPUBJS.core.addCss(EPUBJS.cssPath+"popup.css",!1,b.render.document.head),d.forEach(function(a){function c(){var c,e,f=b.height,j=b.width,p=225;o||(c=l.cloneNode(!0),o=c.querySelector("p")),h[k]||(h[k]=document.createElement("div"),h[k].setAttribute("class","popup"),pop_content=document.createElement("div"),h[k].appendChild(pop_content),pop_content.appendChild(o),pop_content.setAttribute("class","pop_content"),b.render.document.body.appendChild(h[k]),h[k].addEventListener("mouseover",d,!1),h[k].addEventListener("mouseout",g,!1),b.on("renderer:pageChanged",i,this),b.on("renderer:pageChanged",g,this)),c=h[k],e=a.getBoundingClientRect(),m=e.left,n=e.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=m-popRect.width/2+"px",c.style.top=n+"px",p>f/2.5&&(p=f/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+n>=f-25?(c.style.top=n-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),m-popRect.width<=0?(c.style.left=m+"px",c.classList.add("left")):c.classList.remove("left"),m+popRect.width/2>=j?(c.style.left=m-300+"px",popRect=c.getBoundingClientRect(),c.style.left=m-popRect.width+"px",popRect.height+n>=f-25?(c.style.top=n-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")}function d(){h[k].classList.add("on")}function g(){h[k].classList.remove("on")}function i(){setTimeout(function(){h[k].classList.remove("show")},100)}var j,k,l,m,n,o,p=a.getAttribute(e);p==f&&(j=a.getAttribute("href"),k=j.replace("#",""),l=b.render.document.getElementById(k),a.addEventListener("mouseover",c,!1),a.addEventListener("mouseout",i,!1))}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").mathml=function(a,b){if(-1!==b.currentChapter.manifestProperties.indexOf("mathml")){b.render.iframe.contentWindow.mathmlCallback=a;var c=document.createElement("script");c.type="text/x-mathjax-config",c.innerHTML=' MathJax.Hub.Register.StartupHook("End",function () { window.mathmlCallback(); }); MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); ',b.doc.body.appendChild(c),EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",null,b.doc.head)}else a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").smartimages=function(a,b){var c=b.contents.querySelectorAll("img"),d=Array.prototype.slice.call(c),e=b.height;return"reflowable"!=b.layoutSettings.layout?void a():(d.forEach(function(a){function c(){var c,d=a.getBoundingClientRect(),f=d.height,g=d.top,h=a.getAttribute("data-height"),i=h||f,j=Number(getComputedStyle(a,"").fontSize.match(/(\d*(\.\d*)?)px/)[1]),k=j?j/2:0;e=b.contents.clientHeight,0>g&&(g=0),i+g>=e?(e/2>g?(c=e-g-k,a.style.maxHeight=c+"px",a.style.width="auto"):(i>e&&(a.style.maxHeight=e+"px",a.style.width="auto",d=a.getBoundingClientRect(),i=d.height),a.style.display="block",a.style.WebkitColumnBreakBefore="always",a.style.breakBefore="column"),a.setAttribute("data-height",c)):(a.style.removeProperty("max-height"),a.style.removeProperty("margin-top"))}a.addEventListener("load",c,!1),b.on("renderer:resized",c),b.on("renderer:chapterUnloaded",function(){a.removeEventListener("load",c),b.off("renderer:resized",c)}),c()}),void(a&&a()))},EPUBJS.Hooks.register("beforeChapterDisplay").transculsions=function(a,b){var c=b.contents.querySelectorAll("[transclusion]"),d=Array.prototype.slice.call(c);d.forEach(function(a){function c(){j=g,k=h,j>chapter.colWidth&&(d=chapter.colWidth/j,j=chapter.colWidth,k*=d),f.width=j,f.height=k}var d,e=a.getAttribute("ref"),f=document.createElement("iframe"),g=a.getAttribute("width"),h=a.getAttribute("height"),i=a.parentNode,j=g,k=h;c(),b.listenUntil("renderer:resized","renderer:chapterUnloaded",c),f.src=e,i.replaceChild(f,a)}),a&&a()}; -//# sourceMappingURL=hooks.min.map \ No newline at end of file diff --git a/epub.js/hooks.min.map b/epub.js/hooks.min.map deleted file mode 100644 index 1f679c7..0000000 --- a/epub.js/hooks.min.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["hooks.js"],"names":["EPUBJS","Hooks","register","endnotes","callback","renderer","notes","contents","querySelectorAll","items","Array","prototype","slice","call","attr","type","folder","core","location","pathname","popups","cssPath","addCss","render","document","head","forEach","item","showPop","pop","itemRect","iheight","height","iwidth","width","maxHeight","txt","el","cloneNode","querySelector","id","createElement","setAttribute","pop_content","appendChild","body","addEventListener","onPop","offPop","on","hidePop","this","getBoundingClientRect","left","top","classList","add","popRect","style","remove","setTimeout","href","epubType","getAttribute","replace","getElementById","mathml","currentChapter","manifestProperties","indexOf","iframe","contentWindow","mathmlCallback","s","innerHTML","doc","addScript","smartimages","images","layoutSettings","layout","size","newHeight","rectHeight","oHeight","fontSize","Number","getComputedStyle","match","fontAdjust","clientHeight","display","removeProperty","removeEventListener","off","transculsions","trans","orginal_width","orginal_height","chapter","colWidth","ratio","src","parent","parentNode","listenUntil","replaceChild"],"mappings":"AAAAA,OAAOC,MAAMC,SAAS,wBAAwBC,SAAW,SAASC,EAAUC,GAE1E,GAAIC,GAAQD,EAASE,SAASC,iBAAiB,WAC9CC,EAAQC,MAAMC,UAAUC,MAAMC,KAAKP,GACnCQ,EAAO,YACPC,EAAO,UACPC,EAAShB,OAAOiB,KAAKD,OAAOE,SAASC,UAErCC,GADWJ,EAAShB,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AAKkE,oBAAoB,OAAQZ,GACjC5E,EAASyF,IAAI,mBAAoBb,KAGlCA,WAIE7E,GAAUA,OAIfJ,OAAOC,MAAMC,SAAS,wBAAwB6F,cAAgB,SAAS3F,EAAUC,GAO/E,GAAI2F,GAAQ3F,EAASE,SAASC,iBAAiB,kBAC7CC,EAAQC,MAAMC,UAAUC,MAAMC,KAAKmF,EAErCvF,GAAMiB,QAAQ,SAASC,GAWtB,QAASsD,KACR/C,EAAQ+D,EACRjE,EAASkE,EAENhE,EAAQiE,QAAQC,WAClBC,EAAQF,QAAQC,SAAWlE,EAE3BA,EAAQiE,QAAQC,SAChBpE,GAAkBqE,GAGnB/B,EAAOpC,MAAQA,EACfoC,EAAOtC,OAASA,EAtBjB,GAOCqE,GAPGC,EAAM3E,EAAKoC,aAAa,OAC3BO,EAAS9C,SAASiB,cAAc,UAChCwD,EAAgBtE,EAAKoC,aAAa,SAClCmC,EAAiBvE,EAAKoC,aAAa,UACnCwC,EAAS5E,EAAK6E,WACdtE,EAAQ+D,EACRjE,EAASkE,CAoBVjB,KAKA5E,EAASoG,YAAY,mBAAoB,2BAA4BxB,GAErEX,EAAOgC,IAAMA,EAGbC,EAAOG,aAAapC,EAAQ3C,KAQ1BvB,GAAUA","file":"hooks.min.js"} \ No newline at end of file diff --git a/epub.js/humans.txt b/epub.js/humans.txt new file mode 100755 index 0000000..5b037cf --- /dev/null +++ b/epub.js/humans.txt @@ -0,0 +1,15 @@ +# humanstxt.org/ +# The humans responsible & technology colophon + +# TEAM + + -- -- + +# THANKS + + + +# TECHNOLOGY COLOPHON + + HTML5, CSS3 + jQuery, Modernizr diff --git a/epub.js/img/.gitignore b/epub.js/img/.gitignore new file mode 100755 index 0000000..e69de29 diff --git a/epub.js/img/annotator-glyph-sprite.png b/epub.js/img/annotator-glyph-sprite.png new file mode 100644 index 0000000..5bb11cd Binary files /dev/null and b/epub.js/img/annotator-glyph-sprite.png differ diff --git a/epub.js/img/annotator-icon-sprite.png b/epub.js/img/annotator-icon-sprite.png new file mode 100644 index 0000000..3058651 Binary files /dev/null and b/epub.js/img/annotator-icon-sprite.png differ diff --git a/epub.js/img/apple-touch-icon.png b/epub.js/img/apple-touch-icon.png new file mode 100755 index 0000000..efc5c5a Binary files /dev/null and b/epub.js/img/apple-touch-icon.png differ diff --git a/epub.js/img/cancelfullscreen.png b/epub.js/img/cancelfullscreen.png new file mode 100644 index 0000000..bcf409e Binary files /dev/null and b/epub.js/img/cancelfullscreen.png differ diff --git a/epub.js/img/close.png b/epub.js/img/close.png new file mode 100644 index 0000000..46189e5 Binary files /dev/null and b/epub.js/img/close.png differ diff --git a/epub.js/img/fullscreen.png b/epub.js/img/fullscreen.png new file mode 100644 index 0000000..2f8d48d Binary files /dev/null and b/epub.js/img/fullscreen.png differ diff --git a/epub.js/img/menu-icon.png b/epub.js/img/menu-icon.png new file mode 100644 index 0000000..5f40e0e Binary files /dev/null and b/epub.js/img/menu-icon.png differ diff --git a/epub.js/img/save.png b/epub.js/img/save.png new file mode 100644 index 0000000..5a5bc0e Binary files /dev/null and b/epub.js/img/save.png differ diff --git a/epub.js/img/saved.png b/epub.js/img/saved.png new file mode 100644 index 0000000..0f1981b Binary files /dev/null and b/epub.js/img/saved.png differ diff --git a/epub.js/img/settings-s.png b/epub.js/img/settings-s.png new file mode 100644 index 0000000..fc21e78 Binary files /dev/null and b/epub.js/img/settings-s.png differ diff --git a/epub.js/img/settings.png b/epub.js/img/settings.png new file mode 100644 index 0000000..be20cba Binary files /dev/null and b/epub.js/img/settings.png differ diff --git a/epub.js/img/star.png b/epub.js/img/star.png new file mode 100644 index 0000000..4510893 Binary files /dev/null and b/epub.js/img/star.png differ diff --git a/epub.js/index.html b/epub.js/index.html new file mode 100755 index 0000000..f37cfd5 --- /dev/null +++ b/epub.js/index.html @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ Menu +
+
+ +   –   + +
+ +
+ +
+ +
+ + +
+
+ +
+ + diff --git a/epub.js/js/epub.js b/epub.js/js/epub.js new file mode 100644 index 0000000..1a1d2e4 --- /dev/null +++ b/epub.js/js/epub.js @@ -0,0 +1,16780 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("xmldom"), (function webpackLoadOptionalExternalModule() { try { return require("jszip"); } catch(e) {} }())); + else if(typeof define === 'function' && define.amd) + define(["xmldom", "jszip"], factory); + else if(typeof exports === 'object') + exports["ePub"] = factory(require("xmldom"), (function webpackLoadOptionalExternalModule() { try { return require("jszip"); } catch(e) {} }())); + else + root["ePub"] = factory(root["xmldom"], root["jszip"]); +})(this, function(__WEBPACK_EXTERNAL_MODULE_16__, __WEBPACK_EXTERNAL_MODULE_68__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/dist/"; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 25); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +exports.uuid = uuid; +exports.documentHeight = documentHeight; +exports.isElement = isElement; +exports.isNumber = isNumber; +exports.isFloat = isFloat; +exports.prefixed = prefixed; +exports.defaults = defaults; +exports.extend = extend; +exports.insert = insert; +exports.locationOf = locationOf; +exports.indexOfSorted = indexOfSorted; +exports.bounds = bounds; +exports.borders = borders; +exports.windowBounds = windowBounds; +exports.indexOfNode = indexOfNode; +exports.indexOfTextNode = indexOfTextNode; +exports.indexOfElementNode = indexOfElementNode; +exports.isXml = isXml; +exports.createBlob = createBlob; +exports.createBlobUrl = createBlobUrl; +exports.revokeBlobUrl = revokeBlobUrl; +exports.createBase64Url = createBase64Url; +exports.type = type; +exports.parse = parse; +exports.qs = qs; +exports.qsa = qsa; +exports.qsp = qsp; +exports.sprint = sprint; +exports.treeWalker = treeWalker; +exports.walk = walk; +exports.blob2base64 = blob2base64; +exports.defer = defer; +exports.querySelectorByType = querySelectorByType; +exports.findChildren = findChildren; +exports.parents = parents; +exports.filterChildren = filterChildren; +exports.getParentByTagName = getParentByTagName; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Core Utilities and Helpers + * @module Core +*/ + +/** + * Vendor prefixed requestAnimationFrame + * @returns {function} requestAnimationFrame + * @memberof Core + */ +var requestAnimationFrame = exports.requestAnimationFrame = typeof window != "undefined" ? window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame : false; +var ELEMENT_NODE = 1; +var TEXT_NODE = 3; +var COMMENT_NODE = 8; +var DOCUMENT_NODE = 9; +var _URL = typeof URL != "undefined" ? URL : typeof window != "undefined" ? window.URL || window.webkitURL || window.mozURL : undefined; + +/** + * Generates a UUID + * based on: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript + * @returns {string} uuid + * @memberof Core + */ +function uuid() { + var d = new Date().getTime(); + var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c == "x" ? r : r & 0x7 | 0x8).toString(16); + }); + return uuid; +} + +/** + * Gets the height of a document + * @returns {number} height + * @memberof Core + */ +function documentHeight() { + return Math.max(document.documentElement.clientHeight, document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight); +} + +/** + * Checks if a node is an element + * @returns {boolean} + * @memberof Core + */ +function isElement(obj) { + return !!(obj && obj.nodeType == 1); +} + +/** + * @returns {boolean} + * @memberof Core + */ +function isNumber(n) { + return !isNaN(parseFloat(n)) && isFinite(n); +} + +/** + * @returns {boolean} + * @memberof Core + */ +function isFloat(n) { + var f = parseFloat(n); + return f === n && isNumber(n) && Math.floor(f) !== n; +} + +/** + * Get a prefixed css property + * @returns {string} + * @memberof Core + */ +function prefixed(unprefixed) { + var vendors = ["Webkit", "webkit", "Moz", "O", "ms"]; + var prefixes = ["-webkit-", "-webkit-", "-moz-", "-o-", "-ms-"]; + var upper = unprefixed[0].toUpperCase() + unprefixed.slice(1); + var length = vendors.length; + + if (typeof document === "undefined" || typeof document.body.style[unprefixed] != "undefined") { + return unprefixed; + } + + for (var i = 0; i < length; i++) { + if (typeof document.body.style[vendors[i] + upper] != "undefined") { + return prefixes[i] + unprefixed; + } + } + + return unprefixed; +} + +/** + * Apply defaults to an object + * @param {object} obj + * @returns {object} + * @memberof Core + */ +function defaults(obj) { + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + for (var prop in source) { + if (obj[prop] === void 0) obj[prop] = source[prop]; + } + } + return obj; +} + +/** + * Extend properties of an object + * @param {object} target + * @returns {object} + * @memberof Core + */ +function extend(target) { + var sources = [].slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) return; + Object.getOwnPropertyNames(source).forEach(function (propName) { + Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); + }); + }); + return target; +} + +/** + * Fast quicksort insert for sorted array -- based on: + * http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers + * @param {any} item + * @param {array} array + * @param {function} [compareFunction] + * @returns {number} location (in array) + * @memberof Core + */ +function insert(item, array, compareFunction) { + var location = locationOf(item, array, compareFunction); + array.splice(location, 0, item); + + return location; +} + +/** + * Finds where something would fit into a sorted array + * @param {any} item + * @param {array} array + * @param {function} [compareFunction] + * @param {function} [_start] + * @param {function} [_end] + * @returns {number} location (in array) + * @memberof Core + */ +function locationOf(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if (!compareFunction) { + compareFunction = function compareFunction(a, b) { + if (a > b) return 1; + if (a < b) return -1; + if (a == b) return 0; + }; + } + if (end - start <= 0) { + return pivot; + } + + compared = compareFunction(array[pivot], item); + if (end - start === 1) { + return compared >= 0 ? pivot : pivot + 1; + } + if (compared === 0) { + return pivot; + } + if (compared === -1) { + return locationOf(item, array, compareFunction, pivot, end); + } else { + return locationOf(item, array, compareFunction, start, pivot); + } +} + +/** + * Finds index of something in a sorted array + * Returns -1 if not found + * @param {any} item + * @param {array} array + * @param {function} [compareFunction] + * @param {function} [_start] + * @param {function} [_end] + * @returns {number} index (in array) or -1 + * @memberof Core + */ +function indexOfSorted(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if (!compareFunction) { + compareFunction = function compareFunction(a, b) { + if (a > b) return 1; + if (a < b) return -1; + if (a == b) return 0; + }; + } + if (end - start <= 0) { + return -1; // Not found + } + + compared = compareFunction(array[pivot], item); + if (end - start === 1) { + return compared === 0 ? pivot : -1; + } + if (compared === 0) { + return pivot; // Found + } + if (compared === -1) { + return indexOfSorted(item, array, compareFunction, pivot, end); + } else { + return indexOfSorted(item, array, compareFunction, start, pivot); + } +} +/** + * Find the bounds of an element + * taking padding and margin into account + * @param {element} el + * @returns {{ width: Number, height: Number}} + * @memberof Core + */ +function bounds(el) { + + var style = window.getComputedStyle(el); + var widthProps = ["width", "paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"]; + var heightProps = ["height", "paddingTop", "paddingBottom", "marginTop", "marginBottom", "borderTopWidth", "borderBottomWidth"]; + + var width = 0; + var height = 0; + + widthProps.forEach(function (prop) { + width += parseFloat(style[prop]) || 0; + }); + + heightProps.forEach(function (prop) { + height += parseFloat(style[prop]) || 0; + }); + + return { + height: height, + width: width + }; +} + +/** + * Find the bounds of an element + * taking padding, margin and borders into account + * @param {element} el + * @returns {{ width: Number, height: Number}} + * @memberof Core + */ +function borders(el) { + + var style = window.getComputedStyle(el); + var widthProps = ["paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"]; + var heightProps = ["paddingTop", "paddingBottom", "marginTop", "marginBottom", "borderTopWidth", "borderBottomWidth"]; + + var width = 0; + var height = 0; + + widthProps.forEach(function (prop) { + width += parseFloat(style[prop]) || 0; + }); + + heightProps.forEach(function (prop) { + height += parseFloat(style[prop]) || 0; + }); + + return { + height: height, + width: width + }; +} + +/** + * Find the equivelent of getBoundingClientRect of a browser window + * @returns {{ width: Number, height: Number, top: Number, left: Number, right: Number, bottom: Number }} + * @memberof Core + */ +function windowBounds() { + + var width = window.innerWidth; + var height = window.innerHeight; + + return { + top: 0, + left: 0, + right: width, + bottom: height, + width: width, + height: height + }; +} + +/** + * Gets the index of a node in its parent + * @private + * @memberof Core + */ +function indexOfNode(node, typeId) { + var parent = node.parentNode; + var children = parent.childNodes; + var sib; + var index = -1; + for (var i = 0; i < children.length; i++) { + sib = children[i]; + if (sib.nodeType === typeId) { + index++; + } + if (sib == node) break; + } + + return index; +} + +/** + * Gets the index of a text node in its parent + * @param {node} textNode + * @returns {number} index + * @memberof Core + */ +function indexOfTextNode(textNode) { + return indexOfNode(textNode, TEXT_NODE); +} + +/** + * Gets the index of an element node in its parent + * @param {element} elementNode + * @returns {number} index + * @memberof Core + */ +function indexOfElementNode(elementNode) { + return indexOfNode(elementNode, ELEMENT_NODE); +} + +/** + * Check if extension is xml + * @param {string} ext + * @returns {boolean} + * @memberof Core + */ +function isXml(ext) { + return ["xml", "opf", "ncx"].indexOf(ext) > -1; +} + +/** + * Create a new blob + * @param {any} content + * @param {string} mime + * @returns {Blob} + * @memberof Core + */ +function createBlob(content, mime) { + return new Blob([content], { type: mime }); +} + +/** + * Create a new blob url + * @param {any} content + * @param {string} mime + * @returns {string} url + * @memberof Core + */ +function createBlobUrl(content, mime) { + var tempUrl; + var blob = createBlob(content, mime); + + tempUrl = _URL.createObjectURL(blob); + + return tempUrl; +} + +/** + * Remove a blob url + * @param {string} url + * @memberof Core + */ +function revokeBlobUrl(url) { + return _URL.revokeObjectURL(url); +} + +/** + * Create a new base64 encoded url + * @param {any} content + * @param {string} mime + * @returns {string} url + * @memberof Core + */ +function createBase64Url(content, mime) { + var data; + var datauri; + + if (typeof content !== "string") { + // Only handles strings + return; + } + + data = btoa(encodeURIComponent(content)); + + datauri = "data:" + mime + ";base64," + data; + + return datauri; +} + +/** + * Get type of an object + * @param {object} obj + * @returns {string} type + * @memberof Core + */ +function type(obj) { + return Object.prototype.toString.call(obj).slice(8, -1); +} + +/** + * Parse xml (or html) markup + * @param {string} markup + * @param {string} mime + * @param {boolean} forceXMLDom force using xmlDom to parse instead of native parser + * @returns {document} document + * @memberof Core + */ +function parse(markup, mime, forceXMLDom) { + var doc; + var Parser; + + if (typeof DOMParser === "undefined" || forceXMLDom) { + Parser = __webpack_require__(16).DOMParser; + } else { + Parser = DOMParser; + } + + // Remove byte order mark before parsing + // https://www.w3.org/International/questions/qa-byte-order-mark + if (markup.charCodeAt(0) === 0xFEFF) { + markup = markup.slice(1); + } + + doc = new Parser().parseFromString(markup, mime); + + return doc; +} + +/** + * querySelector polyfill + * @param {element} el + * @param {string} sel selector string + * @returns {element} element + * @memberof Core + */ +function qs(el, sel) { + var elements; + if (!el) { + throw new Error("No Element Provided"); + } + + if (typeof el.querySelector != "undefined") { + return el.querySelector(sel); + } else { + elements = el.getElementsByTagName(sel); + if (elements.length) { + return elements[0]; + } + } +} + +/** + * querySelectorAll polyfill + * @param {element} el + * @param {string} sel selector string + * @returns {element[]} elements + * @memberof Core + */ +function qsa(el, sel) { + + if (typeof el.querySelector != "undefined") { + return el.querySelectorAll(sel); + } else { + return el.getElementsByTagName(sel); + } +} + +/** + * querySelector by property + * @param {element} el + * @param {string} sel selector string + * @param {props[]} props + * @returns {element[]} elements + * @memberof Core + */ +function qsp(el, sel, props) { + var q, filtered; + if (typeof el.querySelector != "undefined") { + sel += "["; + for (var prop in props) { + sel += prop + "~='" + props[prop] + "'"; + } + sel += "]"; + return el.querySelector(sel); + } else { + q = el.getElementsByTagName(sel); + filtered = Array.prototype.slice.call(q, 0).filter(function (el) { + for (var prop in props) { + if (el.getAttribute(prop) === props[prop]) { + return true; + } + } + return false; + }); + + if (filtered) { + return filtered[0]; + } + } +} + +/** + * Sprint through all text nodes in a document + * @memberof Core + * @param {element} root element to start with + * @param {function} func function to run on each element + */ +function sprint(root, func) { + var doc = root.ownerDocument || root; + if (typeof doc.createTreeWalker !== "undefined") { + treeWalker(root, func, NodeFilter.SHOW_TEXT); + } else { + walk(root, function (node) { + if (node && node.nodeType === 3) { + // Node.TEXT_NODE + func(node); + } + }, true); + } +} + +function treeWalker(root, func, filter) { + var treeWalker = document.createTreeWalker(root, filter, null, false); + var node = void 0; + while (node = treeWalker.nextNode()) { + func(node); + } +} + +/** + * @memberof Core + * @param {node} node + * @param {callback} return false for continue,true for break inside callback + */ +function walk(node, callback) { + if (callback(node)) { + return true; + } + node = node.firstChild; + if (node) { + do { + var walked = walk(node, callback); + if (walked) { + return true; + } + node = node.nextSibling; + } while (node); + } +} + +/** + * Convert a blob to a base64 encoded string + * @param {Blog} blob + * @returns {string} + * @memberof Core + */ +function blob2base64(blob) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = function () { + resolve(reader.result); + }; + }); +} + +/** + * Creates a new pending promise and provides methods to resolve or reject it. + * From: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#backwards_forwards_compatible + * @memberof Core + */ +function defer() { + var _this = this; + + /* A method to resolve the associated Promise with the value passed. + * If the promise is already settled it does nothing. + * + * @param {anything} value : This value is used to resolve the promise + * If the value is a Promise then the associated promise assumes the state + * of Promise passed as value. + */ + this.resolve = null; + + /* A method to reject the assocaited Promise with the value passed. + * If the promise is already settled it does nothing. + * + * @param {anything} reason: The reason for the rejection of the Promise. + * Generally its an Error object. If however a Promise is passed, then the Promise + * itself will be the reason for rejection no matter the state of the Promise. + */ + this.reject = null; + + this.id = uuid(); + + /* A newly created Pomise object. + * Initially in pending state. + */ + this.promise = new Promise(function (resolve, reject) { + _this.resolve = resolve; + _this.reject = reject; + }); + Object.freeze(this); +} + +/** + * querySelector with filter by epub type + * @param {element} html + * @param {string} element element type to find + * @param {string} type epub type to find + * @returns {element[]} elements + * @memberof Core + */ +function querySelectorByType(html, element, type) { + var query; + if (typeof html.querySelector != "undefined") { + query = html.querySelector(element + "[*|type=\"" + type + "\"]"); + } + // Handle IE not supporting namespaced epub:type in querySelector + if (!query || query.length === 0) { + query = qsa(html, element); + for (var i = 0; i < query.length; i++) { + if (query[i].getAttributeNS("http://www.idpf.org/2007/ops", "type") === type || query[i].getAttribute("epub:type") === type) { + return query[i]; + } + } + } else { + return query; + } +} + +/** + * Find direct decendents of an element + * @param {element} el + * @returns {element[]} children + * @memberof Core + */ +function findChildren(el) { + var result = []; + var childNodes = el.childNodes; + for (var i = 0; i < childNodes.length; i++) { + var node = childNodes[i]; + if (node.nodeType === 1) { + result.push(node); + } + } + return result; +} + +/** + * Find all parents (ancestors) of an element + * @param {element} node + * @returns {element[]} parents + * @memberof Core + */ +function parents(node) { + var nodes = [node]; + for (; node; node = node.parentNode) { + nodes.unshift(node); + } + return nodes; +} + +/** + * Find all direct decendents of a specific type + * @param {element} el + * @param {string} nodeName + * @param {boolean} [single] + * @returns {element[]} children + * @memberof Core + */ +function filterChildren(el, nodeName, single) { + var result = []; + var childNodes = el.childNodes; + for (var i = 0; i < childNodes.length; i++) { + var node = childNodes[i]; + if (node.nodeType === 1 && node.nodeName.toLowerCase() === nodeName) { + if (single) { + return node; + } else { + result.push(node); + } + } + } + if (!single) { + return result; + } +} + +/** + * Filter all parents (ancestors) with tag name + * @param {element} node + * @param {string} tagname + * @returns {element[]} parents + * @memberof Core + */ +function getParentByTagName(node, tagname) { + var parent = void 0; + if (node === null || tagname === '') return; + parent = node.parentNode; + while (parent.nodeType === 1) { + if (parent.tagName.toLowerCase() === tagname) { + return parent; + } + parent = parent.parentNode; + } +} + +/** + * Lightweight Polyfill for DOM Range + * @class + * @memberof Core + */ + +var RangeObject = exports.RangeObject = function () { + function RangeObject() { + _classCallCheck(this, RangeObject); + + this.collapsed = false; + this.commonAncestorContainer = undefined; + this.endContainer = undefined; + this.endOffset = undefined; + this.startContainer = undefined; + this.startOffset = undefined; + } + + _createClass(RangeObject, [{ + key: "setStart", + value: function setStart(startNode, startOffset) { + this.startContainer = startNode; + this.startOffset = startOffset; + + if (!this.endContainer) { + this.collapse(true); + } else { + this.commonAncestorContainer = this._commonAncestorContainer(); + } + + this._checkCollapsed(); + } + }, { + key: "setEnd", + value: function setEnd(endNode, endOffset) { + this.endContainer = endNode; + this.endOffset = endOffset; + + if (!this.startContainer) { + this.collapse(false); + } else { + this.collapsed = false; + this.commonAncestorContainer = this._commonAncestorContainer(); + } + + this._checkCollapsed(); + } + }, { + key: "collapse", + value: function collapse(toStart) { + this.collapsed = true; + if (toStart) { + this.endContainer = this.startContainer; + this.endOffset = this.startOffset; + this.commonAncestorContainer = this.startContainer.parentNode; + } else { + this.startContainer = this.endContainer; + this.startOffset = this.endOffset; + this.commonAncestorContainer = this.endOffset.parentNode; + } + } + }, { + key: "selectNode", + value: function selectNode(referenceNode) { + var parent = referenceNode.parentNode; + var index = Array.prototype.indexOf.call(parent.childNodes, referenceNode); + this.setStart(parent, index); + this.setEnd(parent, index + 1); + } + }, { + key: "selectNodeContents", + value: function selectNodeContents(referenceNode) { + var end = referenceNode.childNodes[referenceNode.childNodes - 1]; + var endIndex = referenceNode.nodeType === 3 ? referenceNode.textContent.length : parent.childNodes.length; + this.setStart(referenceNode, 0); + this.setEnd(referenceNode, endIndex); + } + }, { + key: "_commonAncestorContainer", + value: function _commonAncestorContainer(startContainer, endContainer) { + var startParents = parents(startContainer || this.startContainer); + var endParents = parents(endContainer || this.endContainer); + + if (startParents[0] != endParents[0]) return undefined; + + for (var i = 0; i < startParents.length; i++) { + if (startParents[i] != endParents[i]) { + return startParents[i - 1]; + } + } + } + }, { + key: "_checkCollapsed", + value: function _checkCollapsed() { + if (this.startContainer === this.endContainer && this.startOffset === this.endOffset) { + this.collapsed = true; + } else { + this.collapsed = false; + } + } + }, { + key: "toString", + value: function toString() { + // TODO: implement walking between start and end to find text + } + }]); + + return RangeObject; +}(); + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var ELEMENT_NODE = 1; +var TEXT_NODE = 3; +var COMMENT_NODE = 8; +var DOCUMENT_NODE = 9; + +/** + * Parsing and creation of EpubCFIs: http://www.idpf.org/epub/linking/cfi/epub-cfi.html + + * Implements: + * - Character Offset: epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3) + * - Simple Ranges : epubcfi(/6/4[chap01ref]!/4[body01]/10[para05],/2/1:1,/3:4) + + * Does Not Implement: + * - Temporal Offset (~) + * - Spatial Offset (@) + * - Temporal-Spatial Offset (~ + @) + * - Text Location Assertion ([) + * @class + @param {string | Range | Node } [cfiFrom] + @param {string | object} [base] + @param {string} [ignoreClass] class to ignore when parsing DOM +*/ + +var EpubCFI = function () { + function EpubCFI(cfiFrom, base, ignoreClass) { + _classCallCheck(this, EpubCFI); + + var type; + + this.str = ""; + + this.base = {}; + this.spinePos = 0; // For compatibility + + this.range = false; // true || false; + + this.path = {}; + this.start = null; + this.end = null; + + // Allow instantiation without the "new" keyword + if (!(this instanceof EpubCFI)) { + return new EpubCFI(cfiFrom, base, ignoreClass); + } + + if (typeof base === "string") { + this.base = this.parseComponent(base); + } else if ((typeof base === "undefined" ? "undefined" : _typeof(base)) === "object" && base.steps) { + this.base = base; + } + + type = this.checkType(cfiFrom); + + if (type === "string") { + this.str = cfiFrom; + return (0, _core.extend)(this, this.parse(cfiFrom)); + } else if (type === "range") { + return (0, _core.extend)(this, this.fromRange(cfiFrom, this.base, ignoreClass)); + } else if (type === "node") { + return (0, _core.extend)(this, this.fromNode(cfiFrom, this.base, ignoreClass)); + } else if (type === "EpubCFI" && cfiFrom.path) { + return cfiFrom; + } else if (!cfiFrom) { + return this; + } else { + throw new TypeError("not a valid argument for EpubCFI"); + } + } + + /** + * Check the type of constructor input + * @private + */ + + + _createClass(EpubCFI, [{ + key: "checkType", + value: function checkType(cfi) { + + if (this.isCfiString(cfi)) { + return "string"; + // Is a range object + } else if ((typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && ((0, _core.type)(cfi) === "Range" || typeof cfi.startContainer != "undefined")) { + return "range"; + } else if ((typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && typeof cfi.nodeType != "undefined") { + // || typeof cfi === "function" + return "node"; + } else if ((typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && cfi instanceof EpubCFI) { + return "EpubCFI"; + } else { + return false; + } + } + + /** + * Parse a cfi string to a CFI object representation + * @param {string} cfiStr + * @returns {object} cfi + */ + + }, { + key: "parse", + value: function parse(cfiStr) { + var cfi = { + spinePos: -1, + range: false, + base: {}, + path: {}, + start: null, + end: null + }; + var baseComponent, pathComponent, range; + + if (typeof cfiStr !== "string") { + return { spinePos: -1 }; + } + + if (cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length - 1] === ")") { + // Remove intial epubcfi( and ending ) + cfiStr = cfiStr.slice(8, cfiStr.length - 1); + } + + baseComponent = this.getChapterComponent(cfiStr); + + // Make sure this is a valid cfi or return + if (!baseComponent) { + return { spinePos: -1 }; + } + + cfi.base = this.parseComponent(baseComponent); + + pathComponent = this.getPathComponent(cfiStr); + cfi.path = this.parseComponent(pathComponent); + + range = this.getRange(cfiStr); + + if (range) { + cfi.range = true; + cfi.start = this.parseComponent(range[0]); + cfi.end = this.parseComponent(range[1]); + } + + // Get spine node position + // cfi.spineSegment = cfi.base.steps[1]; + + // Chapter segment is always the second step + cfi.spinePos = cfi.base.steps[1].index; + + return cfi; + } + }, { + key: "parseComponent", + value: function parseComponent(componentStr) { + var component = { + steps: [], + terminal: { + offset: null, + assertion: null + } + }; + var parts = componentStr.split(":"); + var steps = parts[0].split("/"); + var terminal; + + if (parts.length > 1) { + terminal = parts[1]; + component.terminal = this.parseTerminal(terminal); + } + + if (steps[0] === "") { + steps.shift(); // Ignore the first slash + } + + component.steps = steps.map(function (step) { + return this.parseStep(step); + }.bind(this)); + + return component; + } + }, { + key: "parseStep", + value: function parseStep(stepStr) { + var type, num, index, has_brackets, id; + + has_brackets = stepStr.match(/\[(.*)\]/); + if (has_brackets && has_brackets[1]) { + id = has_brackets[1]; + } + + //-- Check if step is a text node or element + num = parseInt(stepStr); + + if (isNaN(num)) { + return; + } + + if (num % 2 === 0) { + // Even = is an element + type = "element"; + index = num / 2 - 1; + } else { + type = "text"; + index = (num - 1) / 2; + } + + return { + "type": type, + "index": index, + "id": id || null + }; + } + }, { + key: "parseTerminal", + value: function parseTerminal(termialStr) { + var characterOffset, textLocationAssertion; + var assertion = termialStr.match(/\[(.*)\]/); + + if (assertion && assertion[1]) { + characterOffset = parseInt(termialStr.split("[")[0]); + textLocationAssertion = assertion[1]; + } else { + characterOffset = parseInt(termialStr); + } + + if (!(0, _core.isNumber)(characterOffset)) { + characterOffset = null; + } + + return { + "offset": characterOffset, + "assertion": textLocationAssertion + }; + } + }, { + key: "getChapterComponent", + value: function getChapterComponent(cfiStr) { + + var indirection = cfiStr.split("!"); + + return indirection[0]; + } + }, { + key: "getPathComponent", + value: function getPathComponent(cfiStr) { + + var indirection = cfiStr.split("!"); + + if (indirection[1]) { + var ranges = indirection[1].split(","); + return ranges[0]; + } + } + }, { + key: "getRange", + value: function getRange(cfiStr) { + + var ranges = cfiStr.split(","); + + if (ranges.length === 3) { + return [ranges[1], ranges[2]]; + } + + return false; + } + }, { + key: "getCharecterOffsetComponent", + value: function getCharecterOffsetComponent(cfiStr) { + var splitStr = cfiStr.split(":"); + return splitStr[1] || ""; + } + }, { + key: "joinSteps", + value: function joinSteps(steps) { + if (!steps) { + return ""; + } + + return steps.map(function (part) { + var segment = ""; + + if (part.type === "element") { + segment += (part.index + 1) * 2; + } + + if (part.type === "text") { + segment += 1 + 2 * part.index; // TODO: double check that this is odd + } + + if (part.id) { + segment += "[" + part.id + "]"; + } + + return segment; + }).join("/"); + } + }, { + key: "segmentString", + value: function segmentString(segment) { + var segmentString = "/"; + + segmentString += this.joinSteps(segment.steps); + + if (segment.terminal && segment.terminal.offset != null) { + segmentString += ":" + segment.terminal.offset; + } + + if (segment.terminal && segment.terminal.assertion != null) { + segmentString += "[" + segment.terminal.assertion + "]"; + } + + return segmentString; + } + + /** + * Convert CFI to a epubcfi(...) string + * @returns {string} epubcfi + */ + + }, { + key: "toString", + value: function toString() { + var cfiString = "epubcfi("; + + cfiString += this.segmentString(this.base); + + cfiString += "!"; + cfiString += this.segmentString(this.path); + + // Add Range, if present + if (this.range && this.start) { + cfiString += ","; + cfiString += this.segmentString(this.start); + } + + if (this.range && this.end) { + cfiString += ","; + cfiString += this.segmentString(this.end); + } + + cfiString += ")"; + + return cfiString; + } + + /** + * Compare which of two CFIs is earlier in the text + * @returns {number} First is earlier = 1, Second is earlier = -1, They are equal = 0 + */ + + }, { + key: "compare", + value: function compare(cfiOne, cfiTwo) { + var stepsA, stepsB; + var terminalA, terminalB; + + var rangeAStartSteps, rangeAEndSteps; + var rangeBEndSteps, rangeBEndSteps; + var rangeAStartTerminal, rangeAEndTerminal; + var rangeBStartTerminal, rangeBEndTerminal; + + if (typeof cfiOne === "string") { + cfiOne = new EpubCFI(cfiOne); + } + if (typeof cfiTwo === "string") { + cfiTwo = new EpubCFI(cfiTwo); + } + // Compare Spine Positions + if (cfiOne.spinePos > cfiTwo.spinePos) { + return 1; + } + if (cfiOne.spinePos < cfiTwo.spinePos) { + return -1; + } + + if (cfiOne.range) { + stepsA = cfiOne.path.steps.concat(cfiOne.start.steps); + terminalA = cfiOne.start.terminal; + } else { + stepsA = cfiOne.path.steps; + terminalA = cfiOne.path.terminal; + } + + if (cfiTwo.range) { + stepsB = cfiTwo.path.steps.concat(cfiTwo.start.steps); + terminalB = cfiTwo.start.terminal; + } else { + stepsB = cfiTwo.path.steps; + terminalB = cfiTwo.path.terminal; + } + + // Compare Each Step in the First item + for (var i = 0; i < stepsA.length; i++) { + if (!stepsA[i]) { + return -1; + } + if (!stepsB[i]) { + return 1; + } + if (stepsA[i].index > stepsB[i].index) { + return 1; + } + if (stepsA[i].index < stepsB[i].index) { + return -1; + } + // Otherwise continue checking + } + + // All steps in First equal to Second and First is Less Specific + if (stepsA.length < stepsB.length) { + return 1; + } + + // Compare the charecter offset of the text node + if (terminalA.offset > terminalB.offset) { + return 1; + } + if (terminalA.offset < terminalB.offset) { + return -1; + } + + // CFI's are equal + return 0; + } + }, { + key: "step", + value: function step(node) { + var nodeType = node.nodeType === TEXT_NODE ? "text" : "element"; + + return { + "id": node.id, + "tagName": node.tagName, + "type": nodeType, + "index": this.position(node) + }; + } + }, { + key: "filteredStep", + value: function filteredStep(node, ignoreClass) { + var filteredNode = this.filter(node, ignoreClass); + var nodeType; + + // Node filtered, so ignore + if (!filteredNode) { + return; + } + + // Otherwise add the filter node in + nodeType = filteredNode.nodeType === TEXT_NODE ? "text" : "element"; + + return { + "id": filteredNode.id, + "tagName": filteredNode.tagName, + "type": nodeType, + "index": this.filteredPosition(filteredNode, ignoreClass) + }; + } + }, { + key: "pathTo", + value: function pathTo(node, offset, ignoreClass) { + var segment = { + steps: [], + terminal: { + offset: null, + assertion: null + } + }; + var currentNode = node; + var step; + + while (currentNode && currentNode.parentNode && currentNode.parentNode.nodeType != DOCUMENT_NODE) { + + if (ignoreClass) { + step = this.filteredStep(currentNode, ignoreClass); + } else { + step = this.step(currentNode); + } + + if (step) { + segment.steps.unshift(step); + } + + currentNode = currentNode.parentNode; + } + + if (offset != null && offset >= 0) { + + segment.terminal.offset = offset; + + // Make sure we are getting to a textNode if there is an offset + if (segment.steps[segment.steps.length - 1].type != "text") { + segment.steps.push({ + "type": "text", + "index": 0 + }); + } + } + + return segment; + } + }, { + key: "equalStep", + value: function equalStep(stepA, stepB) { + if (!stepA || !stepB) { + return false; + } + + if (stepA.index === stepB.index && stepA.id === stepB.id && stepA.type === stepB.type) { + return true; + } + + return false; + } + + /** + * Create a CFI object from a Range + * @param {Range} range + * @param {string | object} base + * @param {string} [ignoreClass] + * @returns {object} cfi + */ + + }, { + key: "fromRange", + value: function fromRange(range, base, ignoreClass) { + var cfi = { + range: false, + base: {}, + path: {}, + start: null, + end: null + }; + + var start = range.startContainer; + var end = range.endContainer; + + var startOffset = range.startOffset; + var endOffset = range.endOffset; + + var needsIgnoring = false; + + if (ignoreClass) { + // Tell pathTo if / what to ignore + needsIgnoring = start.ownerDocument.querySelector("." + ignoreClass) != null; + } + + if (typeof base === "string") { + cfi.base = this.parseComponent(base); + cfi.spinePos = cfi.base.steps[1].index; + } else if ((typeof base === "undefined" ? "undefined" : _typeof(base)) === "object") { + cfi.base = base; + } + + if (range.collapsed) { + if (needsIgnoring) { + startOffset = this.patchOffset(start, startOffset, ignoreClass); + } + cfi.path = this.pathTo(start, startOffset, ignoreClass); + } else { + cfi.range = true; + + if (needsIgnoring) { + startOffset = this.patchOffset(start, startOffset, ignoreClass); + } + + cfi.start = this.pathTo(start, startOffset, ignoreClass); + if (needsIgnoring) { + endOffset = this.patchOffset(end, endOffset, ignoreClass); + } + + cfi.end = this.pathTo(end, endOffset, ignoreClass); + + // Create a new empty path + cfi.path = { + steps: [], + terminal: null + }; + + // Push steps that are shared between start and end to the common path + var len = cfi.start.steps.length; + var i; + + for (i = 0; i < len; i++) { + if (this.equalStep(cfi.start.steps[i], cfi.end.steps[i])) { + if (i === len - 1) { + // Last step is equal, check terminals + if (cfi.start.terminal === cfi.end.terminal) { + // CFI's are equal + cfi.path.steps.push(cfi.start.steps[i]); + // Not a range + cfi.range = false; + } + } else { + cfi.path.steps.push(cfi.start.steps[i]); + } + } else { + break; + } + } + + cfi.start.steps = cfi.start.steps.slice(cfi.path.steps.length); + cfi.end.steps = cfi.end.steps.slice(cfi.path.steps.length); + + // TODO: Add Sanity check to make sure that the end if greater than the start + } + + return cfi; + } + + /** + * Create a CFI object from a Node + * @param {Node} anchor + * @param {string | object} base + * @param {string} [ignoreClass] + * @returns {object} cfi + */ + + }, { + key: "fromNode", + value: function fromNode(anchor, base, ignoreClass) { + var cfi = { + range: false, + base: {}, + path: {}, + start: null, + end: null + }; + + if (typeof base === "string") { + cfi.base = this.parseComponent(base); + cfi.spinePos = cfi.base.steps[1].index; + } else if ((typeof base === "undefined" ? "undefined" : _typeof(base)) === "object") { + cfi.base = base; + } + + cfi.path = this.pathTo(anchor, null, ignoreClass); + + return cfi; + } + }, { + key: "filter", + value: function filter(anchor, ignoreClass) { + var needsIgnoring; + var sibling; // to join with + var parent, previousSibling, nextSibling; + var isText = false; + + if (anchor.nodeType === TEXT_NODE) { + isText = true; + parent = anchor.parentNode; + needsIgnoring = anchor.parentNode.classList.contains(ignoreClass); + } else { + isText = false; + needsIgnoring = anchor.classList.contains(ignoreClass); + } + + if (needsIgnoring && isText) { + previousSibling = parent.previousSibling; + nextSibling = parent.nextSibling; + + // If the sibling is a text node, join the nodes + if (previousSibling && previousSibling.nodeType === TEXT_NODE) { + sibling = previousSibling; + } else if (nextSibling && nextSibling.nodeType === TEXT_NODE) { + sibling = nextSibling; + } + + if (sibling) { + return sibling; + } else { + // Parent will be ignored on next step + return anchor; + } + } else if (needsIgnoring && !isText) { + // Otherwise just skip the element node + return false; + } else { + // No need to filter + return anchor; + } + } + }, { + key: "patchOffset", + value: function patchOffset(anchor, offset, ignoreClass) { + if (anchor.nodeType != TEXT_NODE) { + throw new Error("Anchor must be a text node"); + } + + var curr = anchor; + var totalOffset = offset; + + // If the parent is a ignored node, get offset from it's start + if (anchor.parentNode.classList.contains(ignoreClass)) { + curr = anchor.parentNode; + } + + while (curr.previousSibling) { + if (curr.previousSibling.nodeType === ELEMENT_NODE) { + // Originally a text node, so join + if (curr.previousSibling.classList.contains(ignoreClass)) { + totalOffset += curr.previousSibling.textContent.length; + } else { + break; // Normal node, dont join + } + } else { + // If the previous sibling is a text node, join the nodes + totalOffset += curr.previousSibling.textContent.length; + } + + curr = curr.previousSibling; + } + + return totalOffset; + } + }, { + key: "normalizedMap", + value: function normalizedMap(children, nodeType, ignoreClass) { + var output = {}; + var prevIndex = -1; + var i, + len = children.length; + var currNodeType; + var prevNodeType; + + for (i = 0; i < len; i++) { + + currNodeType = children[i].nodeType; + + // Check if needs ignoring + if (currNodeType === ELEMENT_NODE && children[i].classList.contains(ignoreClass)) { + currNodeType = TEXT_NODE; + } + + if (i > 0 && currNodeType === TEXT_NODE && prevNodeType === TEXT_NODE) { + // join text nodes + output[i] = prevIndex; + } else if (nodeType === currNodeType) { + prevIndex = prevIndex + 1; + output[i] = prevIndex; + } + + prevNodeType = currNodeType; + } + + return output; + } + }, { + key: "position", + value: function position(anchor) { + var children, index; + if (anchor.nodeType === ELEMENT_NODE) { + children = anchor.parentNode.children; + if (!children) { + children = (0, _core.findChildren)(anchor.parentNode); + } + index = Array.prototype.indexOf.call(children, anchor); + } else { + children = this.textNodes(anchor.parentNode); + index = children.indexOf(anchor); + } + + return index; + } + }, { + key: "filteredPosition", + value: function filteredPosition(anchor, ignoreClass) { + var children, index, map; + + if (anchor.nodeType === ELEMENT_NODE) { + children = anchor.parentNode.children; + map = this.normalizedMap(children, ELEMENT_NODE, ignoreClass); + } else { + children = anchor.parentNode.childNodes; + // Inside an ignored node + if (anchor.parentNode.classList.contains(ignoreClass)) { + anchor = anchor.parentNode; + children = anchor.parentNode.childNodes; + } + map = this.normalizedMap(children, TEXT_NODE, ignoreClass); + } + + index = Array.prototype.indexOf.call(children, anchor); + + return map[index]; + } + }, { + key: "stepsToXpath", + value: function stepsToXpath(steps) { + var xpath = [".", "*"]; + + steps.forEach(function (step) { + var position = step.index + 1; + + if (step.id) { + xpath.push("*[position()=" + position + " and @id='" + step.id + "']"); + } else if (step.type === "text") { + xpath.push("text()[" + position + "]"); + } else { + xpath.push("*[" + position + "]"); + } + }); + + return xpath.join("/"); + } + + /* + To get the last step if needed: + // Get the terminal step + lastStep = steps[steps.length-1]; + // Get the query string + query = this.stepsToQuery(steps); + // Find the containing element + startContainerParent = doc.querySelector(query); + // Find the text node within that element + if(startContainerParent && lastStep.type == "text") { + container = startContainerParent.childNodes[lastStep.index]; + } + */ + + }, { + key: "stepsToQuerySelector", + value: function stepsToQuerySelector(steps) { + var query = ["html"]; + + steps.forEach(function (step) { + var position = step.index + 1; + + if (step.id) { + query.push("#" + step.id); + } else if (step.type === "text") { + // unsupported in querySelector + // query.push("text()[" + position + "]"); + } else { + query.push("*:nth-child(" + position + ")"); + } + }); + + return query.join(">"); + } + }, { + key: "textNodes", + value: function textNodes(container, ignoreClass) { + return Array.prototype.slice.call(container.childNodes).filter(function (node) { + if (node.nodeType === TEXT_NODE) { + return true; + } else if (ignoreClass && node.classList.contains(ignoreClass)) { + return true; + } + return false; + }); + } + }, { + key: "walkToNode", + value: function walkToNode(steps, _doc, ignoreClass) { + var doc = _doc || document; + var container = doc.documentElement; + var children; + var step; + var len = steps.length; + var i; + + for (i = 0; i < len; i++) { + step = steps[i]; + + if (step.type === "element") { + //better to get a container using id as some times step.index may not be correct + //For ex.https://github.com/futurepress/epub.js/issues/561 + if (step.id) { + container = doc.getElementById(step.id); + } else { + children = container.children || (0, _core.findChildren)(container); + container = children[step.index]; + } + } else if (step.type === "text") { + container = this.textNodes(container, ignoreClass)[step.index]; + } + if (!container) { + //Break the for loop as due to incorrect index we can get error if + //container is undefined so that other functionailties works fine + //like navigation + break; + } + } + + return container; + } + }, { + key: "findNode", + value: function findNode(steps, _doc, ignoreClass) { + var doc = _doc || document; + var container; + var xpath; + + if (!ignoreClass && typeof doc.evaluate != "undefined") { + xpath = this.stepsToXpath(steps); + container = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } else if (ignoreClass) { + container = this.walkToNode(steps, doc, ignoreClass); + } else { + container = this.walkToNode(steps, doc); + } + + return container; + } + }, { + key: "fixMiss", + value: function fixMiss(steps, offset, _doc, ignoreClass) { + var container = this.findNode(steps.slice(0, -1), _doc, ignoreClass); + var children = container.childNodes; + var map = this.normalizedMap(children, TEXT_NODE, ignoreClass); + var child; + var len; + var lastStepIndex = steps[steps.length - 1].index; + + for (var childIndex in map) { + if (!map.hasOwnProperty(childIndex)) return; + + if (map[childIndex] === lastStepIndex) { + child = children[childIndex]; + len = child.textContent.length; + if (offset > len) { + offset = offset - len; + } else { + if (child.nodeType === ELEMENT_NODE) { + container = child.childNodes[0]; + } else { + container = child; + } + break; + } + } + } + + return { + container: container, + offset: offset + }; + } + + /** + * Creates a DOM range representing a CFI + * @param {document} _doc document referenced in the base + * @param {string} [ignoreClass] + * @return {Range} + */ + + }, { + key: "toRange", + value: function toRange(_doc, ignoreClass) { + var doc = _doc || document; + var range; + var start, end, startContainer, endContainer; + var cfi = this; + var startSteps, endSteps; + var needsIgnoring = ignoreClass ? doc.querySelector("." + ignoreClass) != null : false; + var missed; + + if (typeof doc.createRange !== "undefined") { + range = doc.createRange(); + } else { + range = new _core.RangeObject(); + } + + if (cfi.range) { + start = cfi.start; + startSteps = cfi.path.steps.concat(start.steps); + startContainer = this.findNode(startSteps, doc, needsIgnoring ? ignoreClass : null); + end = cfi.end; + endSteps = cfi.path.steps.concat(end.steps); + endContainer = this.findNode(endSteps, doc, needsIgnoring ? ignoreClass : null); + } else { + start = cfi.path; + startSteps = cfi.path.steps; + startContainer = this.findNode(cfi.path.steps, doc, needsIgnoring ? ignoreClass : null); + } + + if (startContainer) { + try { + + if (start.terminal.offset != null) { + range.setStart(startContainer, start.terminal.offset); + } else { + range.setStart(startContainer, 0); + } + } catch (e) { + missed = this.fixMiss(startSteps, start.terminal.offset, doc, needsIgnoring ? ignoreClass : null); + range.setStart(missed.container, missed.offset); + } + } else { + console.log("No startContainer found for", this.toString()); + // No start found + return null; + } + + if (endContainer) { + try { + + if (end.terminal.offset != null) { + range.setEnd(endContainer, end.terminal.offset); + } else { + range.setEnd(endContainer, 0); + } + } catch (e) { + missed = this.fixMiss(endSteps, cfi.end.terminal.offset, doc, needsIgnoring ? ignoreClass : null); + range.setEnd(missed.container, missed.offset); + } + } + + // doc.defaultView.getSelection().addRange(range); + return range; + } + + /** + * Check if a string is wrapped with "epubcfi()" + * @param {string} str + * @returns {boolean} + */ + + }, { + key: "isCfiString", + value: function isCfiString(str) { + if (typeof str === "string" && str.indexOf("epubcfi(") === 0 && str[str.length - 1] === ")") { + return true; + } + + return false; + } + }, { + key: "generateChapterComponent", + value: function generateChapterComponent(_spineNodeIndex, _pos, id) { + var pos = parseInt(_pos), + spineNodeIndex = (_spineNodeIndex + 1) * 2, + cfi = "/" + spineNodeIndex + "/"; + + cfi += (pos + 1) * 2; + + if (id) { + cfi += "[" + id + "]"; + } + + return cfi; + } + + /** + * Collapse a CFI Range to a single CFI Position + * @param {boolean} [toStart=false] + */ + + }, { + key: "collapse", + value: function collapse(toStart) { + if (!this.range) { + return; + } + + this.range = false; + + if (toStart) { + this.path.steps = this.path.steps.concat(this.start.steps); + this.path.terminal = this.start.terminal; + } else { + this.path.steps = this.path.steps.concat(this.end.steps); + this.path.terminal = this.end.terminal; + } + } + }]); + + return EpubCFI; +}(); + +exports.default = EpubCFI; +module.exports = exports["default"]; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var d = __webpack_require__(27) + , callable = __webpack_require__(41) + + , apply = Function.prototype.apply, call = Function.prototype.call + , create = Object.create, defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , hasOwnProperty = Object.prototype.hasOwnProperty + , descriptor = { configurable: true, enumerable: false, writable: true } + + , on, once, off, emit, methods, descriptors, base; + +on = function (type, listener) { + var data; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) { + data = descriptor.value = create(null); + defineProperty(this, '__ee__', descriptor); + descriptor.value = null; + } else { + data = this.__ee__; + } + if (!data[type]) data[type] = listener; + else if (typeof data[type] === 'object') data[type].push(listener); + else data[type] = [data[type], listener]; + + return this; +}; + +once = function (type, listener) { + var once, self; + + callable(listener); + self = this; + on.call(this, type, once = function () { + off.call(self, type, once); + apply.call(listener, this, arguments); + }); + + once.__eeOnceListener__ = listener; + return this; +}; + +off = function (type, listener) { + var data, listeners, candidate, i; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) return this; + data = this.__ee__; + if (!data[type]) return this; + listeners = data[type]; + + if (typeof listeners === 'object') { + for (i = 0; (candidate = listeners[i]); ++i) { + if ((candidate === listener) || + (candidate.__eeOnceListener__ === listener)) { + if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; + else listeners.splice(i, 1); + } + } + } else { + if ((listeners === listener) || + (listeners.__eeOnceListener__ === listener)) { + delete data[type]; + } + } + + return this; +}; + +emit = function (type) { + var i, l, listener, listeners, args; + + if (!hasOwnProperty.call(this, '__ee__')) return; + listeners = this.__ee__[type]; + if (!listeners) return; + + if (typeof listeners === 'object') { + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + + listeners = listeners.slice(); + for (i = 0; (listener = listeners[i]); ++i) { + apply.call(listener, this, args); + } + } else { + switch (arguments.length) { + case 1: + call.call(listeners, this); + break; + case 2: + call.call(listeners, this, arguments[1]); + break; + case 3: + call.call(listeners, this, arguments[1], arguments[2]); + break; + default: + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + apply.call(listeners, this, args); + } + } +}; + +methods = { + on: on, + once: once, + off: off, + emit: emit +}; + +descriptors = { + on: d(on), + once: d(once), + off: d(off), + emit: d(emit) +}; + +base = defineProperties({}, descriptors); + +module.exports = exports = function (o) { + return (o == null) ? create(base) : defineProperties(Object(o), descriptors); +}; +exports.methods = methods; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Dom events to listen for +var DOM_EVENTS = exports.DOM_EVENTS = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart"]; + +var EVENTS = exports.EVENTS = { + BOOK: { + OPEN_FAILED: "openFailed" + }, + CONTENTS: { + EXPAND: "expand", + RESIZE: "resize", + SELECTED: "selected", + SELECTED_RANGE: "selectedRange", + LINK_CLICKED: "linkClicked" + }, + LOCATIONS: { + CHANGED: "changed" + }, + MANAGERS: { + RESIZE: "resize", + RESIZED: "resized", + ORIENTATION_CHANGE: "orientationchange", + ADDED: "added", + SCROLL: "scroll", + SCROLLED: "scrolled" + }, + VIEWS: { + AXIS: "axis", + LOAD_ERROR: "loaderror", + RENDERED: "rendered", + RESIZED: "resized", + DISPLAYED: "displayed", + SHOWN: "shown", + HIDDEN: "hidden", + MARK_CLICKED: "markClicked" + }, + RENDITION: { + STARTED: "started", + ATTACHED: "attached", + DISPLAYED: "displayed", + DISPLAY_ERROR: "displayerror", + RENDERED: "rendered", + REMOVED: "removed", + RESIZED: "resized", + ORIENTATION_CHANGE: "orientationchange", + LOCATION_CHANGED: "locationChanged", + RELOCATED: "relocated", + MARK_CLICKED: "markClicked", + SELECTED: "selected", + LAYOUT: "layout" + }, + LAYOUT: { + UPDATED: "updated" + } +}; + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _pathWebpack = __webpack_require__(6); + +var _pathWebpack2 = _interopRequireDefault(_pathWebpack); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Path object for parsing and manipulation of a path strings + * + * Uses a polyfill for Nodejs path: https://nodejs.org/api/path.html + * @param {string} pathString a url string (relative or absolute) + * @class + */ +var Path = function () { + function Path(pathString) { + _classCallCheck(this, Path); + + var protocol; + var parsed; + + protocol = pathString.indexOf("://"); + if (protocol > -1) { + pathString = new URL(pathString).pathname; + } + + parsed = this.parse(pathString); + + this.path = pathString; + + if (this.isDirectory(pathString)) { + this.directory = pathString; + } else { + this.directory = parsed.dir + "/"; + } + + this.filename = parsed.base; + this.extension = parsed.ext.slice(1); + } + + /** + * Parse the path: https://nodejs.org/api/path.html#path_path_parse_path + * @param {string} what + * @returns {object} + */ + + + _createClass(Path, [{ + key: "parse", + value: function parse(what) { + return _pathWebpack2.default.parse(what); + } + + /** + * @param {string} what + * @returns {boolean} + */ + + }, { + key: "isAbsolute", + value: function isAbsolute(what) { + return _pathWebpack2.default.isAbsolute(what || this.path); + } + + /** + * Check if path ends with a directory + * @param {string} what + * @returns {boolean} + */ + + }, { + key: "isDirectory", + value: function isDirectory(what) { + return what.charAt(what.length - 1) === "/"; + } + + /** + * Resolve a path against the directory of the Path + * + * https://nodejs.org/api/path.html#path_path_resolve_paths + * @param {string} what + * @returns {string} resolved + */ + + }, { + key: "resolve", + value: function resolve(what) { + return _pathWebpack2.default.resolve(this.directory, what); + } + + /** + * Resolve a path relative to the directory of the Path + * + * https://nodejs.org/api/path.html#path_path_relative_from_to + * @param {string} what + * @returns {string} relative + */ + + }, { + key: "relative", + value: function relative(what) { + return _pathWebpack2.default.relative(this.directory, what); + } + }, { + key: "splitPath", + value: function splitPath(filename) { + return this.splitPathRe.exec(filename).slice(1); + } + + /** + * Return the path string + * @returns {string} path + */ + + }, { + key: "toString", + value: function toString() { + return this.path; + } + }]); + + return Path; +}(); + +exports.default = Path; +module.exports = exports["default"]; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _path = __webpack_require__(4); + +var _path2 = _interopRequireDefault(_path); + +var _pathWebpack = __webpack_require__(6); + +var _pathWebpack2 = _interopRequireDefault(_pathWebpack); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * creates a Url object for parsing and manipulation of a url string + * @param {string} urlString a url string (relative or absolute) + * @param {string} [baseString] optional base for the url, + * default to window.location.href + */ +var Url = function () { + function Url(urlString, baseString) { + _classCallCheck(this, Url); + + var absolute = urlString.indexOf("://") > -1; + var pathname = urlString; + var basePath; + + this.Url = undefined; + this.href = urlString; + this.protocol = ""; + this.origin = ""; + this.hash = ""; + this.hash = ""; + this.search = ""; + this.base = baseString; + + if (!absolute && baseString !== false && typeof baseString !== "string" && window && window.location) { + this.base = window.location.href; + } + + // URL Polyfill doesn't throw an error if base is empty + if (absolute || this.base) { + try { + if (this.base) { + // Safari doesn't like an undefined base + this.Url = new URL(urlString, this.base); + } else { + this.Url = new URL(urlString); + } + this.href = this.Url.href; + + this.protocol = this.Url.protocol; + this.origin = this.Url.origin; + this.hash = this.Url.hash; + this.search = this.Url.search; + + pathname = this.Url.pathname; + } catch (e) { + // Skip URL parsing + this.Url = undefined; + // resolve the pathname from the base + if (this.base) { + basePath = new _path2.default(this.base); + pathname = basePath.resolve(pathname); + } + } + } + + this.Path = new _path2.default(pathname); + + this.directory = this.Path.directory; + this.filename = this.Path.filename; + this.extension = this.Path.extension; + } + + /** + * @returns {Path} + */ + + + _createClass(Url, [{ + key: "path", + value: function path() { + return this.Path; + } + + /** + * Resolves a relative path to a absolute url + * @returns {string} url + */ + + }, { + key: "resolve", + value: function resolve(what) { + var isAbsolute = what.indexOf("://") > -1; + var fullpath; + + if (isAbsolute) { + return what; + } + + fullpath = _pathWebpack2.default.resolve(this.directory, what); + return this.origin + fullpath; + } + + /** + * Resolve a path relative to the url + * @returns {string} path + */ + + }, { + key: "relative", + value: function relative(what) { + return _pathWebpack2.default.relative(what, this.directory); + } + + /** + * @returns {string} + */ + + }, { + key: "toString", + value: function toString() { + return this.href; + } + }]); + + return Url; +}(); + +exports.default = Url; +module.exports = exports["default"]; + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +if (!process) { + var process = { + "cwd" : function () { return '/' } + }; +} + +function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError('Path must be a string. Received ' + path); + } +} + +// Resolves . and .. elements in a path with directory names +function normalizeStringPosix(path, allowAboveRoot) { + var res = ''; + var lastSlash = -1; + var dots = 0; + var code; + for (var i = 0; i <= path.length; ++i) { + if (i < path.length) + code = path.charCodeAt(i); + else if (code === 47/*/*/) + break; + else + code = 47/*/*/; + if (code === 47/*/*/) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || + res.charCodeAt(res.length - 1) !== 46/*.*/ || + res.charCodeAt(res.length - 2) !== 46/*.*/) { + if (res.length > 2) { + var start = res.length - 1; + var j = start; + for (; j >= 0; --j) { + if (res.charCodeAt(j) === 47/*/*/) + break; + } + if (j !== start) { + if (j === -1) + res = ''; + else + res = res.slice(0, j); + lastSlash = i; + dots = 0; + continue; + } + } else if (res.length === 2 || res.length === 1) { + res = ''; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) + res += '/..'; + else + res = '..'; + } + } else { + if (res.length > 0) + res += '/' + path.slice(lastSlash + 1, i); + else + res = path.slice(lastSlash + 1, i); + } + lastSlash = i; + dots = 0; + } else if (code === 46/*.*/ && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +function _format(sep, pathObject) { + var dir = pathObject.dir || pathObject.root; + var base = pathObject.base || + ((pathObject.name || '') + (pathObject.ext || '')); + if (!dir) { + return base; + } + if (dir === pathObject.root) { + return dir + base; + } + return dir + sep + base; +} + +var posix = { + // path.resolve([from ...], to) + resolve: function resolve() { + var resolvedPath = ''; + var resolvedAbsolute = false; + var cwd; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path; + if (i >= 0) + path = arguments[i]; + else { + if (cwd === undefined) + cwd = process.cwd(); + path = cwd; + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charCodeAt(0) === 47/*/*/; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute); + + if (resolvedAbsolute) { + if (resolvedPath.length > 0) + return '/' + resolvedPath; + else + return '/'; + } else if (resolvedPath.length > 0) { + return resolvedPath; + } else { + return '.'; + } + }, + + + normalize: function normalize(path) { + assertPath(path); + + if (path.length === 0) + return '.'; + + var isAbsolute = path.charCodeAt(0) === 47/*/*/; + var trailingSeparator = path.charCodeAt(path.length - 1) === 47/*/*/; + + // Normalize the path + path = normalizeStringPosix(path, !isAbsolute); + + if (path.length === 0 && !isAbsolute) + path = '.'; + if (path.length > 0 && trailingSeparator) + path += '/'; + + if (isAbsolute) + return '/' + path; + return path; + }, + + + isAbsolute: function isAbsolute(path) { + assertPath(path); + return path.length > 0 && path.charCodeAt(0) === 47/*/*/; + }, + + + join: function join() { + if (arguments.length === 0) + return '.'; + var joined; + for (var i = 0; i < arguments.length; ++i) { + var arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) + joined = arg; + else + joined += '/' + arg; + } + } + if (joined === undefined) + return '.'; + return posix.normalize(joined); + }, + + + relative: function relative(from, to) { + assertPath(from); + assertPath(to); + + if (from === to) + return ''; + + from = posix.resolve(from); + to = posix.resolve(to); + + if (from === to) + return ''; + + // Trim any leading backslashes + var fromStart = 1; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== 47/*/*/) + break; + } + var fromEnd = from.length; + var fromLen = (fromEnd - fromStart); + + // Trim any leading backslashes + var toStart = 1; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== 47/*/*/) + break; + } + var toEnd = to.length; + var toLen = (toEnd - toStart); + + // Compare paths to find the longest common path from root + var length = (fromLen < toLen ? fromLen : toLen); + var lastCommonSep = -1; + var i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === 47/*/*/) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === 47/*/*/) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + var fromCode = from.charCodeAt(fromStart + i); + var toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) + break; + else if (fromCode === 47/*/*/) + lastCommonSep = i; + } + + var out = ''; + // Generate the relative path based on the path difference between `to` + // and `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === 47/*/*/) { + if (out.length === 0) + out += '..'; + else + out += '/..'; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) + return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (to.charCodeAt(toStart) === 47/*/*/) + ++toStart; + return to.slice(toStart); + } + }, + + + _makeLong: function _makeLong(path) { + return path; + }, + + + dirname: function dirname(path) { + assertPath(path); + if (path.length === 0) + return '.'; + var code = path.charCodeAt(0); + var hasRoot = (code === 47/*/*/); + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) + return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) + return '//'; + return path.slice(0, end); + }, + + + basename: function basename(path, ext) { + if (ext !== undefined && typeof ext !== 'string') + throw new TypeError('"ext" argument must be a string'); + assertPath(path); + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) + return ''; + var extIdx = ext.length - 1; + var firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47/*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) + end = firstNonSlashEnd; + else if (end === -1) + end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47/*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) + return ''; + return path.slice(start, end); + } + }, + + + extname: function extname(path) { + assertPath(path); + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47/*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46/*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && + startDot === end - 1 && + startDot === startPart + 1)) { + return ''; + } + return path.slice(startDot, end); + }, + + + format: function format(pathObject) { + if (pathObject === null || typeof pathObject !== 'object') { + throw new TypeError( + 'Parameter "pathObject" must be an object, not ' + typeof(pathObject) + ); + } + return _format('/', pathObject); + }, + + + parse: function parse(path) { + assertPath(path); + + var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) + return ret; + var code = path.charCodeAt(0); + var isAbsolute = (code === 47/*/*/); + var start; + if (isAbsolute) { + ret.root = '/'; + start = 1; + } else { + start = 0; + } + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + var i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46/*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && + startDot === end - 1 && + startDot === startPart + 1)) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + ret.base = ret.name = path.slice(1, end); + else + ret.base = ret.name = path.slice(startPart, end); + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + + if (startPart > 0) + ret.dir = path.slice(0, startPart - 1); + else if (isAbsolute) + ret.dir = '/'; + + return ret; + }, + + + sep: '/', + delimiter: ':', + posix: null +}; + + +module.exports = posix; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.replaceBase = replaceBase; +exports.replaceCanonical = replaceCanonical; +exports.replaceMeta = replaceMeta; +exports.replaceLinks = replaceLinks; +exports.substitute = substitute; + +var _core = __webpack_require__(0); + +var _url = __webpack_require__(5); + +var _url2 = _interopRequireDefault(_url); + +var _path = __webpack_require__(4); + +var _path2 = _interopRequireDefault(_path); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function replaceBase(doc, section) { + var base; + var head; + var url = section.url; + var absolute = url.indexOf("://") > -1; + + if (!doc) { + return; + } + + head = (0, _core.qs)(doc, "head"); + base = (0, _core.qs)(head, "base"); + + if (!base) { + base = doc.createElement("base"); + head.insertBefore(base, head.firstChild); + } + + // Fix for Safari crashing if the url doesn't have an origin + if (!absolute && window && window.location) { + url = window.location.origin + url; + } + + base.setAttribute("href", url); +} + +function replaceCanonical(doc, section) { + var head; + var link; + var url = section.canonical; + + if (!doc) { + return; + } + + head = (0, _core.qs)(doc, "head"); + link = (0, _core.qs)(head, "link[rel='canonical']"); + + if (link) { + link.setAttribute("href", url); + } else { + link = doc.createElement("link"); + link.setAttribute("rel", "canonical"); + link.setAttribute("href", url); + head.appendChild(link); + } +} + +function replaceMeta(doc, section) { + var head; + var meta; + var id = section.idref; + if (!doc) { + return; + } + + head = (0, _core.qs)(doc, "head"); + meta = (0, _core.qs)(head, "link[property='dc.identifier']"); + + if (meta) { + meta.setAttribute("content", id); + } else { + meta = doc.createElement("meta"); + meta.setAttribute("name", "dc.identifier"); + meta.setAttribute("content", id); + head.appendChild(meta); + } +} + +// TODO: move me to Contents +function replaceLinks(contents, fn) { + + var links = contents.querySelectorAll("a[href]"); + + if (!links.length) { + return; + } + + var base = (0, _core.qs)(contents.ownerDocument, "base"); + var location = base ? base.getAttribute("href") : undefined; + var replaceLink = function (link) { + var href = link.getAttribute("href"); + + if (href.indexOf("mailto:") === 0) { + return; + } + + var absolute = href.indexOf("://") > -1; + var linkUrl = new _url2.default(href, location); + + if (absolute) { + + link.setAttribute("target", "_blank"); + } else { + link.onclick = function () { + + if (linkUrl && linkUrl.hash) { + fn(linkUrl.Path.path + linkUrl.hash); + } else if (linkUrl) { + fn(linkUrl.Path.path); + } else { + fn(href); + } + + return false; + }; + } + }.bind(this); + + for (var i = 0; i < links.length; i++) { + replaceLink(links[i]); + } +} + +function substitute(content, urls, replacements) { + urls.forEach(function (url, i) { + if (url && replacements[i]) { + content = content.replace(new RegExp(url, "g"), replacements[i]); + } + }); + return content; +} + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _undefined = __webpack_require__(34)(); // Support ES3 engines + +module.exports = function (val) { + return (val !== _undefined) && (val !== null); +}; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Hooks allow for injecting functions that must all complete in order before finishing + * They will execute in parallel but all must finish before continuing + * Functions may return a promise if they are asycn. + * @param {any} context scope of this + * @example this.content = new EPUBJS.Hook(this); + */ +var Hook = function () { + function Hook(context) { + _classCallCheck(this, Hook); + + this.context = context || this; + this.hooks = []; + } + + /** + * Adds a function to be run before a hook completes + * @example this.content.register(function(){...}); + */ + + + _createClass(Hook, [{ + key: "register", + value: function register() { + for (var i = 0; i < arguments.length; ++i) { + if (typeof arguments[i] === "function") { + this.hooks.push(arguments[i]); + } else { + // unpack array + for (var j = 0; j < arguments[i].length; ++j) { + this.hooks.push(arguments[i][j]); + } + } + } + } + + /** + * Triggers a hook to run all functions + * @example this.content.trigger(args).then(function(){...}); + */ + + }, { + key: "trigger", + value: function trigger() { + var args = arguments; + var context = this.context; + var promises = []; + + this.hooks.forEach(function (task) { + var executing = task.apply(context, args); + + if (executing && typeof executing["then"] === "function") { + // Task is a function that returns a promise + promises.push(executing); + } + // Otherwise Task resolves immediately, continue + }); + + return Promise.all(promises); + } + + // Adds a function to be run before a hook completes + + }, { + key: "list", + value: function list() { + return this.hooks; + } + }, { + key: "clear", + value: function clear() { + return this.hooks = []; + } + }]); + + return Hook; +}(); + +exports.default = Hook; +module.exports = exports["default"]; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _core = __webpack_require__(0); + +var _path = __webpack_require__(4); + +var _path2 = _interopRequireDefault(_path); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function request(url, type, withCredentials, headers) { + var supportsURL = typeof window != "undefined" ? window.URL : false; // TODO: fallback for url if window isn't defined + var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; + + var deferred = new _core.defer(); + + var xhr = new XMLHttpRequest(); + + //-- Check from PDF.js: + // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js + var xhrPrototype = XMLHttpRequest.prototype; + + var header; + + if (!("overrideMimeType" in xhrPrototype)) { + // IE10 might have response, but not overrideMimeType + Object.defineProperty(xhrPrototype, "overrideMimeType", { + value: function xmlHttpRequestOverrideMimeType() {} + }); + } + + if (withCredentials) { + xhr.withCredentials = true; + } + + xhr.onreadystatechange = handler; + xhr.onerror = err; + + xhr.open("GET", url, true); + + for (header in headers) { + xhr.setRequestHeader(header, headers[header]); + } + + if (type == "json") { + xhr.setRequestHeader("Accept", "application/json"); + } + + // If type isn"t set, determine it from the file extension + if (!type) { + type = new _path2.default(url).extension; + } + + if (type == "blob") { + xhr.responseType = BLOB_RESPONSE; + } + + if ((0, _core.isXml)(type)) { + // xhr.responseType = "document"; + xhr.overrideMimeType("text/xml"); // for OPF parsing + } + + if (type == "xhtml") { + // xhr.responseType = "document"; + } + + if (type == "html" || type == "htm") { + // xhr.responseType = "document"; + } + + if (type == "binary") { + xhr.responseType = "arraybuffer"; + } + + xhr.send(); + + function err(e) { + deferred.reject(e); + } + + function handler() { + if (this.readyState === XMLHttpRequest.DONE) { + var responseXML = false; + + if (this.responseType === "" || this.responseType === "document") { + responseXML = this.responseXML; + } + + if (this.status === 200 || responseXML) { + //-- Firefox is reporting 0 for blob urls + var r; + + if (!this.response && !responseXML) { + deferred.reject({ + status: this.status, + message: "Empty Response", + stack: new Error().stack + }); + return deferred.promise; + } + + if (this.status === 403) { + deferred.reject({ + status: this.status, + response: this.response, + message: "Forbidden", + stack: new Error().stack + }); + return deferred.promise; + } + if (responseXML) { + r = this.responseXML; + } else if ((0, _core.isXml)(type)) { + // xhr.overrideMimeType("text/xml"); // for OPF parsing + // If this.responseXML wasn't set, try to parse using a DOMParser from text + r = (0, _core.parse)(this.response, "text/xml"); + } else if (type == "xhtml") { + r = (0, _core.parse)(this.response, "application/xhtml+xml"); + } else if (type == "html" || type == "htm") { + r = (0, _core.parse)(this.response, "text/html"); + } else if (type == "json") { + r = JSON.parse(this.response); + } else if (type == "blob") { + + if (supportsURL) { + r = this.response; + } else { + //-- Safari doesn't support responseType blob, so create a blob from arraybuffer + r = new Blob([this.response]); + } + } else { + r = this.response; + } + + deferred.resolve(r); + } else { + + deferred.reject({ + status: this.status, + message: this.response, + stack: new Error().stack + }); + } + } + } + + return deferred.promise; +} + +exports.default = request; +module.exports = exports["default"]; + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Task = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Queue for handling tasks one at a time + * @class + * @param {scope} context what this will resolve to in the tasks + */ +var Queue = function () { + function Queue(context) { + _classCallCheck(this, Queue); + + this._q = []; + this.context = context; + this.tick = _core.requestAnimationFrame; + this.running = false; + this.paused = false; + } + + /** + * Add an item to the queue + * @return {Promise} + */ + + + _createClass(Queue, [{ + key: "enqueue", + value: function enqueue() { + var deferred, promise; + var queued; + var task = [].shift.call(arguments); + var args = arguments; + + // Handle single args without context + // if(args && !Array.isArray(args)) { + // args = [args]; + // } + if (!task) { + throw new Error("No Task Provided"); + } + + if (typeof task === "function") { + + deferred = new _core.defer(); + promise = deferred.promise; + + queued = { + "task": task, + "args": args, + //"context" : context, + "deferred": deferred, + "promise": promise + }; + } else { + // Task is a promise + queued = { + "promise": task + }; + } + + this._q.push(queued); + + // Wait to start queue flush + if (this.paused == false && !this.running) { + // setTimeout(this.flush.bind(this), 0); + // this.tick.call(window, this.run.bind(this)); + this.run(); + } + + return queued.promise; + } + + /** + * Run one item + * @return {Promise} + */ + + }, { + key: "dequeue", + value: function dequeue() { + var inwait, task, result; + + if (this._q.length && !this.paused) { + inwait = this._q.shift(); + task = inwait.task; + if (task) { + // console.log(task) + + result = task.apply(this.context, inwait.args); + + if (result && typeof result["then"] === "function") { + // Task is a function that returns a promise + return result.then(function () { + inwait.deferred.resolve.apply(this.context, arguments); + }.bind(this), function () { + inwait.deferred.reject.apply(this.context, arguments); + }.bind(this)); + } else { + // Task resolves immediately + inwait.deferred.resolve.apply(this.context, result); + return inwait.promise; + } + } else if (inwait.promise) { + // Task is a promise + return inwait.promise; + } + } else { + inwait = new _core.defer(); + inwait.deferred.resolve(); + return inwait.promise; + } + } + + // Run All Immediately + + }, { + key: "dump", + value: function dump() { + while (this._q.length) { + this.dequeue(); + } + } + + /** + * Run all tasks sequentially, at convince + * @return {Promise} + */ + + }, { + key: "run", + value: function run() { + var _this = this; + + if (!this.running) { + this.running = true; + this.defered = new _core.defer(); + } + + this.tick.call(window, function () { + + if (_this._q.length) { + + _this.dequeue().then(function () { + this.run(); + }.bind(_this)); + } else { + _this.defered.resolve(); + _this.running = undefined; + } + }); + + // Unpause + if (this.paused == true) { + this.paused = false; + } + + return this.defered.promise; + } + + /** + * Flush all, as quickly as possible + * @return {Promise} + */ + + }, { + key: "flush", + value: function flush() { + + if (this.running) { + return this.running; + } + + if (this._q.length) { + this.running = this.dequeue().then(function () { + this.running = undefined; + return this.flush(); + }.bind(this)); + + return this.running; + } + } + + /** + * Clear all items in wait + */ + + }, { + key: "clear", + value: function clear() { + this._q = []; + } + + /** + * Get the number of tasks in the queue + * @return {int} tasks + */ + + }, { + key: "length", + value: function length() { + return this._q.length; + } + + /** + * Pause a running queue + */ + + }, { + key: "pause", + value: function pause() { + this.paused = true; + } + + /** + * End the queue + */ + + }, { + key: "stop", + value: function stop() { + this._q = []; + this.running = false; + this.paused = true; + } + }]); + + return Queue; +}(); + +/** + * Create a new task from a callback + * @class + * @private + * @param {function} task + * @param {array} args + * @param {scope} context + * @return {function} task + */ + + +var Task = function Task(task, args, context) { + _classCallCheck(this, Task); + + return function () { + var _this2 = this; + + var toApply = arguments || []; + + return new Promise(function (resolve, reject) { + var callback = function callback(value, err) { + if (!value && err) { + reject(err); + } else { + resolve(value); + } + }; + // Add the callback to the arguments list + toApply.push(callback); + + // Apply all arguments to the functions + task.apply(context || _this2, toApply); + }); + }; +}; + +exports.default = Queue; +exports.Task = Task; + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +var _core = __webpack_require__(0); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _mapping = __webpack_require__(19); + +var _mapping2 = _interopRequireDefault(_mapping); + +var _replacements = __webpack_require__(7); + +var _constants = __webpack_require__(3); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var isChrome = /Chrome/.test(navigator.userAgent); +var isWebkit = !isChrome && /AppleWebKit/.test(navigator.userAgent); + +var ELEMENT_NODE = 1; +var TEXT_NODE = 3; + +/** + * Handles DOM manipulation, queries and events for View contents + * @class + * @param {document} doc Document + * @param {element} content Parent Element (typically Body) + * @param {string} cfiBase Section component of CFIs + * @param {number} sectionIndex Index in Spine of Conntent's Section + */ + +var Contents = function () { + function Contents(doc, content, cfiBase, sectionIndex) { + _classCallCheck(this, Contents); + + // Blank Cfi for Parsing + this.epubcfi = new _epubcfi2.default(); + + this.document = doc; + this.documentElement = this.document.documentElement; + this.content = content || this.document.body; + this.window = this.document.defaultView; + + this._size = { + width: 0, + height: 0 + }; + + this.sectionIndex = sectionIndex || 0; + this.cfiBase = cfiBase || ""; + + this.epubReadingSystem("epub.js", ePub.VERSION); + + this.listeners(); + } + + /** + * Get DOM events that are listened for and passed along + */ + + + _createClass(Contents, [{ + key: "width", + + + /** + * Get or Set width + * @param {number} [w] + * @returns {number} width + */ + value: function width(w) { + // var frame = this.documentElement; + var frame = this.content; + + if (w && (0, _core.isNumber)(w)) { + w = w + "px"; + } + + if (w) { + frame.style.width = w; + // this.content.style.width = w; + } + + return this.window.getComputedStyle(frame)["width"]; + } + + /** + * Get or Set height + * @param {number} [h] + * @returns {number} height + */ + + }, { + key: "height", + value: function height(h) { + // var frame = this.documentElement; + var frame = this.content; + + if (h && (0, _core.isNumber)(h)) { + h = h + "px"; + } + + if (h) { + frame.style.height = h; + // this.content.style.height = h; + } + + return this.window.getComputedStyle(frame)["height"]; + } + + /** + * Get or Set width of the contents + * @param {number} [w] + * @returns {number} width + */ + + }, { + key: "contentWidth", + value: function contentWidth(w) { + + var content = this.content || this.document.body; + + if (w && (0, _core.isNumber)(w)) { + w = w + "px"; + } + + if (w) { + content.style.width = w; + } + + return this.window.getComputedStyle(content)["width"]; + } + + /** + * Get or Set height of the contents + * @param {number} [h] + * @returns {number} height + */ + + }, { + key: "contentHeight", + value: function contentHeight(h) { + + var content = this.content || this.document.body; + + if (h && (0, _core.isNumber)(h)) { + h = h + "px"; + } + + if (h) { + content.style.height = h; + } + + return this.window.getComputedStyle(content)["height"]; + } + + /** + * Get the width of the text using Range + * @returns {number} width + */ + + }, { + key: "textWidth", + value: function textWidth() { + var width = void 0; + var range = this.document.createRange(); + var content = this.content || this.document.body; + var border = (0, _core.borders)(content); + + // Select the contents of frame + range.selectNodeContents(content); + + // get the width of the text content + width = range.getBoundingClientRect().width; + + if (border && border.width) { + width += border.width; + } + + return Math.round(width); + } + + /** + * Get the height of the text using Range + * @returns {number} height + */ + + }, { + key: "textHeight", + value: function textHeight() { + var height = void 0; + var range = this.document.createRange(); + var content = this.content || this.document.body; + var border = (0, _core.borders)(content); + + range.selectNodeContents(content); + + height = range.getBoundingClientRect().height; + + if (height && border.height) { + height += border.height; + } + + return Math.round(height); + } + + /** + * Get documentElement scrollWidth + * @returns {number} width + */ + + }, { + key: "scrollWidth", + value: function scrollWidth() { + var width = this.documentElement.scrollWidth; + + return width; + } + + /** + * Get documentElement scrollHeight + * @returns {number} height + */ + + }, { + key: "scrollHeight", + value: function scrollHeight() { + var height = this.documentElement.scrollHeight; + + return height; + } + + /** + * Set overflow css style of the contents + * @param {string} [overflow] + */ + + }, { + key: "overflow", + value: function overflow(_overflow) { + + if (_overflow) { + this.documentElement.style.overflow = _overflow; + } + + return this.window.getComputedStyle(this.documentElement)["overflow"]; + } + + /** + * Set overflowX css style of the documentElement + * @param {string} [overflow] + */ + + }, { + key: "overflowX", + value: function overflowX(overflow) { + + if (overflow) { + this.documentElement.style.overflowX = overflow; + } + + return this.window.getComputedStyle(this.documentElement)["overflowX"]; + } + + /** + * Set overflowY css style of the documentElement + * @param {string} [overflow] + */ + + }, { + key: "overflowY", + value: function overflowY(overflow) { + + if (overflow) { + this.documentElement.style.overflowY = overflow; + } + + return this.window.getComputedStyle(this.documentElement)["overflowY"]; + } + + /** + * Set Css styles on the contents element (typically Body) + * @param {string} property + * @param {string} value + * @param {boolean} [priority] set as "important" + */ + + }, { + key: "css", + value: function css(property, value, priority) { + var content = this.content || this.document.body; + + if (value) { + content.style.setProperty(property, value, priority ? "important" : ""); + } + + return this.window.getComputedStyle(content)[property]; + } + + /** + * Get or Set the viewport element + * @param {object} [options] + * @param {string} [options.width] + * @param {string} [options.height] + * @param {string} [options.scale] + * @param {string} [options.minimum] + * @param {string} [options.maximum] + * @param {string} [options.scalable] + */ + + }, { + key: "viewport", + value: function viewport(options) { + var _width, _height, _scale, _minimum, _maximum, _scalable; + // var width, height, scale, minimum, maximum, scalable; + var $viewport = this.document.querySelector("meta[name='viewport']"); + var parsed = { + "width": undefined, + "height": undefined, + "scale": undefined, + "minimum": undefined, + "maximum": undefined, + "scalable": undefined + }; + var newContent = []; + var settings = {}; + + /* + * check for the viewport size + * + */ + if ($viewport && $viewport.hasAttribute("content")) { + var content = $viewport.getAttribute("content"); + var _width2 = content.match(/width\s*=\s*([^,]*)/); + var _height2 = content.match(/height\s*=\s*([^,]*)/); + var _scale2 = content.match(/initial-scale\s*=\s*([^,]*)/); + var _minimum2 = content.match(/minimum-scale\s*=\s*([^,]*)/); + var _maximum2 = content.match(/maximum-scale\s*=\s*([^,]*)/); + var _scalable2 = content.match(/user-scalable\s*=\s*([^,]*)/); + + if (_width2 && _width2.length && typeof _width2[1] !== "undefined") { + parsed.width = _width2[1]; + } + if (_height2 && _height2.length && typeof _height2[1] !== "undefined") { + parsed.height = _height2[1]; + } + if (_scale2 && _scale2.length && typeof _scale2[1] !== "undefined") { + parsed.scale = _scale2[1]; + } + if (_minimum2 && _minimum2.length && typeof _minimum2[1] !== "undefined") { + parsed.minimum = _minimum2[1]; + } + if (_maximum2 && _maximum2.length && typeof _maximum2[1] !== "undefined") { + parsed.maximum = _maximum2[1]; + } + if (_scalable2 && _scalable2.length && typeof _scalable2[1] !== "undefined") { + parsed.scalable = _scalable2[1]; + } + } + + settings = (0, _core.defaults)(options || {}, parsed); + + if (options) { + if (settings.width) { + newContent.push("width=" + settings.width); + } + + if (settings.height) { + newContent.push("height=" + settings.height); + } + + if (settings.scale) { + newContent.push("initial-scale=" + settings.scale); + } + + if (settings.scalable === "no") { + newContent.push("minimum-scale=" + settings.scale); + newContent.push("maximum-scale=" + settings.scale); + newContent.push("user-scalable=" + settings.scalable); + } else { + + if (settings.scalable) { + newContent.push("user-scalable=" + settings.scalable); + } + + if (settings.minimum) { + newContent.push("minimum-scale=" + settings.minimum); + } + + if (settings.maximum) { + newContent.push("minimum-scale=" + settings.maximum); + } + } + + if (!$viewport) { + $viewport = this.document.createElement("meta"); + $viewport.setAttribute("name", "viewport"); + this.document.querySelector("head").appendChild($viewport); + } + + $viewport.setAttribute("content", newContent.join(", ")); + + this.window.scrollTo(0, 0); + } + + return settings; + } + + /** + * Event emitter for when the contents has expanded + * @private + */ + + }, { + key: "expand", + value: function expand() { + this.emit(_constants.EVENTS.CONTENTS.EXPAND); + } + + /** + * Add DOM listeners + * @private + */ + + }, { + key: "listeners", + value: function listeners() { + + this.imageLoadListeners(); + + this.mediaQueryListeners(); + + // this.fontLoadListeners(); + + this.addEventListeners(); + + this.addSelectionListeners(); + + // this.transitionListeners(); + + this.resizeListeners(); + + // this.resizeObservers(); + + this.linksHandler(); + } + + /** + * Remove DOM listeners + * @private + */ + + }, { + key: "removeListeners", + value: function removeListeners() { + + this.removeEventListeners(); + + this.removeSelectionListeners(); + + clearTimeout(this.expanding); + } + + /** + * Check if size of contents has changed and + * emit 'resize' event if it has. + * @private + */ + + }, { + key: "resizeCheck", + value: function resizeCheck() { + var width = this.textWidth(); + var height = this.textHeight(); + + if (width != this._size.width || height != this._size.height) { + + this._size = { + width: width, + height: height + }; + + this.onResize && this.onResize(this._size); + this.emit(_constants.EVENTS.CONTENTS.RESIZE, this._size); + } + } + + /** + * Poll for resize detection + * @private + */ + + }, { + key: "resizeListeners", + value: function resizeListeners() { + var width, height; + // Test size again + clearTimeout(this.expanding); + + requestAnimationFrame(this.resizeCheck.bind(this)); + + this.expanding = setTimeout(this.resizeListeners.bind(this), 350); + } + + /** + * Use css transitions to detect resize + * @private + */ + + }, { + key: "transitionListeners", + value: function transitionListeners() { + var body = this.content; + + body.style['transitionProperty'] = "font, font-size, font-size-adjust, font-stretch, font-variation-settings, font-weight, width, height"; + body.style['transitionDuration'] = "0.001ms"; + body.style['transitionTimingFunction'] = "linear"; + body.style['transitionDelay'] = "0"; + + this.document.addEventListener('transitionend', this.resizeCheck.bind(this)); + } + + /** + * Listen for media query changes and emit 'expand' event + * Adapted from: https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js + * @private + */ + + }, { + key: "mediaQueryListeners", + value: function mediaQueryListeners() { + var sheets = this.document.styleSheets; + var mediaChangeHandler = function (m) { + if (m.matches && !this._expanding) { + setTimeout(this.expand.bind(this), 1); + } + }.bind(this); + + for (var i = 0; i < sheets.length; i += 1) { + var rules; + // Firefox errors if we access cssRules cross-domain + try { + rules = sheets[i].cssRules; + } catch (e) { + return; + } + if (!rules) return; // Stylesheets changed + for (var j = 0; j < rules.length; j += 1) { + //if (rules[j].constructor === CSSMediaRule) { + if (rules[j].media) { + var mql = this.window.matchMedia(rules[j].media.mediaText); + mql.addListener(mediaChangeHandler); + //mql.onchange = mediaChangeHandler; + } + } + } + } + + /** + * Use MutationObserver to listen for changes in the DOM and check for resize + * @private + */ + + }, { + key: "resizeObservers", + value: function resizeObservers() { + var _this = this; + + // create an observer instance + this.observer = new MutationObserver(function (mutations) { + _this.resizeCheck(); + }); + + // configuration of the observer: + var config = { attributes: true, childList: true, characterData: true, subtree: true }; + + // pass in the target node, as well as the observer options + this.observer.observe(this.document, config); + } + }, { + key: "imageLoadListeners", + value: function imageLoadListeners(target) { + var images = this.document.querySelectorAll("img"); + var img; + for (var i = 0; i < images.length; i++) { + img = images[i]; + + if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) { + img.onload = this.expand.bind(this); + } + } + } + + /** + * Listen for font load and check for resize when loaded + * @private + */ + + }, { + key: "fontLoadListeners", + value: function fontLoadListeners(target) { + if (!this.document || !this.document.fonts) { + return; + } + + this.document.fonts.ready.then(function () { + this.resizeCheck(); + }.bind(this)); + } + + /** + * Get the documentElement + * @returns {element} documentElement + */ + + }, { + key: "root", + value: function root() { + if (!this.document) return null; + return this.document.documentElement; + } + + /** + * Get the location offset of a EpubCFI or an #id + * @param {string | EpubCFI} target + * @param {string} [ignoreClass] for the cfi + * @returns { {left: Number, top: Number } + */ + + }, { + key: "locationOf", + value: function locationOf(target, ignoreClass) { + var position; + var targetPos = { "left": 0, "top": 0 }; + + if (!this.document) return targetPos; + + if (this.epubcfi.isCfiString(target)) { + var range = new _epubcfi2.default(target).toRange(this.document, ignoreClass); + + if (range) { + if (range.startContainer.nodeType === Node.ELEMENT_NODE) { + position = range.startContainer.getBoundingClientRect(); + targetPos.left = position.left; + targetPos.top = position.top; + } else { + // Webkit does not handle collapsed range bounds correctly + // https://bugs.webkit.org/show_bug.cgi?id=138949 + + // Construct a new non-collapsed range + if (isWebkit) { + var container = range.startContainer; + var newRange = new Range(); + try { + if (container.nodeType === ELEMENT_NODE) { + position = container.getBoundingClientRect(); + } else if (range.startOffset + 2 < container.length) { + newRange.setStart(container, range.startOffset); + newRange.setEnd(container, range.startOffset + 2); + position = newRange.getBoundingClientRect(); + } else if (range.startOffset - 2 > 0) { + newRange.setStart(container, range.startOffset - 2); + newRange.setEnd(container, range.startOffset); + position = newRange.getBoundingClientRect(); + } else { + // empty, return the parent element + position = container.parentNode.getBoundingClientRect(); + } + } catch (e) { + console.error(e, e.stack); + } + } else { + position = range.getBoundingClientRect(); + } + } + } + } else if (typeof target === "string" && target.indexOf("#") > -1) { + + var id = target.substring(target.indexOf("#") + 1); + var el = this.document.getElementById(id); + + if (el) { + position = el.getBoundingClientRect(); + } + } + + if (position) { + targetPos.left = position.left; + targetPos.top = position.top; + } + + return targetPos; + } + + /** + * Append a stylesheet link to the document head + * @param {string} src url + */ + + }, { + key: "addStylesheet", + value: function addStylesheet(src) { + return new Promise(function (resolve, reject) { + var $stylesheet; + var ready = false; + + if (!this.document) { + resolve(false); + return; + } + + // Check if link already exists + $stylesheet = this.document.querySelector("link[href='" + src + "']"); + if ($stylesheet) { + resolve(true); + return; // already present + } + + $stylesheet = this.document.createElement("link"); + $stylesheet.type = "text/css"; + $stylesheet.rel = "stylesheet"; + $stylesheet.href = src; + $stylesheet.onload = $stylesheet.onreadystatechange = function () { + if (!ready && (!this.readyState || this.readyState == "complete")) { + ready = true; + // Let apply + setTimeout(function () { + resolve(true); + }, 1); + } + }; + + this.document.head.appendChild($stylesheet); + }.bind(this)); + } + + /** + * Append stylesheet rules to a generate stylesheet + * Array: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule + * Object: https://github.com/desirable-objects/json-to-css + * @param {array | object} rules + */ + + }, { + key: "addStylesheetRules", + value: function addStylesheetRules(rules) { + var styleEl; + var styleSheet; + var key = "epubjs-inserted-css"; + + if (!this.document || !rules || rules.length === 0) return; + + // Check if link already exists + styleEl = this.document.getElementById("#" + key); + if (!styleEl) { + styleEl = this.document.createElement("style"); + styleEl.id = key; + } + + // Append style element to head + this.document.head.appendChild(styleEl); + + // Grab style sheet + styleSheet = styleEl.sheet; + + if (Object.prototype.toString.call(rules) === "[object Array]") { + for (var i = 0, rl = rules.length; i < rl; i++) { + var j = 1, + rule = rules[i], + selector = rules[i][0], + propStr = ""; + // If the second argument of a rule is an array of arrays, correct our variables. + if (Object.prototype.toString.call(rule[1][0]) === "[object Array]") { + rule = rule[1]; + j = 0; + } + + for (var pl = rule.length; j < pl; j++) { + var prop = rule[j]; + propStr += prop[0] + ":" + prop[1] + (prop[2] ? " !important" : "") + ";\n"; + } + + // Insert CSS Rule + styleSheet.insertRule(selector + "{" + propStr + "}", styleSheet.cssRules.length); + } + } else { + var selectors = Object.keys(rules); + selectors.forEach(function (selector) { + var definition = rules[selector]; + if (Array.isArray(definition)) { + definition.forEach(function (item) { + var _rules = Object.keys(item); + var result = _rules.map(function (rule) { + return rule + ":" + item[rule]; + }).join(';'); + styleSheet.insertRule(selector + "{" + result + "}", styleSheet.cssRules.length); + }); + } else { + var _rules = Object.keys(definition); + var result = _rules.map(function (rule) { + return rule + ":" + definition[rule]; + }).join(';'); + styleSheet.insertRule(selector + "{" + result + "}", styleSheet.cssRules.length); + } + }); + } + } + + /** + * Append a script tag to the document head + * @param {string} src url + * @returns {Promise} loaded + */ + + }, { + key: "addScript", + value: function addScript(src) { + + return new Promise(function (resolve, reject) { + var $script; + var ready = false; + + if (!this.document) { + resolve(false); + return; + } + + $script = this.document.createElement("script"); + $script.type = "text/javascript"; + $script.async = true; + $script.src = src; + $script.onload = $script.onreadystatechange = function () { + if (!ready && (!this.readyState || this.readyState == "complete")) { + ready = true; + setTimeout(function () { + resolve(true); + }, 1); + } + }; + + this.document.head.appendChild($script); + }.bind(this)); + } + + /** + * Add a class to the contents container + * @param {string} className + */ + + }, { + key: "addClass", + value: function addClass(className) { + var content; + + if (!this.document) return; + + content = this.content || this.document.body; + + if (content) { + content.classList.add(className); + } + } + + /** + * Remove a class from the contents container + * @param {string} removeClass + */ + + }, { + key: "removeClass", + value: function removeClass(className) { + var content; + + if (!this.document) return; + + content = this.content || this.document.body; + + if (content) { + content.classList.remove(className); + } + } + + /** + * Add DOM event listeners + * @private + */ + + }, { + key: "addEventListeners", + value: function addEventListeners() { + if (!this.document) { + return; + } + + _constants.DOM_EVENTS.forEach(function (eventName) { + this.document.addEventListener(eventName, this.triggerEvent.bind(this), false); + }, this); + } + + /** + * Remove DOM event listeners + * @private + */ + + }, { + key: "removeEventListeners", + value: function removeEventListeners() { + if (!this.document) { + return; + } + _constants.DOM_EVENTS.forEach(function (eventName) { + this.document.removeEventListener(eventName, this.triggerEvent, false); + }, this); + } + + /** + * Emit passed browser events + * @private + */ + + }, { + key: "triggerEvent", + value: function triggerEvent(e) { + this.emit(e.type, e); + } + + /** + * Add listener for text selection + * @private + */ + + }, { + key: "addSelectionListeners", + value: function addSelectionListeners() { + if (!this.document) { + return; + } + this.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); + } + + /** + * Remove listener for text selection + * @private + */ + + }, { + key: "removeSelectionListeners", + value: function removeSelectionListeners() { + if (!this.document) { + return; + } + this.document.removeEventListener("selectionchange", this.onSelectionChange, false); + } + + /** + * Handle getting text on selection + * @private + */ + + }, { + key: "onSelectionChange", + value: function onSelectionChange(e) { + if (this.selectionEndTimeout) { + clearTimeout(this.selectionEndTimeout); + } + this.selectionEndTimeout = setTimeout(function () { + var selection = this.window.getSelection(); + this.triggerSelectedEvent(selection); + }.bind(this), 250); + } + + /** + * Emit event on text selection + * @private + */ + + }, { + key: "triggerSelectedEvent", + value: function triggerSelectedEvent(selection) { + var range, cfirange; + + if (selection && selection.rangeCount > 0) { + range = selection.getRangeAt(0); + if (!range.collapsed) { + // cfirange = this.section.cfiFromRange(range); + cfirange = new _epubcfi2.default(range, this.cfiBase).toString(); + this.emit(_constants.EVENTS.CONTENTS.SELECTED, cfirange); + this.emit(_constants.EVENTS.CONTENTS.SELECTED_RANGE, range); + } + } + } + + /** + * Get a Dom Range from EpubCFI + * @param {EpubCFI} _cfi + * @param {string} [ignoreClass] + * @returns {Range} range + */ + + }, { + key: "range", + value: function range(_cfi, ignoreClass) { + var cfi = new _epubcfi2.default(_cfi); + return cfi.toRange(this.document, ignoreClass); + } + + /** + * Get an EpubCFI from a Dom Range + * @param {Range} range + * @param {string} [ignoreClass] + * @returns {EpubCFI} cfi + */ + + }, { + key: "cfiFromRange", + value: function cfiFromRange(range, ignoreClass) { + return new _epubcfi2.default(range, this.cfiBase, ignoreClass).toString(); + } + + /** + * Get an EpubCFI from a Dom node + * @param {node} node + * @param {string} [ignoreClass] + * @returns {EpubCFI} cfi + */ + + }, { + key: "cfiFromNode", + value: function cfiFromNode(node, ignoreClass) { + return new _epubcfi2.default(node, this.cfiBase, ignoreClass).toString(); + } + + // TODO: find where this is used - remove? + + }, { + key: "map", + value: function map(layout) { + var map = new _mapping2.default(layout); + return map.section(); + } + + /** + * Size the contents to a given width and height + * @param {number} [width] + * @param {number} [height] + */ + + }, { + key: "size", + value: function size(width, height) { + var viewport = { scale: 1.0, scalable: "no" }; + + this.layoutStyle("scrolling"); + + if (width >= 0) { + this.width(width); + viewport.width = width; + this.css("padding", "0 " + width / 12 + "px", true); + } + + if (height >= 0) { + this.height(height); + viewport.height = height; + } + + this.css("margin", "0"); + this.css("box-sizing", "border-box"); + + this.viewport(viewport); + } + + /** + * Apply columns to the contents for pagination + * @param {number} width + * @param {number} height + * @param {number} columnWidth + * @param {number} gap + */ + + }, { + key: "columns", + value: function columns(width, height, columnWidth, gap) { + var COLUMN_AXIS = (0, _core.prefixed)("column-axis"); + var COLUMN_GAP = (0, _core.prefixed)("column-gap"); + var COLUMN_WIDTH = (0, _core.prefixed)("column-width"); + var COLUMN_FILL = (0, _core.prefixed)("column-fill"); + + var writingMode = this.writingMode(); + var axis = writingMode.indexOf("vertical") === 0 ? "vertical" : "horizontal"; + + this.layoutStyle("paginated"); + + // Fix body width issues if rtl is only set on body element + if (this.content.dir === "rtl") { + this.direction("rtl"); + } + + this.width(width); + this.height(height); + + // Deal with Mobile trying to scale to viewport + this.viewport({ width: width, height: height, scale: 1.0, scalable: "no" }); + + // TODO: inline-block needs more testing + // Fixes Safari column cut offs, but causes RTL issues + // this.css("display", "inline-block"); + + this.css("overflow-y", "hidden"); + this.css("margin", "0", true); + + if (axis === "vertical") { + this.css("padding", gap / 2 + "px 20px", true); + } else { + this.css("padding", "20px " + gap / 2 + "px", true); + } + + this.css("box-sizing", "border-box"); + this.css("max-width", "inherit"); + + this.css(COLUMN_AXIS, "horizontal"); + this.css(COLUMN_FILL, "auto"); + + this.css(COLUMN_GAP, gap + "px"); + this.css(COLUMN_WIDTH, columnWidth + "px"); + } + + /** + * Scale contents from center + * @param {number} scale + * @param {number} offsetX + * @param {number} offsetY + */ + + }, { + key: "scaler", + value: function scaler(scale, offsetX, offsetY) { + var scaleStr = "scale(" + scale + ")"; + var translateStr = ""; + // this.css("position", "absolute")); + this.css("transform-origin", "top left"); + + if (offsetX >= 0 || offsetY >= 0) { + translateStr = " translate(" + (offsetX || 0) + "px, " + (offsetY || 0) + "px )"; + } + + this.css("transform", scaleStr + translateStr); + } + + /** + * Fit contents into a fixed width and height + * @param {number} width + * @param {number} height + */ + + }, { + key: "fit", + value: function fit(width, height) { + var viewport = this.viewport(); + var widthScale = width / parseInt(viewport.width); + var heightScale = height / parseInt(viewport.height); + var scale = widthScale < heightScale ? widthScale : heightScale; + + var offsetY = (height - viewport.height * scale) / 2; + + this.layoutStyle("paginated"); + + this.width(width); + this.height(height); + this.overflow("hidden"); + + // Scale to the correct size + this.scaler(scale, 0, offsetY); + + this.css("background-color", "transparent"); + } + + /** + * Set the direction of the text + * @param {string} [dir="ltr"] "rtl" | "ltr" + */ + + }, { + key: "direction", + value: function direction(dir) { + if (this.documentElement) { + this.documentElement.style["direction"] = dir; + } + } + }, { + key: "mapPage", + value: function mapPage(cfiBase, layout, start, end, dev) { + var mapping = new _mapping2.default(layout, dev); + + return mapping.page(this, cfiBase, start, end); + } + + /** + * Emit event when link in content is clicked + * @private + */ + + }, { + key: "linksHandler", + value: function linksHandler() { + var _this2 = this; + + (0, _replacements.replaceLinks)(this.content, function (href) { + _this2.emit(_constants.EVENTS.CONTENTS.LINK_CLICKED, href); + }); + } + + /** + * Set the writingMode of the text + * @param {string} [mode="horizontal-tb"] "horizontal-tb" | "vertical-rl" | "vertical-lr" + */ + + }, { + key: "writingMode", + value: function writingMode(mode) { + var WRITING_MODE = (0, _core.prefixed)("writing-mode"); + + if (mode && this.documentElement) { + this.documentElement.style[WRITING_MODE] = mode; + } + + return this.window.getComputedStyle(this.documentElement)[WRITING_MODE] || ''; + } + + /** + * Set the layoutStyle of the content + * @param {string} [style="paginated"] "scrolling" | "paginated" + * @private + */ + + }, { + key: "layoutStyle", + value: function layoutStyle(style) { + + if (style) { + this._layoutStyle = style; + navigator.epubReadingSystem.layoutStyle = this._layoutStyle; + } + + return this._layoutStyle || "paginated"; + } + + /** + * Add the epubReadingSystem object to the navigator + * @param {string} name + * @param {string} version + * @private + */ + + }, { + key: "epubReadingSystem", + value: function epubReadingSystem(name, version) { + navigator.epubReadingSystem = { + name: name, + version: version, + layoutStyle: this.layoutStyle(), + hasFeature: function hasFeature(feature) { + switch (feature) { + case "dom-manipulation": + return true; + case "layout-changes": + return true; + case "touch-events": + return true; + case "mouse-events": + return true; + case "keyboard-events": + return true; + case "spine-scripting": + return false; + default: + return false; + } + } + }; + return navigator.epubReadingSystem; + } + }, { + key: "destroy", + value: function destroy() { + // Stop observing + if (this.observer) { + this.observer.disconnect(); + } + + this.document.removeEventListener('transitionend', this.resizeCheck); + + this.removeListeners(); + } + }], [{ + key: "listenedEvents", + get: function get() { + return _constants.DOM_EVENTS; + } + }]); + + return Contents; +}(); + +(0, _eventEmitter2.default)(Contents.prototype); + +exports.default = Contents; +module.exports = exports["default"]; + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +var _core = __webpack_require__(0); + +var _mapping = __webpack_require__(19); + +var _mapping2 = _interopRequireDefault(_mapping); + +var _queue = __webpack_require__(12); + +var _queue2 = _interopRequireDefault(_queue); + +var _stage = __webpack_require__(56); + +var _stage2 = _interopRequireDefault(_stage); + +var _views = __webpack_require__(66); + +var _views2 = _interopRequireDefault(_views); + +var _constants = __webpack_require__(3); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DefaultViewManager = function () { + function DefaultViewManager(options) { + _classCallCheck(this, DefaultViewManager); + + this.name = "default"; + this.View = options.view; + this.request = options.request; + this.renditionQueue = options.queue; + this.q = new _queue2.default(this); + + this.settings = (0, _core.extend)(this.settings || {}, { + infinite: true, + hidden: false, + width: undefined, + height: undefined, + axis: undefined, + flow: "scrolled", + ignoreClass: "" + }); + + (0, _core.extend)(this.settings, options.settings || {}); + + this.viewSettings = { + ignoreClass: this.settings.ignoreClass, + axis: this.settings.axis, + flow: this.settings.flow, + layout: this.layout, + method: this.settings.method, // srcdoc, blobUrl, write + width: 0, + height: 0, + forceEvenPages: true + }; + + this.rendered = false; + } + + _createClass(DefaultViewManager, [{ + key: "render", + value: function render(element, size) { + var tag = element.tagName; + + if (tag && (tag.toLowerCase() == "body" || tag.toLowerCase() == "html")) { + this.fullsize = true; + } + + if (this.fullsize) { + this.settings.overflow = "visible"; + this.overflow = this.settings.overflow; + } + + this.settings.size = size; + + // Save the stage + this.stage = new _stage2.default({ + width: size.width, + height: size.height, + overflow: this.overflow, + hidden: this.settings.hidden, + axis: this.settings.axis, + fullsize: this.fullsize, + direction: this.settings.direction + }); + + this.stage.attachTo(element); + + // Get this stage container div + this.container = this.stage.getContainer(); + + // Views array methods + this.views = new _views2.default(this.container); + + // Calculate Stage Size + this._bounds = this.bounds(); + this._stageSize = this.stage.size(); + + // Set the dimensions for views + this.viewSettings.width = this._stageSize.width; + this.viewSettings.height = this._stageSize.height; + + // Function to handle a resize event. + // Will only attach if width and height are both fixed. + this.stage.onResize(this.onResized.bind(this)); + + this.stage.onOrientationChange(this.onOrientationChange.bind(this)); + + // Add Event Listeners + this.addEventListeners(); + + // Add Layout method + // this.applyLayoutMethod(); + if (this.layout) { + this.updateLayout(); + } + + this.rendered = true; + } + }, { + key: "addEventListeners", + value: function addEventListeners() { + var scroller; + + window.addEventListener("unload", function (e) { + this.destroy(); + }.bind(this)); + + if (!this.fullsize) { + scroller = this.container; + } else { + scroller = window; + } + + scroller.addEventListener("scroll", this.onScroll.bind(this)); + } + }, { + key: "removeEventListeners", + value: function removeEventListeners() { + var scroller; + + if (!this.fullsize) { + scroller = this.container; + } else { + scroller = window; + } + + scroller.removeEventListener("scroll", this.onScroll.bind(this)); + } + }, { + key: "destroy", + value: function destroy() { + clearTimeout(this.orientationTimeout); + clearTimeout(this.resizeTimeout); + clearTimeout(this.afterScrolled); + + this.clear(); + + this.removeEventListeners(); + + this.stage.destroy(); + + this.rendered = false; + + /* + clearTimeout(this.trimTimeout); + if(this.settings.hidden) { + this.element.removeChild(this.wrapper); + } else { + this.element.removeChild(this.container); + } + */ + } + }, { + key: "onOrientationChange", + value: function onOrientationChange(e) { + var _window = window, + orientation = _window.orientation; + + + this.resize(); + + // Per ampproject: + // In IOS 10.3, the measured size of an element is incorrect if the + // element size depends on window size directly and the measurement + // happens in window.resize event. Adding a timeout for correct + // measurement. See https://github.com/ampproject/amphtml/issues/8479 + clearTimeout(this.orientationTimeout); + this.orientationTimeout = setTimeout(function () { + this.orientationTimeout = undefined; + this.resize(); + this.emit(_constants.EVENTS.MANAGERS.ORIENTATION_CHANGE, orientation); + }.bind(this), 500); + } + }, { + key: "onResized", + value: function onResized(e) { + this.resize(); + } + }, { + key: "resize", + value: function resize(width, height) { + var stageSize = this.stage.size(width, height); + + // For Safari, wait for orientation to catch up + // if the window is a square + this.winBounds = (0, _core.windowBounds)(); + if (this.orientationTimeout && this.winBounds.width === this.winBounds.height) { + // reset the stage size for next resize + this._stageSize = undefined; + return; + } + + if (this._stageSize && this._stageSize.width === stageSize.width && this._stageSize.height === stageSize.height) { + // Size is the same, no need to resize + return; + } + + this._stageSize = stageSize; + + this._bounds = this.bounds(); + + // Clear current views + this.clear(); + + // Update for new views + this.viewSettings.width = this._stageSize.width; + this.viewSettings.height = this._stageSize.height; + + this.updateLayout(); + + this.emit(_constants.EVENTS.MANAGERS.RESIZED, { + width: this._stageSize.width, + height: this._stageSize.height + }); + } + }, { + key: "createView", + value: function createView(section) { + return new this.View(section, this.viewSettings); + } + }, { + key: "display", + value: function display(section, target) { + + var displaying = new _core.defer(); + var displayed = displaying.promise; + + // Check if moving to target is needed + if (target === section.href || (0, _core.isNumber)(target)) { + target = undefined; + } + + // Check to make sure the section we want isn't already shown + var visible = this.views.find(section); + + // View is already shown, just move to correct location in view + if (visible && section) { + var offset = visible.offset(); + + if (this.settings.direction === "ltr") { + this.scrollTo(offset.left, offset.top, true); + } else { + var width = visible.width(); + this.scrollTo(offset.left + width, offset.top, true); + } + + if (target) { + var _offset = visible.locationOf(target); + this.moveTo(_offset); + } + + displaying.resolve(); + return displayed; + } + + // Hide all current views + this.clear(); + + this.add(section).then(function (view) { + + // Move to correct place within the section, if needed + if (target) { + var _offset2 = view.locationOf(target); + this.moveTo(_offset2); + } + }.bind(this), function (err) { + displaying.reject(err); + }).then(function () { + var next; + if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) { + next = section.next(); + if (next) { + return this.add(next); + } + } + }.bind(this)).then(function () { + + this.views.show(); + + displaying.resolve(); + }.bind(this)); + // .then(function(){ + // return this.hooks.display.trigger(view); + // }.bind(this)) + // .then(function(){ + // this.views.show(); + // }.bind(this)); + return displayed; + } + }, { + key: "afterDisplayed", + value: function afterDisplayed(view) { + this.emit(_constants.EVENTS.MANAGERS.ADDED, view); + } + }, { + key: "afterResized", + value: function afterResized(view) { + this.emit(_constants.EVENTS.MANAGERS.RESIZE, view.section); + } + }, { + key: "moveTo", + value: function moveTo(offset) { + var distX = 0, + distY = 0; + + if (!this.isPaginated) { + distY = offset.top; + } else { + distX = Math.floor(offset.left / this.layout.delta) * this.layout.delta; + + if (distX + this.layout.delta > this.container.scrollWidth) { + distX = this.container.scrollWidth - this.layout.delta; + } + } + this.scrollTo(distX, distY, true); + } + }, { + key: "add", + value: function add(section) { + var _this = this; + + var view = this.createView(section); + + this.views.append(view); + + // view.on(EVENTS.VIEWS.SHOWN, this.afterDisplayed.bind(this)); + view.onDisplayed = this.afterDisplayed.bind(this); + view.onResize = this.afterResized.bind(this); + + view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) { + _this.updateAxis(axis); + }); + + return view.display(this.request); + } + }, { + key: "append", + value: function append(section) { + var _this2 = this; + + var view = this.createView(section); + this.views.append(view); + + view.onDisplayed = this.afterDisplayed.bind(this); + view.onResize = this.afterResized.bind(this); + + view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) { + _this2.updateAxis(axis); + }); + + return view.display(this.request); + } + }, { + key: "prepend", + value: function prepend(section) { + var _this3 = this; + + var view = this.createView(section); + + view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) { + _this3.counter(bounds); + }); + + this.views.prepend(view); + + view.onDisplayed = this.afterDisplayed.bind(this); + view.onResize = this.afterResized.bind(this); + + view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) { + _this3.updateAxis(axis); + }); + + return view.display(this.request); + } + }, { + key: "counter", + value: function counter(bounds) { + if (this.settings.axis === "vertical") { + this.scrollBy(0, bounds.heightDelta, true); + } else { + this.scrollBy(bounds.widthDelta, 0, true); + } + } + + // resizeView(view) { + // + // if(this.settings.globalLayoutProperties.layout === "pre-paginated") { + // view.lock("both", this.bounds.width, this.bounds.height); + // } else { + // view.lock("width", this.bounds.width, this.bounds.height); + // } + // + // }; + + }, { + key: "next", + value: function next() { + var next; + var left; + + var dir = this.settings.direction; + + if (!this.views.length) return; + + if (this.isPaginated && this.settings.axis === "horizontal" && (!dir || dir === "ltr")) { + + this.scrollLeft = this.container.scrollLeft; + + left = this.container.scrollLeft + this.container.offsetWidth + this.layout.delta; + + if (left <= this.container.scrollWidth) { + this.scrollBy(this.layout.delta, 0, true); + } else { + next = this.views.last().section.next(); + } + } else if (this.isPaginated && this.settings.axis === "horizontal" && dir === "rtl") { + + this.scrollLeft = this.container.scrollLeft; + + left = this.container.scrollLeft; + + if (left > 0) { + this.scrollBy(this.layout.delta, 0, true); + } else { + next = this.views.last().section.next(); + } + } else if (this.isPaginated && this.settings.axis === "vertical") { + + this.scrollTop = this.container.scrollTop; + + var top = this.container.scrollTop + this.container.offsetHeight; + + if (top < this.container.scrollHeight) { + this.scrollBy(0, this.layout.height, true); + } else { + next = this.views.last().section.next(); + } + } else { + next = this.views.last().section.next(); + } + + if (next) { + this.clear(); + + return this.append(next).then(function () { + var right; + if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) { + right = next.next(); + if (right) { + return this.append(right); + } + } + }.bind(this), function (err) { + displaying.reject(err); + }).then(function () { + this.views.show(); + }.bind(this)); + } + } + }, { + key: "prev", + value: function prev() { + var prev; + var left; + var dir = this.settings.direction; + + if (!this.views.length) return; + + if (this.isPaginated && this.settings.axis === "horizontal" && (!dir || dir === "ltr")) { + + this.scrollLeft = this.container.scrollLeft; + + left = this.container.scrollLeft; + + if (left > 0) { + this.scrollBy(-this.layout.delta, 0, true); + } else { + prev = this.views.first().section.prev(); + } + } else if (this.isPaginated && this.settings.axis === "horizontal" && dir === "rtl") { + + this.scrollLeft = this.container.scrollLeft; + + left = this.container.scrollLeft + this.container.offsetWidth + this.layout.delta; + + if (left <= this.container.scrollWidth) { + this.scrollBy(-this.layout.delta, 0, true); + } else { + prev = this.views.first().section.prev(); + } + } else if (this.isPaginated && this.settings.axis === "vertical") { + + this.scrollTop = this.container.scrollTop; + + var top = this.container.scrollTop; + + if (top > 0) { + this.scrollBy(0, -this.layout.height, true); + } else { + prev = this.views.first().section.prev(); + } + } else { + + prev = this.views.first().section.prev(); + } + + if (prev) { + this.clear(); + + return this.prepend(prev).then(function () { + var left; + if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) { + left = prev.prev(); + if (left) { + return this.prepend(left); + } + } + }.bind(this), function (err) { + displaying.reject(err); + }).then(function () { + if (this.isPaginated && this.settings.axis === "horizontal") { + if (this.settings.direction === "rtl") { + this.scrollTo(0, 0, true); + } else { + this.scrollTo(this.container.scrollWidth - this.layout.delta, 0, true); + } + } + this.views.show(); + }.bind(this)); + } + } + }, { + key: "current", + value: function current() { + var visible = this.visible(); + if (visible.length) { + // Current is the last visible view + return visible[visible.length - 1]; + } + return null; + } + }, { + key: "clear", + value: function clear() { + + // this.q.clear(); + + if (this.views) { + this.views.hide(); + this.scrollTo(0, 0, true); + this.views.clear(); + } + } + }, { + key: "currentLocation", + value: function currentLocation() { + + if (this.settings.axis === "vertical") { + this.location = this.scrolledLocation(); + } else { + this.location = this.paginatedLocation(); + } + return this.location; + } + }, { + key: "scrolledLocation", + value: function scrolledLocation() { + var _this4 = this; + + var visible = this.visible(); + var container = this.container.getBoundingClientRect(); + var pageHeight = container.height < window.innerHeight ? container.height : window.innerHeight; + + var offset = 0; + var used = 0; + + if (this.fullsize) { + offset = window.scrollY; + } + + var sections = visible.map(function (view) { + var _view$section = view.section, + index = _view$section.index, + href = _view$section.href; + + var position = view.position(); + var height = view.height(); + + var startPos = offset + container.top - position.top + used; + var endPos = startPos + pageHeight - used; + if (endPos > height) { + endPos = height; + used = endPos - startPos; + } + + var totalPages = _this4.layout.count(height, pageHeight).pages; + + var currPage = Math.ceil(startPos / pageHeight); + var pages = []; + var endPage = Math.ceil(endPos / pageHeight); + + pages = []; + for (var i = currPage; i <= endPage; i++) { + var pg = i + 1; + pages.push(pg); + } + + var mapping = _this4.mapping.page(view.contents, view.section.cfiBase, startPos, endPos); + + return { + index: index, + href: href, + pages: pages, + totalPages: totalPages, + mapping: mapping + }; + }); + + return sections; + } + }, { + key: "paginatedLocation", + value: function paginatedLocation() { + var _this5 = this; + + var visible = this.visible(); + var container = this.container.getBoundingClientRect(); + + var left = 0; + var used = 0; + + if (this.fullsize) { + left = window.scrollX; + } + + var sections = visible.map(function (view) { + var _view$section2 = view.section, + index = _view$section2.index, + href = _view$section2.href; + + var offset = view.offset().left; + var position = view.position().left; + var width = view.width(); + + // Find mapping + var start = left + container.left - position + used; + var end = start + _this5.layout.width - used; + + var mapping = _this5.mapping.page(view.contents, view.section.cfiBase, start, end); + + // Find displayed pages + //console.log("pre", end, offset + width); + // if (end > offset + width) { + // end = offset + width; + // used = this.layout.pageWidth; + // } + // console.log("post", end); + + var totalPages = _this5.layout.count(width).pages; + var startPage = Math.floor(start / _this5.layout.pageWidth); + var pages = []; + var endPage = Math.floor(end / _this5.layout.pageWidth); + + // start page should not be negative + if (startPage < 0) { + startPage = 0; + endPage = endPage + 1; + } + + // Reverse page counts for rtl + if (_this5.settings.direction === "rtl") { + var tempStartPage = startPage; + startPage = totalPages - endPage; + endPage = totalPages - tempStartPage; + } + + for (var i = startPage + 1; i <= endPage; i++) { + var pg = i; + pages.push(pg); + } + + return { + index: index, + href: href, + pages: pages, + totalPages: totalPages, + mapping: mapping + }; + }); + + return sections; + } + }, { + key: "isVisible", + value: function isVisible(view, offsetPrev, offsetNext, _container) { + var position = view.position(); + var container = _container || this.bounds(); + + if (this.settings.axis === "horizontal" && position.right > container.left - offsetPrev && position.left < container.right + offsetNext) { + + return true; + } else if (this.settings.axis === "vertical" && position.bottom > container.top - offsetPrev && position.top < container.bottom + offsetNext) { + + return true; + } + + return false; + } + }, { + key: "visible", + value: function visible() { + var container = this.bounds(); + var views = this.views.displayed(); + var viewsLength = views.length; + var visible = []; + var isVisible; + var view; + + for (var i = 0; i < viewsLength; i++) { + view = views[i]; + isVisible = this.isVisible(view, 0, 0, container); + + if (isVisible === true) { + visible.push(view); + } + } + return visible; + } + }, { + key: "scrollBy", + value: function scrollBy(x, y, silent) { + var dir = this.settings.direction === "rtl" ? -1 : 1; + + if (silent) { + this.ignore = true; + } + + if (!this.fullsize) { + if (x) this.container.scrollLeft += x * dir; + if (y) this.container.scrollTop += y; + } else { + window.scrollBy(x * dir, y * dir); + } + this.scrolled = true; + } + }, { + key: "scrollTo", + value: function scrollTo(x, y, silent) { + if (silent) { + this.ignore = true; + } + + if (!this.fullsize) { + this.container.scrollLeft = x; + this.container.scrollTop = y; + } else { + window.scrollTo(x, y); + } + this.scrolled = true; + } + }, { + key: "onScroll", + value: function onScroll() { + var scrollTop = void 0; + var scrollLeft = void 0; + + if (!this.fullsize) { + scrollTop = this.container.scrollTop; + scrollLeft = this.container.scrollLeft; + } else { + scrollTop = window.scrollY; + scrollLeft = window.scrollX; + } + + this.scrollTop = scrollTop; + this.scrollLeft = scrollLeft; + + if (!this.ignore) { + this.emit(_constants.EVENTS.MANAGERS.SCROLL, { + top: scrollTop, + left: scrollLeft + }); + + clearTimeout(this.afterScrolled); + this.afterScrolled = setTimeout(function () { + this.emit(_constants.EVENTS.MANAGERS.SCROLLED, { + top: this.scrollTop, + left: this.scrollLeft + }); + }.bind(this), 20); + } else { + this.ignore = false; + } + } + }, { + key: "bounds", + value: function bounds() { + var bounds; + + bounds = this.stage.bounds(); + + return bounds; + } + }, { + key: "applyLayout", + value: function applyLayout(layout) { + + this.layout = layout; + this.updateLayout(); + // this.manager.layout(this.layout.format); + } + }, { + key: "updateLayout", + value: function updateLayout() { + + if (!this.stage) { + return; + } + + this._stageSize = this.stage.size(); + + if (!this.isPaginated) { + this.layout.calculate(this._stageSize.width, this._stageSize.height); + } else { + this.layout.calculate(this._stageSize.width, this._stageSize.height, this.settings.gap); + + // Set the look ahead offset for what is visible + this.settings.offset = this.layout.delta; + + // this.stage.addStyleRules("iframe", [{"margin-right" : this.layout.gap + "px"}]); + } + + // Set the dimensions for views + this.viewSettings.width = this.layout.width; + this.viewSettings.height = this.layout.height; + + this.setLayout(this.layout); + } + }, { + key: "setLayout", + value: function setLayout(layout) { + + this.viewSettings.layout = layout; + + this.mapping = new _mapping2.default(layout.props, this.settings.direction, this.settings.axis); + + if (this.views) { + + this.views.forEach(function (view) { + if (view) { + view.setLayout(layout); + } + }); + } + } + }, { + key: "updateAxis", + value: function updateAxis(axis, forceUpdate) { + + if (!this.isPaginated) { + axis = "vertical"; + } + + if (!forceUpdate && axis === this.settings.axis) { + return; + } + + this.settings.axis = axis; + + this.stage && this.stage.axis(axis); + + this.viewSettings.axis = axis; + + if (this.mapping) { + this.mapping = new _mapping2.default(this.layout.props, this.settings.direction, this.settings.axis); + } + + if (this.layout) { + if (axis === "vertical") { + this.layout.spread("none"); + } else { + this.layout.spread(this.layout.settings.spread); + } + } + } + }, { + key: "updateFlow", + value: function updateFlow(flow) { + var isPaginated = flow === "paginated" || flow === "auto"; + + this.isPaginated = isPaginated; + + if (flow === "scrolled-doc" || flow === "scrolled-continuous" || flow === "scrolled") { + this.updateAxis("vertical"); + } + + this.viewSettings.flow = flow; + + if (!this.settings.overflow) { + this.overflow = isPaginated ? "hidden" : "auto"; + } else { + this.overflow = this.settings.overflow; + } + // this.views.forEach(function(view){ + // view.setAxis(axis); + // }); + + this.updateLayout(); + } + }, { + key: "getContents", + value: function getContents() { + var contents = []; + if (!this.views) { + return contents; + } + this.views.forEach(function (view) { + var viewContents = view && view.contents; + if (viewContents) { + contents.push(viewContents); + } + }); + return contents; + } + }, { + key: "direction", + value: function direction() { + var dir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "ltr"; + + this.settings.direction = dir; + + this.stage && this.stage.direction(dir); + + this.viewSettings.direction = dir; + + this.updateLayout(); + } + }, { + key: "isRendered", + value: function isRendered() { + return this.rendered; + } + }]); + + return DefaultViewManager; +}(); + +//-- Enable binding events to Manager + + +(0, _eventEmitter2.default)(DefaultViewManager.prototype); + +exports.default = DefaultViewManager; +module.exports = exports["default"]; + +/***/ }), +/* 15 */ +/***/ (function(module, exports) { + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +module.exports = isObject; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_16__; + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* + From Zip.js, by Gildas Lormeau +edited down + */ + +var table = { + "application": { + "ecmascript": ["es", "ecma"], + "javascript": "js", + "ogg": "ogx", + "pdf": "pdf", + "postscript": ["ps", "ai", "eps", "epsi", "epsf", "eps2", "eps3"], + "rdf+xml": "rdf", + "smil": ["smi", "smil"], + "xhtml+xml": ["xhtml", "xht"], + "xml": ["xml", "xsl", "xsd", "opf", "ncx"], + "zip": "zip", + "x-httpd-eruby": "rhtml", + "x-latex": "latex", + "x-maker": ["frm", "maker", "frame", "fm", "fb", "book", "fbdoc"], + "x-object": "o", + "x-shockwave-flash": ["swf", "swfl"], + "x-silverlight": "scr", + "epub+zip": "epub", + "font-tdpfr": "pfr", + "inkml+xml": ["ink", "inkml"], + "json": "json", + "jsonml+json": "jsonml", + "mathml+xml": "mathml", + "metalink+xml": "metalink", + "mp4": "mp4s", + // "oebps-package+xml" : "opf", + "omdoc+xml": "omdoc", + "oxps": "oxps", + "vnd.amazon.ebook": "azw", + "widget": "wgt", + // "x-dtbncx+xml" : "ncx", + "x-dtbook+xml": "dtb", + "x-dtbresource+xml": "res", + "x-font-bdf": "bdf", + "x-font-ghostscript": "gsf", + "x-font-linux-psf": "psf", + "x-font-otf": "otf", + "x-font-pcf": "pcf", + "x-font-snf": "snf", + "x-font-ttf": ["ttf", "ttc"], + "x-font-type1": ["pfa", "pfb", "pfm", "afm"], + "x-font-woff": "woff", + "x-mobipocket-ebook": ["prc", "mobi"], + "x-mspublisher": "pub", + "x-nzb": "nzb", + "x-tgif": "obj", + "xaml+xml": "xaml", + "xml-dtd": "dtd", + "xproc+xml": "xpl", + "xslt+xml": "xslt", + "internet-property-stream": "acx", + "x-compress": "z", + "x-compressed": "tgz", + "x-gzip": "gz" + }, + "audio": { + "flac": "flac", + "midi": ["mid", "midi", "kar", "rmi"], + "mpeg": ["mpga", "mpega", "mp2", "mp3", "m4a", "mp2a", "m2a", "m3a"], + "mpegurl": "m3u", + "ogg": ["oga", "ogg", "spx"], + "x-aiff": ["aif", "aiff", "aifc"], + "x-ms-wma": "wma", + "x-wav": "wav", + "adpcm": "adp", + "mp4": "mp4a", + "webm": "weba", + "x-aac": "aac", + "x-caf": "caf", + "x-matroska": "mka", + "x-pn-realaudio-plugin": "rmp", + "xm": "xm", + "mid": ["mid", "rmi"] + }, + "image": { + "gif": "gif", + "ief": "ief", + "jpeg": ["jpeg", "jpg", "jpe"], + "pcx": "pcx", + "png": "png", + "svg+xml": ["svg", "svgz"], + "tiff": ["tiff", "tif"], + "x-icon": "ico", + "bmp": "bmp", + "webp": "webp", + "x-pict": ["pic", "pct"], + "x-tga": "tga", + "cis-cod": "cod" + }, + "text": { + "cache-manifest": ["manifest", "appcache"], + "css": "css", + "csv": "csv", + "html": ["html", "htm", "shtml", "stm"], + "mathml": "mml", + "plain": ["txt", "text", "brf", "conf", "def", "list", "log", "in", "bas"], + "richtext": "rtx", + "tab-separated-values": "tsv", + "x-bibtex": "bib" + }, + "video": { + "mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v", "mp2", "mpa", "mpv2"], + "mp4": ["mp4", "mp4v", "mpg4"], + "quicktime": ["qt", "mov"], + "ogg": "ogv", + "vnd.mpegurl": ["mxu", "m4u"], + "x-flv": "flv", + "x-la-asf": ["lsf", "lsx"], + "x-mng": "mng", + "x-ms-asf": ["asf", "asx", "asr"], + "x-ms-wm": "wm", + "x-ms-wmv": "wmv", + "x-ms-wmx": "wmx", + "x-ms-wvx": "wvx", + "x-msvideo": "avi", + "x-sgi-movie": "movie", + "x-matroska": ["mpv", "mkv", "mk3d", "mks"], + "3gpp2": "3g2", + "h261": "h261", + "h263": "h263", + "h264": "h264", + "jpeg": "jpgv", + "jpm": ["jpm", "jpgm"], + "mj2": ["mj2", "mjp2"], + "vnd.ms-playready.media.pyv": "pyv", + "vnd.uvvu.mp4": ["uvu", "uvvu"], + "vnd.vivo": "viv", + "webm": "webm", + "x-f4v": "f4v", + "x-m4v": "m4v", + "x-ms-vob": "vob", + "x-smv": "smv" + } +}; + +var mimeTypes = function () { + var type, + subtype, + val, + index, + mimeTypes = {}; + for (type in table) { + if (table.hasOwnProperty(type)) { + for (subtype in table[type]) { + if (table[type].hasOwnProperty(subtype)) { + val = table[type][subtype]; + if (typeof val == "string") { + mimeTypes[val] = type + "/" + subtype; + } else { + for (index = 0; index < val.length; index++) { + mimeTypes[val[index]] = type + "/" + subtype; + } + } + } + } + } + } + return mimeTypes; +}(); + +var defaultValue = "text/plain"; //"application/octet-stream"; + +function lookup(filename) { + return filename && mimeTypes[filename.split(".").pop().toLowerCase()] || defaultValue; +}; + +module.exports = { + 'lookup': lookup +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); +// import Mapping from "./mapping"; + + +// Default Views + + +// Default View Managers + + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +var _core = __webpack_require__(0); + +var _hook = __webpack_require__(10); + +var _hook2 = _interopRequireDefault(_hook); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _queue = __webpack_require__(12); + +var _queue2 = _interopRequireDefault(_queue); + +var _layout = __webpack_require__(50); + +var _layout2 = _interopRequireDefault(_layout); + +var _themes = __webpack_require__(51); + +var _themes2 = _interopRequireDefault(_themes); + +var _contents = __webpack_require__(13); + +var _contents2 = _interopRequireDefault(_contents); + +var _annotations = __webpack_require__(52); + +var _annotations2 = _interopRequireDefault(_annotations); + +var _constants = __webpack_require__(3); + +var _iframe = __webpack_require__(20); + +var _iframe2 = _interopRequireDefault(_iframe); + +var _index = __webpack_require__(14); + +var _index2 = _interopRequireDefault(_index); + +var _index3 = __webpack_require__(24); + +var _index4 = _interopRequireDefault(_index3); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Displays an Epub as a series of Views for each Section. + * Requires Manager and View class to handle specifics of rendering + * the section contetn. + * @class + * @param {Book} book + * @param {object} [options] + * @param {number} [options.width] + * @param {number} [options.height] + * @param {string} [options.ignoreClass] class for the cfi parser to ignore + * @param {string | function | object} [options.manager='default'] + * @param {string | function} [options.view='iframe'] + * @param {string} [options.layout] layout to force + * @param {string} [options.spread] force spread value + * @param {number} [options.minSpreadWidth] overridden by spread: none (never) / both (always) + * @param {string} [options.stylesheet] url of stylesheet to be injected + * @param {string} [options.script] url of script to be injected + */ +var Rendition = function () { + function Rendition(book, options) { + _classCallCheck(this, Rendition); + + this.settings = (0, _core.extend)(this.settings || {}, { + width: null, + height: null, + ignoreClass: "", + manager: "default", + view: "iframe", + flow: null, + layout: null, + spread: null, + minSpreadWidth: 800, + stylesheet: null, + script: null + }); + + (0, _core.extend)(this.settings, options); + + if (_typeof(this.settings.manager) === "object") { + this.manager = this.settings.manager; + } + + this.book = book; + + /** + * Adds Hook methods to the Rendition prototype + * @member {object} hooks + * @property {Hook} hooks.content + * @memberof Rendition + */ + this.hooks = {}; + this.hooks.display = new _hook2.default(this); + this.hooks.serialize = new _hook2.default(this); + this.hooks.content = new _hook2.default(this); + this.hooks.unloaded = new _hook2.default(this); + this.hooks.layout = new _hook2.default(this); + this.hooks.render = new _hook2.default(this); + this.hooks.show = new _hook2.default(this); + + this.hooks.content.register(this.handleLinks.bind(this)); + this.hooks.content.register(this.passEvents.bind(this)); + this.hooks.content.register(this.adjustImages.bind(this)); + + this.book.spine.hooks.content.register(this.injectIdentifier.bind(this)); + + if (this.settings.stylesheet) { + this.book.spine.hooks.content.register(this.injectStylesheet.bind(this)); + } + + if (this.settings.script) { + this.book.spine.hooks.content.register(this.injectScript.bind(this)); + } + + /** + * @member {Themes} themes + * @memberof Rendition + */ + this.themes = new _themes2.default(this); + + /** + * @member {Annotations} annotations + * @memberof Rendition + */ + this.annotations = new _annotations2.default(this); + + this.epubcfi = new _epubcfi2.default(); + + this.q = new _queue2.default(this); + + /** + * A Rendered Location Range + * @typedef location + * @type {Object} + * @property {object} start + * @property {string} start.index + * @property {string} start.href + * @property {object} start.displayed + * @property {EpubCFI} start.cfi + * @property {number} start.location + * @property {number} start.percentage + * @property {number} start.displayed.page + * @property {number} start.displayed.total + * @property {object} end + * @property {string} end.index + * @property {string} end.href + * @property {object} end.displayed + * @property {EpubCFI} end.cfi + * @property {number} end.location + * @property {number} end.percentage + * @property {number} end.displayed.page + * @property {number} end.displayed.total + * @property {boolean} atStart + * @property {boolean} atEnd + * @memberof Rendition + */ + this.location = undefined; + + // Hold queue until book is opened + this.q.enqueue(this.book.opened); + + this.starting = new _core.defer(); + /** + * @member {promise} started returns after the rendition has started + * @memberof Rendition + */ + this.started = this.starting.promise; + // Block the queue until rendering is started + this.q.enqueue(this.start); + } + + /** + * Set the manager function + * @param {function} manager + */ + + + _createClass(Rendition, [{ + key: "setManager", + value: function setManager(manager) { + this.manager = manager; + } + + /** + * Require the manager from passed string, or as a class function + * @param {string|object} manager [description] + * @return {method} + */ + + }, { + key: "requireManager", + value: function requireManager(manager) { + var viewManager; + + // If manager is a string, try to load from imported managers + if (typeof manager === "string" && manager === "default") { + viewManager = _index2.default; + } else if (typeof manager === "string" && manager === "continuous") { + viewManager = _index4.default; + } else { + // otherwise, assume we were passed a class function + viewManager = manager; + } + + return viewManager; + } + + /** + * Require the view from passed string, or as a class function + * @param {string|object} view + * @return {view} + */ + + }, { + key: "requireView", + value: function requireView(view) { + var View; + + // If view is a string, try to load from imported views, + if (typeof view == "string" && view === "iframe") { + View = _iframe2.default; + } else { + // otherwise, assume we were passed a class function + View = view; + } + + return View; + } + + /** + * Start the rendering + * @return {Promise} rendering has started + */ + + }, { + key: "start", + value: function start() { + + if (!this.manager) { + this.ViewManager = this.requireManager(this.settings.manager); + this.View = this.requireView(this.settings.view); + + this.manager = new this.ViewManager({ + view: this.View, + queue: this.q, + request: this.book.load.bind(this.book), + settings: this.settings + }); + } + + this.direction(this.book.package.metadata.direction); + + // Parse metadata to get layout props + this.settings.globalLayoutProperties = this.determineLayoutProperties(this.book.package.metadata); + + this.flow(this.settings.globalLayoutProperties.flow); + + this.layout(this.settings.globalLayoutProperties); + + // Listen for displayed views + this.manager.on(_constants.EVENTS.MANAGERS.ADDED, this.afterDisplayed.bind(this)); + this.manager.on(_constants.EVENTS.MANAGERS.REMOVED, this.afterRemoved.bind(this)); + + // Listen for resizing + this.manager.on(_constants.EVENTS.MANAGERS.RESIZED, this.onResized.bind(this)); + + // Listen for rotation + this.manager.on(_constants.EVENTS.MANAGERS.ORIENTATION_CHANGE, this.onOrientationChange.bind(this)); + + // Listen for scroll changes + this.manager.on(_constants.EVENTS.MANAGERS.SCROLLED, this.reportLocation.bind(this)); + + /** + * Emit that rendering has started + * @event started + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.STARTED); + + // Start processing queue + this.starting.resolve(); + } + + /** + * Call to attach the container to an element in the dom + * Container must be attached before rendering can begin + * @param {element} element to attach to + * @return {Promise} + */ + + }, { + key: "attachTo", + value: function attachTo(element) { + + return this.q.enqueue(function () { + + // Start rendering + this.manager.render(element, { + "width": this.settings.width, + "height": this.settings.height + }); + + /** + * Emit that rendering has attached to an element + * @event attached + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.ATTACHED); + }.bind(this)); + } + + /** + * Display a point in the book + * The request will be added to the rendering Queue, + * so it will wait until book is opened, rendering started + * and all other rendering tasks have finished to be called. + * @param {string} target Url or EpubCFI + * @return {Promise} + */ + + }, { + key: "display", + value: function display(target) { + if (this.displaying) { + this.displaying.resolve(); + } + return this.q.enqueue(this._display, target); + } + + /** + * Tells the manager what to display immediately + * @private + * @param {string} target Url or EpubCFI + * @return {Promise} + */ + + }, { + key: "_display", + value: function _display(target) { + var _this = this; + + if (!this.book) { + return; + } + var isCfiString = this.epubcfi.isCfiString(target); + var displaying = new _core.defer(); + var displayed = displaying.promise; + var section; + var moveTo; + + this.displaying = displaying; + + // Check if this is a book percentage + if (this.book.locations.length() && ((0, _core.isFloat)(target) || target === "1.0") // Handle 1.0 + ) { + target = this.book.locations.cfiFromPercentage(parseFloat(target)); + } + + section = this.book.spine.get(target); + + if (!section) { + displaying.reject(new Error("No Section Found")); + return displayed; + } + + this.manager.display(section, target).then(function () { + displaying.resolve(section); + _this.displaying = undefined; + + /** + * Emit that a section has been displayed + * @event displayed + * @param {Section} section + * @memberof Rendition + */ + _this.emit(_constants.EVENTS.RENDITION.DISPLAYED, section); + _this.reportLocation(); + }, function (err) { + /** + * Emit that has been an error displaying + * @event displayError + * @param {Section} section + * @memberof Rendition + */ + _this.emit(_constants.EVENTS.RENDITION.DISPLAY_ERROR, err); + }); + + return displayed; + } + + /* + render(view, show) { + // view.onLayout = this.layout.format.bind(this.layout); + view.create(); + // Fit to size of the container, apply padding + this.manager.resizeView(view); + // Render Chain + return view.section.render(this.book.request) + .then(function(contents){ + return view.load(contents); + }.bind(this)) + .then(function(doc){ + return this.hooks.content.trigger(view, this); + }.bind(this)) + .then(function(){ + this.layout.format(view.contents); + return this.hooks.layout.trigger(view, this); + }.bind(this)) + .then(function(){ + return view.display(); + }.bind(this)) + .then(function(){ + return this.hooks.render.trigger(view, this); + }.bind(this)) + .then(function(){ + if(show !== false) { + this.q.enqueue(function(view){ + view.show(); + }, view); + } + // this.map = new Map(view, this.layout); + this.hooks.show.trigger(view, this); + this.trigger("rendered", view.section); + }.bind(this)) + .catch(function(e){ + this.trigger("loaderror", e); + }.bind(this)); + } + */ + + /** + * Report what section has been displayed + * @private + * @param {*} view + */ + + }, { + key: "afterDisplayed", + value: function afterDisplayed(view) { + var _this2 = this; + + view.on(_constants.EVENTS.VIEWS.MARK_CLICKED, function (cfiRange, data) { + return _this2.triggerMarkEvent(cfiRange, data, view); + }); + + this.hooks.render.trigger(view, this).then(function () { + if (view.contents) { + _this2.hooks.content.trigger(view.contents, _this2).then(function () { + /** + * Emit that a section has been rendered + * @event rendered + * @param {Section} section + * @param {View} view + * @memberof Rendition + */ + _this2.emit(_constants.EVENTS.RENDITION.RENDERED, view.section, view); + }); + } else { + _this2.emit(_constants.EVENTS.RENDITION.RENDERED, view.section, view); + } + }); + } + + /** + * Report what has been removed + * @private + * @param {*} view + */ + + }, { + key: "afterRemoved", + value: function afterRemoved(view) { + var _this3 = this; + + this.hooks.unloaded.trigger(view, this).then(function () { + /** + * Emit that a section has been removed + * @event removed + * @param {Section} section + * @param {View} view + * @memberof Rendition + */ + _this3.emit(_constants.EVENTS.RENDITION.REMOVED, view.section, view); + }); + } + + /** + * Report resize events and display the last seen location + * @private + */ + + }, { + key: "onResized", + value: function onResized(size) { + + /** + * Emit that the rendition has been resized + * @event resized + * @param {number} width + * @param {height} height + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.RESIZED, { + width: size.width, + height: size.height + }); + + if (this.location && this.location.start) { + this.display(this.location.start.cfi); + } + } + + /** + * Report orientation events and display the last seen location + * @private + */ + + }, { + key: "onOrientationChange", + value: function onOrientationChange(orientation) { + /** + * Emit that the rendition has been rotated + * @event orientationchange + * @param {string} orientation + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.ORIENTATION_CHANGE, orientation); + } + + /** + * Move the Rendition to a specific offset + * Usually you would be better off calling display() + * @param {object} offset + */ + + }, { + key: "moveTo", + value: function moveTo(offset) { + this.manager.moveTo(offset); + } + + /** + * Trigger a resize of the views + * @param {number} [width] + * @param {number} [height] + */ + + }, { + key: "resize", + value: function resize(width, height) { + if (width) { + this.settings.width = width; + } + if (height) { + this.settings.height = height; + } + this.manager.resize(width, height); + } + + /** + * Clear all rendered views + */ + + }, { + key: "clear", + value: function clear() { + this.manager.clear(); + } + + /** + * Go to the next "page" in the rendition + * @return {Promise} + */ + + }, { + key: "next", + value: function next() { + return this.q.enqueue(this.manager.next.bind(this.manager)).then(this.reportLocation.bind(this)); + } + + /** + * Go to the previous "page" in the rendition + * @return {Promise} + */ + + }, { + key: "prev", + value: function prev() { + return this.q.enqueue(this.manager.prev.bind(this.manager)).then(this.reportLocation.bind(this)); + } + + //-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering + /** + * Determine the Layout properties from metadata and settings + * @private + * @param {object} metadata + * @return {object} properties + */ + + }, { + key: "determineLayoutProperties", + value: function determineLayoutProperties(metadata) { + var properties; + var layout = this.settings.layout || metadata.layout || "reflowable"; + var spread = this.settings.spread || metadata.spread || "auto"; + var orientation = this.settings.orientation || metadata.orientation || "auto"; + var flow = this.settings.flow || metadata.flow || "auto"; + var viewport = metadata.viewport || ""; + var minSpreadWidth = this.settings.minSpreadWidth || metadata.minSpreadWidth || 800; + var direction = this.settings.direction || metadata.direction || "ltr"; + + if ((this.settings.width === 0 || this.settings.width > 0) && (this.settings.height === 0 || this.settings.height > 0)) { + // viewport = "width="+this.settings.width+", height="+this.settings.height+""; + } + + properties = { + layout: layout, + spread: spread, + orientation: orientation, + flow: flow, + viewport: viewport, + minSpreadWidth: minSpreadWidth, + direction: direction + }; + + return properties; + } + + /** + * Adjust the flow of the rendition to paginated or scrolled + * (scrolled-continuous vs scrolled-doc are handled by different view managers) + * @param {string} flow + */ + + }, { + key: "flow", + value: function flow(_flow2) { + var _flow = _flow2; + if (_flow2 === "scrolled" || _flow2 === "scrolled-doc" || _flow2 === "scrolled-continuous") { + _flow = "scrolled"; + } + + if (_flow2 === "auto" || _flow2 === "paginated") { + _flow = "paginated"; + } + + this.settings.flow = _flow2; + + if (this._layout) { + this._layout.flow(_flow); + } + + if (this.manager && this._layout) { + this.manager.applyLayout(this._layout); + } + + if (this.manager) { + this.manager.updateFlow(_flow); + } + + if (this.manager && this.manager.isRendered() && this.location) { + this.manager.clear(); + this.display(this.location.start.cfi); + } + } + + /** + * Adjust the layout of the rendition to reflowable or pre-paginated + * @param {object} settings + */ + + }, { + key: "layout", + value: function layout(settings) { + var _this4 = this; + + if (settings) { + this._layout = new _layout2.default(settings); + this._layout.spread(settings.spread, this.settings.minSpreadWidth); + + // this.mapping = new Mapping(this._layout.props); + + this._layout.on(_constants.EVENTS.LAYOUT.UPDATED, function (props, changed) { + _this4.emit(_constants.EVENTS.RENDITION.LAYOUT, props, changed); + }); + } + + if (this.manager && this._layout) { + this.manager.applyLayout(this._layout); + } + + return this._layout; + } + + /** + * Adjust if the rendition uses spreads + * @param {string} spread none | auto (TODO: implement landscape, portrait, both) + * @param {int} min min width to use spreads at + */ + + }, { + key: "spread", + value: function spread(_spread, min) { + + this._layout.spread(_spread, min); + + if (this.manager.isRendered()) { + this.manager.updateLayout(); + } + } + + /** + * Adjust the direction of the rendition + * @param {string} dir + */ + + }, { + key: "direction", + value: function direction(dir) { + + this.settings.direction = dir || "ltr"; + + if (this.manager) { + this.manager.direction(this.settings.direction); + } + + if (this.manager && this.manager.isRendered() && this.location) { + this.manager.clear(); + this.display(this.location.start.cfi); + } + } + + /** + * Report the current location + * @fires relocated + * @fires locationChanged + */ + + }, { + key: "reportLocation", + value: function reportLocation() { + return this.q.enqueue(function reportedLocation() { + requestAnimationFrame(function reportedLocationAfterRAF() { + var location = this.manager.currentLocation(); + if (location && location.then && typeof location.then === "function") { + location.then(function (result) { + var located = this.located(result); + + if (!located || !located.start || !located.end) { + return; + } + + this.location = located; + + this.emit(_constants.EVENTS.RENDITION.LOCATION_CHANGED, { + index: this.location.start.index, + href: this.location.start.href, + start: this.location.start.cfi, + end: this.location.end.cfi, + percentage: this.location.start.percentage + }); + + this.emit(_constants.EVENTS.RENDITION.RELOCATED, this.location); + }.bind(this)); + } else if (location) { + var located = this.located(location); + + if (!located || !located.start || !located.end) { + return; + } + + this.location = located; + + /** + * @event locationChanged + * @deprecated + * @type {object} + * @property {number} index + * @property {string} href + * @property {EpubCFI} start + * @property {EpubCFI} end + * @property {number} percentage + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.LOCATION_CHANGED, { + index: this.location.start.index, + href: this.location.start.href, + start: this.location.start.cfi, + end: this.location.end.cfi, + percentage: this.location.start.percentage + }); + + /** + * @event relocated + * @type {displayedLocation} + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.RELOCATED, this.location); + } + }.bind(this)); + }.bind(this)); + } + + /** + * Get the Current Location object + * @return {displayedLocation | promise} location (may be a promise) + */ + + }, { + key: "currentLocation", + value: function currentLocation() { + var location = this.manager.currentLocation(); + if (location && location.then && typeof location.then === "function") { + location.then(function (result) { + var located = this.located(result); + return located; + }.bind(this)); + } else if (location) { + var located = this.located(location); + return located; + } + } + + /** + * Creates a Rendition#locationRange from location + * passed by the Manager + * @returns {displayedLocation} + * @private + */ + + }, { + key: "located", + value: function located(location) { + if (!location.length) { + return {}; + } + var start = location[0]; + var end = location[location.length - 1]; + + var located = { + start: { + index: start.index, + href: start.href, + cfi: start.mapping.start, + displayed: { + page: start.pages[0] || 1, + total: start.totalPages + } + }, + end: { + index: end.index, + href: end.href, + cfi: end.mapping.end, + displayed: { + page: end.pages[end.pages.length - 1] || 1, + total: end.totalPages + } + } + }; + + var locationStart = this.book.locations.locationFromCfi(start.mapping.start); + var locationEnd = this.book.locations.locationFromCfi(end.mapping.end); + + if (locationStart != null) { + located.start.location = locationStart; + located.start.percentage = this.book.locations.percentageFromLocation(locationStart); + } + if (locationEnd != null) { + located.end.location = locationEnd; + located.end.percentage = this.book.locations.percentageFromLocation(locationEnd); + } + + var pageStart = this.book.pageList.pageFromCfi(start.mapping.start); + var pageEnd = this.book.pageList.pageFromCfi(end.mapping.end); + + if (pageStart != -1) { + located.start.page = pageStart; + } + if (pageEnd != -1) { + located.end.page = pageEnd; + } + + if (end.index === this.book.spine.last().index && located.end.displayed.page >= located.end.displayed.total) { + located.atEnd = true; + } + + if (start.index === this.book.spine.first().index && located.start.displayed.page === 1) { + located.atStart = true; + } + + return located; + } + + /** + * Remove and Clean Up the Rendition + */ + + }, { + key: "destroy", + value: function destroy() { + // Clear the queue + // this.q.clear(); + // this.q = undefined; + + this.manager && this.manager.destroy(); + + this.book = undefined; + + // this.views = null; + + // this.hooks.display.clear(); + // this.hooks.serialize.clear(); + // this.hooks.content.clear(); + // this.hooks.layout.clear(); + // this.hooks.render.clear(); + // this.hooks.show.clear(); + // this.hooks = {}; + + // this.themes.destroy(); + // this.themes = undefined; + + // this.epubcfi = undefined; + + // this.starting = undefined; + // this.started = undefined; + + } + + /** + * Pass the events from a view's Contents + * @private + * @param {View} view + */ + + }, { + key: "passEvents", + value: function passEvents(contents) { + var _this5 = this; + + var listenedEvents = _contents2.default.listenedEvents; + + listenedEvents.forEach(function (e) { + contents.on(e, function (ev) { + return _this5.triggerViewEvent(ev, contents); + }); + }); + + contents.on(_constants.EVENTS.CONTENTS.SELECTED, function (e) { + return _this5.triggerSelectedEvent(e, contents); + }); + } + + /** + * Emit events passed by a view + * @private + * @param {event} e + */ + + }, { + key: "triggerViewEvent", + value: function triggerViewEvent(e, contents) { + this.emit(e.type, e, contents); + } + + /** + * Emit a selection event's CFI Range passed from a a view + * @private + * @param {EpubCFI} cfirange + */ + + }, { + key: "triggerSelectedEvent", + value: function triggerSelectedEvent(cfirange, contents) { + /** + * Emit that a text selection has occured + * @event selected + * @param {EpubCFI} cfirange + * @param {Contents} contents + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.SELECTED, cfirange, contents); + } + + /** + * Emit a markClicked event with the cfiRange and data from a mark + * @private + * @param {EpubCFI} cfirange + */ + + }, { + key: "triggerMarkEvent", + value: function triggerMarkEvent(cfiRange, data, contents) { + /** + * Emit that a mark was clicked + * @event markClicked + * @param {EpubCFI} cfirange + * @param {object} data + * @param {Contents} contents + * @memberof Rendition + */ + this.emit(_constants.EVENTS.RENDITION.MARK_CLICKED, cfiRange, data, contents); + } + + /** + * Get a Range from a Visible CFI + * @param {string} cfi EpubCfi String + * @param {string} ignoreClass + * @return {range} + */ + + }, { + key: "getRange", + value: function getRange(cfi, ignoreClass) { + var _cfi = new _epubcfi2.default(cfi); + var found = this.manager.visible().filter(function (view) { + if (_cfi.spinePos === view.index) return true; + }); + + // Should only every return 1 item + if (found.length) { + return found[0].contents.range(_cfi, ignoreClass); + } + } + + /** + * Hook to adjust images to fit in columns + * @param {Contents} contents + * @private + */ + + }, { + key: "adjustImages", + value: function adjustImages(contents) { + + if (this._layout.name === "pre-paginated") { + return new Promise(function (resolve) { + resolve(); + }); + } + + contents.addStylesheetRules({ + "img": { + "max-width": (this._layout.columnWidth ? this._layout.columnWidth + "px" : "100%") + "!important", + "max-height": (this._layout.height ? this._layout.height * 0.6 + "px" : "60%") + "!important", + "object-fit": "contain", + "page-break-inside": "avoid" + }, + "svg": { + "max-width": (this._layout.columnWidth ? this._layout.columnWidth + "px" : "100%") + "!important", + "max-height": (this._layout.height ? this._layout.height * 0.6 + "px" : "60%") + "!important", + "page-break-inside": "avoid" + } + }); + + return new Promise(function (resolve, reject) { + // Wait to apply + setTimeout(function () { + resolve(); + }, 1); + }); + } + + /** + * Get the Contents object of each rendered view + * @returns {Contents[]} + */ + + }, { + key: "getContents", + value: function getContents() { + return this.manager ? this.manager.getContents() : []; + } + + /** + * Get the views member from the manager + * @returns {Views} + */ + + }, { + key: "views", + value: function views() { + var views = this.manager ? this.manager.views : undefined; + return views || []; + } + + /** + * Hook to handle link clicks in rendered content + * @param {Contents} contents + * @private + */ + + }, { + key: "handleLinks", + value: function handleLinks(contents) { + var _this6 = this; + + if (contents) { + contents.on(_constants.EVENTS.CONTENTS.LINK_CLICKED, function (href) { + var relative = _this6.book.path.relative(href); + _this6.display(relative); + }); + } + } + + /** + * Hook to handle injecting stylesheet before + * a Section is serialized + * @param {document} doc + * @param {Section} section + * @private + */ + + }, { + key: "injectStylesheet", + value: function injectStylesheet(doc, section) { + var style = doc.createElement("link"); + style.setAttribute("type", "text/css"); + style.setAttribute("rel", "stylesheet"); + style.setAttribute("href", this.settings.stylesheet); + doc.getElementsByTagName("head")[0].appendChild(style); + } + + /** + * Hook to handle injecting scripts before + * a Section is serialized + * @param {document} doc + * @param {Section} section + * @private + */ + + }, { + key: "injectScript", + value: function injectScript(doc, section) { + var script = doc.createElement("script"); + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", this.settings.script); + script.textContent = " "; // Needed to prevent self closing tag + doc.getElementsByTagName("head")[0].appendChild(script); + } + + /** + * Hook to handle the document identifier before + * a Section is serialized + * @param {document} doc + * @param {Section} section + * @private + */ + + }, { + key: "injectIdentifier", + value: function injectIdentifier(doc, section) { + var ident = this.book.package.metadata.identifier; + var meta = doc.createElement("meta"); + meta.setAttribute("name", "dc.relation.ispartof"); + if (ident) { + meta.setAttribute("content", ident); + } + doc.getElementsByTagName("head")[0].appendChild(meta); + } + }]); + + return Rendition; +}(); + +//-- Enable binding events to Renderer + + +(0, _eventEmitter2.default)(Rendition.prototype); + +exports.default = Rendition; +module.exports = exports["default"]; + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Map text locations to CFI ranges + * @class + */ +var Mapping = function () { + function Mapping(layout, direction, axis, dev) { + _classCallCheck(this, Mapping); + + this.layout = layout; + this.horizontal = axis === "horizontal" ? true : false; + this.direction = direction || "ltr"; + this._dev = dev; + } + + /** + * Find CFI pairs for entire section at once + */ + + + _createClass(Mapping, [{ + key: "section", + value: function section(view) { + var ranges = this.findRanges(view); + var map = this.rangeListToCfiList(view.section.cfiBase, ranges); + + return map; + } + + /** + * Find CFI pairs for a page + */ + + }, { + key: "page", + value: function page(contents, cfiBase, start, end) { + var root = contents && contents.document ? contents.document.body : false; + var result; + + if (!root) { + return; + } + + result = this.rangePairToCfiPair(cfiBase, { + start: this.findStart(root, start, end), + end: this.findEnd(root, start, end) + }); + + if (this._dev === true) { + var doc = contents.document; + var startRange = new _epubcfi2.default(result.start).toRange(doc); + var endRange = new _epubcfi2.default(result.end).toRange(doc); + + var selection = doc.defaultView.getSelection(); + var r = doc.createRange(); + selection.removeAllRanges(); + r.setStart(startRange.startContainer, startRange.startOffset); + r.setEnd(endRange.endContainer, endRange.endOffset); + selection.addRange(r); + } + + return result; + } + }, { + key: "walk", + value: function walk(root, func) { + // IE11 has strange issue, if root is text node IE throws exception on + // calling treeWalker.nextNode(), saying + // Unexpected call to method or property access instead of returing null value + if (root && root.nodeType === Node.TEXT_NODE) { + return; + } + // safeFilter is required so that it can work in IE as filter is a function for IE + // and for other browser filter is an object. + var filter = { + acceptNode: function acceptNode(node) { + if (node.data.trim().length > 0) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }; + var safeFilter = filter.acceptNode; + safeFilter.acceptNode = filter.acceptNode; + + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, safeFilter, false); + var node; + var result; + while (node = treeWalker.nextNode()) { + result = func(node); + if (result) break; + } + + return result; + } + }, { + key: "findRanges", + value: function findRanges(view) { + var columns = []; + var scrollWidth = view.contents.scrollWidth(); + var spreads = Math.ceil(scrollWidth / this.layout.spreadWidth); + var count = spreads * this.layout.divisor; + var columnWidth = this.layout.columnWidth; + var gap = this.layout.gap; + var start, end; + + for (var i = 0; i < count.pages; i++) { + start = (columnWidth + gap) * i; + end = columnWidth * (i + 1) + gap * i; + columns.push({ + start: this.findStart(view.document.body, start, end), + end: this.findEnd(view.document.body, start, end) + }); + } + + return columns; + } + }, { + key: "findStart", + value: function findStart(root, start, end) { + var _this = this; + + var stack = [root]; + var $el; + var found; + var $prev = root; + + while (stack.length) { + + $el = stack.shift(); + + found = this.walk($el, function (node) { + var left, right, top, bottom; + var elPos; + var elRange; + + elPos = _this.getBounds(node); + + if (_this.horizontal && _this.direction === "ltr") { + + left = _this.horizontal ? elPos.left : elPos.top; + right = _this.horizontal ? elPos.right : elPos.bottom; + + if (left >= start && left <= end) { + return node; + } else if (right > start) { + return node; + } else { + $prev = node; + stack.push(node); + } + } else if (_this.horizontal && _this.direction === "rtl") { + + left = elPos.left; + right = elPos.right; + + if (right <= end && right >= start) { + return node; + } else if (left < end) { + return node; + } else { + $prev = node; + stack.push(node); + } + } else { + + top = elPos.top; + bottom = elPos.bottom; + + if (top >= start && top <= end) { + return node; + } else if (bottom > start) { + return node; + } else { + $prev = node; + stack.push(node); + } + } + }); + + if (found) { + return this.findTextStartRange(found, start, end); + } + } + + // Return last element + return this.findTextStartRange($prev, start, end); + } + }, { + key: "findEnd", + value: function findEnd(root, start, end) { + var _this2 = this; + + var stack = [root]; + var $el; + var $prev = root; + var found; + + while (stack.length) { + + $el = stack.shift(); + + found = this.walk($el, function (node) { + + var left, right, top, bottom; + var elPos; + var elRange; + + elPos = _this2.getBounds(node); + + if (_this2.horizontal && _this2.direction === "ltr") { + + left = Math.round(elPos.left); + right = Math.round(elPos.right); + + if (left > end && $prev) { + return $prev; + } else if (right > end) { + return node; + } else { + $prev = node; + stack.push(node); + } + } else if (_this2.horizontal && _this2.direction === "rtl") { + + left = Math.round(_this2.horizontal ? elPos.left : elPos.top); + right = Math.round(_this2.horizontal ? elPos.right : elPos.bottom); + + if (right < start && $prev) { + return $prev; + } else if (left < start) { + return node; + } else { + $prev = node; + stack.push(node); + } + } else { + + top = Math.round(elPos.top); + bottom = Math.round(elPos.bottom); + + if (top > end && $prev) { + return $prev; + } else if (bottom > end) { + return node; + } else { + $prev = node; + stack.push(node); + } + } + }); + + if (found) { + return this.findTextEndRange(found, start, end); + } + } + + // end of chapter + return this.findTextEndRange($prev, start, end); + } + }, { + key: "findTextStartRange", + value: function findTextStartRange(node, start, end) { + var ranges = this.splitTextNodeIntoRanges(node); + var range; + var pos; + var left, top, right; + + for (var i = 0; i < ranges.length; i++) { + range = ranges[i]; + + pos = range.getBoundingClientRect(); + + if (this.horizontal && this.direction === "ltr") { + + left = pos.left; + if (left >= start) { + return range; + } + } else if (this.horizontal && this.direction === "rtl") { + + right = pos.right; + if (right <= end) { + return range; + } + } else { + + top = pos.top; + if (top >= start) { + return range; + } + } + + // prev = range; + } + + return ranges[0]; + } + }, { + key: "findTextEndRange", + value: function findTextEndRange(node, start, end) { + var ranges = this.splitTextNodeIntoRanges(node); + var prev; + var range; + var pos; + var left, right, top, bottom; + + for (var i = 0; i < ranges.length; i++) { + range = ranges[i]; + + pos = range.getBoundingClientRect(); + + if (this.horizontal && this.direction === "ltr") { + + left = pos.left; + right = pos.right; + + if (left > end && prev) { + return prev; + } else if (right > end) { + return range; + } + } else if (this.horizontal && this.direction === "rtl") { + + left = pos.left; + right = pos.right; + + if (right < start && prev) { + return prev; + } else if (left < start) { + return range; + } + } else { + + top = pos.top; + bottom = pos.bottom; + + if (top > end && prev) { + return prev; + } else if (bottom > end) { + return range; + } + } + + prev = range; + } + + // Ends before limit + return ranges[ranges.length - 1]; + } + }, { + key: "splitTextNodeIntoRanges", + value: function splitTextNodeIntoRanges(node, _splitter) { + var ranges = []; + var textContent = node.textContent || ""; + var text = textContent.trim(); + var range; + var doc = node.ownerDocument; + var splitter = _splitter || " "; + + var pos = text.indexOf(splitter); + + if (pos === -1 || node.nodeType != Node.TEXT_NODE) { + range = doc.createRange(); + range.selectNodeContents(node); + return [range]; + } + + range = doc.createRange(); + range.setStart(node, 0); + range.setEnd(node, pos); + ranges.push(range); + range = false; + + while (pos != -1) { + + pos = text.indexOf(splitter, pos + 1); + if (pos > 0) { + + if (range) { + range.setEnd(node, pos); + ranges.push(range); + } + + range = doc.createRange(); + range.setStart(node, pos + 1); + } + } + + if (range) { + range.setEnd(node, text.length); + ranges.push(range); + } + + return ranges; + } + }, { + key: "rangePairToCfiPair", + value: function rangePairToCfiPair(cfiBase, rangePair) { + + var startRange = rangePair.start; + var endRange = rangePair.end; + + startRange.collapse(true); + endRange.collapse(false); + + var startCfi = new _epubcfi2.default(startRange, cfiBase).toString(); + var endCfi = new _epubcfi2.default(endRange, cfiBase).toString(); + + return { + start: startCfi, + end: endCfi + }; + } + }, { + key: "rangeListToCfiList", + value: function rangeListToCfiList(cfiBase, columns) { + var map = []; + var cifPair; + + for (var i = 0; i < columns.length; i++) { + cifPair = this.rangePairToCfiPair(cfiBase, columns[i]); + + map.push(cifPair); + } + + return map; + } + }, { + key: "getBounds", + value: function getBounds(node) { + var elPos = void 0; + if (node.nodeType == Node.TEXT_NODE) { + var elRange = document.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + } else { + elPos = node.getBoundingClientRect(); + } + return elPos; + } + }, { + key: "axis", + value: function axis(_axis) { + if (_axis) { + this.horizontal = _axis === "horizontal" ? true : false; + } + return this.horizontal; + } + }]); + + return Mapping; +}(); + +exports.default = Mapping; +module.exports = exports["default"]; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +var _core = __webpack_require__(0); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _contents = __webpack_require__(13); + +var _contents2 = _interopRequireDefault(_contents); + +var _constants = __webpack_require__(3); + +var _marksPane = __webpack_require__(53); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var IframeView = function () { + function IframeView(section, options) { + _classCallCheck(this, IframeView); + + this.settings = (0, _core.extend)({ + ignoreClass: "", + axis: options.layout && options.layout.props.flow === "scrolled" ? "vertical" : "horizontal", + direction: undefined, + width: 0, + height: 0, + layout: undefined, + globalLayoutProperties: {}, + method: undefined + }, options || {}); + + this.id = "epubjs-view-" + (0, _core.uuid)(); + this.section = section; + this.index = section.index; + + this.element = this.container(this.settings.axis); + + this.added = false; + this.displayed = false; + this.rendered = false; + + // this.width = this.settings.width; + // this.height = this.settings.height; + + this.fixedWidth = 0; + this.fixedHeight = 0; + + // Blank Cfi for Parsing + this.epubcfi = new _epubcfi2.default(); + + this.layout = this.settings.layout; + // Dom events to listen for + // this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart"]; + + this.pane = undefined; + this.highlights = {}; + this.underlines = {}; + this.marks = {}; + } + + _createClass(IframeView, [{ + key: "container", + value: function container(axis) { + var element = document.createElement("div"); + + element.classList.add("epub-view"); + + // this.element.style.minHeight = "100px"; + element.style.height = "0px"; + element.style.width = "0px"; + element.style.overflow = "hidden"; + element.style.position = "relative"; + element.style.display = "block"; + + if (axis && axis == "horizontal") { + element.style.flex = "none"; + } else { + element.style.flex = "initial"; + } + + return element; + } + }, { + key: "create", + value: function create() { + + if (this.iframe) { + return this.iframe; + } + + if (!this.element) { + this.element = this.createContainer(); + } + + this.iframe = document.createElement("iframe"); + this.iframe.id = this.id; + this.iframe.scrolling = "no"; // Might need to be removed: breaks ios width calculations + this.iframe.style.overflow = "hidden"; + this.iframe.seamless = "seamless"; + // Back up if seamless isn't supported + this.iframe.style.border = "none"; + + this.iframe.setAttribute("enable-annotation", "true"); + + this.resizing = true; + + // this.iframe.style.display = "none"; + this.element.style.visibility = "hidden"; + this.iframe.style.visibility = "hidden"; + + this.iframe.style.width = "0"; + this.iframe.style.height = "0"; + this._width = 0; + this._height = 0; + + this.element.setAttribute("ref", this.index); + + this.element.appendChild(this.iframe); + this.added = true; + + this.elementBounds = (0, _core.bounds)(this.element); + + // if(width || height){ + // this.resize(width, height); + // } else if(this.width && this.height){ + // this.resize(this.width, this.height); + // } else { + // this.iframeBounds = bounds(this.iframe); + // } + + + if ("srcdoc" in this.iframe) { + this.supportsSrcdoc = true; + } else { + this.supportsSrcdoc = false; + } + + if (!this.settings.method) { + this.settings.method = this.supportsSrcdoc ? "srcdoc" : "write"; + } + + return this.iframe; + } + }, { + key: "render", + value: function render(request, show) { + + // view.onLayout = this.layout.format.bind(this.layout); + this.create(); + + // Fit to size of the container, apply padding + this.size(); + + if (!this.sectionRender) { + this.sectionRender = this.section.render(request); + } + + // Render Chain + return this.sectionRender.then(function (contents) { + return this.load(contents); + }.bind(this)).then(function () { + var _this = this; + + // apply the layout function to the contents + this.layout.format(this.contents); + + // find and report the writingMode axis + var writingMode = this.contents.writingMode(); + var axis = writingMode.indexOf("vertical") === 0 ? "vertical" : "horizontal"; + + this.setAxis(axis); + this.emit(_constants.EVENTS.VIEWS.AXIS, axis); + + // Listen for events that require an expansion of the iframe + this.addListeners(); + + return new Promise(function (resolve, reject) { + // Expand the iframe to the full size of the content + _this.expand(); + resolve(); + }); + }.bind(this), function (e) { + this.emit(_constants.EVENTS.VIEWS.LOAD_ERROR, e); + return new Promise(function (resolve, reject) { + reject(e); + }); + }.bind(this)).then(function () { + this.emit(_constants.EVENTS.VIEWS.RENDERED, this.section); + }.bind(this)); + } + }, { + key: "reset", + value: function reset() { + if (this.iframe) { + this.iframe.style.width = "0"; + this.iframe.style.height = "0"; + this._width = 0; + this._height = 0; + this._textWidth = undefined; + this._contentWidth = undefined; + this._textHeight = undefined; + this._contentHeight = undefined; + } + this._needsReframe = true; + } + + // Determine locks base on settings + + }, { + key: "size", + value: function size(_width, _height) { + var width = _width || this.settings.width; + var height = _height || this.settings.height; + + if (this.layout.name === "pre-paginated") { + this.lock("both", width, height); + } else if (this.settings.axis === "horizontal") { + this.lock("height", width, height); + } else { + this.lock("width", width, height); + } + + this.settings.width = width; + this.settings.height = height; + } + + // Lock an axis to element dimensions, taking borders into account + + }, { + key: "lock", + value: function lock(what, width, height) { + var elBorders = (0, _core.borders)(this.element); + var iframeBorders; + + if (this.iframe) { + iframeBorders = (0, _core.borders)(this.iframe); + } else { + iframeBorders = { width: 0, height: 0 }; + } + + if (what == "width" && (0, _core.isNumber)(width)) { + this.lockedWidth = width - elBorders.width - iframeBorders.width; + // this.resize(this.lockedWidth, width); // width keeps ratio correct + } + + if (what == "height" && (0, _core.isNumber)(height)) { + this.lockedHeight = height - elBorders.height - iframeBorders.height; + // this.resize(width, this.lockedHeight); + } + + if (what === "both" && (0, _core.isNumber)(width) && (0, _core.isNumber)(height)) { + + this.lockedWidth = width - elBorders.width - iframeBorders.width; + this.lockedHeight = height - elBorders.height - iframeBorders.height; + // this.resize(this.lockedWidth, this.lockedHeight); + } + + if (this.displayed && this.iframe) { + + // this.contents.layout(); + this.expand(); + } + } + + // Resize a single axis based on content dimensions + + }, { + key: "expand", + value: function expand(force) { + var width = this.lockedWidth; + var height = this.lockedHeight; + var columns; + + var textWidth, textHeight; + + if (!this.iframe || this._expanding) return; + + this._expanding = true; + + if (this.layout.name === "pre-paginated") { + width = this.layout.columnWidth; + height = this.layout.height; + } + // Expand Horizontally + else if (this.settings.axis === "horizontal") { + // Get the width of the text + width = this.contents.textWidth(); + + if (width % this.layout.pageWidth > 0) { + width = Math.ceil(width / this.layout.pageWidth) * this.layout.pageWidth; + } + + if (this.settings.forceEvenPages) { + columns = width / this.layout.delta; + if (this.layout.divisor > 1 && this.layout.name === "reflowable" && columns % 2 > 0) { + // add a blank page + width += this.layout.gap + this.layout.columnWidth; + } + } + } // Expand Vertically + else if (this.settings.axis === "vertical") { + height = this.contents.textHeight(); + } + + // Only Resize if dimensions have changed or + // if Frame is still hidden, so needs reframing + if (this._needsReframe || width != this._width || height != this._height) { + this.reframe(width, height); + } + + this._expanding = false; + } + }, { + key: "reframe", + value: function reframe(width, height) { + var size; + + if ((0, _core.isNumber)(width)) { + this.element.style.width = width + "px"; + this.iframe.style.width = width + "px"; + this._width = width; + } + + if ((0, _core.isNumber)(height)) { + this.element.style.height = height + "px"; + this.iframe.style.height = height + "px"; + this._height = height; + } + + var widthDelta = this.prevBounds ? width - this.prevBounds.width : width; + var heightDelta = this.prevBounds ? height - this.prevBounds.height : height; + + size = { + width: width, + height: height, + widthDelta: widthDelta, + heightDelta: heightDelta + }; + + this.pane && this.pane.render(); + + this.onResize(this, size); + + this.emit(_constants.EVENTS.VIEWS.RESIZED, size); + + this.prevBounds = size; + + this.elementBounds = (0, _core.bounds)(this.element); + } + }, { + key: "load", + value: function load(contents) { + var loading = new _core.defer(); + var loaded = loading.promise; + + if (!this.iframe) { + loading.reject(new Error("No Iframe Available")); + return loaded; + } + + this.iframe.onload = function (event) { + + this.onLoad(event, loading); + }.bind(this); + + if (this.settings.method === "blobUrl") { + this.blobUrl = (0, _core.createBlobUrl)(contents, "application/xhtml+xml"); + this.iframe.src = this.blobUrl; + } else if (this.settings.method === "srcdoc") { + this.iframe.srcdoc = contents; + } else { + + this.document = this.iframe.contentDocument; + + if (!this.document) { + loading.reject(new Error("No Document Available")); + return loaded; + } + + this.iframe.contentDocument.open(); + this.iframe.contentDocument.write(contents); + this.iframe.contentDocument.close(); + } + + return loaded; + } + }, { + key: "onLoad", + value: function onLoad(event, promise) { + var _this2 = this; + + this.window = this.iframe.contentWindow; + this.document = this.iframe.contentDocument; + + this.contents = new _contents2.default(this.document, this.document.body, this.section.cfiBase, this.section.index); + + this.rendering = false; + + var link = this.document.querySelector("link[rel='canonical']"); + if (link) { + link.setAttribute("href", this.section.canonical); + } else { + link = this.document.createElement("link"); + link.setAttribute("rel", "canonical"); + link.setAttribute("href", this.section.canonical); + this.document.querySelector("head").appendChild(link); + } + + this.contents.on(_constants.EVENTS.CONTENTS.EXPAND, function () { + if (_this2.displayed && _this2.iframe) { + _this2.expand(); + if (_this2.contents) { + _this2.layout.format(_this2.contents); + } + } + }); + + this.contents.on(_constants.EVENTS.CONTENTS.RESIZE, function (e) { + if (_this2.displayed && _this2.iframe) { + _this2.expand(); + if (_this2.contents) { + _this2.layout.format(_this2.contents); + } + } + }); + + promise.resolve(this.contents); + } + }, { + key: "setLayout", + value: function setLayout(layout) { + this.layout = layout; + + if (this.contents) { + this.layout.format(this.contents); + this.expand(); + } + } + }, { + key: "setAxis", + value: function setAxis(axis) { + + // Force vertical for scrolled + if (this.layout.props.flow === "scrolled") { + axis = "vertical"; + } + + this.settings.axis = axis; + + if (axis == "horizontal") { + this.element.style.flex = "none"; + } else { + this.element.style.flex = "initial"; + } + + this.size(); + } + }, { + key: "addListeners", + value: function addListeners() { + //TODO: Add content listeners for expanding + } + }, { + key: "removeListeners", + value: function removeListeners(layoutFunc) { + //TODO: remove content listeners for expanding + } + }, { + key: "display", + value: function display(request) { + var displayed = new _core.defer(); + + if (!this.displayed) { + + this.render(request).then(function () { + + this.emit(_constants.EVENTS.VIEWS.DISPLAYED, this); + this.onDisplayed(this); + + this.displayed = true; + displayed.resolve(this); + }.bind(this), function (err) { + displayed.reject(err, this); + }); + } else { + displayed.resolve(this); + } + + return displayed.promise; + } + }, { + key: "show", + value: function show() { + + this.element.style.visibility = "visible"; + + if (this.iframe) { + this.iframe.style.visibility = "visible"; + } + + this.emit(_constants.EVENTS.VIEWS.SHOWN, this); + } + }, { + key: "hide", + value: function hide() { + // this.iframe.style.display = "none"; + this.element.style.visibility = "hidden"; + this.iframe.style.visibility = "hidden"; + + this.stopExpanding = true; + this.emit(_constants.EVENTS.VIEWS.HIDDEN, this); + } + }, { + key: "offset", + value: function offset() { + return { + top: this.element.offsetTop, + left: this.element.offsetLeft + }; + } + }, { + key: "width", + value: function width() { + return this._width; + } + }, { + key: "height", + value: function height() { + return this._height; + } + }, { + key: "position", + value: function position() { + return this.element.getBoundingClientRect(); + } + }, { + key: "locationOf", + value: function locationOf(target) { + var parentPos = this.iframe.getBoundingClientRect(); + var targetPos = this.contents.locationOf(target, this.settings.ignoreClass); + + return { + "left": targetPos.left, + "top": targetPos.top + }; + } + }, { + key: "onDisplayed", + value: function onDisplayed(view) { + // Stub, override with a custom functions + } + }, { + key: "onResize", + value: function onResize(view, e) { + // Stub, override with a custom functions + } + }, { + key: "bounds", + value: function bounds(force) { + if (force || !this.elementBounds) { + this.elementBounds = (0, _core.bounds)(this.element); + } + + return this.elementBounds; + } + }, { + key: "highlight", + value: function highlight(cfiRange) { + var _this3 = this; + + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var cb = arguments[2]; + + if (!this.contents) { + return; + } + var range = this.contents.range(cfiRange); + + var emitter = function emitter() { + _this3.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); + }; + + data["epubcfi"] = cfiRange; + + if (!this.pane) { + this.pane = new _marksPane.Pane(this.iframe, this.element); + } + + var m = new _marksPane.Highlight(range, "epubjs-hl", data, { 'fill': 'yellow', 'fill-opacity': '0.3', 'mix-blend-mode': 'multiply' }); + var h = this.pane.addMark(m); + + this.highlights[cfiRange] = { "mark": h, "element": h.element, "listeners": [emitter, cb] }; + + h.element.setAttribute("ref", "epubjs-hl"); + h.element.addEventListener("click", emitter); + h.element.addEventListener("touchstart", emitter); + + if (cb) { + h.element.addEventListener("click", cb); + h.element.addEventListener("touchstart", cb); + } + return h; + } + }, { + key: "underline", + value: function underline(cfiRange) { + var _this4 = this; + + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var cb = arguments[2]; + + if (!this.contents) { + return; + } + var range = this.contents.range(cfiRange); + var emitter = function emitter() { + _this4.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); + }; + + data["epubcfi"] = cfiRange; + + if (!this.pane) { + this.pane = new _marksPane.Pane(this.iframe, this.element); + } + + var m = new _marksPane.Underline(range, "epubjs-ul", data, { 'stroke': 'black', 'stroke-opacity': '0.3', 'mix-blend-mode': 'multiply' }); + var h = this.pane.addMark(m); + + this.underlines[cfiRange] = { "mark": h, "element": h.element, "listeners": [emitter, cb] }; + + h.element.setAttribute("ref", "epubjs-ul"); + h.element.addEventListener("click", emitter); + h.element.addEventListener("touchstart", emitter); + + if (cb) { + h.element.addEventListener("click", cb); + h.element.addEventListener("touchstart", cb); + } + return h; + } + }, { + key: "mark", + value: function mark(cfiRange) { + var _this5 = this; + + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var cb = arguments[2]; + + + if (!this.contents) { + return; + } + + if (cfiRange in this.marks) { + var item = this.marks[cfiRange]; + return item; + } + + var range = this.contents.range(cfiRange); + if (!range) { + return; + } + var container = range.commonAncestorContainer; + var parent = container.nodeType === 1 ? container : container.parentNode; + + var emitter = function emitter(e) { + _this5.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); + }; + + if (range.collapsed && container.nodeType === 1) { + range = new Range(); + range.selectNodeContents(container); + } else if (range.collapsed) { + // Webkit doesn't like collapsed ranges + range = new Range(); + range.selectNodeContents(parent); + } + + var top = void 0, + right = void 0, + left = void 0; + + if (this.layout.name === "pre-paginated" || this.settings.axis !== "horizontal") { + var pos = range.getBoundingClientRect(); + top = pos.top; + right = pos.right; + } else { + // Element might break columns, so find the left most element + var rects = range.getClientRects(); + var rect = void 0; + for (var i = 0; i != rects.length; i++) { + rect = rects[i]; + if (!left || rect.left < left) { + left = rect.left; + right = left + this.layout.columnWidth - this.layout.gap; + top = rect.top; + } + } + } + + var mark = this.document.createElement('a'); + mark.setAttribute("ref", "epubjs-mk"); + mark.style.position = "absolute"; + mark.style.top = top + "px"; + mark.style.left = right + "px"; + + mark.dataset["epubcfi"] = cfiRange; + + if (data) { + Object.keys(data).forEach(function (key) { + mark.dataset[key] = data[key]; + }); + } + + if (cb) { + mark.addEventListener("click", cb); + mark.addEventListener("touchstart", cb); + } + + mark.addEventListener("click", emitter); + mark.addEventListener("touchstart", emitter); + + this.element.appendChild(mark); + + this.marks[cfiRange] = { "element": mark, "listeners": [emitter, cb] }; + + return parent; + } + }, { + key: "unhighlight", + value: function unhighlight(cfiRange) { + var item = void 0; + if (cfiRange in this.highlights) { + item = this.highlights[cfiRange]; + + this.pane.removeMark(item.mark); + item.listeners.forEach(function (l) { + if (l) { + item.element.removeEventListener("click", l); + }; + }); + delete this.highlights[cfiRange]; + } + } + }, { + key: "ununderline", + value: function ununderline(cfiRange) { + var item = void 0; + if (cfiRange in this.underlines) { + item = this.underlines[cfiRange]; + this.pane.removeMark(item.mark); + item.listeners.forEach(function (l) { + if (l) { + item.element.removeEventListener("click", l); + }; + }); + delete this.underlines[cfiRange]; + } + } + }, { + key: "unmark", + value: function unmark(cfiRange) { + var item = void 0; + if (cfiRange in this.marks) { + item = this.marks[cfiRange]; + this.element.removeChild(item.element); + item.listeners.forEach(function (l) { + if (l) { + item.element.removeEventListener("click", l); + }; + }); + delete this.marks[cfiRange]; + } + } + }, { + key: "destroy", + value: function destroy() { + + for (var cfiRange in this.highlights) { + this.unhighlight(cfiRange); + } + + for (var _cfiRange in this.underlines) { + this.ununderline(_cfiRange); + } + + for (var _cfiRange2 in this.marks) { + this.unmark(_cfiRange2); + } + + if (this.blobUrl) { + (0, _core.revokeBlobUrl)(this.blobUrl); + } + + if (this.displayed) { + this.displayed = false; + + this.removeListeners(); + + this.stopExpanding = true; + this.element.removeChild(this.iframe); + + this.iframe = null; + + this._textWidth = null; + this._textHeight = null; + this._width = null; + this._height = null; + } + // this.element.style.height = "0px"; + // this.element.style.width = "0px"; + } + }]); + + return IframeView; +}(); + +(0, _eventEmitter2.default)(IframeView.prototype); + +exports.default = IframeView; +module.exports = exports["default"]; + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +var isObject = __webpack_require__(15), + now = __webpack_require__(58), + toNumber = __webpack_require__(60); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +module.exports = debounce; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +var freeGlobal = __webpack_require__(59); + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +module.exports = root; + + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +var root = __webpack_require__(22); + +/** Built-in value references. */ +var Symbol = root.Symbol; + +module.exports = Symbol; + + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +var _default = __webpack_require__(14); + +var _default2 = _interopRequireDefault(_default); + +var _constants = __webpack_require__(3); + +var _debounce = __webpack_require__(21); + +var _debounce2 = _interopRequireDefault(_debounce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var ContinuousViewManager = function (_DefaultViewManager) { + _inherits(ContinuousViewManager, _DefaultViewManager); + + function ContinuousViewManager(options) { + _classCallCheck(this, ContinuousViewManager); + + var _this = _possibleConstructorReturn(this, (ContinuousViewManager.__proto__ || Object.getPrototypeOf(ContinuousViewManager)).call(this, options)); + + _this.name = "continuous"; + + _this.settings = (0, _core.extend)(_this.settings || {}, { + infinite: true, + overflow: undefined, + axis: undefined, + flow: "scrolled", + offset: 500, + offsetDelta: 250, + width: undefined, + height: undefined + }); + + (0, _core.extend)(_this.settings, options.settings || {}); + + // Gap can be 0, but defaults doesn't handle that + if (options.settings.gap != "undefined" && options.settings.gap === 0) { + _this.settings.gap = options.settings.gap; + } + + _this.viewSettings = { + ignoreClass: _this.settings.ignoreClass, + axis: _this.settings.axis, + flow: _this.settings.flow, + layout: _this.layout, + width: 0, + height: 0, + forceEvenPages: false + }; + + _this.scrollTop = 0; + _this.scrollLeft = 0; + return _this; + } + + _createClass(ContinuousViewManager, [{ + key: "display", + value: function display(section, target) { + return _default2.default.prototype.display.call(this, section, target).then(function () { + return this.fill(); + }.bind(this)); + } + }, { + key: "fill", + value: function fill(_full) { + var _this2 = this; + + var full = _full || new _core.defer(); + + this.q.enqueue(function () { + return _this2.check(); + }).then(function (result) { + if (result) { + _this2.fill(full); + } else { + full.resolve(); + } + }); + + return full.promise; + } + }, { + key: "moveTo", + value: function moveTo(offset) { + // var bounds = this.stage.bounds(); + // var dist = Math.floor(offset.top / bounds.height) * bounds.height; + var distX = 0, + distY = 0; + + var offsetX = 0, + offsetY = 0; + + if (!this.isPaginated) { + distY = offset.top; + offsetY = offset.top + this.settings.offset; + } else { + distX = Math.floor(offset.left / this.layout.delta) * this.layout.delta; + offsetX = distX + this.settings.offset; + } + + if (distX > 0 || distY > 0) { + this.scrollBy(distX, distY, true); + } + } + }, { + key: "afterResized", + value: function afterResized(view) { + this.emit(_constants.EVENTS.MANAGERS.RESIZE, view.section); + } + + // Remove Previous Listeners if present + + }, { + key: "removeShownListeners", + value: function removeShownListeners(view) { + + // view.off("shown", this.afterDisplayed); + // view.off("shown", this.afterDisplayedAbove); + view.onDisplayed = function () {}; + } + }, { + key: "add", + value: function add(section) { + var _this3 = this; + + var view = this.createView(section); + + this.views.append(view); + + view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) { + view.expanded = true; + }); + + view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) { + _this3.updateAxis(axis); + }); + + // view.on(EVENTS.VIEWS.SHOWN, this.afterDisplayed.bind(this)); + view.onDisplayed = this.afterDisplayed.bind(this); + view.onResize = this.afterResized.bind(this); + + return view.display(this.request); + } + }, { + key: "append", + value: function append(section) { + var view = this.createView(section); + + view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) { + view.expanded = true; + }); + + /* + view.on(EVENTS.VIEWS.AXIS, (axis) => { + this.updateAxis(axis); + }); + */ + + this.views.append(view); + + view.onDisplayed = this.afterDisplayed.bind(this); + + return view; + } + }, { + key: "prepend", + value: function prepend(section) { + var _this4 = this; + + var view = this.createView(section); + + view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) { + _this4.counter(bounds); + view.expanded = true; + }); + + /* + view.on(EVENTS.VIEWS.AXIS, (axis) => { + this.updateAxis(axis); + }); + */ + + this.views.prepend(view); + + view.onDisplayed = this.afterDisplayed.bind(this); + + return view; + } + }, { + key: "counter", + value: function counter(bounds) { + if (this.settings.axis === "vertical") { + this.scrollBy(0, bounds.heightDelta, true); + } else { + this.scrollBy(bounds.widthDelta, 0, true); + } + } + }, { + key: "update", + value: function update(_offset) { + var container = this.bounds(); + var views = this.views.all(); + var viewsLength = views.length; + var visible = []; + var offset = typeof _offset != "undefined" ? _offset : this.settings.offset || 0; + var isVisible; + var view; + + var updating = new _core.defer(); + var promises = []; + for (var i = 0; i < viewsLength; i++) { + view = views[i]; + + isVisible = this.isVisible(view, offset, offset, container); + + if (isVisible === true) { + // console.log("visible " + view.index); + + if (!view.displayed) { + var displayed = view.display(this.request).then(function (view) { + view.show(); + }, function (err) { + view.hide(); + }); + promises.push(displayed); + } else { + view.show(); + } + visible.push(view); + } else { + this.q.enqueue(view.destroy.bind(view)); + // console.log("hidden " + view.index); + + clearTimeout(this.trimTimeout); + this.trimTimeout = setTimeout(function () { + this.q.enqueue(this.trim.bind(this)); + }.bind(this), 250); + } + } + + if (promises.length) { + return Promise.all(promises).catch(function (err) { + updating.reject(err); + }); + } else { + updating.resolve(); + return updating.promise; + } + } + }, { + key: "check", + value: function check(_offsetLeft, _offsetTop) { + var _this5 = this; + + var checking = new _core.defer(); + var newViews = []; + + var horizontal = this.settings.axis === "horizontal"; + var delta = this.settings.offset || 0; + + if (_offsetLeft && horizontal) { + delta = _offsetLeft; + } + + if (_offsetTop && !horizontal) { + delta = _offsetTop; + } + + var bounds = this._bounds; // bounds saved this until resize + + var rtl = this.settings.direction === "rtl"; + var dir = horizontal && rtl ? -1 : 1; //RTL reverses scrollTop + + var offset = horizontal ? this.scrollLeft : this.scrollTop * dir; + var visibleLength = horizontal ? bounds.width : bounds.height; + var contentLength = horizontal ? this.container.scrollWidth : this.container.scrollHeight; + + var prepend = function prepend() { + var first = _this5.views.first(); + var prev = first && first.section.prev(); + + if (prev) { + newViews.push(_this5.prepend(prev)); + } + }; + + var append = function append() { + var last = _this5.views.last(); + var next = last && last.section.next(); + + if (next) { + newViews.push(_this5.append(next)); + } + }; + + if (offset + visibleLength + delta >= contentLength) { + if (horizontal && rtl) { + prepend(); + } else { + append(); + } + } + + if (offset - delta < 0) { + if (horizontal && rtl) { + append(); + } else { + prepend(); + } + } + + var promises = newViews.map(function (view) { + return view.displayed; + }); + + if (newViews.length) { + return Promise.all(promises).then(function () { + if (_this5.layout.name === "pre-paginated" && _this5.layout.props.spread) { + return _this5.check(); + } + }).then(function () { + // Check to see if anything new is on screen after rendering + return _this5.update(delta); + }, function (err) { + return err; + }); + } else { + this.q.enqueue(function () { + this.update(); + }.bind(this)); + checking.resolve(false); + return checking.promise; + } + } + }, { + key: "trim", + value: function trim() { + var task = new _core.defer(); + var displayed = this.views.displayed(); + var first = displayed[0]; + var last = displayed[displayed.length - 1]; + var firstIndex = this.views.indexOf(first); + var lastIndex = this.views.indexOf(last); + var above = this.views.slice(0, firstIndex); + var below = this.views.slice(lastIndex + 1); + + // Erase all but last above + for (var i = 0; i < above.length - 1; i++) { + this.erase(above[i], above); + } + + // Erase all except first below + for (var j = 1; j < below.length; j++) { + this.erase(below[j]); + } + + task.resolve(); + return task.promise; + } + }, { + key: "erase", + value: function erase(view, above) { + //Trim + + var prevTop; + var prevLeft; + + if (this.settings.height) { + prevTop = this.container.scrollTop; + prevLeft = this.container.scrollLeft; + } else { + prevTop = window.scrollY; + prevLeft = window.scrollX; + } + + var bounds = view.bounds(); + + this.views.remove(view); + + if (above) { + if (this.settings.axis === "vertical") { + this.scrollTo(0, prevTop - bounds.height, true); + } else { + this.scrollTo(prevLeft - bounds.width, 0, true); + } + } + } + }, { + key: "addEventListeners", + value: function addEventListeners(stage) { + + window.addEventListener("unload", function (e) { + this.ignore = true; + // this.scrollTo(0,0); + this.destroy(); + }.bind(this)); + + this.addScrollListeners(); + } + }, { + key: "addScrollListeners", + value: function addScrollListeners() { + var scroller; + + this.tick = _core.requestAnimationFrame; + + if (this.settings.height) { + this.prevScrollTop = this.container.scrollTop; + this.prevScrollLeft = this.container.scrollLeft; + } else { + this.prevScrollTop = window.scrollY; + this.prevScrollLeft = window.scrollX; + } + + this.scrollDeltaVert = 0; + this.scrollDeltaHorz = 0; + + if (this.settings.height) { + scroller = this.container; + this.scrollTop = this.container.scrollTop; + this.scrollLeft = this.container.scrollLeft; + } else { + scroller = window; + this.scrollTop = window.scrollY; + this.scrollLeft = window.scrollX; + } + + scroller.addEventListener("scroll", this.onScroll.bind(this)); + this._scrolled = (0, _debounce2.default)(this.scrolled.bind(this), 30); + // this.tick.call(window, this.onScroll.bind(this)); + + this.didScroll = false; + } + }, { + key: "removeEventListeners", + value: function removeEventListeners() { + var scroller; + + if (this.settings.height) { + scroller = this.container; + } else { + scroller = window; + } + + scroller.removeEventListener("scroll", this.onScroll.bind(this)); + } + }, { + key: "onScroll", + value: function onScroll() { + var scrollTop = void 0; + var scrollLeft = void 0; + var dir = this.settings.direction === "rtl" ? -1 : 1; + + if (this.settings.height) { + scrollTop = this.container.scrollTop; + scrollLeft = this.container.scrollLeft; + } else { + scrollTop = window.scrollY * dir; + scrollLeft = window.scrollX * dir; + } + + this.scrollTop = scrollTop; + this.scrollLeft = scrollLeft; + + if (!this.ignore) { + + this._scrolled(); + } else { + this.ignore = false; + } + + this.scrollDeltaVert += Math.abs(scrollTop - this.prevScrollTop); + this.scrollDeltaHorz += Math.abs(scrollLeft - this.prevScrollLeft); + + this.prevScrollTop = scrollTop; + this.prevScrollLeft = scrollLeft; + + clearTimeout(this.scrollTimeout); + this.scrollTimeout = setTimeout(function () { + this.scrollDeltaVert = 0; + this.scrollDeltaHorz = 0; + }.bind(this), 150); + + this.didScroll = false; + } + }, { + key: "scrolled", + value: function scrolled() { + this.q.enqueue(function () { + this.check(); + }.bind(this)); + + this.emit(_constants.EVENTS.MANAGERS.SCROLL, { + top: this.scrollTop, + left: this.scrollLeft + }); + + clearTimeout(this.afterScrolled); + this.afterScrolled = setTimeout(function () { + this.emit(_constants.EVENTS.MANAGERS.SCROLLED, { + top: this.scrollTop, + left: this.scrollLeft + }); + }.bind(this)); + } + }, { + key: "next", + value: function next() { + + var dir = this.settings.direction; + var delta = this.layout.props.name === "pre-paginated" && this.layout.props.spread ? this.layout.props.delta * 2 : this.layout.props.delta; + + if (!this.views.length) return; + + if (this.isPaginated && this.settings.axis === "horizontal") { + + this.scrollBy(delta, 0, true); + } else { + + this.scrollBy(0, this.layout.height, true); + } + + this.q.enqueue(function () { + this.check(); + }.bind(this)); + } + }, { + key: "prev", + value: function prev() { + + var dir = this.settings.direction; + var delta = this.layout.props.name === "pre-paginated" && this.layout.props.spread ? this.layout.props.delta * 2 : this.layout.props.delta; + + if (!this.views.length) return; + + if (this.isPaginated && this.settings.axis === "horizontal") { + + this.scrollBy(-delta, 0, true); + } else { + + this.scrollBy(0, -this.layout.height, true); + } + + this.q.enqueue(function () { + this.check(); + }.bind(this)); + } + }, { + key: "updateAxis", + value: function updateAxis(axis, forceUpdate) { + + if (!this.isPaginated) { + axis = "vertical"; + } + + if (!forceUpdate && axis === this.settings.axis) { + return; + } + + this.settings.axis = axis; + + this.stage && this.stage.axis(axis); + + this.viewSettings.axis = axis; + + if (this.mapping) { + this.mapping.axis(axis); + } + + if (this.layout) { + if (axis === "vertical") { + this.layout.spread("none"); + } else { + this.layout.spread(this.layout.settings.spread); + } + } + + if (axis === "vertical") { + this.settings.infinite = true; + } else { + this.settings.infinite = false; + } + } + }]); + + return ContinuousViewManager; +}(_default2.default); + +exports.default = ContinuousViewManager; +module.exports = exports["default"]; + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _book = __webpack_require__(26); + +var _book2 = _interopRequireDefault(_book); + +var _rendition = __webpack_require__(18); + +var _rendition2 = _interopRequireDefault(_rendition); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _contents = __webpack_require__(13); + +var _contents2 = _interopRequireDefault(_contents); + +var _core = __webpack_require__(0); + +var utils = _interopRequireWildcard(_core); + +__webpack_require__(69); + +var _iframe = __webpack_require__(20); + +var _iframe2 = _interopRequireDefault(_iframe); + +var _default = __webpack_require__(14); + +var _default2 = _interopRequireDefault(_default); + +var _continuous = __webpack_require__(24); + +var _continuous2 = _interopRequireDefault(_continuous); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Creates a new Book + * @param {string|ArrayBuffer} url URL, Path or ArrayBuffer + * @param {object} options to pass to the book + * @returns {Book} a new Book object + * @example ePub("/path/to/book.epub", {}) + */ +function ePub(url, options) { + return new _book2.default(url, options); +} + +ePub.VERSION = "0.3"; + +if (typeof global !== "undefined") { + global.EPUBJS_VERSION = ePub.VERSION; +} + +ePub.Book = _book2.default; +ePub.Rendition = _rendition2.default; +ePub.Contents = _contents2.default; +ePub.CFI = _epubcfi2.default; +ePub.utils = utils; + +exports.default = ePub; +module.exports = exports["default"]; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +var _core = __webpack_require__(0); + +var _url = __webpack_require__(5); + +var _url2 = _interopRequireDefault(_url); + +var _path = __webpack_require__(4); + +var _path2 = _interopRequireDefault(_path); + +var _spine = __webpack_require__(42); + +var _spine2 = _interopRequireDefault(_spine); + +var _locations = __webpack_require__(44); + +var _locations2 = _interopRequireDefault(_locations); + +var _container = __webpack_require__(45); + +var _container2 = _interopRequireDefault(_container); + +var _packaging = __webpack_require__(46); + +var _packaging2 = _interopRequireDefault(_packaging); + +var _navigation = __webpack_require__(47); + +var _navigation2 = _interopRequireDefault(_navigation); + +var _resources = __webpack_require__(48); + +var _resources2 = _interopRequireDefault(_resources); + +var _pagelist = __webpack_require__(49); + +var _pagelist2 = _interopRequireDefault(_pagelist); + +var _rendition = __webpack_require__(18); + +var _rendition2 = _interopRequireDefault(_rendition); + +var _archive = __webpack_require__(67); + +var _archive2 = _interopRequireDefault(_archive); + +var _request2 = __webpack_require__(11); + +var _request3 = _interopRequireDefault(_request2); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _constants = __webpack_require__(3); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var CONTAINER_PATH = "META-INF/container.xml"; +var EPUBJS_VERSION = "0.3"; + +var INPUT_TYPE = { + BINARY: "binary", + BASE64: "base64", + EPUB: "epub", + OPF: "opf", + MANIFEST: "json", + DIRECTORY: "directory" +}; + +/** + * An Epub representation with methods for the loading, parsing and manipulation + * of its contents. + * @class + * @param {string} [url] + * @param {object} [options] + * @param {method} [options.requestMethod] a request function to use instead of the default + * @param {boolean} [options.requestCredentials=undefined] send the xhr request withCredentials + * @param {object} [options.requestHeaders=undefined] send the xhr request headers + * @param {string} [options.encoding=binary] optional to pass 'binary' or base64' for archived Epubs + * @param {string} [options.replacements=none] use base64, blobUrl, or none for replacing assets in archived Epubs + * @param {method} [options.canonical] optional function to determine canonical urls for a path + * @returns {Book} + * @example new Book("/path/to/book.epub", {}) + * @example new Book({ replacements: "blobUrl" }) + */ + +var Book = function () { + function Book(url, options) { + var _this = this; + + _classCallCheck(this, Book); + + // Allow passing just options to the Book + if (typeof options === "undefined" && (typeof url === "undefined" ? "undefined" : _typeof(url)) === "object") { + options = url; + url = undefined; + } + + this.settings = (0, _core.extend)(this.settings || {}, { + requestMethod: undefined, + requestCredentials: undefined, + requestHeaders: undefined, + encoding: undefined, + replacements: undefined, + canonical: undefined + }); + + (0, _core.extend)(this.settings, options); + + // Promises + this.opening = new _core.defer(); + /** + * @member {promise} opened returns after the book is loaded + * @memberof Book + */ + this.opened = this.opening.promise; + this.isOpen = false; + + this.loading = { + manifest: new _core.defer(), + spine: new _core.defer(), + metadata: new _core.defer(), + cover: new _core.defer(), + navigation: new _core.defer(), + pageList: new _core.defer(), + resources: new _core.defer() + }; + + this.loaded = { + manifest: this.loading.manifest.promise, + spine: this.loading.spine.promise, + metadata: this.loading.metadata.promise, + cover: this.loading.cover.promise, + navigation: this.loading.navigation.promise, + pageList: this.loading.pageList.promise, + resources: this.loading.resources.promise + }; + + /** + * @member {promise} ready returns after the book is loaded and parsed + * @memberof Book + * @private + */ + this.ready = Promise.all([this.loaded.manifest, this.loaded.spine, this.loaded.metadata, this.loaded.cover, this.loaded.navigation, this.loaded.resources]); + + // Queue for methods used before opening + this.isRendered = false; + // this._q = queue(this); + + /** + * @member {method} request + * @memberof Book + * @private + */ + this.request = this.settings.requestMethod || _request3.default; + + /** + * @member {Spine} spine + * @memberof Book + */ + this.spine = new _spine2.default(); + + /** + * @member {Locations} locations + * @memberof Book + */ + this.locations = new _locations2.default(this.spine, this.load.bind(this)); + + /** + * @member {Navigation} navigation + * @memberof Book + */ + this.navigation = undefined; + + /** + * @member {PageList} pagelist + * @memberof Book + */ + this.pageList = undefined; + + /** + * @member {Url} url + * @memberof Book + * @private + */ + this.url = undefined; + + /** + * @member {Path} path + * @memberof Book + * @private + */ + this.path = undefined; + + /** + * @member {boolean} archived + * @memberof Book + * @private + */ + this.archived = false; + + /** + * @member {Archive} archive + * @memberof Book + * @private + */ + this.archive = undefined; + + /** + * @member {Resources} resources + * @memberof Book + * @private + */ + this.resources = undefined; + + /** + * @member {Rendition} rendition + * @memberof Book + * @private + */ + this.rendition = undefined; + + /** + * @member {Container} container + * @memberof Book + * @private + */ + this.container = undefined; + + /** + * @member {Packaging} packaging + * @memberof Book + * @private + */ + this.packaging = undefined; + + // this.toc = undefined; + + if (url) { + this.open(url).catch(function (error) { + var err = new Error("Cannot load book at " + url); + _this.emit(_constants.EVENTS.BOOK.OPEN_FAILED, err); + }); + } + } + + /** + * Open a epub or url + * @param {string | ArrayBuffer} input Url, Path or ArrayBuffer + * @param {string} [what="binary", "base64", "epub", "opf", "json", "directory"] force opening as a certain type + * @returns {Promise} of when the book has been loaded + * @example book.open("/path/to/book.epub") + */ + + + _createClass(Book, [{ + key: "open", + value: function open(input, what) { + var opening; + var type = what || this.determineType(input); + + if (type === INPUT_TYPE.BINARY) { + this.archived = true; + this.url = new _url2.default("/", ""); + opening = this.openEpub(input); + } else if (type === INPUT_TYPE.BASE64) { + this.archived = true; + this.url = new _url2.default("/", ""); + opening = this.openEpub(input, type); + } else if (type === INPUT_TYPE.EPUB) { + this.archived = true; + this.url = new _url2.default("/", ""); + opening = this.request(input, "binary").then(this.openEpub.bind(this)); + } else if (type == INPUT_TYPE.OPF) { + this.url = new _url2.default(input); + opening = this.openPackaging(this.url.Path.toString()); + } else if (type == INPUT_TYPE.MANIFEST) { + this.url = new _url2.default(input); + opening = this.openManifest(this.url.Path.toString()); + } else { + this.url = new _url2.default(input); + opening = this.openContainer(CONTAINER_PATH).then(this.openPackaging.bind(this)); + } + + return opening; + } + + /** + * Open an archived epub + * @private + * @param {binary} data + * @param {string} [encoding] + * @return {Promise} + */ + + }, { + key: "openEpub", + value: function openEpub(data, encoding) { + var _this2 = this; + + return this.unarchive(data, encoding || this.settings.encoding).then(function () { + return _this2.openContainer(CONTAINER_PATH); + }).then(function (packagePath) { + return _this2.openPackaging(packagePath); + }); + } + + /** + * Open the epub container + * @private + * @param {string} url + * @return {string} packagePath + */ + + }, { + key: "openContainer", + value: function openContainer(url) { + var _this3 = this; + + return this.load(url).then(function (xml) { + _this3.container = new _container2.default(xml); + return _this3.resolve(_this3.container.packagePath); + }); + } + + /** + * Open the Open Packaging Format Xml + * @private + * @param {string} url + * @return {Promise} + */ + + }, { + key: "openPackaging", + value: function openPackaging(url) { + var _this4 = this; + + this.path = new _path2.default(url); + return this.load(url).then(function (xml) { + _this4.packaging = new _packaging2.default(xml); + return _this4.unpack(_this4.packaging); + }); + } + + /** + * Open the manifest JSON + * @private + * @param {string} url + * @return {Promise} + */ + + }, { + key: "openManifest", + value: function openManifest(url) { + var _this5 = this; + + this.path = new _path2.default(url); + return this.load(url).then(function (json) { + _this5.packaging = new _packaging2.default(); + _this5.packaging.load(json); + return _this5.unpack(_this5.packaging); + }); + } + + /** + * Load a resource from the Book + * @param {string} path path to the resource to load + * @return {Promise} returns a promise with the requested resource + */ + + }, { + key: "load", + value: function load(path) { + var resolved; + + if (this.archived) { + resolved = this.resolve(path); + return this.archive.request(resolved); + } else { + resolved = this.resolve(path); + return this.request(resolved, null, this.settings.requestCredentials, this.settings.requestHeaders); + } + } + + /** + * Resolve a path to it's absolute position in the Book + * @param {string} path + * @param {boolean} [absolute] force resolving the full URL + * @return {string} the resolved path string + */ + + }, { + key: "resolve", + value: function resolve(path, absolute) { + if (!path) { + return; + } + var resolved = path; + var isAbsolute = path.indexOf("://") > -1; + + if (isAbsolute) { + return path; + } + + if (this.path) { + resolved = this.path.resolve(path); + } + + if (absolute != false && this.url) { + resolved = this.url.resolve(resolved); + } + + return resolved; + } + + /** + * Get a canonical link to a path + * @param {string} path + * @return {string} the canonical path string + */ + + }, { + key: "canonical", + value: function canonical(path) { + var url = path; + + if (!path) { + return ""; + } + + if (this.settings.canonical) { + url = this.settings.canonical(path); + } else { + url = this.resolve(path, true); + } + + return url; + } + + /** + * Determine the type of they input passed to open + * @private + * @param {string} input + * @return {string} binary | directory | epub | opf + */ + + }, { + key: "determineType", + value: function determineType(input) { + var url; + var path; + var extension; + + if (this.settings.encoding === "base64") { + return INPUT_TYPE.BASE64; + } + + if (typeof input != "string") { + return INPUT_TYPE.BINARY; + } + + url = new _url2.default(input); + path = url.path(); + extension = path.extension; + + if (!extension) { + return INPUT_TYPE.DIRECTORY; + } + + if (extension === "epub") { + return INPUT_TYPE.EPUB; + } + + if (extension === "opf") { + return INPUT_TYPE.OPF; + } + + if (extension === "json") { + return INPUT_TYPE.MANIFEST; + } + } + + /** + * unpack the contents of the Books packageXml + * @private + * @param {document} packageXml XML Document + */ + + }, { + key: "unpack", + value: function unpack(opf) { + var _this6 = this; + + this.package = opf; + + this.spine.unpack(this.package, this.resolve.bind(this), this.canonical.bind(this)); + + this.resources = new _resources2.default(this.package.manifest, { + archive: this.archive, + resolver: this.resolve.bind(this), + request: this.request.bind(this), + replacements: this.settings.replacements || (this.archived ? "blobUrl" : "base64") + }); + + this.loadNavigation(this.package).then(function () { + // this.toc = this.navigation.toc; + _this6.loading.navigation.resolve(_this6.navigation); + }); + + if (this.package.coverPath) { + this.cover = this.resolve(this.package.coverPath); + } + // Resolve promises + this.loading.manifest.resolve(this.package.manifest); + this.loading.metadata.resolve(this.package.metadata); + this.loading.spine.resolve(this.spine); + this.loading.cover.resolve(this.cover); + this.loading.resources.resolve(this.resources); + this.loading.pageList.resolve(this.pageList); + + this.isOpen = true; + + if (this.archived || this.settings.replacements && this.settings.replacements != "none") { + this.replacements().then(function () { + _this6.opening.resolve(_this6); + }).catch(function (err) { + console.error(err); + }); + } else { + // Resolve book opened promise + this.opening.resolve(this); + } + } + + /** + * Load Navigation and PageList from package + * @private + * @param {document} opf XML Document + */ + + }, { + key: "loadNavigation", + value: function loadNavigation(opf) { + var _this7 = this; + + var navPath = opf.navPath || opf.ncxPath; + var toc = opf.toc; + + // From json manifest + if (toc) { + return new Promise(function (resolve, reject) { + _this7.navigation = new _navigation2.default(toc); + + if (opf.pageList) { + _this7.pageList = new _pagelist2.default(opf.pageList); // TODO: handle page lists from Manifest + } + + resolve(_this7.navigation); + }); + } + + if (!navPath) { + return new Promise(function (resolve, reject) { + _this7.navigation = new _navigation2.default(); + _this7.pageList = new _pagelist2.default(); + + resolve(_this7.navigation); + }); + } + + return this.load(navPath, "xml").then(function (xml) { + _this7.navigation = new _navigation2.default(xml); + _this7.pageList = new _pagelist2.default(xml); + return _this7.navigation; + }); + } + + /** + * Gets a Section of the Book from the Spine + * Alias for `book.spine.get` + * @param {string} target + * @return {Section} + */ + + }, { + key: "section", + value: function section(target) { + return this.spine.get(target); + } + + /** + * Sugar to render a book to an element + * @param {element | string} element element or string to add a rendition to + * @param {object} [options] + * @return {Rendition} + */ + + }, { + key: "renderTo", + value: function renderTo(element, options) { + this.rendition = new _rendition2.default(this, options); + this.rendition.attachTo(element); + + return this.rendition; + } + + /** + * Set if request should use withCredentials + * @param {boolean} credentials + */ + + }, { + key: "setRequestCredentials", + value: function setRequestCredentials(credentials) { + this.settings.requestCredentials = credentials; + } + + /** + * Set headers request should use + * @param {object} headers + */ + + }, { + key: "setRequestHeaders", + value: function setRequestHeaders(headers) { + this.settings.requestHeaders = headers; + } + + /** + * Unarchive a zipped epub + * @private + * @param {binary} input epub data + * @param {string} [encoding] + * @return {Archive} + */ + + }, { + key: "unarchive", + value: function unarchive(input, encoding) { + this.archive = new _archive2.default(); + return this.archive.open(input, encoding); + } + + /** + * Get the cover url + * @return {string} coverUrl + */ + + }, { + key: "coverUrl", + value: function coverUrl() { + var _this8 = this; + + var retrieved = this.loaded.cover.then(function (url) { + if (_this8.archived) { + // return this.archive.createUrl(this.cover); + return _this8.resources.get(_this8.cover); + } else { + return _this8.cover; + } + }); + + return retrieved; + } + + /** + * Load replacement urls + * @private + * @return {Promise} completed loading urls + */ + + }, { + key: "replacements", + value: function replacements() { + var _this9 = this; + + this.spine.hooks.serialize.register(function (output, section) { + section.output = _this9.resources.substitute(output, section.url); + }); + + return this.resources.replacements().then(function () { + return _this9.resources.replaceCss(); + }); + } + + /** + * Find a DOM Range for a given CFI Range + * @param {EpubCFI} cfiRange a epub cfi range + * @return {Range} + */ + + }, { + key: "getRange", + value: function getRange(cfiRange) { + var cfi = new _epubcfi2.default(cfiRange); + var item = this.spine.get(cfi.spinePos); + var _request = this.load.bind(this); + if (!item) { + return new Promise(function (resolve, reject) { + reject("CFI could not be found"); + }); + } + return item.load(_request).then(function (contents) { + var range = cfi.toRange(item.document); + return range; + }); + } + + /** + * Generates the Book Key using the identifer in the manifest or other string provided + * @param {string} [identifier] to use instead of metadata identifier + * @return {string} key + */ + + }, { + key: "key", + value: function key(identifier) { + var ident = identifier || this.package.metadata.identifier || this.url.filename; + return "epubjs:" + EPUBJS_VERSION + ":" + ident; + } + + /** + * Destroy the Book and all associated objects + */ + + }, { + key: "destroy", + value: function destroy() { + this.opened = undefined; + this.loading = undefined; + this.loaded = undefined; + this.ready = undefined; + + this.isOpen = false; + this.isRendered = false; + + this.spine && this.spine.destroy(); + this.locations && this.locations.destroy(); + this.pageList && this.pageList.destroy(); + this.archive && this.archive.destroy(); + this.resources && this.resources.destroy(); + this.container && this.container.destroy(); + this.packaging && this.packaging.destroy(); + this.rendition && this.rendition.destroy(); + + this.spine = undefined; + this.locations = undefined; + this.pageList = undefined; + this.archive = undefined; + this.resources = undefined; + this.container = undefined; + this.packaging = undefined; + this.rendition = undefined; + + this.navigation = undefined; + this.url = undefined; + this.path = undefined; + this.archived = false; + } + }]); + + return Book; +}(); + +//-- Enable binding events to book + + +(0, _eventEmitter2.default)(Book.prototype); + +exports.default = Book; +module.exports = exports["default"]; + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var assign = __webpack_require__(28) + , normalizeOpts = __webpack_require__(36) + , isCallable = __webpack_require__(37) + , contains = __webpack_require__(38) + + , d; + +d = module.exports = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + w = contains.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!isCallable(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!isCallable(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(29)() + ? Object.assign + : __webpack_require__(30); + + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function () { + var assign = Object.assign, obj; + if (typeof assign !== "function") return false; + obj = { foo: "raz" }; + assign(obj, { bar: "dwa" }, { trzy: "trzy" }); + return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy"; +}; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var keys = __webpack_require__(31) + , value = __webpack_require__(35) + , max = Math.max; + +module.exports = function (dest, src /*, …srcn*/) { + var error, i, length = max(arguments.length, 2), assign; + dest = Object(value(dest)); + assign = function (key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + keys(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(32)() + ? Object.keys + : __webpack_require__(33); + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function () { + try { + Object.keys("primitive"); + return true; + } catch (e) { + return false; +} +}; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isValue = __webpack_require__(9); + +var keys = Object.keys; + +module.exports = function (object) { + return keys(isValue(object) ? Object(object) : object); +}; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// eslint-disable-next-line no-empty-function +module.exports = function () {}; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isValue = __webpack_require__(9); + +module.exports = function (value) { + if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); + return value; +}; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isValue = __webpack_require__(9); + +var forEach = Array.prototype.forEach, create = Object.create; + +var process = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +// eslint-disable-next-line no-unused-vars +module.exports = function (opts1 /*, …options*/) { + var result = create(null); + forEach.call(arguments, function (options) { + if (!isValue(options)) return; + process(Object(options), result); + }); + return result; +}; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Deprecated + + + +module.exports = function (obj) { + return typeof obj === "function"; +}; + + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(39)() + ? String.prototype.contains + : __webpack_require__(40); + + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var str = "razdwatrzy"; + +module.exports = function () { + if (typeof str.contains !== "function") return false; + return (str.contains("dwa") === true) && (str.contains("foo") === false); +}; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var indexOf = String.prototype.indexOf; + +module.exports = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function (fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; +}; + + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _hook = __webpack_require__(10); + +var _hook2 = _interopRequireDefault(_hook); + +var _section = __webpack_require__(43); + +var _section2 = _interopRequireDefault(_section); + +var _replacements = __webpack_require__(7); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A collection of Spine Items + */ +var Spine = function () { + function Spine() { + _classCallCheck(this, Spine); + + this.spineItems = []; + this.spineByHref = {}; + this.spineById = {}; + + this.hooks = {}; + this.hooks.serialize = new _hook2.default(); + this.hooks.content = new _hook2.default(); + + // Register replacements + this.hooks.content.register(_replacements.replaceBase); + this.hooks.content.register(_replacements.replaceCanonical); + this.hooks.content.register(_replacements.replaceMeta); + + this.epubcfi = new _epubcfi2.default(); + + this.loaded = false; + + this.items = undefined; + this.manifest = undefined; + this.spineNodeIndex = undefined; + this.baseUrl = undefined; + this.length = undefined; + } + + /** + * Unpack items from a opf into spine items + * @param {Package} _package + * @param {method} resolver URL resolver + */ + + + _createClass(Spine, [{ + key: "unpack", + value: function unpack(_package, resolver, canonical) { + var _this = this; + + this.items = _package.spine; + this.manifest = _package.manifest; + this.spineNodeIndex = _package.spineNodeIndex; + this.baseUrl = _package.baseUrl || _package.basePath || ""; + this.length = this.items.length; + + this.items.forEach(function (item, index) { + var manifestItem = _this.manifest[item.idref]; + var spineItem; + + item.index = index; + item.cfiBase = _this.epubcfi.generateChapterComponent(_this.spineNodeIndex, item.index, item.idref); + + if (item.href) { + item.url = resolver(item.href, true); + item.canonical = canonical(item.href); + } + + if (manifestItem) { + item.href = manifestItem.href; + item.url = resolver(item.href, true); + item.canonical = canonical(item.href); + + if (manifestItem.properties.length) { + item.properties.push.apply(item.properties, manifestItem.properties); + } + } + + if (item.linear === "yes") { + item.prev = function () { + var prevIndex = item.index; + while (prevIndex > 0) { + var prev = this.get(prevIndex - 1); + if (prev && prev.linear) { + return prev; + } + prevIndex -= 1; + } + return; + }.bind(_this); + item.next = function () { + var nextIndex = item.index; + while (nextIndex < this.spineItems.length - 1) { + var next = this.get(nextIndex + 1); + if (next && next.linear) { + return next; + } + nextIndex += 1; + } + return; + }.bind(_this); + } else { + item.prev = function () { + return; + }; + item.next = function () { + return; + }; + } + + spineItem = new _section2.default(item, _this.hooks); + + _this.append(spineItem); + }); + + this.loaded = true; + } + + /** + * Get an item from the spine + * @param {string|int} [target] + * @return {Section} section + * @example spine.get(); + * @example spine.get(1); + * @example spine.get("chap1.html"); + * @example spine.get("#id1234"); + */ + + }, { + key: "get", + value: function get(target) { + var index = 0; + + if (typeof target === "undefined") { + while (index < this.spineItems.length) { + var next = this.spineItems[index]; + if (next && next.linear) { + break; + } + index += 1; + } + } else if (this.epubcfi.isCfiString(target)) { + var cfi = new _epubcfi2.default(target); + index = cfi.spinePos; + } else if (typeof target === "number" || isNaN(target) === false) { + index = target; + } else if (typeof target === "string" && target.indexOf("#") === 0) { + index = this.spineById[target.substring(1)]; + } else if (typeof target === "string") { + // Remove fragments + target = target.split("#")[0]; + index = this.spineByHref[target] || this.spineByHref[encodeURI(target)]; + } + + return this.spineItems[index] || null; + } + + /** + * Append a Section to the Spine + * @private + * @param {Section} section + */ + + }, { + key: "append", + value: function append(section) { + var index = this.spineItems.length; + section.index = index; + + this.spineItems.push(section); + + // Encode and Decode href lookups + // see pr for details: https://github.com/futurepress/epub.js/pull/358 + this.spineByHref[decodeURI(section.href)] = index; + this.spineByHref[encodeURI(section.href)] = index; + this.spineByHref[section.href] = index; + + this.spineById[section.idref] = index; + + return index; + } + + /** + * Prepend a Section to the Spine + * @private + * @param {Section} section + */ + + }, { + key: "prepend", + value: function prepend(section) { + // var index = this.spineItems.unshift(section); + this.spineByHref[section.href] = 0; + this.spineById[section.idref] = 0; + + // Re-index + this.spineItems.forEach(function (item, index) { + item.index = index; + }); + + return 0; + } + + // insert(section, index) { + // + // }; + + /** + * Remove a Section from the Spine + * @private + * @param {Section} section + */ + + }, { + key: "remove", + value: function remove(section) { + var index = this.spineItems.indexOf(section); + + if (index > -1) { + delete this.spineByHref[section.href]; + delete this.spineById[section.idref]; + + return this.spineItems.splice(index, 1); + } + } + + /** + * Loop over the Sections in the Spine + * @return {method} forEach + */ + + }, { + key: "each", + value: function each() { + return this.spineItems.forEach.apply(this.spineItems, arguments); + } + }, { + key: "first", + value: function first() { + var index = 0; + + do { + var next = this.get(index); + + if (next && next.linear) { + return next; + } + index += 1; + } while (index < this.spineItems.length); + } + }, { + key: "last", + value: function last() { + var index = this.spineItems.length - 1; + + do { + var prev = this.get(index); + if (prev && prev.linear) { + return prev; + } + index -= 1; + } while (index >= 0); + } + }, { + key: "destroy", + value: function destroy() { + this.each(function (section) { + return section.destroy(); + }); + + this.spineItems = undefined; + this.spineByHref = undefined; + this.spineById = undefined; + + this.hooks.serialize.clear(); + this.hooks.content.clear(); + this.hooks = undefined; + + this.epubcfi = undefined; + + this.loaded = false; + + this.items = undefined; + this.manifest = undefined; + this.spineNodeIndex = undefined; + this.baseUrl = undefined; + this.length = undefined; + } + }]); + + return Spine; +}(); + +exports.default = Spine; +module.exports = exports["default"]; + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _hook = __webpack_require__(10); + +var _hook2 = _interopRequireDefault(_hook); + +var _replacements = __webpack_require__(7); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Represents a Section of the Book + * + * In most books this is equivelent to a Chapter + * @param {object} item The spine item representing the section + * @param {object} hooks hooks for serialize and content + */ +var Section = function () { + function Section(item, hooks) { + _classCallCheck(this, Section); + + this.idref = item.idref; + this.linear = item.linear === "yes"; + this.properties = item.properties; + this.index = item.index; + this.href = item.href; + this.url = item.url; + this.canonical = item.canonical; + this.next = item.next; + this.prev = item.prev; + + this.cfiBase = item.cfiBase; + + if (hooks) { + this.hooks = hooks; + } else { + this.hooks = {}; + this.hooks.serialize = new _hook2.default(this); + this.hooks.content = new _hook2.default(this); + } + + this.document = undefined; + this.contents = undefined; + this.output = undefined; + } + + /** + * Load the section from its url + * @param {method} _request a request method to use for loading + * @return {document} a promise with the xml document + */ + + + _createClass(Section, [{ + key: "load", + value: function load(_request) { + var request = _request || this.request || __webpack_require__(11); + var loading = new _core.defer(); + var loaded = loading.promise; + + if (this.contents) { + loading.resolve(this.contents); + } else { + request(this.url).then(function (xml) { + // var directory = new Url(this.url).directory; + + this.document = xml; + this.contents = xml.documentElement; + + return this.hooks.content.trigger(this.document, this); + }.bind(this)).then(function () { + loading.resolve(this.contents); + }.bind(this)).catch(function (error) { + loading.reject(error); + }); + } + + return loaded; + } + + /** + * Adds a base tag for resolving urls in the section + * @private + */ + + }, { + key: "base", + value: function base() { + return (0, _replacements.replaceBase)(this.document, this); + } + + /** + * Render the contents of a section + * @param {method} _request a request method to use for loading + * @return {string} output a serialized XML Document + */ + + }, { + key: "render", + value: function render(_request) { + var rendering = new _core.defer(); + var rendered = rendering.promise; + this.output; // TODO: better way to return this from hooks? + + this.load(_request).then(function (contents) { + var userAgent = typeof navigator !== 'undefined' && navigator.userAgent || ''; + var isIE = userAgent.indexOf('Trident') >= 0; + var Serializer; + if (typeof XMLSerializer === "undefined" || isIE) { + Serializer = __webpack_require__(16).XMLSerializer; + } else { + Serializer = XMLSerializer; + } + var serializer = new Serializer(); + this.output = serializer.serializeToString(contents); + return this.output; + }.bind(this)).then(function () { + return this.hooks.serialize.trigger(this.output, this); + }.bind(this)).then(function () { + rendering.resolve(this.output); + }.bind(this)).catch(function (error) { + rendering.reject(error); + }); + + return rendered; + } + + /** + * Find a string in a section + * @param {string} _query The query string to find + * @return {object[]} A list of matches, with form {cfi, excerpt} + */ + + }, { + key: "find", + value: function find(_query) { + var section = this; + var matches = []; + var query = _query.toLowerCase(); + var find = function find(node) { + var text = node.textContent.toLowerCase(); + var range = section.document.createRange(); + var cfi; + var pos; + var last = -1; + var excerpt; + var limit = 150; + + while (pos != -1) { + // Search for the query + pos = text.indexOf(query, last + 1); + + if (pos != -1) { + // We found it! Generate a CFI + range = section.document.createRange(); + range.setStart(node, pos); + range.setEnd(node, pos + query.length); + + cfi = section.cfiFromRange(range); + + // Generate the excerpt + if (node.textContent.length < limit) { + excerpt = node.textContent; + } else { + excerpt = node.textContent.substring(pos - limit / 2, pos + limit / 2); + excerpt = "..." + excerpt + "..."; + } + + // Add the CFI to the matches list + matches.push({ + cfi: cfi, + excerpt: excerpt + }); + } + + last = pos; + } + }; + + (0, _core.sprint)(section.document, function (node) { + find(node); + }); + + return matches; + } + }, { + key: "reconcileLayoutSettings", + + + /** + * Reconciles the current chapters layout properies with + * the global layout properities. + * @param {object} global The globa layout settings object, chapter properties string + * @return {object} layoutProperties Object with layout properties + */ + value: function reconcileLayoutSettings(global) { + //-- Get the global defaults + var settings = { + layout: global.layout, + spread: global.spread, + orientation: global.orientation + }; + + //-- Get the chapter's display type + this.properties.forEach(function (prop) { + var rendition = prop.replace("rendition:", ""); + var split = rendition.indexOf("-"); + var property, value; + + if (split != -1) { + property = rendition.slice(0, split); + value = rendition.slice(split + 1); + + settings[property] = value; + } + }); + return settings; + } + + /** + * Get a CFI from a Range in the Section + * @param {range} _range + * @return {string} cfi an EpubCFI string + */ + + }, { + key: "cfiFromRange", + value: function cfiFromRange(_range) { + return new _epubcfi2.default(_range, this.cfiBase).toString(); + } + + /** + * Get a CFI from an Element in the Section + * @param {element} el + * @return {string} cfi an EpubCFI string + */ + + }, { + key: "cfiFromElement", + value: function cfiFromElement(el) { + return new _epubcfi2.default(el, this.cfiBase).toString(); + } + + /** + * Unload the section document + */ + + }, { + key: "unload", + value: function unload() { + this.document = undefined; + this.contents = undefined; + this.output = undefined; + } + }, { + key: "destroy", + value: function destroy() { + this.unload(); + this.hooks.serialize.clear(); + this.hooks.content.clear(); + + this.hooks = undefined; + this.idref = undefined; + this.linear = undefined; + this.properties = undefined; + this.index = undefined; + this.href = undefined; + this.url = undefined; + this.next = undefined; + this.prev = undefined; + + this.cfiBase = undefined; + } + }]); + + return Section; +}(); + +exports.default = Section; +module.exports = exports["default"]; + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +var _queue = __webpack_require__(12); + +var _queue2 = _interopRequireDefault(_queue); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _constants = __webpack_require__(3); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Find Locations for a Book + * @param {Spine} spine + * @param {request} request + */ +var Locations = function () { + function Locations(spine, request, pause) { + _classCallCheck(this, Locations); + + this.spine = spine; + this.request = request; + this.pause = pause || 100; + + this.q = new _queue2.default(this); + this.epubcfi = new _epubcfi2.default(); + + this._locations = []; + this.total = 0; + + this.break = 150; + + this._current = 0; + + this.currentLocation = ''; + this._currentCfi = ''; + this.processingTimeout = undefined; + } + + /** + * Load all of sections in the book to generate locations + * @param {int} chars how many chars to split on + * @return {object} locations + */ + + + _createClass(Locations, [{ + key: "generate", + value: function generate(chars) { + + if (chars) { + this.break = chars; + } + + this.q.pause(); + + this.spine.each(function (section) { + if (section.linear) { + this.q.enqueue(this.process.bind(this), section); + } + }.bind(this)); + + return this.q.run().then(function () { + this.total = this._locations.length - 1; + + if (this._currentCfi) { + this.currentLocation = this._currentCfi; + } + + return this._locations; + // console.log(this.percentage(this.book.rendition.location.start), this.percentage(this.book.rendition.location.end)); + }.bind(this)); + } + }, { + key: "createRange", + value: function createRange() { + return { + startContainer: undefined, + startOffset: undefined, + endContainer: undefined, + endOffset: undefined + }; + } + }, { + key: "process", + value: function process(section) { + + return section.load(this.request).then(function (contents) { + var completed = new _core.defer(); + var locations = this.parse(contents, section.cfiBase); + this._locations = this._locations.concat(locations); + + section.unload(); + + this.processingTimeout = setTimeout(function () { + return completed.resolve(locations); + }, this.pause); + return completed.promise; + }.bind(this)); + } + }, { + key: "parse", + value: function parse(contents, cfiBase, chars) { + var locations = []; + var range; + var doc = contents.ownerDocument; + var body = (0, _core.qs)(doc, "body"); + var counter = 0; + var prev; + var _break = chars || this.break; + var parser = function parser(node) { + var len = node.length; + var dist; + var pos = 0; + + if (node.textContent.trim().length === 0) { + return false; // continue + } + + // Start range + if (counter == 0) { + range = this.createRange(); + range.startContainer = node; + range.startOffset = 0; + } + + dist = _break - counter; + + // Node is smaller than a break, + // skip over it + if (dist > len) { + counter += len; + pos = len; + } + + while (pos < len) { + dist = _break - counter; + + if (counter === 0) { + // Start new range + pos += 1; + range = this.createRange(); + range.startContainer = node; + range.startOffset = pos; + } + + // pos += dist; + + // Gone over + if (pos + dist >= len) { + // Continue counter for next node + counter += len - pos; + // break + pos = len; + // At End + } else { + // Advance pos + pos += dist; + + // End the previous range + range.endContainer = node; + range.endOffset = pos; + // cfi = section.cfiFromRange(range); + var cfi = new _epubcfi2.default(range, cfiBase).toString(); + locations.push(cfi); + counter = 0; + } + } + prev = node; + }; + + (0, _core.sprint)(body, parser.bind(this)); + + // Close remaining + if (range && range.startContainer && prev) { + range.endContainer = prev; + range.endOffset = prev.length; + var cfi = new _epubcfi2.default(range, cfiBase).toString(); + locations.push(cfi); + counter = 0; + } + + return locations; + } + + /** + * Get a location from an EpubCFI + * @param {EpubCFI} cfi + * @return {number} + */ + + }, { + key: "locationFromCfi", + value: function locationFromCfi(cfi) { + var loc = void 0; + if (_epubcfi2.default.prototype.isCfiString(cfi)) { + cfi = new _epubcfi2.default(cfi); + } + // Check if the location has not been set yet + if (this._locations.length === 0) { + return -1; + } + + loc = (0, _core.locationOf)(cfi, this._locations, this.epubcfi.compare); + + if (loc > this.total) { + return this.total; + } + + return loc; + } + + /** + * Get a percentage position in locations from an EpubCFI + * @param {EpubCFI} cfi + * @return {number} + */ + + }, { + key: "percentageFromCfi", + value: function percentageFromCfi(cfi) { + if (this._locations.length === 0) { + return null; + } + // Find closest cfi + var loc = this.locationFromCfi(cfi); + // Get percentage in total + return this.percentageFromLocation(loc); + } + + /** + * Get a percentage position from a location index + * @param {number} location + * @return {number} + */ + + }, { + key: "percentageFromLocation", + value: function percentageFromLocation(loc) { + if (!loc || !this.total) { + return 0; + } + + return loc / this.total; + } + + /** + * Get an EpubCFI from location index + * @param {number} loc + * @return {EpubCFI} cfi + */ + + }, { + key: "cfiFromLocation", + value: function cfiFromLocation(loc) { + var cfi = -1; + // check that pg is an int + if (typeof loc != "number") { + loc = parseInt(loc); + } + + if (loc >= 0 && loc < this._locations.length) { + cfi = this._locations[loc]; + } + + return cfi; + } + + /** + * Get an EpubCFI from location percentage + * @param {number} percentage + * @return {EpubCFI} cfi + */ + + }, { + key: "cfiFromPercentage", + value: function cfiFromPercentage(percentage) { + var loc = void 0; + if (percentage > 1) { + console.warn("Normalize cfiFromPercentage value to between 0 - 1"); + } + + // Make sure 1 goes to very end + if (percentage >= 1) { + var cfi = new _epubcfi2.default(this._locations[this.total]); + cfi.collapse(); + return cfi.toString(); + } + + loc = Math.ceil(this.total * percentage); + return this.cfiFromLocation(loc); + } + + /** + * Load locations from JSON + * @param {json} locations + */ + + }, { + key: "load", + value: function load(locations) { + if (typeof locations === "string") { + this._locations = JSON.parse(locations); + } else { + this._locations = locations; + } + this.total = this._locations.length - 1; + return this._locations; + } + + /** + * Save locations to JSON + * @return {json} + */ + + }, { + key: "save", + value: function save() { + return JSON.stringify(this._locations); + } + }, { + key: "getCurrent", + value: function getCurrent() { + return this._current; + } + }, { + key: "setCurrent", + value: function setCurrent(curr) { + var loc; + + if (typeof curr == "string") { + this._currentCfi = curr; + } else if (typeof curr == "number") { + this._current = curr; + } else { + return; + } + + if (this._locations.length === 0) { + return; + } + + if (typeof curr == "string") { + loc = this.locationFromCfi(curr); + this._current = loc; + } else { + loc = curr; + } + + this.emit(_constants.EVENTS.LOCATIONS.CHANGED, { + percentage: this.percentageFromLocation(loc) + }); + } + + /** + * Get the current location + */ + + }, { + key: "length", + + + /** + * Locations length + */ + value: function length() { + return this._locations.length; + } + }, { + key: "destroy", + value: function destroy() { + this.spine = undefined; + this.request = undefined; + this.pause = undefined; + + this.q.stop(); + this.q = undefined; + this.epubcfi = undefined; + + this._locations = undefined; + this.total = undefined; + + this.break = undefined; + this._current = undefined; + + this.currentLocation = undefined; + this._currentCfi = undefined; + clearTimeout(this.processingTimeout); + } + }, { + key: "currentLocation", + get: function get() { + return this._current; + } + + /** + * Set the current location + */ + , + set: function set(curr) { + this.setCurrent(curr); + } + }]); + + return Locations; +}(); + +(0, _eventEmitter2.default)(Locations.prototype); + +exports.default = Locations; +module.exports = exports["default"]; + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _pathWebpack = __webpack_require__(6); + +var _pathWebpack2 = _interopRequireDefault(_pathWebpack); + +var _core = __webpack_require__(0); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Handles Parsing and Accessing an Epub Container + * @class + * @param {document} [containerDocument] xml document + */ +var Container = function () { + function Container(containerDocument) { + _classCallCheck(this, Container); + + this.packagePath = ''; + this.directory = ''; + this.encoding = ''; + + if (containerDocument) { + this.parse(containerDocument); + } + } + + /** + * Parse the Container XML + * @param {document} containerDocument + */ + + + _createClass(Container, [{ + key: "parse", + value: function parse(containerDocument) { + //-- + var rootfile; + + if (!containerDocument) { + throw new Error("Container File Not Found"); + } + + rootfile = (0, _core.qs)(containerDocument, "rootfile"); + + if (!rootfile) { + throw new Error("No RootFile Found"); + } + + this.packagePath = rootfile.getAttribute("full-path"); + this.directory = _pathWebpack2.default.dirname(this.packagePath); + this.encoding = containerDocument.xmlEncoding; + } + }, { + key: "destroy", + value: function destroy() { + this.packagePath = undefined; + this.directory = undefined; + this.encoding = undefined; + } + }]); + + return Container; +}(); + +exports.default = Container; +module.exports = exports["default"]; + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Open Packaging Format Parser + * @class + * @param {document} packageDocument OPF XML + */ +var Packaging = function () { + function Packaging(packageDocument) { + _classCallCheck(this, Packaging); + + this.manifest = {}; + this.navPath = ''; + this.ncxPath = ''; + this.coverPath = ''; + this.spineNodeIndex = 0; + this.spine = []; + this.metadata = {}; + + if (packageDocument) { + this.parse(packageDocument); + } + } + + /** + * Parse OPF XML + * @param {document} packageDocument OPF XML + * @return {object} parsed package parts + */ + + + _createClass(Packaging, [{ + key: 'parse', + value: function parse(packageDocument) { + var metadataNode, manifestNode, spineNode; + + if (!packageDocument) { + throw new Error("Package File Not Found"); + } + + metadataNode = (0, _core.qs)(packageDocument, "metadata"); + if (!metadataNode) { + throw new Error("No Metadata Found"); + } + + manifestNode = (0, _core.qs)(packageDocument, "manifest"); + if (!manifestNode) { + throw new Error("No Manifest Found"); + } + + spineNode = (0, _core.qs)(packageDocument, "spine"); + if (!spineNode) { + throw new Error("No Spine Found"); + } + + this.manifest = this.parseManifest(manifestNode); + this.navPath = this.findNavPath(manifestNode); + this.ncxPath = this.findNcxPath(manifestNode, spineNode); + this.coverPath = this.findCoverPath(packageDocument); + + this.spineNodeIndex = (0, _core.indexOfElementNode)(spineNode); + + this.spine = this.parseSpine(spineNode, this.manifest); + + this.metadata = this.parseMetadata(metadataNode); + + this.metadata.direction = spineNode.getAttribute("page-progression-direction"); + + return { + "metadata": this.metadata, + "spine": this.spine, + "manifest": this.manifest, + "navPath": this.navPath, + "ncxPath": this.ncxPath, + "coverPath": this.coverPath, + "spineNodeIndex": this.spineNodeIndex + }; + } + + /** + * Parse Metadata + * @private + * @param {document} xml + * @return {object} metadata + */ + + }, { + key: 'parseMetadata', + value: function parseMetadata(xml) { + var metadata = {}; + + metadata.title = this.getElementText(xml, "title"); + metadata.creator = this.getElementText(xml, "creator"); + metadata.description = this.getElementText(xml, "description"); + + metadata.pubdate = this.getElementText(xml, "date"); + + metadata.publisher = this.getElementText(xml, "publisher"); + + metadata.identifier = this.getElementText(xml, "identifier"); + metadata.language = this.getElementText(xml, "language"); + metadata.rights = this.getElementText(xml, "rights"); + + metadata.modified_date = this.getPropertyText(xml, "dcterms:modified"); + + metadata.layout = this.getPropertyText(xml, "rendition:layout"); + metadata.orientation = this.getPropertyText(xml, "rendition:orientation"); + metadata.flow = this.getPropertyText(xml, "rendition:flow"); + metadata.viewport = this.getPropertyText(xml, "rendition:viewport"); + // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); + + return metadata; + } + + /** + * Parse Manifest + * @private + * @param {document} manifestXml + * @return {object} manifest + */ + + }, { + key: 'parseManifest', + value: function parseManifest(manifestXml) { + var manifest = {}; + + //-- Turn items into an array + // var selected = manifestXml.querySelectorAll("item"); + var selected = (0, _core.qsa)(manifestXml, "item"); + var items = Array.prototype.slice.call(selected); + + //-- Create an object with the id as key + items.forEach(function (item) { + var id = item.getAttribute("id"), + href = item.getAttribute("href") || "", + type = item.getAttribute("media-type") || "", + properties = item.getAttribute("properties") || ""; + + manifest[id] = { + "href": href, + // "url" : href, + "type": type, + "properties": properties.length ? properties.split(" ") : [] + }; + }); + + return manifest; + } + + /** + * Parse Spine + * @param {document} spineXml + * @param {Packaging.manifest} manifest + * @return {object} spine + */ + + }, { + key: 'parseSpine', + value: function parseSpine(spineXml, manifest) { + var spine = []; + + var selected = (0, _core.qsa)(spineXml, "itemref"); + var items = Array.prototype.slice.call(selected); + + // var epubcfi = new EpubCFI(); + + //-- Add to array to mantain ordering and cross reference with manifest + items.forEach(function (item, index) { + var idref = item.getAttribute("idref"); + // var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); + var props = item.getAttribute("properties") || ""; + var propArray = props.length ? props.split(" ") : []; + // var manifestProps = manifest[Id].properties; + // var manifestPropArray = manifestProps.length ? manifestProps.split(" ") : []; + + var itemref = { + "idref": idref, + "linear": item.getAttribute("linear") || "yes", + "properties": propArray, + // "href" : manifest[Id].href, + // "url" : manifest[Id].url, + "index": index + // "cfiBase" : cfiBase + }; + spine.push(itemref); + }); + + return spine; + } + + /** + * Find TOC NAV + * @private + */ + + }, { + key: 'findNavPath', + value: function findNavPath(manifestNode) { + // Find item with property "nav" + // Should catch nav irregardless of order + // var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); + var node = (0, _core.qsp)(manifestNode, "item", { "properties": "nav" }); + return node ? node.getAttribute("href") : false; + } + + /** + * Find TOC NCX + * media-type="application/x-dtbncx+xml" href="toc.ncx" + * @private + */ + + }, { + key: 'findNcxPath', + value: function findNcxPath(manifestNode, spineNode) { + // var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); + var node = (0, _core.qsp)(manifestNode, "item", { "media-type": "application/x-dtbncx+xml" }); + var tocId; + + // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as + // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2, + // "The item that describes the NCX must be referenced by the spine toc attribute." + if (!node) { + tocId = spineNode.getAttribute("toc"); + if (tocId) { + // node = manifestNode.querySelector("item[id='" + tocId + "']"); + node = manifestNode.getElementById(tocId); + } + } + + return node ? node.getAttribute("href") : false; + } + + /** + * Find the Cover Path + * + * Fallback for Epub 2.0 + * @param {document} packageXml + * @return {string} href + */ + + }, { + key: 'findCoverPath', + value: function findCoverPath(packageXml) { + var pkg = (0, _core.qs)(packageXml, "package"); + var epubVersion = pkg.getAttribute("version"); + + if (epubVersion === "2.0") { + var metaCover = (0, _core.qsp)(packageXml, "meta", { "name": "cover" }); + if (metaCover) { + var coverId = metaCover.getAttribute("content"); + // var cover = packageXml.querySelector("item[id='" + coverId + "']"); + var cover = packageXml.getElementById(coverId); + return cover ? cover.getAttribute("href") : ""; + } else { + return false; + } + } else { + // var node = packageXml.querySelector("item[properties='cover-image']"); + var node = (0, _core.qsp)(packageXml, "item", { "properties": "cover-image" }); + return node ? node.getAttribute("href") : ""; + } + } + + /** + * Get text of a namespaced element + * @private + * @param {document} xml + * @param {string} tag + * @return {string} text + */ + + }, { + key: 'getElementText', + value: function getElementText(xml, tag) { + var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag); + var el; + + if (!found || found.length === 0) return ""; + + el = found[0]; + + if (el.childNodes.length) { + return el.childNodes[0].nodeValue; + } + + return ""; + } + + /** + * Get text by property + * @private + * @param {document} xml + * @param {string} property + * @return {string} text + */ + + }, { + key: 'getPropertyText', + value: function getPropertyText(xml, property) { + var el = (0, _core.qsp)(xml, "meta", { "property": property }); + + if (el && el.childNodes.length) { + return el.childNodes[0].nodeValue; + } + + return ""; + } + + /** + * Load JSON Manifest + * @param {document} packageDocument OPF XML + * @return {object} parsed package parts + */ + + }, { + key: 'load', + value: function load(json) { + var _this = this; + + this.metadata = json.metadata; + + this.spine = json.spine.map(function (item, index) { + item.index = index; + return item; + }); + + json.resources.forEach(function (item, index) { + _this.manifest[index] = item; + + if (item.rel && item.rel[0] === "cover") { + _this.coverPath = item.href; + } + }); + + this.spineNodeIndex = 0; + + this.toc = json.toc.map(function (item, index) { + item.label = item.title; + return item; + }); + + return { + "metadata": this.metadata, + "spine": this.spine, + "manifest": this.manifest, + "navPath": this.navPath, + "ncxPath": this.ncxPath, + "coverPath": this.coverPath, + "spineNodeIndex": this.spineNodeIndex, + "toc": this.toc + }; + } + }, { + key: 'destroy', + value: function destroy() { + this.manifest = undefined; + this.navPath = undefined; + this.ncxPath = undefined; + this.coverPath = undefined; + this.spineNodeIndex = undefined; + this.spine = undefined; + this.metadata = undefined; + } + }]); + + return Packaging; +}(); + +exports.default = Packaging; +module.exports = exports['default']; + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Navigation Parser + * @param {document} xml navigation html / xhtml / ncx + */ +var Navigation = function () { + function Navigation(xml) { + _classCallCheck(this, Navigation); + + this.toc = []; + this.tocByHref = {}; + this.tocById = {}; + + this.landmarks = []; + this.landmarksByType = {}; + + this.length = 0; + if (xml) { + this.parse(xml); + } + } + + /** + * Parse out the navigation items + * @param {document} xml navigation html / xhtml / ncx + */ + + + _createClass(Navigation, [{ + key: "parse", + value: function parse(xml) { + var isXml = xml.nodeType; + var html = void 0; + var ncx = void 0; + + if (isXml) { + html = (0, _core.qs)(xml, "html"); + ncx = (0, _core.qs)(xml, "ncx"); + } + + if (!isXml) { + this.toc = this.load(xml); + } else if (html) { + this.toc = this.parseNav(xml); + this.landmarks = this.parseLandmarks(xml); + } else if (ncx) { + this.toc = this.parseNcx(xml); + } + + this.length = 0; + + this.unpack(this.toc); + } + + /** + * Unpack navigation items + * @private + * @param {array} toc + */ + + }, { + key: "unpack", + value: function unpack(toc) { + var item; + + for (var i = 0; i < toc.length; i++) { + item = toc[i]; + + if (item.href) { + this.tocByHref[item.href] = i; + } + + if (item.id) { + this.tocById[item.id] = i; + } + + this.length++; + + if (item.subitems.length) { + this.unpack(item.subitems); + } + } + } + + /** + * Get an item from the navigation + * @param {string} target + * @return {object} navItems + */ + + }, { + key: "get", + value: function get(target) { + var index; + + if (!target) { + return this.toc; + } + + if (target.indexOf("#") === 0) { + index = this.tocById[target.substring(1)]; + } else if (target in this.tocByHref) { + index = this.tocByHref[target]; + } + + return this.toc[index]; + } + + /** + * Get a landmark by type + * List of types: https://idpf.github.io/epub-vocabs/structure/ + * @param {string} type + * @return {object} landmarkItems + */ + + }, { + key: "landmark", + value: function landmark(type) { + var index; + + if (!type) { + return this.landmarks; + } + + index = this.landmarksByType[type]; + + return this.landmarks[index]; + } + + /** + * Parse toc from a Epub > 3.0 Nav + * @private + * @param {document} navHtml + * @return {array} navigation list + */ + + }, { + key: "parseNav", + value: function parseNav(navHtml) { + var navElement = (0, _core.querySelectorByType)(navHtml, "nav", "toc"); + var navItems = navElement ? (0, _core.qsa)(navElement, "li") : []; + var length = navItems.length; + var i; + var toc = {}; + var list = []; + var item, parent; + + if (!navItems || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.navItem(navItems[i]); + if (item) { + toc[item.id] = item; + if (!item.parent) { + list.push(item); + } else { + parent = toc[item.parent]; + parent.subitems.push(item); + } + } + } + + return list; + } + + /** + * Create a navItem + * @private + * @param {element} item + * @return {object} navItem + */ + + }, { + key: "navItem", + value: function navItem(item) { + var id = item.getAttribute("id") || undefined; + var content = (0, _core.filterChildren)(item, "a", true); + + if (!content) { + return; + } + + var src = content.getAttribute("href") || ""; + var text = content.textContent || ""; + var subitems = []; + var parentItem = (0, _core.getParentByTagName)(item, "li"); + var parent = void 0; + + if (parentItem) { + parent = parentItem.getAttribute("id"); + } + + while (!parent && parentItem) { + parentItem = (0, _core.getParentByTagName)(parentItem, "li"); + if (parentItem) { + parent = parentItem.getAttribute("id"); + } + } + + return { + "id": id, + "href": src, + "label": text, + "subitems": subitems, + "parent": parent + }; + } + + /** + * Parse landmarks from a Epub > 3.0 Nav + * @private + * @param {document} navHtml + * @return {array} landmarks list + */ + + }, { + key: "parseLandmarks", + value: function parseLandmarks(navHtml) { + var navElement = (0, _core.querySelectorByType)(navHtml, "nav", "landmarks"); + var navItems = navElement ? (0, _core.qsa)(navElement, "li") : []; + var length = navItems.length; + var i; + var list = []; + var item; + + if (!navItems || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.landmarkItem(navItems[i]); + if (item) { + list.push(item); + this.landmarksByType[item.type] = i; + } + } + + return list; + } + + /** + * Create a landmarkItem + * @private + * @param {element} item + * @return {object} landmarkItem + */ + + }, { + key: "landmarkItem", + value: function landmarkItem(item) { + var content = (0, _core.filterChildren)(item, "a", true); + + if (!content) { + return; + } + + var type = content.getAttributeNS("http://www.idpf.org/2007/ops", "type") || undefined; + var href = content.getAttribute("href") || ""; + var text = content.textContent || ""; + + return { + "href": href, + "label": text, + "type": type + }; + } + + /** + * Parse from a Epub > 3.0 NC + * @private + * @param {document} navHtml + * @return {array} navigation list + */ + + }, { + key: "parseNcx", + value: function parseNcx(tocXml) { + var navPoints = (0, _core.qsa)(tocXml, "navPoint"); + var length = navPoints.length; + var i; + var toc = {}; + var list = []; + var item, parent; + + if (!navPoints || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.ncxItem(navPoints[i]); + toc[item.id] = item; + if (!item.parent) { + list.push(item); + } else { + parent = toc[item.parent]; + parent.subitems.push(item); + } + } + + return list; + } + + /** + * Create a ncxItem + * @private + * @param {element} item + * @return {object} ncxItem + */ + + }, { + key: "ncxItem", + value: function ncxItem(item) { + var id = item.getAttribute("id") || false, + content = (0, _core.qs)(item, "content"), + src = content.getAttribute("src"), + navLabel = (0, _core.qs)(item, "navLabel"), + text = navLabel.textContent ? navLabel.textContent : "", + subitems = [], + parentNode = item.parentNode, + parent; + + if (parentNode && parentNode.nodeName === "navPoint") { + parent = parentNode.getAttribute("id"); + } + + return { + "id": id, + "href": src, + "label": text, + "subitems": subitems, + "parent": parent + }; + } + + /** + * Load Spine Items + * @param {object} json the items to be loaded + */ + + }, { + key: "load", + value: function load(json) { + var _this = this; + + return json.map(function (item) { + item.label = item.title; + if (item.children) { + item.subitems = _this.load(item.children); + } + return item; + }); + } + + /** + * forEach pass through + * @param {Function} fn function to run on each item + * @return {method} forEach loop + */ + + }, { + key: "forEach", + value: function forEach(fn) { + return this.toc.forEach(fn); + } + }]); + + return Navigation; +}(); + +exports.default = Navigation; +module.exports = exports["default"]; + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _replacements = __webpack_require__(7); + +var _core = __webpack_require__(0); + +var _url = __webpack_require__(5); + +var _url2 = _interopRequireDefault(_url); + +var _mime = __webpack_require__(17); + +var _mime2 = _interopRequireDefault(_mime); + +var _path = __webpack_require__(4); + +var _path2 = _interopRequireDefault(_path); + +var _pathWebpack = __webpack_require__(6); + +var _pathWebpack2 = _interopRequireDefault(_pathWebpack); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Handle Package Resources + * @class + * @param {Manifest} manifest + * @param {[object]} options + * @param {[string="base64"]} options.replacements + * @param {[Archive]} options.archive + * @param {[method]} options.resolver + */ +var Resources = function () { + function Resources(manifest, options) { + _classCallCheck(this, Resources); + + this.settings = { + replacements: options && options.replacements || "base64", + archive: options && options.archive, + resolver: options && options.resolver, + request: options && options.request + }; + this.manifest = manifest; + this.resources = Object.keys(manifest).map(function (key) { + return manifest[key]; + }); + + this.replacementUrls = []; + + this.html = []; + this.assets = []; + this.css = []; + + this.urls = []; + this.cssUrls = []; + + this.split(); + this.splitUrls(); + } + + /** + * Split resources by type + * @private + */ + + + _createClass(Resources, [{ + key: "split", + value: function split() { + + // HTML + this.html = this.resources.filter(function (item) { + if (item.type === "application/xhtml+xml" || item.type === "text/html") { + return true; + } + }); + + // Exclude HTML + this.assets = this.resources.filter(function (item) { + if (item.type !== "application/xhtml+xml" && item.type !== "text/html") { + return true; + } + }); + + // Only CSS + this.css = this.resources.filter(function (item) { + if (item.type === "text/css") { + return true; + } + }); + } + + /** + * Convert split resources into Urls + * @private + */ + + }, { + key: "splitUrls", + value: function splitUrls() { + + // All Assets Urls + this.urls = this.assets.map(function (item) { + return item.href; + }.bind(this)); + + // Css Urls + this.cssUrls = this.css.map(function (item) { + return item.href; + }); + } + }, { + key: "createUrl", + value: function createUrl(url) { + var parsedUrl = new _url2.default(url); + var mimeType = _mime2.default.lookup(parsedUrl.filename); + + if (this.settings.archive) { + return this.settings.archive.createUrl(url, { "base64": this.settings.replacements === "base64" }); + } else { + if (this.settings.replacements === "base64") { + return this.settings.request(url, 'blob').then(function (blob) { + return (0, _core.blob2base64)(blob); + }).then(function (blob) { + return (0, _core.createBase64Url)(blob, mimeType); + }); + } else { + return this.settings.request(url, 'blob').then(function (blob) { + return (0, _core.createBlobUrl)(blob, mimeType); + }); + } + } + } + + /** + * Create blob urls for all the assets + * @return {Promise} returns replacement urls + */ + + }, { + key: "replacements", + value: function replacements() { + var _this = this; + + if (this.settings.replacements === "none") { + return new Promise(function (resolve) { + resolve(this.urls); + }.bind(this)); + } + + var replacements = this.urls.map(function (url) { + var absolute = _this.settings.resolver(url); + + return _this.createUrl(absolute).catch(function (err) { + console.error(err); + return null; + }); + }); + + return Promise.all(replacements).then(function (replacementUrls) { + _this.replacementUrls = replacementUrls.filter(function (url) { + return typeof url === "string"; + }); + return replacementUrls; + }); + } + + /** + * Replace URLs in CSS resources + * @private + * @param {Archive} [archive] + * @param {method} [resolver] + * @return {Promise} + */ + + }, { + key: "replaceCss", + value: function replaceCss(archive, resolver) { + var replaced = []; + archive = archive || this.settings.archive; + resolver = resolver || this.settings.resolver; + this.cssUrls.forEach(function (href) { + var replacement = this.createCssFile(href, archive, resolver).then(function (replacementUrl) { + // switch the url in the replacementUrls + var indexInUrls = this.urls.indexOf(href); + if (indexInUrls > -1) { + this.replacementUrls[indexInUrls] = replacementUrl; + } + }.bind(this)); + + replaced.push(replacement); + }.bind(this)); + return Promise.all(replaced); + } + + /** + * Create a new CSS file with the replaced URLs + * @private + * @param {string} href the original css file + * @return {Promise} returns a BlobUrl to the new CSS file or a data url + */ + + }, { + key: "createCssFile", + value: function createCssFile(href) { + var _this2 = this; + + var newUrl; + + if (_pathWebpack2.default.isAbsolute(href)) { + return new Promise(function (resolve) { + resolve(); + }); + } + + var absolute = this.settings.resolver(href); + + // Get the text of the css file from the archive + var textResponse; + + if (this.settings.archive) { + textResponse = this.settings.archive.getText(absolute); + } else { + textResponse = this.settings.request(absolute, "text"); + } + + // Get asset links relative to css file + var relUrls = this.urls.map(function (assetHref) { + var resolved = _this2.settings.resolver(assetHref); + var relative = new _path2.default(absolute).relative(resolved); + + return relative; + }); + + if (!textResponse) { + // file not found, don't replace + return new Promise(function (resolve) { + resolve(); + }); + } + + return textResponse.then(function (text) { + // Replacements in the css text + text = (0, _replacements.substitute)(text, relUrls, _this2.replacementUrls); + + // Get the new url + if (_this2.settings.replacements === "base64") { + newUrl = (0, _core.createBase64Url)(text, "text/css"); + } else { + newUrl = (0, _core.createBlobUrl)(text, "text/css"); + } + + return newUrl; + }, function (err) { + // handle response errors + return new Promise(function (resolve) { + resolve(); + }); + }); + } + + /** + * Resolve all resources URLs relative to an absolute URL + * @param {string} absolute to be resolved to + * @param {[resolver]} resolver + * @return {string[]} array with relative Urls + */ + + }, { + key: "relativeTo", + value: function relativeTo(absolute, resolver) { + resolver = resolver || this.settings.resolver; + + // Get Urls relative to current sections + return this.urls.map(function (href) { + var resolved = resolver(href); + var relative = new _path2.default(absolute).relative(resolved); + return relative; + }.bind(this)); + } + + /** + * Get a URL for a resource + * @param {string} path + * @return {string} url + */ + + }, { + key: "get", + value: function get(path) { + var indexInUrls = this.urls.indexOf(path); + if (indexInUrls === -1) { + return; + } + if (this.replacementUrls.length) { + return new Promise(function (resolve, reject) { + resolve(this.replacementUrls[indexInUrls]); + }.bind(this)); + } else { + return this.createUrl(path); + } + } + + /** + * Substitute urls in content, with replacements, + * relative to a url if provided + * @param {string} content + * @param {string} [url] url to resolve to + * @return {string} content with urls substituted + */ + + }, { + key: "substitute", + value: function substitute(content, url) { + var relUrls; + if (url) { + relUrls = this.relativeTo(url); + } else { + relUrls = this.urls; + } + return (0, _replacements.substitute)(content, relUrls, this.replacementUrls); + } + }, { + key: "destroy", + value: function destroy() { + this.settings = undefined; + this.manifest = undefined; + this.resources = undefined; + this.replacementUrls = undefined; + this.html = undefined; + this.assets = undefined; + this.css = undefined; + + this.urls = undefined; + this.cssUrls = undefined; + } + }]); + + return Resources; +}(); + +exports.default = Resources; +module.exports = exports["default"]; + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +var _core = __webpack_require__(0); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Page List Parser + * @param {document} [xml] + */ +var PageList = function () { + function PageList(xml) { + _classCallCheck(this, PageList); + + this.pages = []; + this.locations = []; + this.epubcfi = new _epubcfi2.default(); + + this.firstPage = 0; + this.lastPage = 0; + this.totalPages = 0; + + this.toc = undefined; + this.ncx = undefined; + + if (xml) { + this.pageList = this.parse(xml); + } + + if (this.pageList && this.pageList.length) { + this.process(this.pageList); + } + } + + /** + * Parse PageList Xml + * @param {document} xml + */ + + + _createClass(PageList, [{ + key: "parse", + value: function parse(xml) { + var html = (0, _core.qs)(xml, "html"); + var ncx = (0, _core.qs)(xml, "ncx"); + + if (html) { + return this.parseNav(xml); + } else if (ncx) { + // Not supported + // return this.parseNcx(xml); + return; + } + } + + /** + * Parse a Nav PageList + * @private + * @param {document} navHtml + * @return {PageList.item[]} list + */ + + }, { + key: "parseNav", + value: function parseNav(navHtml) { + var navElement = (0, _core.querySelectorByType)(navHtml, "nav", "page-list"); + var navItems = navElement ? (0, _core.qsa)(navElement, "li") : []; + var length = navItems.length; + var i; + var list = []; + var item; + + if (!navItems || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.item(navItems[i]); + list.push(item); + } + + return list; + } + + /** + * Page List Item + * @private + * @param {object} item + * @return {object} pageListItem + */ + + }, { + key: "item", + value: function item(_item) { + var content = (0, _core.qs)(_item, "a"), + href = content.getAttribute("href") || "", + text = content.textContent || "", + page = parseInt(text), + isCfi = href.indexOf("epubcfi"), + split, + packageUrl, + cfi; + + if (isCfi != -1) { + split = href.split("#"); + packageUrl = split[0]; + cfi = split.length > 1 ? split[1] : false; + return { + "cfi": cfi, + "href": href, + "packageUrl": packageUrl, + "page": page + }; + } else { + return { + "href": href, + "page": page + }; + } + } + + /** + * Process pageList items + * @private + * @param {array} pageList + */ + + }, { + key: "process", + value: function process(pageList) { + pageList.forEach(function (item) { + this.pages.push(item.page); + if (item.cfi) { + this.locations.push(item.cfi); + } + }, this); + this.firstPage = parseInt(this.pages[0]); + this.lastPage = parseInt(this.pages[this.pages.length - 1]); + this.totalPages = this.lastPage - this.firstPage; + } + + /** + * Get a PageList result from a EpubCFI + * @param {string} cfi EpubCFI String + * @return {string} page + */ + + }, { + key: "pageFromCfi", + value: function pageFromCfi(cfi) { + var pg = -1; + + // Check if the pageList has not been set yet + if (this.locations.length === 0) { + return -1; + } + + // TODO: check if CFI is valid? + + // check if the cfi is in the location list + // var index = this.locations.indexOf(cfi); + var index = (0, _core.indexOfSorted)(cfi, this.locations, this.epubcfi.compare); + if (index != -1) { + pg = this.pages[index]; + } else { + // Otherwise add it to the list of locations + // Insert it in the correct position in the locations page + //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare); + index = (0, _core.locationOf)(cfi, this.locations, this.epubcfi.compare); + // Get the page at the location just before the new one, or return the first + pg = index - 1 >= 0 ? this.pages[index - 1] : this.pages[0]; + if (pg !== undefined) { + // Add the new page in so that the locations and page array match up + //this.pages.splice(index, 0, pg); + } else { + pg = -1; + } + } + return pg; + } + + /** + * Get an EpubCFI from a Page List Item + * @param {string} pg + * @return {string} cfi + */ + + }, { + key: "cfiFromPage", + value: function cfiFromPage(pg) { + var cfi = -1; + // check that pg is an int + if (typeof pg != "number") { + pg = parseInt(pg); + } + + // check if the cfi is in the page list + // Pages could be unsorted. + var index = this.pages.indexOf(pg); + if (index != -1) { + cfi = this.locations[index]; + } + // TODO: handle pages not in the list + return cfi; + } + + /** + * Get a Page from Book percentage + * @param {number} percent + * @return {string} page + */ + + }, { + key: "pageFromPercentage", + value: function pageFromPercentage(percent) { + var pg = Math.round(this.totalPages * percent); + return pg; + } + + /** + * Returns a value between 0 - 1 corresponding to the location of a page + * @param {int} pg the page + * @return {number} percentage + */ + + }, { + key: "percentageFromPage", + value: function percentageFromPage(pg) { + var percentage = (pg - this.firstPage) / this.totalPages; + return Math.round(percentage * 1000) / 1000; + } + + /** + * Returns a value between 0 - 1 corresponding to the location of a cfi + * @param {string} cfi EpubCFI String + * @return {number} percentage + */ + + }, { + key: "percentageFromCfi", + value: function percentageFromCfi(cfi) { + var pg = this.pageFromCfi(cfi); + var percentage = this.percentageFromPage(pg); + return percentage; + } + }, { + key: "destroy", + value: function destroy() { + this.pages = undefined; + this.locations = undefined; + this.epubcfi = undefined; + + this.pageList = undefined; + + this.toc = undefined; + this.ncx = undefined; + } + }]); + + return PageList; +}(); + +exports.default = PageList; +module.exports = exports["default"]; + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +var _constants = __webpack_require__(3); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Figures out the CSS values to apply for a layout + * @class + * @param {object} settings + * @param {string} [settings.layout='reflowable'] + * @param {string} [settings.spread] + * @param {int} [settings.minSpreadWidth=800] + * @param {boolean} [settings.evenSpreads=false] + */ +var Layout = function () { + function Layout(settings) { + _classCallCheck(this, Layout); + + this.settings = settings; + this.name = settings.layout || "reflowable"; + this._spread = settings.spread === "none" ? false : true; + this._minSpreadWidth = settings.minSpreadWidth || 800; + this._evenSpreads = settings.evenSpreads || false; + + if (settings.flow === "scrolled" || settings.flow === "scrolled-continuous" || settings.flow === "scrolled-doc") { + this._flow = "scrolled"; + } else { + this._flow = "paginated"; + } + + this.width = 0; + this.height = 0; + this.spreadWidth = 0; + this.delta = 0; + + this.columnWidth = 0; + this.gap = 0; + this.divisor = 1; + + this.props = { + name: this.name, + spread: this._spread, + flow: this._flow, + width: 0, + height: 0, + spreadWidth: 0, + delta: 0, + columnWidth: 0, + gap: 0, + divisor: 1 + }; + } + + /** + * Switch the flow between paginated and scrolled + * @param {string} flow paginated | scrolled + */ + + + _createClass(Layout, [{ + key: "flow", + value: function flow(_flow) { + if (typeof _flow != "undefined") { + if (_flow === "scrolled" || _flow === "scrolled-continuous" || _flow === "scrolled-doc") { + this._flow = "scrolled"; + } else { + this._flow = "paginated"; + } + // this.props.flow = this._flow; + this.update({ flow: this._flow }); + } + return this._flow; + } + + /** + * Switch between using spreads or not, and set the + * width at which they switch to single. + * @param {string} spread true | false + * @param {boolean} min integer in pixels + */ + + }, { + key: "spread", + value: function spread(_spread, min) { + + if (_spread) { + this._spread = _spread === "none" ? false : true; + // this.props.spread = this._spread; + this.update({ spread: this._spread }); + } + + if (min >= 0) { + this._minSpreadWidth = min; + } + + return this._spread; + } + + /** + * Calculate the dimensions of the pagination + * @param {number} _width [description] + * @param {number} _height [description] + * @param {number} _gap [description] + */ + + }, { + key: "calculate", + value: function calculate(_width, _height, _gap) { + + var divisor = 1; + var gap = _gap || 0; + + //-- Check the width and create even width columns + // var fullWidth = Math.floor(_width); + var width = _width; + var height = _height; + + var section = Math.floor(width / 12); + + var columnWidth; + var spreadWidth; + var pageWidth; + var delta; + + if (this._spread && width >= this._minSpreadWidth) { + divisor = 2; + } else { + divisor = 1; + } + + if (this.name === "reflowable" && this._flow === "paginated" && !(_gap >= 0)) { + gap = section % 2 === 0 ? section : section - 1; + } + + if (this.name === "pre-paginated") { + gap = 0; + } + + //-- Double Page + if (divisor > 1) { + // width = width - gap; + // columnWidth = (width - gap) / divisor; + // gap = gap / divisor; + columnWidth = width / divisor - gap; + pageWidth = columnWidth + gap; + } else { + columnWidth = width; + pageWidth = width; + } + + if (this.name === "pre-paginated" && divisor > 1) { + width = columnWidth; + } + + spreadWidth = columnWidth * divisor + gap; + + delta = width; + + this.width = width; + this.height = height; + this.spreadWidth = spreadWidth; + this.pageWidth = pageWidth; + this.delta = delta; + + this.columnWidth = columnWidth; + this.gap = gap; + this.divisor = divisor; + + // this.props.width = width; + // this.props.height = _height; + // this.props.spreadWidth = spreadWidth; + // this.props.pageWidth = pageWidth; + // this.props.delta = delta; + // + // this.props.columnWidth = colWidth; + // this.props.gap = gap; + // this.props.divisor = divisor; + + this.update({ + width: width, + height: height, + spreadWidth: spreadWidth, + pageWidth: pageWidth, + delta: delta, + columnWidth: columnWidth, + gap: gap, + divisor: divisor + }); + } + + /** + * Apply Css to a Document + * @param {Contents} contents + * @return {Promise} + */ + + }, { + key: "format", + value: function format(contents) { + var formating; + + if (this.name === "pre-paginated") { + formating = contents.fit(this.columnWidth, this.height); + } else if (this._flow === "paginated") { + formating = contents.columns(this.width, this.height, this.columnWidth, this.gap); + } else { + // scrolled + formating = contents.size(this.width, null); + } + + return formating; // might be a promise in some View Managers + } + + /** + * Count number of pages + * @param {number} totalLength + * @param {number} pageLength + * @return {{spreads: Number, pages: Number}} + */ + + }, { + key: "count", + value: function count(totalLength, pageLength) { + + var spreads = void 0, + pages = void 0; + + if (this.name === "pre-paginated") { + spreads = 1; + pages = 1; + } else if (this._flow === "paginated") { + pageLength = pageLength || this.delta; + spreads = Math.ceil(totalLength / pageLength); + pages = spreads * this.divisor; + } else { + // scrolled + pageLength = pageLength || this.height; + spreads = Math.ceil(totalLength / pageLength); + pages = spreads; + } + + return { + spreads: spreads, + pages: pages + }; + } + }, { + key: "update", + value: function update(props) { + var _this = this; + + // Remove props that haven't changed + Object.keys(props).forEach(function (propName) { + if (_this.props[propName] === props[propName]) { + delete props[propName]; + } + }); + + if (Object.keys(props).length > 0) { + var newProps = (0, _core.extend)(this.props, props); + this.emit(_constants.EVENTS.LAYOUT.UPDATED, newProps, props); + } + } + }]); + + return Layout; +}(); + +(0, _eventEmitter2.default)(Layout.prototype); + +exports.default = Layout; +module.exports = exports["default"]; + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _url = __webpack_require__(5); + +var _url2 = _interopRequireDefault(_url); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Themes to apply to displayed content + * @class + * @param {Rendition} rendition + */ +var Themes = function () { + function Themes(rendition) { + _classCallCheck(this, Themes); + + this.rendition = rendition; + this._themes = { + "default": { + "rules": {}, + "url": "", + "serialized": "" + } + }; + this._overrides = {}; + this._current = "default"; + this._injected = []; + this.rendition.hooks.content.register(this.inject.bind(this)); + this.rendition.hooks.content.register(this.overrides.bind(this)); + } + + /** + * Add themes to be used by a rendition + * @param {object | string} + * @example themes.register("light", "http://example.com/light.css") + * @example themes.register("light", { "body": { "color": "purple"}}) + * @example themes.register({ "light" : {...}, "dark" : {...}}) + */ + + + _createClass(Themes, [{ + key: "register", + value: function register() { + if (arguments.length === 0) { + return; + } + if (arguments.length === 1 && _typeof(arguments[0]) === "object") { + return this.registerThemes(arguments[0]); + } + if (arguments.length === 1 && typeof arguments[0] === "string") { + return this.default(arguments[0]); + } + if (arguments.length === 2 && typeof arguments[1] === "string") { + return this.registerUrl(arguments[0], arguments[1]); + } + if (arguments.length === 2 && _typeof(arguments[1]) === "object") { + return this.registerRules(arguments[0], arguments[1]); + } + } + + /** + * Add a default theme to be used by a rendition + * @param {object | string} theme + * @example themes.register("http://example.com/default.css") + * @example themes.register({ "body": { "color": "purple"}}) + */ + + }, { + key: "default", + value: function _default(theme) { + if (!theme) { + return; + } + if (typeof theme === "string") { + return this.registerUrl("default", theme); + } + if ((typeof theme === "undefined" ? "undefined" : _typeof(theme)) === "object") { + return this.registerRules("default", theme); + } + } + }, { + key: "registerThemes", + value: function registerThemes(themes) { + for (var theme in themes) { + if (themes.hasOwnProperty(theme)) { + if (typeof themes[theme] === "string") { + this.registerUrl(theme, themes[theme]); + } else { + this.registerRules(theme, themes[theme]); + } + } + } + } + }, { + key: "registerUrl", + value: function registerUrl(name, input) { + var url = new _url2.default(input); + this._themes[name] = { "url": url.toString() }; + if (this._injected[name]) { + this.update(name); + } + } + }, { + key: "registerRules", + value: function registerRules(name, rules) { + this._themes[name] = { "rules": rules }; + // TODO: serialize css rules + if (this._injected[name]) { + this.update(name); + } + } + }, { + key: "select", + value: function select(name) { + var prev = this._current; + var contents; + + this._current = name; + this.update(name); + + contents = this.rendition.getContents(); + contents.forEach(function (content) { + content.removeClass(prev); + content.addClass(name); + }); + } + }, { + key: "update", + value: function update(name) { + var _this = this; + + var contents = this.rendition.getContents(); + contents.forEach(function (content) { + _this.add(name, content); + }); + } + }, { + key: "inject", + value: function inject(contents) { + var links = []; + var themes = this._themes; + var theme; + + for (var name in themes) { + if (themes.hasOwnProperty(name) && (name === this._current || name === "default")) { + theme = themes[name]; + if (theme.rules && Object.keys(theme.rules).length > 0 || theme.url && links.indexOf(theme.url) === -1) { + this.add(name, contents); + } + this._injected.push(name); + } + } + + if (this._current != "default") { + contents.addClass(this._current); + } + } + }, { + key: "add", + value: function add(name, contents) { + var theme = this._themes[name]; + + if (!theme || !contents) { + return; + } + + if (theme.url) { + contents.addStylesheet(theme.url); + } else if (theme.serialized) { + // TODO: handle serialized + } else if (theme.rules) { + contents.addStylesheetRules(theme.rules); + theme.injected = true; + } + } + }, { + key: "override", + value: function override(name, value) { + var _this2 = this; + + var contents = this.rendition.getContents(); + + this._overrides[name] = value; + + contents.forEach(function (content) { + content.css(name, _this2._overrides[name]); + }); + } + }, { + key: "overrides", + value: function overrides(contents) { + var overrides = this._overrides; + + for (var rule in overrides) { + if (overrides.hasOwnProperty(rule)) { + contents.css(rule, overrides[rule]); + } + } + } + + /** + * Adjust the font size of a rendition + * @param {number} size + */ + + }, { + key: "fontSize", + value: function fontSize(size) { + this.override("font-size", size); + } + + /** + * Adjust the font-family of a rendition + * @param {string} f + */ + + }, { + key: "font", + value: function font(f) { + this.override("font-family", f); + } + }, { + key: "destroy", + value: function destroy() { + this.rendition = undefined; + this._themes = undefined; + this._overrides = undefined; + this._current = undefined; + this._injected = undefined; + } + }]); + + return Themes; +}(); + +exports.default = Themes; +module.exports = exports["default"]; + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventEmitter = __webpack_require__(2); + +var _eventEmitter2 = _interopRequireDefault(_eventEmitter); + +var _epubcfi = __webpack_require__(1); + +var _epubcfi2 = _interopRequireDefault(_epubcfi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Handles managing adding & removing Annotations + * @param {Rendition} rendition + * @class + */ +var Annotations = function () { + function Annotations(rendition) { + _classCallCheck(this, Annotations); + + this.rendition = rendition; + this.highlights = []; + this.underlines = []; + this.marks = []; + this._annotations = {}; + this._annotationsBySectionIndex = {}; + + this.rendition.hooks.render.register(this.inject.bind(this)); + this.rendition.hooks.unloaded.register(this.clear.bind(this)); + } + + /** + * Add an annotation to store + * @param {string} type Type of annotation to add: "highlight", "underline", "mark" + * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to + * @param {object} data Data to assign to annotation + * @param {function} [cb] Callback after annotation is added + * @returns {Annotation} annotation + */ + + + _createClass(Annotations, [{ + key: "add", + value: function add(type, cfiRange, data, cb) { + var hash = encodeURI(cfiRange); + var cfi = new _epubcfi2.default(cfiRange); + var sectionIndex = cfi.spinePos; + var annotation = new Annotation({ + type: type, + cfiRange: cfiRange, + data: data, + sectionIndex: sectionIndex, + cb: cb + }); + + this._annotations[hash] = annotation; + + if (sectionIndex in this._annotationsBySectionIndex) { + this._annotationsBySectionIndex[sectionIndex].push(hash); + } else { + this._annotationsBySectionIndex[sectionIndex] = [hash]; + } + + var views = this.rendition.views(); + + views.forEach(function (view) { + if (annotation.sectionIndex === view.index) { + annotation.attach(view); + } + }); + + return annotation; + } + + /** + * Remove an annotation from store + * @param {EpubCFI} cfiRange EpubCFI range the annotation is attached to + * @param {string} type Type of annotation to add: "highlight", "underline", "mark" + */ + + }, { + key: "remove", + value: function remove(cfiRange, type) { + var _this = this; + + var hash = encodeURI(cfiRange); + + if (hash in this._annotations) { + var annotation = this._annotations[hash]; + + if (type && annotation.type !== type) { + return; + } + + var views = this.rendition.views(); + views.forEach(function (view) { + _this._removeFromAnnotationBySectionIndex(annotation.sectionIndex, hash); + if (annotation.sectionIndex === view.index) { + annotation.detach(view); + } + }); + + delete this._annotations[hash]; + } + } + + /** + * Remove an annotations by Section Index + * @private + */ + + }, { + key: "_removeFromAnnotationBySectionIndex", + value: function _removeFromAnnotationBySectionIndex(sectionIndex, hash) { + this._annotationsBySectionIndex[sectionIndex] = this._annotationsAt(sectionIndex).filter(function (h) { + return h !== hash; + }); + } + + /** + * Get annotations by Section Index + * @private + */ + + }, { + key: "_annotationsAt", + value: function _annotationsAt(index) { + return this._annotationsBySectionIndex[index]; + } + + /** + * Add a highlight to the store + * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to + * @param {object} data Data to assign to annotation + * @param {function} cb Callback after annotation is added + */ + + }, { + key: "highlight", + value: function highlight(cfiRange, data, cb) { + this.add("highlight", cfiRange, data, cb); + } + + /** + * Add a underline to the store + * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to + * @param {object} data Data to assign to annotation + * @param {function} cb Callback after annotation is added + */ + + }, { + key: "underline", + value: function underline(cfiRange, data, cb) { + this.add("underline", cfiRange, data, cb); + } + + /** + * Add a mark to the store + * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to + * @param {object} data Data to assign to annotation + * @param {function} cb Callback after annotation is added + */ + + }, { + key: "mark", + value: function mark(cfiRange, data, cb) { + this.add("mark", cfiRange, data, cb); + } + + /** + * iterate over annotations in the store + */ + + }, { + key: "each", + value: function each() { + return this._annotations.forEach.apply(this._annotations, arguments); + } + + /** + * Hook for injecting annotation into a view + * @param {View} view + * @private + */ + + }, { + key: "inject", + value: function inject(view) { + var _this2 = this; + + var sectionIndex = view.index; + if (sectionIndex in this._annotationsBySectionIndex) { + var annotations = this._annotationsBySectionIndex[sectionIndex]; + annotations.forEach(function (hash) { + var annotation = _this2._annotations[hash]; + annotation.attach(view); + }); + } + } + + /** + * Hook for removing annotation from a view + * @param {View} view + * @private + */ + + }, { + key: "clear", + value: function clear(view) { + var _this3 = this; + + var sectionIndex = view.index; + if (sectionIndex in this._annotationsBySectionIndex) { + var annotations = this._annotationsBySectionIndex[sectionIndex]; + annotations.forEach(function (hash) { + var annotation = _this3._annotations[hash]; + annotation.detach(view); + }); + } + } + + /** + * [Not Implemented] Show annotations + * @TODO: needs implementation in View + */ + + }, { + key: "show", + value: function show() {} + + /** + * [Not Implemented] Hide annotations + * @TODO: needs implementation in View + */ + + }, { + key: "hide", + value: function hide() {} + }]); + + return Annotations; +}(); + +/** + * Annotation object + * @class + * @param {object} options + * @param {string} options.type Type of annotation to add: "highlight", "underline", "mark" + * @param {EpubCFI} options.cfiRange EpubCFI range to attach annotation to + * @param {object} options.data Data to assign to annotation + * @param {int} options.sectionIndex Index in the Spine of the Section annotation belongs to + * @param {function} [options.cb] Callback after annotation is added + * @returns {Annotation} annotation + */ + + +var Annotation = function () { + function Annotation(_ref) { + var type = _ref.type, + cfiRange = _ref.cfiRange, + data = _ref.data, + sectionIndex = _ref.sectionIndex, + cb = _ref.cb; + + _classCallCheck(this, Annotation); + + this.type = type; + this.cfiRange = cfiRange; + this.data = data; + this.sectionIndex = sectionIndex; + this.mark = undefined; + this.cb = cb; + } + + /** + * Update stored data + * @param {object} data + */ + + + _createClass(Annotation, [{ + key: "update", + value: function update(data) { + this.data = data; + } + + /** + * Add to a view + * @param {View} view + */ + + }, { + key: "attach", + value: function attach(view) { + var cfiRange = this.cfiRange, + data = this.data, + type = this.type, + mark = this.mark, + cb = this.cb; + + var result = void 0; + + if (type === "highlight") { + result = view.highlight(cfiRange, data, cb); + } else if (type === "underline") { + result = view.underline(cfiRange, data, cb); + } else if (type === "mark") { + result = view.mark(cfiRange, data, cb); + } + + this.mark = result; + + return result; + } + + /** + * Remove from a view + * @param {View} view + */ + + }, { + key: "detach", + value: function detach(view) { + var cfiRange = this.cfiRange, + type = this.type; + + var result = void 0; + + if (view) { + if (type === "highlight") { + result = view.unhighlight(cfiRange); + } else if (type === "underline") { + result = view.ununderline(cfiRange); + } else if (type === "mark") { + result = view.unmark(cfiRange); + } + } + + this.mark = undefined; + + return result; + } + + /** + * [Not Implemented] Get text of an annotation + * @TODO: needs implementation in contents + */ + + }, { + key: "text", + value: function text() {} + }]); + + return Annotation; +}(); + +(0, _eventEmitter2.default)(Annotation.prototype); + +exports.default = Annotations; +module.exports = exports["default"]; + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Underline = exports.Highlight = exports.Mark = exports.Pane = undefined; + +var _get = function get(object, property, receiver) { + if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) { + var parent = Object.getPrototypeOf(object);if (parent === null) { + return undefined; + } else { + return get(parent, property, receiver); + } + } else if ("value" in desc) { + return desc.value; + } else { + var getter = desc.get;if (getter === undefined) { + return undefined; + }return getter.call(receiver); + } +}; + +var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); + } + }return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; + }; +}(); + +var _svg = __webpack_require__(54); + +var _svg2 = _interopRequireDefault(_svg); + +var _events = __webpack_require__(55); + +var _events2 = _interopRequireDefault(_events); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; +} + +function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self; +} + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass))); + }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; +} + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +var Pane = exports.Pane = function () { + function Pane(target) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document.body; + + _classCallCheck(this, Pane); + + this.target = target; + this.element = _svg2.default.createElement('svg'); + this.marks = []; + + // Match the coordinates of the target element + this.element.style.position = 'absolute'; + // Disable pointer events + this.element.setAttribute('pointer-events', 'none'); + + // Set up mouse event proxying between the target element and the marks + _events2.default.proxyMouse(this.target, this.marks); + + this.container = container; + this.container.appendChild(this.element); + + this.render(); + } + + _createClass(Pane, [{ + key: 'addMark', + value: function addMark(mark) { + var g = _svg2.default.createElement('g'); + this.element.appendChild(g); + mark.bind(g, this.container); + + this.marks.push(mark); + + mark.render(); + return mark; + } + }, { + key: 'removeMark', + value: function removeMark(mark) { + var idx = this.marks.indexOf(mark); + if (idx === -1) { + return; + } + var el = mark.unbind(); + this.element.removeChild(el); + this.marks.splice(idx, 1); + } + }, { + key: 'render', + value: function render() { + setCoords(this.element, coords(this.target, this.container)); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this.marks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var m = _step.value; + + m.render(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }]); + + return Pane; +}(); + +var Mark = exports.Mark = function () { + function Mark() { + _classCallCheck(this, Mark); + + this.element = null; + } + + _createClass(Mark, [{ + key: 'bind', + value: function bind(element, container) { + this.element = element; + this.container = container; + } + }, { + key: 'unbind', + value: function unbind() { + var el = this.element; + this.element = null; + return el; + } + }, { + key: 'render', + value: function render() {} + }, { + key: 'dispatchEvent', + value: function dispatchEvent(e) { + if (!this.element) return; + this.element.dispatchEvent(e); + } + }, { + key: 'getBoundingClientRect', + value: function getBoundingClientRect() { + return this.element.getBoundingClientRect(); + } + }, { + key: 'getClientRects', + value: function getClientRects() { + var rects = []; + var el = this.element.firstChild; + while (el) { + rects.push(el.getBoundingClientRect()); + el = el.nextSibling; + } + return rects; + } + }, { + key: 'filteredRanges', + value: function filteredRanges() { + var rects = Array.from(this.range.getClientRects()); + + // De-duplicate the boxes + return rects.filter(function (box) { + for (var i = 0; i < rects.length; i++) { + if (rects[i] === box) { + return true; + } + var contained = contains(rects[i], box); + if (contained) { + return false; + } + } + return true; + }); + } + }]); + + return Mark; +}(); + +var Highlight = exports.Highlight = function (_Mark) { + _inherits(Highlight, _Mark); + + function Highlight(range, className, data, attributes) { + _classCallCheck(this, Highlight); + + var _this = _possibleConstructorReturn(this, (Highlight.__proto__ || Object.getPrototypeOf(Highlight)).call(this)); + + _this.range = range; + _this.className = className; + _this.data = data || {}; + _this.attributes = attributes || {}; + return _this; + } + + _createClass(Highlight, [{ + key: 'bind', + value: function bind(element, container) { + _get(Highlight.prototype.__proto__ || Object.getPrototypeOf(Highlight.prototype), 'bind', this).call(this, element, container); + + for (var attr in this.data) { + if (this.data.hasOwnProperty(attr)) { + this.element.dataset[attr] = this.data[attr]; + } + } + + for (var attr in this.attributes) { + if (this.attributes.hasOwnProperty(attr)) { + this.element.setAttribute(attr, this.attributes[attr]); + } + } + + if (this.className) { + this.element.classList.add(this.className); + } + } + }, { + key: 'render', + value: function render() { + // Empty element + while (this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } + + var docFrag = this.element.ownerDocument.createDocumentFragment(); + var filtered = this.filteredRanges(); + var offset = this.element.getBoundingClientRect(); + var container = this.container.getBoundingClientRect(); + + for (var i = 0, len = filtered.length; i < len; i++) { + var r = filtered[i]; + var el = _svg2.default.createElement('rect'); + el.setAttribute('x', r.left - offset.left + container.left); + el.setAttribute('y', r.top - offset.top + container.top); + el.setAttribute('height', r.height); + el.setAttribute('width', r.width); + docFrag.appendChild(el); + } + + this.element.appendChild(docFrag); + } + }]); + + return Highlight; +}(Mark); + +var Underline = exports.Underline = function (_Highlight) { + _inherits(Underline, _Highlight); + + function Underline(range, className, data, attributes) { + _classCallCheck(this, Underline); + + return _possibleConstructorReturn(this, (Underline.__proto__ || Object.getPrototypeOf(Underline)).call(this, range, className, data, attributes)); + } + + _createClass(Underline, [{ + key: 'render', + value: function render() { + // Empty element + while (this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } + + var docFrag = this.element.ownerDocument.createDocumentFragment(); + var filtered = this.filteredRanges(); + var offset = this.element.getBoundingClientRect(); + var container = this.container.getBoundingClientRect(); + + for (var i = 0, len = filtered.length; i < len; i++) { + var r = filtered[i]; + + var rect = _svg2.default.createElement('rect'); + rect.setAttribute('x', r.left - offset.left + container.left); + rect.setAttribute('y', r.top - offset.top + container.top); + rect.setAttribute('height', r.height); + rect.setAttribute('width', r.width); + rect.setAttribute('fill', 'none'); + + var line = _svg2.default.createElement('line'); + line.setAttribute('x1', r.left - offset.left + container.left); + line.setAttribute('x2', r.left - offset.left + container.left + r.width); + line.setAttribute('y1', r.top - offset.top + container.top + r.height - 1); + line.setAttribute('y2', r.top - offset.top + container.top + r.height - 1); + + line.setAttribute('stroke-width', 1); + line.setAttribute('stroke', 'black'); //TODO: match text color? + line.setAttribute('stroke-linecap', 'square'); + + docFrag.appendChild(rect); + + docFrag.appendChild(line); + } + + this.element.appendChild(docFrag); + } + }]); + + return Underline; +}(Highlight); + +function coords(el, container) { + var offset = container.getBoundingClientRect(); + var rect = el.getBoundingClientRect(); + + return { + top: rect.top - offset.top, + left: rect.left - offset.left, + height: el.scrollHeight, + width: el.scrollWidth + }; +} + +function setCoords(el, coords) { + el.style.top = coords.top + 'px'; + el.style.left = coords.left + 'px'; + el.style.height = coords.height + 'px'; + el.style.width = coords.width + 'px'; +} + +function contains(rect1, rect2) { + return rect2.right <= rect1.right && rect2.left >= rect1.left && rect2.top >= rect1.top && rect2.bottom <= rect1.bottom; +} + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createElement = createElement; +function createElement(name) { + return document.createElementNS('http://www.w3.org/2000/svg', name); +} + +exports.default = { + createElement: createElement +}; + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.proxyMouse = proxyMouse; +exports.clone = clone; +// import 'babelify/polyfill'; // needed for Object.assign + +exports.default = { + proxyMouse: proxyMouse +}; + +/** + * Start proxying all mouse events that occur on the target node to each node in + * a set of tracked nodes. + * + * The items in tracked do not strictly have to be DOM Nodes, but they do have + * to have dispatchEvent, getBoundingClientRect, and getClientRects methods. + * + * @param target {Node} The node on which to listen for mouse events. + * @param tracked {Node[]} A (possibly mutable) array of nodes to which to proxy + * events. + */ + +function proxyMouse(target, tracked) { + function dispatch(e) { + // We walk through the set of tracked elements in reverse order so that + // events are sent to those most recently added first. + // + // This is the least surprising behaviour as it simulates the way the + // browser would work if items added later were drawn "on top of" + // earlier ones. + for (var i = tracked.length - 1; i >= 0; i--) { + var t = tracked[i]; + var x = e.clientX; + var y = e.clientY; + + if (e.touches && e.touches.length) { + x = e.touches[0].clientX; + y = e.touches[0].clientY; + } + + if (!contains(t, target, x, y)) { + continue; + } + + // The event targets this mark, so dispatch a cloned event: + t.dispatchEvent(clone(e)); + // We only dispatch the cloned event to the first matching mark. + break; + } + } + + if (target.nodeName === "iframe" || target.nodeName === "IFRAME") { + + try { + // Try to get the contents if same domain + this.target = target.contentDocument; + } catch (err) { + this.target = target; + } + } else { + this.target = target; + } + + var _arr = ['mouseup', 'mousedown', 'click', 'touchstart']; + for (var _i = 0; _i < _arr.length; _i++) { + var ev = _arr[_i]; + this.target.addEventListener(ev, function (e) { + return dispatch(e); + }, false); + } +} + +/** + * Clone a mouse event object. + * + * @param e {MouseEvent} A mouse event object to clone. + * @returns {MouseEvent} + */ +function clone(e) { + var opts = Object.assign({}, e, { bubbles: false }); + try { + return new MouseEvent(e.type, opts); + } catch (err) { + // compat: webkit + var copy = document.createEvent('MouseEvents'); + copy.initMouseEvent(e.type, false, opts.cancelable, opts.view, opts.detail, opts.screenX, opts.screenY, opts.clientX, opts.clientY, opts.ctrlKey, opts.altKey, opts.shiftKey, opts.metaKey, opts.button, opts.relatedTarget); + return copy; + } +} + +/** + * Check if the item contains the point denoted by the passed coordinates + * @param item {Object} An object with getBoundingClientRect and getClientRects + * methods. + * @param x {Number} + * @param y {Number} + * @returns {Boolean} + */ +function contains(item, target, x, y) { + // offset + var offset = target.getBoundingClientRect(); + + function rectContains(r, x, y) { + var top = r.top - offset.top; + var left = r.left - offset.left; + var bottom = top + r.height; + var right = left + r.width; + return top <= y && left <= x && bottom > y && right > x; + } + + // Check overall bounding box first + var rect = item.getBoundingClientRect(); + if (!rectContains(rect, x, y)) { + return false; + } + + // Then continue to check each child rect + var rects = item.getClientRects(); + for (var i = 0, len = rects.length; i < len; i++) { + if (rectContains(rects[i], x, y)) { + return true; + } + } + return false; +} + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +var _throttle = __webpack_require__(57); + +var _throttle2 = _interopRequireDefault(_throttle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Stage = function () { + function Stage(_options) { + _classCallCheck(this, Stage); + + this.settings = _options || {}; + this.id = "epubjs-container-" + (0, _core.uuid)(); + + this.container = this.create(this.settings); + + if (this.settings.hidden) { + this.wrapper = this.wrap(this.container); + } + } + + /* + * Creates an element to render to. + * Resizes to passed width and height or to the elements size + */ + + + _createClass(Stage, [{ + key: "create", + value: function create(options) { + var height = options.height; // !== false ? options.height : "100%"; + var width = options.width; // !== false ? options.width : "100%"; + var overflow = options.overflow || false; + var axis = options.axis || "vertical"; + var direction = options.direction; + + if (options.height && (0, _core.isNumber)(options.height)) { + height = options.height + "px"; + } + + if (options.width && (0, _core.isNumber)(options.width)) { + width = options.width + "px"; + } + + // Create new container element + var container = document.createElement("div"); + + container.id = this.id; + container.classList.add("epub-container"); + + // Style Element + // container.style.fontSize = "0"; + container.style.wordSpacing = "0"; + container.style.lineHeight = "0"; + container.style.verticalAlign = "top"; + container.style.position = "relative"; + + if (axis === "horizontal") { + // container.style.whiteSpace = "nowrap"; + container.style.display = "flex"; + container.style.flexDirection = "row"; + container.style.flexWrap = "nowrap"; + } + + if (width) { + container.style.width = width; + } + + if (height) { + container.style.height = height; + } + + if (overflow) { + container.style.overflow = overflow; + } + + if (direction) { + container.dir = direction; + container.style["direction"] = direction; + } + + if (direction && this.settings.fullsize) { + document.body.style["direction"] = direction; + } + + return container; + } + }, { + key: "wrap", + value: function wrap(container) { + var wrapper = document.createElement("div"); + + wrapper.style.visibility = "hidden"; + wrapper.style.overflow = "hidden"; + wrapper.style.width = "0"; + wrapper.style.height = "0"; + + wrapper.appendChild(container); + return wrapper; + } + }, { + key: "getElement", + value: function getElement(_element) { + var element; + + if ((0, _core.isElement)(_element)) { + element = _element; + } else if (typeof _element === "string") { + element = document.getElementById(_element); + } + + if (!element) { + throw new Error("Not an Element"); + } + + return element; + } + }, { + key: "attachTo", + value: function attachTo(what) { + + var element = this.getElement(what); + var base; + + if (!element) { + return; + } + + if (this.settings.hidden) { + base = this.wrapper; + } else { + base = this.container; + } + + element.appendChild(base); + + this.element = element; + + return element; + } + }, { + key: "getContainer", + value: function getContainer() { + return this.container; + } + }, { + key: "onResize", + value: function onResize(func) { + // Only listen to window for resize event if width and height are not fixed. + // This applies if it is set to a percent or auto. + if (!(0, _core.isNumber)(this.settings.width) || !(0, _core.isNumber)(this.settings.height)) { + this.resizeFunc = (0, _throttle2.default)(func, 50); + window.addEventListener("resize", this.resizeFunc, false); + } + } + }, { + key: "onOrientationChange", + value: function onOrientationChange(func) { + this.orientationChangeFunc = func; + window.addEventListener("orientationchange", this.orientationChangeFunc, false); + } + }, { + key: "size", + value: function size(width, height) { + var bounds; + // var width = _width || this.settings.width; + // var height = _height || this.settings.height; + + // If width or height are set to false, inherit them from containing element + if (width === null) { + bounds = this.element.getBoundingClientRect(); + + if (bounds.width) { + width = bounds.width; + this.container.style.width = bounds.width + "px"; + } + } + + if (height === null) { + bounds = bounds || this.element.getBoundingClientRect(); + + if (bounds.height) { + height = bounds.height; + this.container.style.height = bounds.height + "px"; + } + } + + if (!(0, _core.isNumber)(width)) { + bounds = this.container.getBoundingClientRect(); + width = bounds.width; + //height = bounds.height; + } + + if (!(0, _core.isNumber)(height)) { + bounds = bounds || this.container.getBoundingClientRect(); + //width = bounds.width; + height = bounds.height; + } + + this.containerStyles = window.getComputedStyle(this.container); + + this.containerPadding = { + left: parseFloat(this.containerStyles["padding-left"]) || 0, + right: parseFloat(this.containerStyles["padding-right"]) || 0, + top: parseFloat(this.containerStyles["padding-top"]) || 0, + bottom: parseFloat(this.containerStyles["padding-bottom"]) || 0 + }; + + // Bounds not set, get them from window + var _windowBounds = (0, _core.windowBounds)(); + if (!width) { + width = _windowBounds.width; + } + if (this.settings.fullsize || !height) { + height = _windowBounds.height; + } + + return { + width: width - this.containerPadding.left - this.containerPadding.right, + height: height - this.containerPadding.top - this.containerPadding.bottom + }; + } + }, { + key: "bounds", + value: function bounds() { + var box = void 0; + if (this.container.style.overflow !== "visible") { + box = this.container && this.container.getBoundingClientRect(); + } + + if (!box || !box.width || !box.height) { + return (0, _core.windowBounds)(); + } else { + return box; + } + } + }, { + key: "getSheet", + value: function getSheet() { + var style = document.createElement("style"); + + // WebKit hack --> https://davidwalsh.name/add-rules-stylesheets + style.appendChild(document.createTextNode("")); + + document.head.appendChild(style); + + return style.sheet; + } + }, { + key: "addStyleRules", + value: function addStyleRules(selector, rulesArray) { + var scope = "#" + this.id + " "; + var rules = ""; + + if (!this.sheet) { + this.sheet = this.getSheet(); + } + + rulesArray.forEach(function (set) { + for (var prop in set) { + if (set.hasOwnProperty(prop)) { + rules += prop + ":" + set[prop] + ";"; + } + } + }); + + this.sheet.insertRule(scope + selector + " {" + rules + "}", 0); + } + }, { + key: "axis", + value: function axis(_axis) { + if (_axis === "horizontal") { + this.container.style.display = "flex"; + this.container.style.flexDirection = "row"; + this.container.style.flexWrap = "nowrap"; + } else { + this.container.style.display = "block"; + } + } + + // orientation(orientation) { + // if (orientation === "landscape") { + // + // } else { + // + // } + // + // this.orientation = orientation; + // } + + }, { + key: "direction", + value: function direction(dir) { + if (this.container) { + this.container.dir = dir; + this.container.style["direction"] = dir; + } + + if (this.settings.fullsize) { + document.body.style["direction"] = dir; + } + } + }, { + key: "destroy", + value: function destroy() { + var base; + + if (this.element) { + + if (this.settings.hidden) { + base = this.wrapper; + } else { + base = this.container; + } + + if (this.element.contains(this.container)) { + this.element.removeChild(this.container); + } + + window.removeEventListener("resize", this.resizeFunc); + window.removeEventListener("orientationChange", this.orientationChangeFunc); + } + } + }]); + + return Stage; +}(); + +exports.default = Stage; +module.exports = exports["default"]; + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + +var debounce = __webpack_require__(21), + isObject = __webpack_require__(15); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ +function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); +} + +module.exports = throttle; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + +var root = __webpack_require__(22); + +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); +}; + +module.exports = now; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +module.exports = freeGlobal; + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +var isObject = __webpack_require__(15), + isSymbol = __webpack_require__(61); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = toNumber; + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +var baseGetTag = __webpack_require__(62), + isObjectLike = __webpack_require__(65); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +module.exports = isSymbol; + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + +var Symbol = __webpack_require__(23), + getRawTag = __webpack_require__(63), + objectToString = __webpack_require__(64); + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +module.exports = baseGetTag; + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + +var Symbol = __webpack_require__(23); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +module.exports = getRawTag; + + +/***/ }), +/* 64 */ +/***/ (function(module, exports) { + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +module.exports = objectToString; + + +/***/ }), +/* 65 */ +/***/ (function(module, exports) { + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +module.exports = isObjectLike; + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Views = function () { + function Views(container) { + _classCallCheck(this, Views); + + this.container = container; + this._views = []; + this.length = 0; + this.hidden = false; + } + + _createClass(Views, [{ + key: "all", + value: function all() { + return this._views; + } + }, { + key: "first", + value: function first() { + return this._views[0]; + } + }, { + key: "last", + value: function last() { + return this._views[this._views.length - 1]; + } + }, { + key: "indexOf", + value: function indexOf(view) { + return this._views.indexOf(view); + } + }, { + key: "slice", + value: function slice() { + return this._views.slice.apply(this._views, arguments); + } + }, { + key: "get", + value: function get(i) { + return this._views[i]; + } + }, { + key: "append", + value: function append(view) { + this._views.push(view); + if (this.container) { + this.container.appendChild(view.element); + } + this.length++; + return view; + } + }, { + key: "prepend", + value: function prepend(view) { + this._views.unshift(view); + if (this.container) { + this.container.insertBefore(view.element, this.container.firstChild); + } + this.length++; + return view; + } + }, { + key: "insert", + value: function insert(view, index) { + this._views.splice(index, 0, view); + + if (this.container) { + if (index < this.container.children.length) { + this.container.insertBefore(view.element, this.container.children[index]); + } else { + this.container.appendChild(view.element); + } + } + + this.length++; + return view; + } + }, { + key: "remove", + value: function remove(view) { + var index = this._views.indexOf(view); + + if (index > -1) { + this._views.splice(index, 1); + } + + this.destroy(view); + + this.length--; + } + }, { + key: "destroy", + value: function destroy(view) { + if (view.displayed) { + view.destroy(); + } + + if (this.container) { + this.container.removeChild(view.element); + } + view = null; + } + + // Iterators + + }, { + key: "forEach", + value: function forEach() { + return this._views.forEach.apply(this._views, arguments); + } + }, { + key: "clear", + value: function clear() { + // Remove all views + var view; + var len = this.length; + + if (!this.length) return; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + this.destroy(view); + } + + this._views = []; + this.length = 0; + } + }, { + key: "find", + value: function find(section) { + + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if (view.displayed && view.section.index == section.index) { + return view; + } + } + } + }, { + key: "displayed", + value: function displayed() { + var displayed = []; + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if (view.displayed) { + displayed.push(view); + } + } + return displayed; + } + }, { + key: "show", + value: function show() { + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if (view.displayed) { + view.show(); + } + } + this.hidden = false; + } + }, { + key: "hide", + value: function hide() { + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if (view.displayed) { + view.hide(); + } + } + this.hidden = true; + } + }]); + + return Views; +}(); + +exports.default = Views; +module.exports = exports["default"]; + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = __webpack_require__(0); + +var _request = __webpack_require__(11); + +var _request2 = _interopRequireDefault(_request); + +var _mime = __webpack_require__(17); + +var _mime2 = _interopRequireDefault(_mime); + +var _path = __webpack_require__(4); + +var _path2 = _interopRequireDefault(_path); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Handles Unzipping a requesting files from an Epub Archive + * @class + */ +var Archive = function () { + function Archive() { + _classCallCheck(this, Archive); + + this.zip = undefined; + this.urlCache = {}; + + this.checkRequirements(); + } + + /** + * Checks to see if JSZip exists in global namspace, + * Requires JSZip if it isn't there + * @private + */ + + + _createClass(Archive, [{ + key: "checkRequirements", + value: function checkRequirements() { + try { + if (typeof JSZip === "undefined") { + var _JSZip = __webpack_require__(68); + this.zip = new _JSZip(); + } else { + this.zip = new JSZip(); + } + } catch (e) { + throw new Error("JSZip lib not loaded"); + } + } + + /** + * Open an archive + * @param {binary} input + * @param {boolean} isBase64 tells JSZip if the input data is base64 encoded + * @return {Promise} zipfile + */ + + }, { + key: "open", + value: function open(input, isBase64) { + return this.zip.loadAsync(input, { "base64": isBase64 }); + } + + /** + * Load and Open an archive + * @param {string} zipUrl + * @param {boolean} isBase64 tells JSZip if the input data is base64 encoded + * @return {Promise} zipfile + */ + + }, { + key: "openUrl", + value: function openUrl(zipUrl, isBase64) { + return (0, _request2.default)(zipUrl, "binary").then(function (data) { + return this.zip.loadAsync(data, { "base64": isBase64 }); + }.bind(this)); + } + + /** + * Request a url from the archive + * @param {string} url a url to request from the archive + * @param {string} [type] specify the type of the returned result + * @return {Promise} + */ + + }, { + key: "request", + value: function request(url, type) { + var deferred = new _core.defer(); + var response; + var path = new _path2.default(url); + + // If type isn't set, determine it from the file extension + if (!type) { + type = path.extension; + } + + if (type == "blob") { + response = this.getBlob(url); + } else { + response = this.getText(url); + } + + if (response) { + response.then(function (r) { + var result = this.handleResponse(r, type); + deferred.resolve(result); + }.bind(this)); + } else { + deferred.reject({ + message: "File not found in the epub: " + url, + stack: new Error().stack + }); + } + return deferred.promise; + } + + /** + * Handle the response from request + * @private + * @param {any} response + * @param {string} [type] + * @return {any} the parsed result + */ + + }, { + key: "handleResponse", + value: function handleResponse(response, type) { + var r; + + if (type == "json") { + r = JSON.parse(response); + } else if ((0, _core.isXml)(type)) { + r = (0, _core.parse)(response, "text/xml"); + } else if (type == "xhtml") { + r = (0, _core.parse)(response, "application/xhtml+xml"); + } else if (type == "html" || type == "htm") { + r = (0, _core.parse)(response, "text/html"); + } else { + r = response; + } + + return r; + } + + /** + * Get a Blob from Archive by Url + * @param {string} url + * @param {string} [mimeType] + * @return {Blob} + */ + + }, { + key: "getBlob", + value: function getBlob(url, mimeType) { + var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash + var entry = this.zip.file(decodededUrl); + + if (entry) { + mimeType = mimeType || _mime2.default.lookup(entry.name); + return entry.async("uint8array").then(function (uint8array) { + return new Blob([uint8array], { type: mimeType }); + }); + } + } + + /** + * Get Text from Archive by Url + * @param {string} url + * @param {string} [encoding] + * @return {string} + */ + + }, { + key: "getText", + value: function getText(url, encoding) { + var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash + var entry = this.zip.file(decodededUrl); + + if (entry) { + return entry.async("string").then(function (text) { + return text; + }); + } + } + + /** + * Get a base64 encoded result from Archive by Url + * @param {string} url + * @param {string} [mimeType] + * @return {string} base64 encoded + */ + + }, { + key: "getBase64", + value: function getBase64(url, mimeType) { + var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash + var entry = this.zip.file(decodededUrl); + + if (entry) { + mimeType = mimeType || _mime2.default.lookup(entry.name); + return entry.async("base64").then(function (data) { + return "data:" + mimeType + ";base64," + data; + }); + } + } + + /** + * Create a Url from an unarchived item + * @param {string} url + * @param {object} [options.base64] use base64 encoding or blob url + * @return {Promise} url promise with Url string + */ + + }, { + key: "createUrl", + value: function createUrl(url, options) { + var deferred = new _core.defer(); + var _URL = window.URL || window.webkitURL || window.mozURL; + var tempUrl; + var response; + var useBase64 = options && options.base64; + + if (url in this.urlCache) { + deferred.resolve(this.urlCache[url]); + return deferred.promise; + } + + if (useBase64) { + response = this.getBase64(url); + + if (response) { + response.then(function (tempUrl) { + + this.urlCache[url] = tempUrl; + deferred.resolve(tempUrl); + }.bind(this)); + } + } else { + + response = this.getBlob(url); + + if (response) { + response.then(function (blob) { + + tempUrl = _URL.createObjectURL(blob); + this.urlCache[url] = tempUrl; + deferred.resolve(tempUrl); + }.bind(this)); + } + } + + if (!response) { + deferred.reject({ + message: "File not found in the epub: " + url, + stack: new Error().stack + }); + } + + return deferred.promise; + } + + /** + * Revoke Temp Url for a achive item + * @param {string} url url of the item in the archive + */ + + }, { + key: "revokeUrl", + value: function revokeUrl(url) { + var _URL = window.URL || window.webkitURL || window.mozURL; + var fromCache = this.urlCache[url]; + if (fromCache) _URL.revokeObjectURL(fromCache); + } + }, { + key: "destroy", + value: function destroy() { + var _URL = window.URL || window.webkitURL || window.mozURL; + for (var fromCache in this.urlCache) { + _URL.revokeObjectURL(fromCache); + } + this.zip = undefined; + this.urlCache = {}; + } + }]); + + return Archive; +}(); + +exports.default = Archive; +module.exports = exports["default"]; + +/***/ }), +/* 68 */ +/***/ (function(module, exports) { + +if(typeof __WEBPACK_EXTERNAL_MODULE_68__ === 'undefined') {var e = new Error("Cannot find module \"jszip\""); e.code = 'MODULE_NOT_FOUND'; throw e;} +module.exports = __WEBPACK_EXTERNAL_MODULE_68__; + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* From https://github.com/webcomponents/URL/blob/master/url.js + * Added UMD, file link handling */ + +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +(function (root, factory) { + // Fix for this being undefined in modules + if (!root) { + root = window || global; + } + if (( false ? 'undefined' : _typeof(module)) === 'object' && module.exports) { + // Node + module.exports = factory(root); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else { + // Browser globals (root is window) + root.URL = factory(root); + } +})(undefined, function (scope) { + // feature detect for URL constructor + var hasWorkingUrl = false; + if (!scope.forceJURL) { + try { + var u = new URL('b', 'http://a'); + u.pathname = 'c%20d'; + hasWorkingUrl = u.href === 'http://a/c%20d'; + } catch (e) {} + } + + if (hasWorkingUrl) return scope.URL; + + var relative = Object.create(null); + relative['ftp'] = 21; + relative['file'] = 0; + relative['gopher'] = 70; + relative['http'] = 80; + relative['https'] = 443; + relative['ws'] = 80; + relative['wss'] = 443; + + var relativePathDotMapping = Object.create(null); + relativePathDotMapping['%2e'] = '.'; + relativePathDotMapping['.%2e'] = '..'; + relativePathDotMapping['%2e.'] = '..'; + relativePathDotMapping['%2e%2e'] = '..'; + + function isRelativeScheme(scheme) { + return relative[scheme] !== undefined; + } + + function invalid() { + clear.call(this); + this._isInvalid = true; + } + + function IDNAToASCII(h) { + if ('' == h) { + invalid.call(this); + } + // XXX + return h.toLowerCase(); + } + + function percentEscape(c) { + var unicode = c.charCodeAt(0); + if (unicode > 0x20 && unicode < 0x7F && + // " # < > ? ` + [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1) { + return c; + } + return encodeURIComponent(c); + } + + function percentEscapeQuery(c) { + // XXX This actually needs to encode c using encoding and then + // convert the bytes one-by-one. + + var unicode = c.charCodeAt(0); + if (unicode > 0x20 && unicode < 0x7F && + // " # < > ` (do not escape '?') + [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1) { + return c; + } + return encodeURIComponent(c); + } + + var EOF = undefined, + ALPHA = /[a-zA-Z]/, + ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; + + function parse(input, stateOverride, base) { + function err(message) { + errors.push(message); + } + + var state = stateOverride || 'scheme start', + cursor = 0, + buffer = '', + seenAt = false, + seenBracket = false, + errors = []; + + loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { + var c = input[cursor]; + switch (state) { + case 'scheme start': + if (c && ALPHA.test(c)) { + buffer += c.toLowerCase(); // ASCII-safe + state = 'scheme'; + } else if (!stateOverride) { + buffer = ''; + state = 'no scheme'; + continue; + } else { + err('Invalid scheme.'); + break loop; + } + break; + + case 'scheme': + if (c && ALPHANUMERIC.test(c)) { + buffer += c.toLowerCase(); // ASCII-safe + } else if (':' == c) { + this._scheme = buffer; + buffer = ''; + if (stateOverride) { + break loop; + } + if (isRelativeScheme(this._scheme)) { + this._isRelative = true; + } + if ('file' == this._scheme) { + state = 'relative'; + } else if (this._isRelative && base && base._scheme == this._scheme) { + state = 'relative or authority'; + } else if (this._isRelative) { + state = 'authority first slash'; + } else { + state = 'scheme data'; + } + } else if (!stateOverride) { + buffer = ''; + cursor = 0; + state = 'no scheme'; + continue; + } else if (EOF == c) { + break loop; + } else { + err('Code point not allowed in scheme: ' + c); + break loop; + } + break; + + case 'scheme data': + if ('?' == c) { + this._query = '?'; + state = 'query'; + } else if ('#' == c) { + this._fragment = '#'; + state = 'fragment'; + } else { + // XXX error handling + if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { + this._schemeData += percentEscape(c); + } + } + break; + + case 'no scheme': + if (!base || !isRelativeScheme(base._scheme)) { + err('Missing scheme.'); + invalid.call(this); + } else { + state = 'relative'; + continue; + } + break; + + case 'relative or authority': + if ('/' == c && '/' == input[cursor + 1]) { + state = 'authority ignore slashes'; + } else { + err('Expected /, got: ' + c); + state = 'relative'; + continue; + } + break; + + case 'relative': + this._isRelative = true; + if ('file' != this._scheme) this._scheme = base._scheme; + if (EOF == c) { + this._host = base._host; + this._port = base._port; + this._path = base._path.slice(); + this._query = base._query; + this._username = base._username; + this._password = base._password; + break loop; + } else if ('/' == c || '\\' == c) { + if ('\\' == c) err('\\ is an invalid code point.'); + state = 'relative slash'; + } else if ('?' == c) { + this._host = base._host; + this._port = base._port; + this._path = base._path.slice(); + this._query = '?'; + this._username = base._username; + this._password = base._password; + state = 'query'; + } else if ('#' == c) { + this._host = base._host; + this._port = base._port; + this._path = base._path.slice(); + this._query = base._query; + this._fragment = '#'; + this._username = base._username; + this._password = base._password; + state = 'fragment'; + } else { + var nextC = input[cursor + 1]; + var nextNextC = input[cursor + 2]; + if ('file' != this._scheme || !ALPHA.test(c) || nextC != ':' && nextC != '|' || EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC) { + this._host = base._host; + this._port = base._port; + this._username = base._username; + this._password = base._password; + this._path = base._path.slice(); + this._path.pop(); + } + state = 'relative path'; + continue; + } + break; + + case 'relative slash': + if ('/' == c || '\\' == c) { + if ('\\' == c) { + err('\\ is an invalid code point.'); + } + if ('file' == this._scheme) { + state = 'file host'; + } else { + state = 'authority ignore slashes'; + } + } else { + if ('file' != this._scheme) { + this._host = base._host; + this._port = base._port; + this._username = base._username; + this._password = base._password; + } + state = 'relative path'; + continue; + } + break; + + case 'authority first slash': + if ('/' == c) { + state = 'authority second slash'; + } else { + err("Expected '/', got: " + c); + state = 'authority ignore slashes'; + continue; + } + break; + + case 'authority second slash': + state = 'authority ignore slashes'; + if ('/' != c) { + err("Expected '/', got: " + c); + continue; + } + break; + + case 'authority ignore slashes': + if ('/' != c && '\\' != c) { + state = 'authority'; + continue; + } else { + err('Expected authority, got: ' + c); + } + break; + + case 'authority': + if ('@' == c) { + if (seenAt) { + err('@ already seen.'); + buffer += '%40'; + } + seenAt = true; + for (var i = 0; i < buffer.length; i++) { + var cp = buffer[i]; + if ('\t' == cp || '\n' == cp || '\r' == cp) { + err('Invalid whitespace in authority.'); + continue; + } + // XXX check URL code points + if (':' == cp && null === this._password) { + this._password = ''; + continue; + } + var tempC = percentEscape(cp); + null !== this._password ? this._password += tempC : this._username += tempC; + } + buffer = ''; + } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { + cursor -= buffer.length; + buffer = ''; + state = 'host'; + continue; + } else { + buffer += c; + } + break; + + case 'file host': + if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { + if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { + state = 'relative path'; + } else if (buffer.length == 0) { + state = 'relative path start'; + } else { + this._host = IDNAToASCII.call(this, buffer); + buffer = ''; + state = 'relative path start'; + } + continue; + } else if ('\t' == c || '\n' == c || '\r' == c) { + err('Invalid whitespace in file host.'); + } else { + buffer += c; + } + break; + + case 'host': + case 'hostname': + if (':' == c && !seenBracket) { + // XXX host parsing + this._host = IDNAToASCII.call(this, buffer); + buffer = ''; + state = 'port'; + if ('hostname' == stateOverride) { + break loop; + } + } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { + this._host = IDNAToASCII.call(this, buffer); + buffer = ''; + state = 'relative path start'; + if (stateOverride) { + break loop; + } + continue; + } else if ('\t' != c && '\n' != c && '\r' != c) { + if ('[' == c) { + seenBracket = true; + } else if (']' == c) { + seenBracket = false; + } + buffer += c; + } else { + err('Invalid code point in host/hostname: ' + c); + } + break; + + case 'port': + if (/[0-9]/.test(c)) { + buffer += c; + } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { + if ('' != buffer) { + var temp = parseInt(buffer, 10); + if (temp != relative[this._scheme]) { + this._port = temp + ''; + } + buffer = ''; + } + if (stateOverride) { + break loop; + } + state = 'relative path start'; + continue; + } else if ('\t' == c || '\n' == c || '\r' == c) { + err('Invalid code point in port: ' + c); + } else { + invalid.call(this); + } + break; + + case 'relative path start': + if ('\\' == c) err("'\\' not allowed in path."); + state = 'relative path'; + if ('/' != c && '\\' != c) { + continue; + } + break; + + case 'relative path': + if (EOF == c || '/' == c || '\\' == c || !stateOverride && ('?' == c || '#' == c)) { + if ('\\' == c) { + err('\\ not allowed in relative path.'); + } + var tmp; + if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { + buffer = tmp; + } + if ('..' == buffer) { + this._path.pop(); + if ('/' != c && '\\' != c) { + this._path.push(''); + } + } else if ('.' == buffer && '/' != c && '\\' != c) { + this._path.push(''); + } else if ('.' != buffer) { + if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { + buffer = buffer[0] + ':'; + } + this._path.push(buffer); + } + buffer = ''; + if ('?' == c) { + this._query = '?'; + state = 'query'; + } else if ('#' == c) { + this._fragment = '#'; + state = 'fragment'; + } + } else if ('\t' != c && '\n' != c && '\r' != c) { + buffer += percentEscape(c); + } + break; + + case 'query': + if (!stateOverride && '#' == c) { + this._fragment = '#'; + state = 'fragment'; + } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { + this._query += percentEscapeQuery(c); + } + break; + + case 'fragment': + if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { + this._fragment += c; + } + break; + } + + cursor++; + } + } + + function clear() { + this._scheme = ''; + this._schemeData = ''; + this._username = ''; + this._password = null; + this._host = ''; + this._port = ''; + this._path = []; + this._query = ''; + this._fragment = ''; + this._isInvalid = false; + this._isRelative = false; + } + + // Does not process domain names or IP addresses. + // Does not handle encoding for the query parameter. + function jURL(url, base /* , encoding */) { + if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base)); + + this._url = url; + clear.call(this); + + var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); + // encoding = encoding || 'utf-8' + + parse.call(this, input, null, base); + } + + jURL.prototype = { + toString: function toString() { + return this.href; + }, + get href() { + if (this._isInvalid) return this._url; + + var authority = ''; + if ('' != this._username || null != this._password) { + authority = this._username + (null != this._password ? ':' + this._password : '') + '@'; + } + + return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; + }, + set href(href) { + clear.call(this); + parse.call(this, href); + }, + + get protocol() { + return this._scheme + ':'; + }, + set protocol(protocol) { + if (this._isInvalid) return; + parse.call(this, protocol + ':', 'scheme start'); + }, + + get host() { + return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; + }, + set host(host) { + if (this._isInvalid || !this._isRelative) return; + parse.call(this, host, 'host'); + }, + + get hostname() { + return this._host; + }, + set hostname(hostname) { + if (this._isInvalid || !this._isRelative) return; + parse.call(this, hostname, 'hostname'); + }, + + get port() { + return this._port; + }, + set port(port) { + if (this._isInvalid || !this._isRelative) return; + parse.call(this, port, 'port'); + }, + + get pathname() { + return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; + }, + set pathname(pathname) { + if (this._isInvalid || !this._isRelative) return; + this._path = []; + parse.call(this, pathname, 'relative path start'); + }, + + get search() { + return this._isInvalid || !this._query || '?' == this._query ? '' : this._query; + }, + set search(search) { + if (this._isInvalid || !this._isRelative) return; + this._query = '?'; + if ('?' == search[0]) search = search.slice(1); + parse.call(this, search, 'query'); + }, + + get hash() { + return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment; + }, + set hash(hash) { + if (this._isInvalid) return; + this._fragment = '#'; + if ('#' == hash[0]) hash = hash.slice(1); + parse.call(this, hash, 'fragment'); + }, + + get origin() { + var host; + if (this._isInvalid || !this._scheme) { + return ''; + } + // javascript: Gecko returns String(""), WebKit/Blink String("null") + // Gecko throws error for "data://" + // data: Gecko returns "", Blink returns "data://", WebKit returns "null" + // Gecko returns String("") for file: mailto: + // WebKit/Blink returns String("SCHEME://") for file: mailto: + switch (this._scheme) { + case 'file': + return 'file://'; // EPUBJS Added + case 'data': + case 'javascript': + case 'mailto': + return 'null'; + } + host = this.host; + if (!host) { + return ''; + } + return this._scheme + '://' + host; + } + }; + + // Copy over the static methods + var OriginalURL = scope.URL; + if (OriginalURL) { + jURL.createObjectURL = function (blob) { + // IE extension allows a second optional options argument. + // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx + return OriginalURL.createObjectURL.apply(OriginalURL, arguments); + }; + jURL.revokeObjectURL = function (url) { + OriginalURL.revokeObjectURL(url); + }; + } + + return jURL; +}); +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8), __webpack_require__(70)(module))) + +/***/ }), +/* 70 */ +/***/ (function(module, exports) { + +module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if(!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; + + +/***/ }) +/******/ ]); +}); +//# sourceMappingURL=epub.js.map \ No newline at end of file diff --git a/epub.js/js/epub.min.map b/epub.js/js/epub.min.map new file mode 100644 index 0000000..a7c3c10 --- /dev/null +++ b/epub.js/js/epub.min.map @@ -0,0 +1 @@ +{"version":3,"file":"epub.min.js","sources":["../../src/base.js","../../node_modules/rsvp/dist/rsvp.js","../../src/book.js","../../src/chapter.js","../../src/core.js","../../src/epubcfi.js","../../src/events.js","../../src/hooks.js","../../src/layout.js","../../src/locations.js","../../src/pagination.js","../../src/parser.js","../../src/render_iframe.js","../../src/renderer.js","../../src/replace.js","../../src/storage.js","../../src/unarchiver.js","../../libs/mime-types/mime-types.js"],"names":["lib$rsvp$utils$$objectOrFunction","x","lib$rsvp$utils$$isFunction","lib$rsvp$utils$$isMaybeThenable","lib$rsvp$utils$$F","lib$rsvp$events$$indexOf","callbacks","callback","i","l","length","lib$rsvp$events$$callbacksFor","object","_promiseCallbacks","lib$rsvp$config$$configure","name","value","lib$rsvp$config$$config","arguments","lib$rsvp$instrument$$scheduleFlush","setTimeout","entry","lib$rsvp$instrument$$queue","payload","guid","key","id","childGuid","childId","error","stack","lib$rsvp$instrument$$instrument","eventName","promise","child","push","_guidKey","_id","detail","_result","label","_label","timeStamp","lib$rsvp$utils$$now","Error","lib$rsvp$$internal$$withOwnPromise","TypeError","lib$rsvp$$internal$$noop","lib$rsvp$$internal$$getThen","then","lib$rsvp$$internal$$GET_THEN_ERROR","lib$rsvp$$internal$$tryThen","fulfillmentHandler","rejectionHandler","call","e","lib$rsvp$$internal$$handleForeignThenable","thenable","async","sealed","lib$rsvp$$internal$$resolve","lib$rsvp$$internal$$fulfill","reason","lib$rsvp$$internal$$reject","lib$rsvp$$internal$$handleOwnThenable","_state","lib$rsvp$$internal$$FULFILLED","lib$rsvp$$internal$$REJECTED","_onError","lib$rsvp$$internal$$subscribe","undefined","lib$rsvp$$internal$$handleMaybeThenable","maybeThenable","constructor","lib$rsvp$$internal$$publishRejection","lib$rsvp$$internal$$publish","lib$rsvp$$internal$$PENDING","_subscribers","instrument","lib$rsvp$instrument$$default","parent","onFulfillment","onRejection","subscribers","settled","lib$rsvp$$internal$$invokeCallback","lib$rsvp$$internal$$ErrorObject","this","lib$rsvp$$internal$$tryCatch","lib$rsvp$$internal$$TRY_CATCH_ERROR","succeeded","failed","hasCallback","lib$rsvp$$internal$$initializePromise","resolver","resolved","lib$rsvp$enumerator$$makeSettledResult","state","position","lib$rsvp$enumerator$$Enumerator","Constructor","input","abortOnReject","enumerator","_instanceConstructor","_abortOnReject","_validateInput","_input","_remaining","_init","_enumerate","_validationError","lib$rsvp$promise$all$$all","entries","lib$rsvp$enumerator$$default","lib$rsvp$promise$race$$race","lib$rsvp$utils$$isArray","resolve","lib$rsvp$promise$resolve$$resolve","lib$rsvp$promise$reject$$reject","lib$rsvp$promise$$needsResolver","lib$rsvp$promise$$needsNew","lib$rsvp$promise$$Promise","lib$rsvp$promise$$counter","lib$rsvp$all$settled$$AllSettled","_superConstructor","lib$rsvp$all$settled$$allSettled","lib$rsvp$promise$$default","lib$rsvp$all$$all","array","all","lib$rsvp$asap$$asap","arg","lib$rsvp$asap$$queue","lib$rsvp$asap$$len","lib$rsvp$asap$$scheduleFlush","lib$rsvp$asap$$useNextTick","nextTick","process","version","versions","node","match","Array","isArray","setImmediate","lib$rsvp$asap$$flush","lib$rsvp$asap$$useVertxTimer","lib$rsvp$asap$$vertxNext","lib$rsvp$asap$$useMutationObserver","iterations","observer","lib$rsvp$asap$$BrowserMutationObserver","document","createTextNode","observe","characterData","data","lib$rsvp$asap$$useMessageChannel","channel","MessageChannel","port1","onmessage","port2","postMessage","lib$rsvp$asap$$useSetTimeout","lib$rsvp$asap$$attemptVertex","r","require","vertx","runOnLoop","runOnContext","lib$rsvp$defer$$defer","deferred","reject","lib$rsvp$filter$$filter","promises","filterFn","values","filtered","results","newLength","lib$rsvp$promise$hash$$PromiseHash","lib$rsvp$hash$settled$$HashSettled","lib$rsvp$hash$settled$$hashSettled","lib$rsvp$hash$$hash","lib$rsvp$promise$hash$$default","lib$rsvp$map$$map","mapFn","lib$rsvp$node$$Result","lib$rsvp$node$$getThen","obj","lib$rsvp$node$$ERROR","lib$rsvp$node$$tryApply","f","s","a","apply","lib$rsvp$node$$makeObject","_","argumentNames","args","lib$rsvp$node$$arrayResult","lib$rsvp$node$$wrapThenable","onFulFillment","lib$rsvp$node$$denodeify","nodeFunc","options","fn","self","promiseInput","lib$rsvp$node$$needsPromiseInput","lib$rsvp$node$$GET_THEN_ERROR","p","err","val","lib$rsvp$node$$handlePromiseInput","lib$rsvp$node$$handleValueInput","__proto__","result","lib$rsvp$race$$race","race","lib$rsvp$reject$$reject","lib$rsvp$resolve$$resolve","lib$rsvp$rethrow$$rethrow","lib$rsvp$$async","lib$rsvp$$on","lib$rsvp$$off","lib$rsvp$utils$$_isArray","Object","prototype","toString","Date","now","getTime","lib$rsvp$utils$$o_create","create","o","lib$rsvp$events$$default","mixin","on","allCallbacks","off","index","splice","trigger","_eachEntry","c","_settledAt","_willSettleAt","_makeResult","lib$rsvp$promise$all$$default","lib$rsvp$promise$race$$default","lib$rsvp$promise$resolve$$default","lib$rsvp$promise$reject$$default","lib$rsvp$promise$$guidKey","cast","after","catch","finally","lib$rsvp$all$settled$$default","lib$rsvp$all$$default","lib$rsvp$asap$$default","lib$rsvp$asap$$browserWindow","window","lib$rsvp$asap$$browserGlobal","MutationObserver","WebKitMutationObserver","lib$rsvp$asap$$isNode","lib$rsvp$asap$$isWorker","Uint8ClampedArray","importScripts","lib$rsvp$defer$$default","lib$rsvp$filter$$default","hasOwnProperty","lib$rsvp$platform$$platform","lib$rsvp$hash$settled$$default","lib$rsvp$hash$$default","lib$rsvp$map$$default","lib$rsvp$node$$default","global","lib$rsvp$platform$$default","lib$rsvp$race$$default","lib$rsvp$reject$$default","lib$rsvp$resolve$$default","lib$rsvp$rethrow$$default","cb","lib$rsvp$$callbacks","lib$rsvp$$eventName","lib$rsvp$umd$$RSVP","Promise","allSettled","hash","hashSettled","denodeify","map","filter","rethrow","defer","EventTarget","configure","define","module","EPUBJS","VERSION","plugins","filePath","Render","root","ePub","bookPath","ArrayBuffer","Book","amd","exports","settings","core","defaults","bookKey","packageUrl","storage","fromStorage","saved","online","contained","width","height","layoutOveride","orientation","minSpreadWidth","gap","restore","reload","goto","styles","headTags","withCredentials","render_method","EPUBJSVERSION","spinePos","stored","navigator","onLine","networkListeners","ready","manifest","RSVP","spine","metadata","cover","toc","pageList","readyPromises","pagination","Pagination","pageListReady","_ready","bind","isRendered","_q","queue","_rendering","_displayQ","_moving","_gotoQ","renderer","Renderer","setMinSpreadWidth","setGap","listenToRenderer","defer_opened","opened","store","open","addEventListener","unload","forceReload","epubpackage","book","isContained","bookUrl","unarchive","loadPackage","urlFrom","localStorage","packageXml","identifier","packageIdentifier","restored","unpack","_registerReplacements","_containerPath","parse","Parser","containerPath","loadXml","containerXml","container","paths","contentsPath","basePath","packagePath","encoding","console","contents","packageContents","spineIndexByURL","generateBookKey","globalLayoutProperties","parseLayoutProperties","coverPath","spineNodeIndex","locations","Locations","navPath","navUrl","navHtml","nav","epubcfi","EpubCFI","wait","forEach","pg","cfi","generateCfiFromHref","href","tocPath","tocUrl","tocXml","createHiddenRender","_width","_height","hiddenContainer","hiddenEl","box","element","getBoundingClientRect","forceSingle","createElement","style","visibility","overflow","appendChild","initialize","generatePageList","flag","pager","spineLength","currentPage","nextChapter","chapter","next","done","cancelled","remove","removeChild","Chapter","displayChapter","pageMap","item","start","page","spreads","end","generatePagination","defered","loadPagination","pagelistJSON","JSON","getPageList","getMetadata","getToc","Events","range","startPage","endPage","percent","pageRange","pageFromCfi","percentageFromPage","anchorPage","percentage","loadChange","url","uri","chapterUri","currentChapter","absolute","path","warn","filename","afterLoad","render","docEl","beforeDisplay","afterDisplay","reformat","unlistenToRenderer","coverUrl","retrieved","getUrl","zip","getXml","request","base","protocol","fromRoot","location","origin","host","baseTag","getElementsByTagName","resolveUrl","pathname","Unarchiver","extension","isSaved","storedSettings","getItem","saveContents","setItem","stringify","removeSavedContents","removeItem","renderTo","elem","rendered","isElement","getEl","direction","setDirection","_rendered","startDisplay","display","previousLocationCfi","gotoCfi","fetch","fromStore","len","clearSaved","chap","pos","enqueue","isNumber","_needsAssetReplacement","registerHook","replace","head","resources","svg","lastPage","preloadNextChapter","dequeue","message","nextPage","prevPage","prev","prevChapter","linear","getCurrentLocationCfi","currentLocationCfi","target","indexOf","gotoPercentage","parseInt","substring","isNaN","gotoPage","gotoHref","cfiString","spineItem","split","section","relativeURL","search","firstPage","cfiFromPage","pageFromPercentage","storeOffline","assets","put","availableOffline","toStorage","isStored","token","Storage","credentials","offline","setStyle","prefixed","noreflow","removeStyle","addHeadTag","tag","attrs","useSpreads","use","_use","force","load","destroy","removeEventListener","flush","applyStyles","applyHeadTags","hrefs","layout","spread","event","spineObject","cfiBase","properties","manifestProperties","pages","loaded","Hooks","getHooks","caches","_store","_credentials","xml","setDocument","doc","querySelector","setAttribute","insertBefore","firstChild","triggerHooks","serializer","XMLSerializer","serializeToString","tempUrl","setPages","num","getPages","getID","ID","revokeUrl","_document","namespaceURI","doctype","implementation","createDocument","importNode","documentElement","evaluate","cfiFromRange","_range","startXpath","endXpath","startContainer","endContainer","cleanEndTextContent","getElementXPath","nsResolver","XPathResult","FIRST_ORDERED_NODE_TYPE","singleNodeValue","collapsed","createRange","setStart","startOffset","setEnd","endOffset","log","cleanStartTextContent","cleanStringForXpath","textContent","generateCfiFromRange","find","_query","matches","query","toLowerCase","excerpt","text","last","limit","textSprint","func","treeWalker","createTreeWalker","NodeFilter","SHOW_TEXT","acceptNode","test","FILTER_ACCEPT","FILTER_REJECT","nextNode","finished","progress","items","querySelectorAll","slice","count","called","full","replaceWithStored","attr","_oldUrls","_newUrls","_cache","_uri","_chapterBase","_attr","_wait","clone","link","src","getAttribute","replaceUrl","timeout","onload","clearTimeout","onerror","getElementById","getEls","classes","getElementsByClassName","type","supportsURL","URL","BLOB_RESPONSE","xhr","XMLHttpRequest","xhrPrototype","handler","readyState","DONE","status","response","responseXML","DOMParser","parseFromString","Blob","defineProperty","onreadystatechange","htm","responseType","setRequestHeader","overrideMimeType","send","toArray","arr","member","newitm","ident","withoutProtocol","dot","firstSlash","directory","fragment","blob","doubleSlash","folder","lastIndexOf","lastSlash","dataURLToBlob","dataURL","parts","contentType","raw","rawLength","uInt8Array","BASE64_MARKER","atob","Uint8Array","charCodeAt","addScript","body","addScripts","srcArr","total","curr","addCss","rel","unprefixed","vendors","upper","toUpperCase","segments","folders","pop","concat","join","uuid","d","Math","random","floor","insert","compareFunction","locationOf","_start","_end","compared","pivot","b","indexOfSorted","_scope","scope","funcName","context","inwait","shift","clear","getElementTreeXPath","nodeName","tagName","pathIndex","isXhtml","ownerDocument","nodeType","Node","TEXT_NODE","indexOfTextNode","parentNode","sibling","previousSibling","DOCUMENT_TYPE_NODE","prefix","ns","xhtml","epub","str","part","textNode","sib","children","childNodes","source","prop","extend","sources","getOwnPropertyNames","propName","getOwnPropertyDescriptor","n","parseFloat","isFinite","isString","String","props","keys","cfiStr","generateChapterComponent","_spineNodeIndex","_pos","generatePathComponent","steps","segment","generateCfiFromElement","pathTo","unshift","getChapterComponent","splitStr","getPathComponent","pathComponent","getCharecterOffsetComponent","getCharacterOffsetComponent","chapSegment","chapterComponent","characterOffsetComponent","assertion","chapId","endInt","parseStep","has_brackets","spineId","step","characterOffset","textLocationAssertion","addMarker","_doc","_marker","lastStep","marker","createMarker","findParent","splitText","classList","add","removeMarker","contains","nextSib","nextSibling","prevSib","sections","compare","cfiOne","cfiTwo","generateCfiFromTextNode","anchor","offset","generateCfiFromRangeAnchor","anchorNode","anchorOffset","startElement","startSteps","startPath","startIndex","endElement","endSteps","endPath","endIndex","generateXpathFromSteps","xpath","generateQueryFromSteps","generateRangeFromCfi","textLength","startContainerParent","debug","selectNode","isCfiString","el","events","createEvent","tell","listen","deafen","listenUntil","evt","CustomEvent","msg","dispatchEvent","bindto","OnEvt","OffEvt","unlisten","hooks","plugs","plugType","hook","toAdd","toFront","removeHook","toRemove","passed","countdown","register","Layout","Reflowable","spreadWidth","format","_gap","columnAxis","columnGap","columnWidth","columnFill","colWidth","pageWidth","pageHeight","calculatePages","totalWidth","displayedPages","scrollWidth","ceil","pageCount","ReflowableSpreads","divisor","fullWidth","Fixed","content","viewport","hasAttribute","_locations","break","_current","generate","chars","_currentCfi","currentLocation","counter","sprint","dist","locationFromCfi","percentageFromCfi","loc","percentageFromLocation","cfiFromLocation","cfiFromPercentage","save","getCurrent","setCurrent","get","set","totalPages","round","baseUrl","rootfile","fullpath","xmlEncoding","metadataNode","getElementText","manifestNode","spineNode","findNavPath","findTocPath","findCoverPath","tocId","bookTitle","creator","description","pubdate","publisher","language","rights","modified_date","querySelectorText","epubVersion","metaCover","coverId","found","getElementsByTagNameNS","nodeValue","q","manifestXml","selected","spineXml","Id","propArray","manifestProps","manifestPropArray","vert","querySelectorByType","html","getAttributeNS","bookSpine","navElement","navItems","list","navItem","subitems","navPoints","tocItem","navLabel","pageListItem","isCfi","Iframe","iframe","bodyEl","leftPos","scrolling","seamless","border","isMobile","userAgent","transform","contentDocument","headEl","contentWindow","resized","setLeft","margin","dir","right","write","close","baseEl","resize","totalHeight","scrollHeight","setPageDimensions","defaultView","scrollTo","tagEl","getPageNumberByElement","left","getPageNumberByRect","boundingClientRect","getBaseElement","getDocumentElement","isElementVisible","rect","scroll","bool","renderMethod","hidden","listenedEvents","upEvent","downEvent","isForcedSingle","onResized","layoutSettings","initWidth","initHeight","clientWidth","clientHeight","globalLayout","warning","removeEventListeners","removeSelectionListeners","chapterPos","currentChapterCfiBase","reconcileLayoutSettings","layoutMethod","determineLayout","visible","formated","addEventListeners","addSelectionListeners","queued","updatePages","visibleRangeCfi","getVisibleRangeCfi","property","rendition","determineSpreads","mapPage","headTag","pageByElement","firstElementisTextNode","leng","trim","isGoodNode","embeddedElements","walk","y","prevNode","startNode","STOP","ITER","containsPoint","childElementCount","filterEmpty","SHOW_ELEMENT","prevRange","prevRanges","prevElement","startRange","endRange","startCfi","endCfi","elLimit","check","elPos","elRange","selectNodeContents","checkText","ranges","splitTextNodeIntoWordsRanges","collapse","indexOfBreakableChar","startPosition","whiteCharacters","charAt","rangePosition","getClientRects","getPageCfi","getRange","forceElement","caretPositionFromPoint","caretRangeFromPoint","visibileEl","findElementAfter","offsetNode","pagesInCurrentChapter","pgs","currentRenderedPage","getRenderedPagesLeft","pagesLeft","findFirstVisible","startEl","setSize","triggerEvent","onSelectionChange","selectionEndTimeout","selectedRange","getSelection","cutoff","replacments","relative","isRelative","onclick","links","srcs","stylesheets","getText","cssUrls","newText","_URL","webkitURL","mozURL","createObjectURL","replaced","checkRequirements","urlCache","current","encodedUrl","encodeURIComponent","localforage","buffer","mimeType","getMimeType","reader","FileReader","readAsText","parser","fromCache","revokeObjectURL","zipUrl","JSZip","decodededUrl","decodeURIComponent","unarchiver","file","asUint8Array","asText","afterSaved","that","delay","saveEntryFileToStorage","table","application","ecmascript","javascript","ogg","pdf","postscript","rdf+xml","smil","xhtml+xml","x-httpd-eruby","x-latex","x-maker","x-object","x-shockwave-flash","x-silverlight","epub+zip","font-tdpfr","inkml+xml","json","jsonml+json","mathml+xml","metalink+xml","mp4","omdoc+xml","oxps","vnd.amazon.ebook","widget","x-dtbook+xml","x-dtbresource+xml","x-font-bdf","x-font-ghostscript","x-font-linux-psf","x-font-otf","x-font-pcf","x-font-snf","x-font-ttf","x-font-type1","x-font-woff","x-mobipocket-ebook","x-mspublisher","x-nzb","x-tgif","xaml+xml","xml-dtd","xproc+xml","xslt+xml","internet-property-stream","x-compress","x-compressed","x-gzip","audio","flac","midi","mpeg","mpegurl","x-aiff","x-ms-wma","x-wav","adpcm","webm","x-aac","x-caf","x-matroska","x-pn-realaudio-plugin","xm","mid","image","gif","ief","jpeg","pcx","png","svg+xml","tiff","x-icon","bmp","webp","x-pict","x-tga","cis-cod","rfc822","cache-manifest","calendar","css","csv","h323","iuls","mathml","plain","richtext","tab-separated-values","x-bibtex","x-dsrc","x-diff","x-haskell","x-java","x-literate-haskell","x-moc","x-pascal","x-pcs-gcd","x-perl","x-python","x-scala","x-setext","x-tcl","x-tex","x-vcard","sgml","x-c","x-fortran","x-opml","x-nfo","x-sfv","x-uuencode","webviewhtml","video","quicktime","vnd.mpegurl","x-flv","x-la-asf","x-mng","x-ms-asf","x-ms-wm","x-ms-wmv","x-ms-wmx","x-ms-wvx","x-msvideo","x-sgi-movie","3gpp2","h261","h263","h264","jpm","mj2","vnd.ms-playready.media.pyv","vnd.uvvu.mp4","vnd.vivo","x-f4v","x-m4v","x-ms-vob","x-smv","mimeTypes","subtype","defaultValue"],"mappings":";;;;;;;AAAA,cCQA,WAEI,QAASA,GAAiCC,GACxC,MAAoB,kBAANA,IAAkC,gBAANA,IAAwB,OAANA,EAG9D,QAASC,GAA2BD,GAClC,MAAoB,kBAANA,GAGhB,QAASE,GAAgCF,GACvC,MAAoB,gBAANA,IAAwB,OAANA,EAgBlC,QAASG,MAYT,QAASC,GAAyBC,EAAWC,GAC3C,IAAK,GAAIC,GAAE,EAAGC,EAAEH,EAAUI,OAAUD,EAAFD,EAAKA,IACrC,GAAIF,EAAUE,KAAOD,EAAY,MAAOC,EAG1C,OAAO,GAGT,QAASG,GAA8BC,GACrC,GAAIN,GAAYM,EAAOC,iBAMvB,OAJKP,KACHA,EAAYM,EAAOC,sBAGdP,EAkMT,QAASQ,GAA2BC,EAAMC,GACxC,MAAa,YAATD,MAIFE,IAA4B,GAAE,QAASD,GAIhB,IAArBE,UAAUR,OAGLO,GAAwBF,QAF/BE,GAAwBF,GAAQC,GAQpC,QAASG,KACPC,WAAW,WAET,IAAK,GADDC,GACKb,EAAI,EAAGA,EAAIc,GAA2BZ,OAAQF,IAAK,CAC1Da,EAAQC,GAA2Bd,EAEnC,IAAIe,GAAUF,EAAME,OAEpBA,GAAQC,KAAOD,EAAQE,IAAMF,EAAQG,GACrCH,EAAQI,UAAYJ,EAAQE,IAAMF,EAAQK,QACtCL,EAAQM,QACVN,EAAQO,MAAQP,EAAQM,MAAMC,OAGhCb,GAAiC,QAAEI,EAAMN,KAAMM,EAAME,SAEvDD,GAA2BZ,OAAS,GACnC,IAGL,QAASqB,GAAgCC,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7E,KAAS,OACT8E,QAAU,MACVC,QAAU,MACVC,WAAa,MACbC,QAAU,QAIRC,EAAY,WACf,GAAI3nB,GAAM4nB,EAASpnC,EAAK4B,EAAOulC,IAC/B;IAAK3nB,IAAQ6e,GACZ,GAAIA,EAAM16B,eAAe6b,GACxB,IAAK4nB,IAAW/I,GAAM7e,GACrB,GAAI6e,EAAM7e,GAAM7b,eAAeyjC,GAE9B,GADApnC,EAAMq+B,EAAM7e,GAAM4nB,GACA,gBAAPpnC,GACVmnC,EAAUnnC,GAAOwf,EAAO,IAAM4nB,MAE9B,KAAKxlC,EAAQ,EAAGA,EAAQ5B,EAAI7M,OAAQyO,IACnCulC,EAAUnnC,EAAI4B,IAAU4d,EAAO,IAAM4nB,CAO3C,OAAOD,KAGR3hC,QAAOa,KAAK62B,YAAc,SAAS/rB,GAClC,GAAIk2B,GAAe,YACnB,OAAOl2B,IAAYg2B,EAAUh2B,EAASiF,MAAM,KAAKmN,MAAM7G,gBAAkB2qB"} \ No newline at end of file diff --git a/epub.js/js/hooks.min.map b/epub.js/js/hooks.min.map new file mode 100644 index 0000000..5da22be --- /dev/null +++ b/epub.js/js/hooks.min.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.min.js","sources":["../../hooks/default/endnotes.js","../../hooks/default/mathml.js","../../hooks/default/smartimages.js","../../hooks/default/transculsions.js"],"names":["EPUBJS","Hooks","register","endnotes","callback","renderer","notes","contents","querySelectorAll","items","Array","prototype","slice","call","attr","type","folder","core","location","pathname","popups","cssPath","addCss","render","document","head","forEach","item","showPop","pop","itemRect","iheight","height","iwidth","width","maxHeight","txt","el","cloneNode","querySelector","id","createElement","setAttribute","pop_content","appendChild","body","addEventListener","onPop","offPop","on","hidePop","this","getBoundingClientRect","left","top","classList","add","popRect","style","remove","setTimeout","href","epubType","getAttribute","replace","getElementById","mathml","currentChapter","manifestProperties","indexOf","iframe","contentWindow","mathmlCallback","s","innerHTML","doc","addScript","smartimages","images","layoutSettings","layout","size","newHeight","rectHeight","oHeight","fontSize","Number","getComputedStyle","match","fontAdjust","clientHeight","display","removeProperty","unloaded","off","transculsions","trans","orginal_width","orginal_height","chapter","colWidth","ratio","src","parent","parentNode","listenUntil","replaceChild"],"mappings":"AAAAA,OAAOC,MAAMC,SAAS,wBAAwBC,SAAW,SAASC,EAAUC,GAE1E,GAAIC,GAAQD,EAASE,SAASC,iBAAiB,WAC9CC,EAAQC,MAAMC,UAAUC,MAAMC,KAAKP,GACnCQ,EAAO,YACPC,EAAO,UACPC,EAAShB,OAAOiB,KAAKD,OAAOE,SAASC,UAErCC,GADWJ,EAAShB,OAAOqB,SAAYL,KAGxChB,QAAOiB,KAAKK,OAAOtB,OAAOqB,QAAU,aAAa,EAAOhB,EAASkB,OAAOC,SAASC,MAGjFhB,EAAMiB,QAAQ,SAASC,GAqBtB,QAASC,KACR,GAICC,GAEAC,EALAC,EAAU1B,EAAS2B,OACnBC,EAAS5B,EAAS6B,MAGlBC,EAAY,GAGTC,KACHP,EAAMQ,EAAGC,WAAU,GACnBF,EAAMP,EAAIU,cAAc,MAKrBnB,EAAOoB,KACVpB,EAAOoB,GAAMhB,SAASiB,cAAc,OACpCrB,EAAOoB,GAAIE,aAAa,QAAS,SAEjCC,YAAcnB,SAASiB,cAAc,OAErCrB,EAAOoB,GAAII,YAAYD,aAEvBA,YAAYC,YAAYR,GACxBO,YAAYD,aAAa,QAAS,eAElCrC,EAASkB,OAAOC,SAASqB,KAAKD,YAAYxB,EAAOoB,IAGjDpB,EAAOoB,GAAIM,iBAAiB,YAAaC,GAAO,GAChD3B,EAAOoB,GAAIM,iBAAiB,WAAYE,GAAQ,GAKhD3C,EAAS4C,GAAG,uBAAwBC,EAASC,MAC7C9C,EAAS4C,GAAG,uBAAwBD,EAAQG,OAI7CtB,EAAMT,EAAOoB,GAIbV,EAAWH,EAAKyB,wBAChBC,EAAOvB,EAASuB,KAChBC,EAAMxB,EAASwB,IAGfzB,EAAI0B,UAAUC,IAAI,QAGlBC,QAAU5B,E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/extensions/highlight.js similarity index 100% rename from epub.js/hooks/extensions/highlight.js rename to epub.js/js/hooks/extensions/highlight.js diff --git a/epub.js/js/libs/screenfull.js b/epub.js/js/libs/screenfull.js new file mode 100644 index 0000000..1b0e055 --- /dev/null +++ b/epub.js/js/libs/screenfull.js @@ -0,0 +1,145 @@ +/*! +* screenfull +* v2.0.0 - 2014-12-22 +* (c) Sindre Sorhus; MIT License +*/ +(function () { + 'use strict'; + + var isCommonjs = typeof module !== 'undefined' && module.exports; + var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element; + + var fn = (function () { + var val; + var valLength; + + var fnMap = [ + [ + 'requestFullscreen', + 'exitFullscreen', + 'fullscreenElement', + 'fullscreenEnabled', + 'fullscreenchange', + 'fullscreenerror' + ], + // new WebKit + [ + 'webkitRequestFullscreen', + 'webkitExitFullscreen', + 'webkitFullscreenElement', + 'webkitFullscreenEnabled', + 'webkitfullscreenchange', + 'webkitfullscreenerror' + + ], + // old WebKit (Safari 5.1) + [ + 'webkitRequestFullScreen', + 'webkitCancelFullScreen', + 'webkitCurrentFullScreenElement', + 'webkitCancelFullScreen', + 'webkitfullscreenchange', + 'webkitfullscreenerror' + + ], + [ + 'mozRequestFullScreen', + 'mozCancelFullScreen', + 'mozFullScreenElement', + 'mozFullScreenEnabled', + 'mozfullscreenchange', + 'mozfullscreenerror' + ], + [ + 'msRequestFullscreen', + 'msExitFullscreen', + 'msFullscreenElement', + 'msFullscreenEnabled', + 'MSFullscreenChange', + 'MSFullscreenError' + ] + ]; + + var i = 0; + var l = fnMap.length; + var ret = {}; + + for (; i < l; i++) { + val = fnMap[i]; + if (val && val[1] in document) { + for (i = 0, valLength = val.length; i < valLength; i++) { + ret[fnMap[0][i]] = val[i]; + } + return ret; + } + } + + return false; + })(); + + var screenfull = { + request: function (elem) { + var request = fn.requestFullscreen; + + elem = elem || document.documentElement; + + // Work around Safari 5.1 bug: reports support for + // keyboard in fullscreen even though it doesn't. + // Browser sniffing, since the alternative with + // setTimeout is even worse. + if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) { + elem[request](); + } else { + elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT); + } + }, + exit: function () { + document[fn.exitFullscreen](); + }, + toggle: function (elem) { + if (this.isFullscreen) { + this.exit(); + } else { + this.request(elem); + } + }, + raw: fn + }; + + if (!fn) { + if (isCommonjs) { + module.exports = false; + } else { + window.screenfull = false; + } + + return; + } + + Object.defineProperties(screenfull, { + isFullscreen: { + get: function () { + return !!document[fn.fullscreenElement]; + } + }, + element: { + enumerable: true, + get: function () { + return document[fn.fullscreenElement]; + } + }, + enabled: { + enumerable: true, + get: function () { + // Coerce to boolean in case of old WebKit + return !!document[fn.fullscreenEnabled]; + } + } + }); + + if (isCommonjs) { + module.exports = screenfull; + } else { + window.screenfull = screenfull; + } +})(); diff --git a/epub.js/plugins/hypothesis.js b/epub.js/js/plugins/hypothesis.js similarity index 100% rename from epub.js/plugins/hypothesis.js rename to epub.js/js/plugins/hypothesis.js diff --git a/epub.js/plugins/search.js b/epub.js/js/plugins/search.js similarity index 100% rename from epub.js/plugins/search.js rename to epub.js/js/plugins/search.js diff --git a/epub.js/js/reader.js b/epub.js/js/reader.js new file mode 100644 index 0000000..db8439a --- /dev/null +++ b/epub.js/js/reader.js @@ -0,0 +1,4374 @@ +/*! + * @overview RSVP - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2016 Yehuda Katz, Tom Dale, Stefan Penner and contributors + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE + * @version 3.6.2 + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.RSVP = global.RSVP || {}))); +}(this, (function (exports) { 'use strict'; + +function indexOf(callbacks, callback) { + for (var i = 0, l = callbacks.length; i < l; i++) { + if (callbacks[i] === callback) { + return i; + } + } + + return -1; +} + +function callbacksFor(object) { + var callbacks = object._promiseCallbacks; + + if (!callbacks) { + callbacks = object._promiseCallbacks = {}; + } + + return callbacks; +} + +/** + @class RSVP.EventTarget +*/ +var EventTarget = { + + /** + `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For + Example: + ```javascript + let object = {}; + RSVP.EventTarget.mixin(object); + object.on('finished', function(event) { + // handle event + }); + object.trigger('finished', { detail: value }); + ``` + `EventTarget.mixin` also works with prototypes: + ```javascript + let Person = function() {}; + RSVP.EventTarget.mixin(Person.prototype); + let yehuda = new Person(); + let tom = new Person(); + yehuda.on('poke', function(event) { + console.log('Yehuda says OW'); + }); + tom.on('poke', function(event) { + console.log('Tom says OW'); + }); + yehuda.trigger('poke'); + tom.trigger('poke'); + ``` + @method mixin + @for RSVP.EventTarget + @private + @param {Object} object object to extend with EventTarget methods + */ + mixin: function (object) { + object['on'] = this['on']; + object['off'] = this['off']; + object['trigger'] = this['trigger']; + object._promiseCallbacks = undefined; + return object; + }, + + + /** + Registers a callback to be executed when `eventName` is triggered + ```javascript + object.on('event', function(eventInfo){ + // handle the event + }); + object.trigger('event'); + ``` + @method on + @for RSVP.EventTarget + @private + @param {String} eventName name of the event to listen for + @param {Function} callback function to be called when the event is triggered. + */ + on: function (eventName, callback) { + if (typeof callback !== 'function') { + throw new TypeError('Callback must be a function'); + } + + var allCallbacks = callbacksFor(this), + callbacks = void 0; + + callbacks = allCallbacks[eventName]; + + if (!callbacks) { + callbacks = allCallbacks[eventName] = []; + } + + if (indexOf(callbacks, callback) === -1) { + callbacks.push(callback); + } + }, + + + /** + You can use `off` to stop firing a particular callback for an event: + ```javascript + function doStuff() { // do stuff! } + object.on('stuff', doStuff); + object.trigger('stuff'); // doStuff will be called + // Unregister ONLY the doStuff callback + object.off('stuff', doStuff); + object.trigger('stuff'); // doStuff will NOT be called + ``` + If you don't pass a `callback` argument to `off`, ALL callbacks for the + event will not be executed when the event fires. For example: + ```javascript + let callback1 = function(){}; + let callback2 = function(){}; + object.on('stuff', callback1); + object.on('stuff', callback2); + object.trigger('stuff'); // callback1 and callback2 will be executed. + object.off('stuff'); + object.trigger('stuff'); // callback1 and callback2 will not be executed! + ``` + @method off + @for RSVP.EventTarget + @private + @param {String} eventName event to stop listening to + @param {Function} callback optional argument. If given, only the function + given will be removed from the event's callback queue. If no `callback` + argument is given, all callbacks will be removed from the event's callback + queue. + */ + off: function (eventName, callback) { + var allCallbacks = callbacksFor(this), + callbacks = void 0, + index = void 0; + + if (!callback) { + allCallbacks[eventName] = []; + return; + } + + callbacks = allCallbacks[eventName]; + + index = indexOf(callbacks, callback); + + if (index !== -1) { + callbacks.splice(index, 1); + } + }, + + + /** + Use `trigger` to fire custom events. For example: + ```javascript + object.on('foo', function(){ + console.log('foo event happened!'); + }); + object.trigger('foo'); + // 'foo event happened!' logged to the console + ``` + You can also pass a value as a second argument to `trigger` that will be + passed as an argument to all event listeners for the event: + ```javascript + object.on('foo', function(value){ + console.log(value.name); + }); + object.trigger('foo', { name: 'bar' }); + // 'bar' logged to the console + ``` + @method trigger + @for RSVP.EventTarget + @private + @param {String} eventName name of the event to be triggered + @param {*} options optional value to be passed to any event handlers for + the given `eventName` + */ + trigger: function (eventName, options, label) { + var allCallbacks = callbacksFor(this), + callbacks = void 0, + callback = void 0; + + if (callbacks = allCallbacks[eventName]) { + // Don't cache the callbacks.length since it may grow + for (var i = 0; i < callbacks.length; i++) { + callback = callbacks[i]; + + callback(options, label); + } + } + } +}; + +var config = { + instrument: false +}; + +EventTarget['mixin'](config); + +function configure(name, value) { + if (arguments.length === 2) { + config[name] = value; + } else { + return config[name]; + } +} + +function objectOrFunction(x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); +} + +function isFunction(x) { + return typeof x === 'function'; +} + +function isObject(x) { + return x !== null && typeof x === 'object'; +} + +function isMaybeThenable(x) { + return x !== null && typeof x === 'object'; +} + +var _isArray = void 0; +if (Array.isArray) { + _isArray = Array.isArray; +} else { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} + +var isArray = _isArray; + +// Date.now is not available in browsers < IE9 +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility +var now = Date.now || function () { + return new Date().getTime(); +}; + +var queue = []; + +function scheduleFlush() { + setTimeout(function () { + for (var i = 0; i < queue.length; i++) { + var entry = queue[i]; + + var payload = entry.payload; + + payload.guid = payload.key + payload.id; + payload.childGuid = payload.key + payload.childId; + if (payload.error) { + payload.stack = payload.error.stack; + } + + config['trigger'](entry.name, entry.payload); + } + queue.length = 0; + }, 50); +} + +function instrument(eventName, promise, child) { + if (1 === queue.push({ + name: eventName, + payload: { + key: promise._guidKey, + id: promise._id, + eventName: eventName, + detail: promise._result, + childId: child && child._id, + label: promise._label, + timeStamp: now(), + error: config["instrument-with-stack"] ? new Error(promise._label) : null + } })) { + scheduleFlush(); + } +} + +/** + `RSVP.Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new RSVP.Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = RSVP.Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {*} object value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve$1(object, label) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop, label); + resolve(promise, object); + return promise; +} + +function withOwnPromise() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { + try { + then$$1.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then$$1) { + config.async(function (promise) { + var sealed = false; + var error = tryThen(then$$1, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + resolve(promise, value, undefined); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + thenable._onError = null; + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + if (thenable !== value) { + resolve(promise, value, undefined); + } else { + fulfill(promise, value); + } + }, function (reason) { + return reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$1) { + var isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$1; + + if (isOwnThenable) { + handleOwnThenable(promise, maybeThenable); + } else if (then$$1 === GET_THEN_ERROR) { + reject(promise, GET_THEN_ERROR.error); + GET_THEN_ERROR.error = null; + } else if (isFunction(then$$1)) { + handleForeignThenable(promise, maybeThenable, then$$1); + } else { + fulfill(promise, maybeThenable); + } +} + +function resolve(promise, value) { + if (promise === value) { + fulfill(promise, value); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onError) { + promise._onError(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length === 0) { + if (config.instrument) { + instrument('fulfilled', promise); + } + } else { + config.async(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + config.async(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onError = null; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + config.async(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (config.instrument) { + instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); + } + + if (subscribers.length === 0) { + return; + } + + var child = void 0, + callback = void 0, + result = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, result); + } else { + callback(result); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, result) { + try { + return callback(result); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(state, promise, callback, result) { + var hasCallback = isFunction(callback); + var value = void 0, + error = void 0; + + if (hasCallback) { + value = tryCatch(callback, result); + + if (value === TRY_CATCH_ERROR) { + error = value.error; + value.error = null; // release + } else if (value === promise) { + reject(promise, withOwnPromise()); + return; + } + } else { + value = result; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && error === undefined) { + resolve(promise, value); + } else if (error !== undefined) { + reject(promise, error); + } else if (state === FULFILLED) { + fulfill(promise, value); + } else if (state === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + var resolved = false; + try { + resolver(function (value) { + if (resolved) { + return; + } + resolved = true; + resolve(promise, value); + }, function (reason) { + if (resolved) { + return; + } + resolved = true; + reject(promise, reason); + }); + } catch (e) { + reject(promise, e); + } +} + +function then(onFulfillment, onRejection, label) { + var parent = this; + var state = parent._state; + + if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { + config.instrument && instrument('chained', parent, parent); + return parent; + } + + parent._onError = null; + + var child = new parent.constructor(noop, label); + var result = parent._result; + + config.instrument && instrument('chained', parent, child); + + if (state === PENDING) { + subscribe(parent, child, onFulfillment, onRejection); + } else { + var callback = state === FULFILLED ? onFulfillment : onRejection; + config.async(function () { + return invokeCallback(state, child, callback, result); + }); + } + + return child; +} + +var Enumerator = function () { + function Enumerator(Constructor, input, abortOnReject, label) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop, label); + this._abortOnReject = abortOnReject; + + this._init.apply(this, arguments); + } + + Enumerator.prototype._init = function _init(Constructor, input) { + var len = input.length || 0; + this.length = len; + this._remaining = len; + this._result = new Array(len); + + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + }; + + Enumerator.prototype._enumerate = function _enumerate(input) { + var length = this.length; + var promise = this.promise; + + for (var i = 0; promise._state === PENDING && i < length; i++) { + this._eachEntry(input[i], i); + } + }; + + Enumerator.prototype._settleMaybeThenable = function _settleMaybeThenable(entry, i) { + var c = this._instanceConstructor; + var resolve$$1 = c.resolve; + + if (resolve$$1 === resolve$1) { + var then$$1 = getThen(entry); + + if (then$$1 === then && entry._state !== PENDING) { + entry._onError = null; + this._settledAt(entry._state, i, entry._result); + } else if (typeof then$$1 !== 'function') { + this._remaining--; + this._result[i] = this._makeResult(FULFILLED, i, entry); + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, then$$1); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$1) { + return resolve$$1(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$1(entry), i); + } + }; + + Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { + if (isMaybeThenable(entry)) { + this._settleMaybeThenable(entry, i); + } else { + this._remaining--; + this._result[i] = this._makeResult(FULFILLED, i, entry); + } + }; + + Enumerator.prototype._settledAt = function _settledAt(state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + if (this._abortOnReject && state === REJECTED) { + reject(promise, value); + } else { + this._remaining--; + this._result[i] = this._makeResult(state, i, value); + if (this._remaining === 0) { + fulfill(promise, this._result); + } + } + } + }; + + Enumerator.prototype._makeResult = function _makeResult(state, i, value) { + return value; + }; + + Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + }; + + return Enumerator; +}(); + +function makeSettledResult(state, position, value) { + if (state === FULFILLED) { + return { + state: 'fulfilled', + value: value + }; + } else { + return { + state: 'rejected', + reason: value + }; + } +} + +/** + `RSVP.Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = RSVP.resolve(1); + let promise2 = RSVP.resolve(2); + let promise3 = RSVP.resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `RSVP.all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = RSVP.resolve(1); + let promise2 = RSVP.reject(new Error("2")); + let promise3 = RSVP.reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries, label) { + if (!isArray(entries)) { + return this.reject(new TypeError("Promise.all must be called with an array"), label); + } + return new Enumerator(this, entries, true /* abort on reject */, label).promise; +} + +/** + `RSVP.Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `RSVP.Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + RSVP.Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} entries array of promises to observe + @param {String} label optional string for describing the promise returned. + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries, label) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(noop, label); + + if (!isArray(entries)) { + reject(promise, new TypeError('Promise.race must be called with an array')); + return promise; + } + + for (var i = 0; promise._state === PENDING && i < entries.length; i++) { + subscribe(Constructor.resolve(entries[i]), undefined, function (value) { + return resolve(promise, value); + }, function (reason) { + return reject(promise, reason); + }); + } + + return promise; +} + +/** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new RSVP.Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = RSVP.Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {*} reason value that the returned promise will be rejected with. + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject$1(reason, label) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop, label); + reject(promise, reason); + return promise; +} + +var guidKey = 'rsvp_' + now() + '-'; +var counter = 0; + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class RSVP.Promise + @param {function} resolver + @param {String} label optional string for labeling the promise. + Useful for tooling. + @constructor +*/ + +var Promise = function () { + function Promise(resolver, label) { + this._id = counter++; + this._label = label; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + config.instrument && instrument('created', this); + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } + } + + Promise.prototype._onError = function _onError(reason) { + var _this = this; + + config.after(function () { + if (_this._onError) { + config.trigger('error', reason, _this._label); + } + }); + }; + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn\'t find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + + + Promise.prototype.catch = function _catch(onRejection, label) { + return this.then(undefined, onRejection, label); + }; + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuthor(); + } finally { + // always runs + // doesn't affect the return value + } + ``` + + Asynchronous example: + + ```js + findAuthor().catch(function(reason){ + return findOtherAuthor(); + }).finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + + + Promise.prototype.finally = function _finally(callback, label) { + var promise = this; + var constructor = promise.constructor; + + return promise.then(function (value) { + return constructor.resolve(callback()).then(function () { + return value; + }); + }, function (reason) { + return constructor.resolve(callback()).then(function () { + throw reason; + }); + }, label); + }; + + return Promise; +}(); + + + +Promise.cast = resolve$1; // deprecated +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve$1; +Promise.reject = reject$1; + +Promise.prototype._guidKey = guidKey; + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we\'re unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + let result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + let author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfillment + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} +*/ +Promise.prototype.then = then; + +function Result() { + this.value = undefined; +} + +var ERROR = new Result(); +var GET_THEN_ERROR$1 = new Result(); + +function getThen$1(obj) { + try { + return obj.then; + } catch (error) { + ERROR.value = error; + return ERROR; + } +} + +function tryApply(f, s, a) { + try { + f.apply(s, a); + } catch (error) { + ERROR.value = error; + return ERROR; + } +} + +function makeObject(_, argumentNames) { + var obj = {}; + var length = _.length; + var args = new Array(length); + + for (var x = 0; x < length; x++) { + args[x] = _[x]; + } + + for (var i = 0; i < argumentNames.length; i++) { + var name = argumentNames[i]; + obj[name] = args[i + 1]; + } + + return obj; +} + +function arrayResult(_) { + var length = _.length; + var args = new Array(length - 1); + + for (var i = 1; i < length; i++) { + args[i - 1] = _[i]; + } + + return args; +} + +function wrapThenable(then, promise) { + return { + then: function (onFulFillment, onRejection) { + return then.call(promise, onFulFillment, onRejection); + } + }; +} + +/** + `RSVP.denodeify` takes a 'node-style' function and returns a function that + will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the + browser when you'd prefer to use promises over using callbacks. For example, + `denodeify` transforms the following: + + ```javascript + let fs = require('fs'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + handleData(data); + }); + ``` + + into: + + ```javascript + let fs = require('fs'); + let readFile = RSVP.denodeify(fs.readFile); + + readFile('myfile.txt').then(handleData, handleError); + ``` + + If the node function has multiple success parameters, then `denodeify` + just returns the first one: + + ```javascript + let request = RSVP.denodeify(require('request')); + + request('http://example.com').then(function(res) { + // ... + }); + ``` + + However, if you need all success parameters, setting `denodeify`'s + second parameter to `true` causes it to return all success parameters + as an array: + + ```javascript + let request = RSVP.denodeify(require('request'), true); + + request('http://example.com').then(function(result) { + // result[0] -> res + // result[1] -> body + }); + ``` + + Or if you pass it an array with names it returns the parameters as a hash: + + ```javascript + let request = RSVP.denodeify(require('request'), ['res', 'body']); + + request('http://example.com').then(function(result) { + // result.res + // result.body + }); + ``` + + Sometimes you need to retain the `this`: + + ```javascript + let app = require('express')(); + let render = RSVP.denodeify(app.render.bind(app)); + ``` + + The denodified function inherits from the original function. It works in all + environments, except IE 10 and below. Consequently all properties of the original + function are available to you. However, any properties you change on the + denodeified function won't be changed on the original function. Example: + + ```javascript + let request = RSVP.denodeify(require('request')), + cookieJar = request.jar(); // <- Inheritance is used here + + request('http://example.com', {jar: cookieJar}).then(function(res) { + // cookieJar.cookies holds now the cookies returned by example.com + }); + ``` + + Using `denodeify` makes it easier to compose asynchronous operations instead + of using callbacks. For example, instead of: + + ```javascript + let fs = require('fs'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) { ... } // Handle error + fs.writeFile('myfile2.txt', data, function(err){ + if (err) { ... } // Handle error + console.log('done') + }); + }); + ``` + + you can chain the operations together using `then` from the returned promise: + + ```javascript + let fs = require('fs'); + let readFile = RSVP.denodeify(fs.readFile); + let writeFile = RSVP.denodeify(fs.writeFile); + + readFile('myfile.txt').then(function(data){ + return writeFile('myfile2.txt', data); + }).then(function(){ + console.log('done') + }).catch(function(error){ + // Handle error + }); + ``` + + @method denodeify + @static + @for RSVP + @param {Function} nodeFunc a 'node-style' function that takes a callback as + its last argument. The callback expects an error to be passed as its first + argument (if an error occurred, otherwise null), and the value from the + operation as its second argument ('function(err, value){ }'). + @param {Boolean|Array} [options] An optional paramter that if set + to `true` causes the promise to fulfill with the callback's success arguments + as an array. This is useful if the node function has multiple success + paramters. If you set this paramter to an array with names, the promise will + fulfill with a hash with these names as keys and the success parameters as + values. + @return {Function} a function that wraps `nodeFunc` to return an + `RSVP.Promise` + @static +*/ +function denodeify(nodeFunc, options) { + var fn = function () { + var self = this; + var l = arguments.length; + var args = new Array(l + 1); + var promiseInput = false; + + for (var i = 0; i < l; ++i) { + var arg = arguments[i]; + + if (!promiseInput) { + // TODO: clean this up + promiseInput = needsPromiseInput(arg); + if (promiseInput === GET_THEN_ERROR$1) { + var p = new Promise(noop); + reject(p, GET_THEN_ERROR$1.value); + return p; + } else if (promiseInput && promiseInput !== true) { + arg = wrapThenable(promiseInput, arg); + } + } + args[i] = arg; + } + + var promise = new Promise(noop); + + args[l] = function (err, val) { + if (err) reject(promise, err);else if (options === undefined) resolve(promise, val);else if (options === true) resolve(promise, arrayResult(arguments));else if (isArray(options)) resolve(promise, makeObject(arguments, options));else resolve(promise, val); + }; + + if (promiseInput) { + return handlePromiseInput(promise, args, nodeFunc, self); + } else { + return handleValueInput(promise, args, nodeFunc, self); + } + }; + + fn.__proto__ = nodeFunc; + + return fn; +} + +function handleValueInput(promise, args, nodeFunc, self) { + var result = tryApply(nodeFunc, self, args); + if (result === ERROR) { + reject(promise, result.value); + } + return promise; +} + +function handlePromiseInput(promise, args, nodeFunc, self) { + return Promise.all(args).then(function (args) { + var result = tryApply(nodeFunc, self, args); + if (result === ERROR) { + reject(promise, result.value); + } + return promise; + }); +} + +function needsPromiseInput(arg) { + if (arg && typeof arg === 'object') { + if (arg.constructor === Promise) { + return true; + } else { + return getThen$1(arg); + } + } else { + return false; + } +} + +/** + This is a convenient alias for `RSVP.Promise.all`. + + @method all + @static + @for RSVP + @param {Array} array Array of promises. + @param {String} label An optional label. This is useful + for tooling. +*/ +function all$1(array, label) { + return Promise.all(array, label); +} + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var AllSettled = function (_Enumerator) { + _inherits(AllSettled, _Enumerator); + + function AllSettled(Constructor, entries, label) { + return _possibleConstructorReturn(this, _Enumerator.call(this, Constructor, entries, false /* don't abort on reject */, label)); + } + + return AllSettled; +}(Enumerator); + +AllSettled.prototype._makeResult = makeSettledResult; + +/** +`RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing +a fail-fast method, it waits until all the promises have returned and +shows you all the results. This is useful if you want to handle multiple +promises' failure states together as a set. + Returns a promise that is fulfilled when all the given promises have been +settled. The return promise is fulfilled with an array of the states of +the promises passed into the `promises` array argument. + Each state object will either indicate fulfillment or rejection, and +provide the corresponding value or reason. The states will take one of +the following formats: + ```javascript +{ state: 'fulfilled', value: value } + or +{ state: 'rejected', reason: reason } +``` + Example: + ```javascript +let promise1 = RSVP.Promise.resolve(1); +let promise2 = RSVP.Promise.reject(new Error('2')); +let promise3 = RSVP.Promise.reject(new Error('3')); +let promises = [ promise1, promise2, promise3 ]; + RSVP.allSettled(promises).then(function(array){ + // array == [ + // { state: 'fulfilled', value: 1 }, + // { state: 'rejected', reason: Error }, + // { state: 'rejected', reason: Error } + // ] + // Note that for the second item, reason.message will be '2', and for the + // third item, reason.message will be '3'. +}, function(error) { + // Not run. (This block would only be called if allSettled had failed, + // for instance if passed an incorrect argument type.) +}); +``` + @method allSettled +@static +@for RSVP +@param {Array} entries +@param {String} label - optional string that describes the promise. +Useful for tooling. +@return {Promise} promise that is fulfilled with an array of the settled +states of the constituent promises. +*/ + +function allSettled(entries, label) { + if (!isArray(entries)) { + return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label); + } + + return new AllSettled(Promise, entries, label).promise; +} + +/** + This is a convenient alias for `RSVP.Promise.race`. + + @method race + @static + @for RSVP + @param {Array} array Array of promises. + @param {String} label An optional label. This is useful + for tooling. + */ +function race$1(array, label) { + return Promise.race(array, label); +} + +function _possibleConstructorReturn$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var PromiseHash = function (_Enumerator) { + _inherits$1(PromiseHash, _Enumerator); + + function PromiseHash(Constructor, object) { + var abortOnReject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + var label = arguments[3]; + return _possibleConstructorReturn$1(this, _Enumerator.call(this, Constructor, object, abortOnReject, label)); + } + + PromiseHash.prototype._init = function _init(Constructor, object) { + this._result = {}; + + this._enumerate(object); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + }; + + PromiseHash.prototype._enumerate = function _enumerate(input) { + var promise = this.promise; + var results = []; + + for (var key in input) { + if (hasOwnProperty.call(input, key)) { + results.push({ + position: key, + entry: input[key] + }); + } + } + + var length = results.length; + this._remaining = length; + var result = void 0; + + for (var i = 0; promise._state === PENDING && i < length; i++) { + result = results[i]; + this._eachEntry(result.entry, result.position); + } + }; + + return PromiseHash; +}(Enumerator); + +/** + `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array + for its `promises` argument. + + Returns a promise that is fulfilled when all the given promises have been + fulfilled, or rejected if any of them become rejected. The returned promise + is fulfilled with a hash that has the same key names as the `promises` object + argument. If any of the values in the object are not promises, they will + simply be copied over to the fulfilled object. + + Example: + + ```javascript + let promises = { + myPromise: RSVP.resolve(1), + yourPromise: RSVP.resolve(2), + theirPromise: RSVP.resolve(3), + notAPromise: 4 + }; + + RSVP.hash(promises).then(function(hash){ + // hash here is an object that looks like: + // { + // myPromise: 1, + // yourPromise: 2, + // theirPromise: 3, + // notAPromise: 4 + // } + }); + ```` + + If any of the `promises` given to `RSVP.hash` are rejected, the first promise + that is rejected will be given as the reason to the rejection handler. + + Example: + + ```javascript + let promises = { + myPromise: RSVP.resolve(1), + rejectedPromise: RSVP.reject(new Error('rejectedPromise')), + anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')), + }; + + RSVP.hash(promises).then(function(hash){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === 'rejectedPromise' + }); + ``` + + An important note: `RSVP.hash` is intended for plain JavaScript objects that + are just a set of keys and values. `RSVP.hash` will NOT preserve prototype + chains. + + Example: + + ```javascript + function MyConstructor(){ + this.example = RSVP.resolve('Example'); + } + + MyConstructor.prototype = { + protoProperty: RSVP.resolve('Proto Property') + }; + + let myObject = new MyConstructor(); + + RSVP.hash(myObject).then(function(hash){ + // protoProperty will not be present, instead you will just have an + // object that looks like: + // { + // example: 'Example' + // } + // + // hash.hasOwnProperty('protoProperty'); // false + // 'undefined' === typeof hash.protoProperty + }); + ``` + + @method hash + @static + @for RSVP + @param {Object} object + @param {String} label optional string that describes the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all properties of `promises` + have been fulfilled, or rejected if any of them become rejected. +*/ +function hash(object, label) { + if (!isObject(object)) { + return Promise.reject(new TypeError("Promise.hash must be called with an object"), label); + } + + return new PromiseHash(Promise, object, label).promise; +} + +function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var HashSettled = function (_PromiseHash) { + _inherits$2(HashSettled, _PromiseHash); + + function HashSettled(Constructor, object, label) { + return _possibleConstructorReturn$2(this, _PromiseHash.call(this, Constructor, object, false, label)); + } + + return HashSettled; +}(PromiseHash); + +HashSettled.prototype._makeResult = makeSettledResult; + +/** + `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object + instead of an array for its `promises` argument. + + Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method, + but like `RSVP.allSettled`, `hashSettled` waits until all the + constituent promises have returned and then shows you all the results + with their states and values/reasons. This is useful if you want to + handle multiple promises' failure states together as a set. + + Returns a promise that is fulfilled when all the given promises have been + settled, or rejected if the passed parameters are invalid. + + The returned promise is fulfilled with a hash that has the same key names as + the `promises` object argument. If any of the values in the object are not + promises, they will be copied over to the fulfilled object and marked with state + 'fulfilled'. + + Example: + + ```javascript + let promises = { + myPromise: RSVP.Promise.resolve(1), + yourPromise: RSVP.Promise.resolve(2), + theirPromise: RSVP.Promise.resolve(3), + notAPromise: 4 + }; + + RSVP.hashSettled(promises).then(function(hash){ + // hash here is an object that looks like: + // { + // myPromise: { state: 'fulfilled', value: 1 }, + // yourPromise: { state: 'fulfilled', value: 2 }, + // theirPromise: { state: 'fulfilled', value: 3 }, + // notAPromise: { state: 'fulfilled', value: 4 } + // } + }); + ``` + + If any of the `promises` given to `RSVP.hash` are rejected, the state will + be set to 'rejected' and the reason for rejection provided. + + Example: + + ```javascript + let promises = { + myPromise: RSVP.Promise.resolve(1), + rejectedPromise: RSVP.Promise.reject(new Error('rejection')), + anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')), + }; + + RSVP.hashSettled(promises).then(function(hash){ + // hash here is an object that looks like: + // { + // myPromise: { state: 'fulfilled', value: 1 }, + // rejectedPromise: { state: 'rejected', reason: Error }, + // anotherRejectedPromise: { state: 'rejected', reason: Error }, + // } + // Note that for rejectedPromise, reason.message == 'rejection', + // and for anotherRejectedPromise, reason.message == 'more rejection'. + }); + ``` + + An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that + are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype + chains. + + Example: + + ```javascript + function MyConstructor(){ + this.example = RSVP.Promise.resolve('Example'); + } + + MyConstructor.prototype = { + protoProperty: RSVP.Promise.resolve('Proto Property') + }; + + let myObject = new MyConstructor(); + + RSVP.hashSettled(myObject).then(function(hash){ + // protoProperty will not be present, instead you will just have an + // object that looks like: + // { + // example: { state: 'fulfilled', value: 'Example' } + // } + // + // hash.hasOwnProperty('protoProperty'); // false + // 'undefined' === typeof hash.protoProperty + }); + ``` + + @method hashSettled + @for RSVP + @param {Object} object + @param {String} label optional string that describes the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when when all properties of `promises` + have been settled. + @static +*/ + +function hashSettled(object, label) { + if (!isObject(object)) { + return Promise.reject(new TypeError("RSVP.hashSettled must be called with an object"), label); + } + + return new HashSettled(Promise, object, false, label).promise; +} + +/** + `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event + loop in order to aid debugging. + + Promises A+ specifies that any exceptions that occur with a promise must be + caught by the promises implementation and bubbled to the last handler. For + this reason, it is recommended that you always specify a second rejection + handler function to `then`. However, `RSVP.rethrow` will throw the exception + outside of the promise, so it bubbles up to your console if in the browser, + or domain/cause uncaught exception in Node. `rethrow` will also throw the + error again so the error can be handled by the promise per the spec. + + ```javascript + function throws(){ + throw new Error('Whoops!'); + } + + let promise = new RSVP.Promise(function(resolve, reject){ + throws(); + }); + + promise.catch(RSVP.rethrow).then(function(){ + // Code here doesn't run because the promise became rejected due to an + // error! + }, function (err){ + // handle the error here + }); + ``` + + The 'Whoops' error will be thrown on the next turn of the event loop + and you can watch for it in your console. You can also handle it using a + rejection handler given to `.then` or `.catch` on the returned promise. + + @method rethrow + @static + @for RSVP + @param {Error} reason reason the promise became rejected. + @throws Error + @static +*/ +function rethrow(reason) { + setTimeout(function () { + throw reason; + }); + throw reason; +} + +/** + `RSVP.defer` returns an object similar to jQuery's `$.Deferred`. + `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s + interface. New code should use the `RSVP.Promise` constructor instead. + + The object returned from `RSVP.defer` is a plain object with three properties: + + * promise - an `RSVP.Promise`. + * reject - a function that causes the `promise` property on this object to + become rejected + * resolve - a function that causes the `promise` property on this object to + become fulfilled. + + Example: + + ```javascript + let deferred = RSVP.defer(); + + deferred.resolve("Success!"); + + deferred.promise.then(function(value){ + // value here is "Success!" + }); + ``` + + @method defer + @static + @for RSVP + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Object} + */ + +function defer(label) { + var deferred = { resolve: undefined, reject: undefined }; + + deferred.promise = new Promise(function (resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }, label); + + return deferred; +} + +/** + `RSVP.map` is similar to JavaScript's native `map` method, except that it + waits for all promises to become fulfilled before running the `mapFn` on + each item in given to `promises`. `RSVP.map` returns a promise that will + become fulfilled with the result of running `mapFn` on the values the promises + become fulfilled with. + + For example: + + ```javascript + + let promise1 = RSVP.resolve(1); + let promise2 = RSVP.resolve(2); + let promise3 = RSVP.resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + let mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(result){ + // result is [ 2, 3, 4 ] + }); + ``` + + If any of the `promises` given to `RSVP.map` are rejected, the first promise + that is rejected will be given as an argument to the returned promise's + rejection handler. For example: + + ```javascript + let promise1 = RSVP.resolve(1); + let promise2 = RSVP.reject(new Error('2')); + let promise3 = RSVP.reject(new Error('3')); + let promises = [ promise1, promise2, promise3 ]; + + let mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === '2' + }); + ``` + + `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, + say you want to get all comments from a set of blog posts, but you need + the blog posts first because they contain a url to those comments. + + ```javscript + + let mapFn = function(blogPost){ + // getComments does some ajax and returns an RSVP.Promise that is fulfilled + // with some comments data + return getComments(blogPost.comments_url); + }; + + // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled + // with some blog post data + RSVP.map(getBlogPosts(), mapFn).then(function(comments){ + // comments is the result of asking the server for the comments + // of all blog posts returned from getBlogPosts() + }); + ``` + + @method map + @static + @for RSVP + @param {Array} promises + @param {Function} mapFn function to be called on each fulfilled promise. + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled with the result of calling + `mapFn` on each fulfilled promise or value when they become fulfilled. + The promise will be rejected if any of the given `promises` become rejected. + @static +*/ +function map(promises, mapFn, label) { + if (!isArray(promises)) { + return Promise.reject(new TypeError("RSVP.map must be called with an array"), label); + } + + if (!isFunction(mapFn)) { + return Promise.reject(new TypeError("RSVP.map expects a function as a second argument"), label); + } + + return Promise.all(promises, label).then(function (values) { + var length = values.length; + var results = new Array(length); + + for (var i = 0; i < length; i++) { + results[i] = mapFn(values[i]); + } + + return Promise.all(results, label); + }); +} + +/** + This is a convenient alias for `RSVP.Promise.resolve`. + + @method resolve + @static + @for RSVP + @param {*} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve$2(value, label) { + return Promise.resolve(value, label); +} + +/** + This is a convenient alias for `RSVP.Promise.reject`. + + @method reject + @static + @for RSVP + @param {*} reason value that the returned promise will be rejected with. + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject$2(reason, label) { + return Promise.reject(reason, label); +} + +/** + `RSVP.filter` is similar to JavaScript's native `filter` method, except that it + waits for all promises to become fulfilled before running the `filterFn` on + each item in given to `promises`. `RSVP.filter` returns a promise that will + become fulfilled with the result of running `filterFn` on the values the + promises become fulfilled with. + + For example: + + ```javascript + + let promise1 = RSVP.resolve(1); + let promise2 = RSVP.resolve(2); + let promise3 = RSVP.resolve(3); + + let promises = [promise1, promise2, promise3]; + + let filterFn = function(item){ + return item > 1; + }; + + RSVP.filter(promises, filterFn).then(function(result){ + // result is [ 2, 3 ] + }); + ``` + + If any of the `promises` given to `RSVP.filter` are rejected, the first promise + that is rejected will be given as an argument to the returned promise's + rejection handler. For example: + + ```javascript + let promise1 = RSVP.resolve(1); + let promise2 = RSVP.reject(new Error('2')); + let promise3 = RSVP.reject(new Error('3')); + let promises = [ promise1, promise2, promise3 ]; + + let filterFn = function(item){ + return item > 1; + }; + + RSVP.filter(promises, filterFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === '2' + }); + ``` + + `RSVP.filter` will also wait for any promises returned from `filterFn`. + For instance, you may want to fetch a list of users then return a subset + of those users based on some asynchronous operation: + + ```javascript + + let alice = { name: 'alice' }; + let bob = { name: 'bob' }; + let users = [ alice, bob ]; + + let promises = users.map(function(user){ + return RSVP.resolve(user); + }); + + let filterFn = function(user){ + // Here, Alice has permissions to create a blog post, but Bob does not. + return getPrivilegesForUser(user).then(function(privs){ + return privs.can_create_blog_post === true; + }); + }; + RSVP.filter(promises, filterFn).then(function(users){ + // true, because the server told us only Alice can create a blog post. + users.length === 1; + // false, because Alice is the only user present in `users` + users[0] === bob; + }); + ``` + + @method filter + @static + @for RSVP + @param {Array} promises + @param {Function} filterFn - function to be called on each resolved value to + filter the final results. + @param {String} label optional string describing the promise. Useful for + tooling. + @return {Promise} +*/ + +function resolveAll(promises, label) { + return Promise.all(promises, label); +} + +function resolveSingle(promise, label) { + return Promise.resolve(promise, label).then(function (promises) { + return resolveAll(promises, label); + }); +} + +function filter(promises, filterFn, label) { + if (!isArray(promises) && !(isObject(promises) && promises.then !== undefined)) { + return Promise.reject(new TypeError("RSVP.filter must be called with an array or promise"), label); + } + + if (!isFunction(filterFn)) { + return Promise.reject(new TypeError("RSVP.filter expects function as a second argument"), label); + } + + var promise = isArray(promises) ? resolveAll(promises, label) : resolveSingle(promises, label); + return promise.then(function (values) { + var length = values.length; + var filtered = new Array(length); + + for (var i = 0; i < length; i++) { + filtered[i] = filterFn(values[i]); + } + + return resolveAll(filtered, label).then(function (filtered) { + var results = new Array(length); + var newLength = 0; + + for (var _i = 0; _i < length; _i++) { + if (filtered[_i]) { + results[newLength] = values[_i]; + newLength++; + } + } + + results.length = newLength; + + return results; + }); + }); +} + +var len = 0; +var vertxNext = void 0; +function asap(callback, arg) { + queue$1[len] = callback; + queue$1[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 1, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + scheduleFlush$1(); + } +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function () { + return nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + return node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + return function () { + return setTimeout(flush, 1); + }; +} + +var queue$1 = new Array(1000); + +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue$1[i]; + var arg = queue$1[i + 1]; + + callback(arg); + + queue$1[i] = undefined; + queue$1[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush$1 = void 0; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush$1 = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush$1 = useMutationObserver(); +} else if (isWorker) { + scheduleFlush$1 = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush$1 = attemptVertex(); +} else { + scheduleFlush$1 = useSetTimeout(); +} + +var platform = void 0; + +/* global self */ +if (typeof self === 'object') { + platform = self; + + /* global global */ +} else if (typeof global === 'object') { + platform = global; +} else { + throw new Error('no global: `self` or `global` found'); +} + +var _asap$cast$Promise$Ev; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// defaults +config.async = asap; +config.after = function (cb) { + return setTimeout(cb, 0); +}; +var cast = resolve$2; + +var async = function (callback, arg) { + return config.async(callback, arg); +}; + +function on() { + config['on'].apply(config, arguments); +} + +function off() { + config['off'].apply(config, arguments); +} + +// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` +if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { + var callbacks = window['__PROMISE_INSTRUMENTATION__']; + configure('instrument', true); + for (var eventName in callbacks) { + if (callbacks.hasOwnProperty(eventName)) { + on(eventName, callbacks[eventName]); + } + } +} + +// the default export here is for backwards compat: +// https://github.com/tildeio/rsvp.js/issues/434 +var rsvp = (_asap$cast$Promise$Ev = { + asap: asap, + cast: cast, + Promise: Promise, + EventTarget: EventTarget, + all: all$1, + allSettled: allSettled, + race: race$1, + hash: hash, + hashSettled: hashSettled, + rethrow: rethrow, + defer: defer, + denodeify: denodeify, + configure: configure, + on: on, + off: off, + resolve: resolve$2, + reject: reject$2, + map: map +}, _defineProperty(_asap$cast$Promise$Ev, 'async', async), _defineProperty(_asap$cast$Promise$Ev, 'filter', filter), _asap$cast$Promise$Ev); + +exports['default'] = rsvp; +exports.asap = asap; +exports.cast = cast; +exports.Promise = Promise; +exports.EventTarget = EventTarget; +exports.all = all$1; +exports.allSettled = allSettled; +exports.race = race$1; +exports.hash = hash; +exports.hashSettled = hashSettled; +exports.rethrow = rethrow; +exports.defer = defer; +exports.denodeify = denodeify; +exports.configure = configure; +exports.on = on; +exports.off = off; +exports.resolve = resolve$2; +exports.reject = reject$2; +exports.map = map; +exports.async = async; +exports.filter = filter; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + +// + +var EPUBJS = EPUBJS || {}; +EPUBJS.core = {}; + +var ELEMENT_NODE = 1; +var TEXT_NODE = 3; +var COMMENT_NODE = 8; +var DOCUMENT_NODE = 9; + +//-- Get a element for an id +EPUBJS.core.getEl = function(elem) { + return document.getElementById(elem); +}; + +//-- Get all elements for a class +EPUBJS.core.getEls = function(classes) { + return document.getElementsByClassName(classes); +}; + +EPUBJS.core.request = function(url, type, withCredentials) { + var supportsURL = window.URL; + var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; + var deferred = new RSVP.defer(); + var xhr = new XMLHttpRequest(); + var uri; + + //-- Check from PDF.js: + // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js + var xhrPrototype = XMLHttpRequest.prototype; + + var handler = function() { + var r; + + if (this.readyState != this.DONE) return; + + if ((this.status === 200 || this.status === 0) && this.response) { // Android & Firefox reporting 0 for local & blob urls + if (type == 'xml'){ + // If this.responseXML wasn't set, try to parse using a DOMParser from text + if(!this.responseXML) { + r = new DOMParser().parseFromString(this.response, "application/xml"); + } else { + r = this.responseXML; + } + } else if (type == 'xhtml') { + if (!this.responseXML){ + r = new DOMParser().parseFromString(this.response, "application/xhtml+xml"); + } else { + r = this.responseXML; + } + } else if (type == 'html') { + if (!this.responseXML){ + r = new DOMParser().parseFromString(this.response, "text/html"); + } else { + r = this.responseXML; + } + } else if (type == 'json') { + r = JSON.parse(this.response); + } else if (type == 'blob') { + if (supportsURL) { + r = this.response; + } else { + //-- Safari doesn't support responseType blob, so create a blob from arraybuffer + r = new Blob([this.response]); + } + } else { + r = this.response; + } + + deferred.resolve(r); + } else { + deferred.reject({ + message : this.response, + stack : new Error().stack + }); + } + }; + + if (!('overrideMimeType' in xhrPrototype)) { + // IE10 might have response, but not overrideMimeType + Object.defineProperty(xhrPrototype, 'overrideMimeType', { + value: function xmlHttpRequestOverrideMimeType(mimeType) {} + }); + } + + xhr.onreadystatechange = handler; + xhr.open("GET", url, true); + + if(withCredentials) { + xhr.withCredentials = true; + } + + // If type isn't set, determine it from the file extension + if(!type) { + uri = EPUBJS.core.uri(url); + type = uri.extension; + type = { + 'htm': 'html' + }[type] || type; + } + + if(type == 'blob'){ + xhr.responseType = BLOB_RESPONSE; + } + + if(type == "json") { + xhr.setRequestHeader("Accept", "application/json"); + } + + if(type == 'xml') { + xhr.responseType = "document"; + xhr.overrideMimeType('text/xml'); // for OPF parsing + } + + if(type == 'xhtml') { + xhr.responseType = "document"; + } + + if(type == 'html') { + xhr.responseType = "document"; + } + + if(type == "binary") { + xhr.responseType = "arraybuffer"; + } + + xhr.send(); + + return deferred.promise; +}; + +EPUBJS.core.toArray = function(obj) { + var arr = []; + + for (var member in obj) { + var newitm; + if ( obj.hasOwnProperty(member) ) { + newitm = obj[member]; + newitm.ident = member; + arr.push(newitm); + } + } + + return arr; +}; + +//-- Parse the different parts of a url, returning a object +EPUBJS.core.uri = function(url){ + var uri = { + protocol : '', + host : '', + path : '', + origin : '', + directory : '', + base : '', + filename : '', + extension : '', + fragment : '', + href : url + }, + blob = url.indexOf('blob:'), + doubleSlash = url.indexOf('://'), + search = url.indexOf('?'), + fragment = url.indexOf("#"), + withoutProtocol, + dot, + firstSlash; + + if(blob === 0) { + uri.protocol = "blob"; + uri.base = url.indexOf(0, fragment); + return uri; + } + + if(fragment != -1) { + uri.fragment = url.slice(fragment + 1); + url = url.slice(0, fragment); + } + + if(search != -1) { + uri.search = url.slice(search + 1); + url = url.slice(0, search); + href = uri.href; + } + + if(doubleSlash != -1) { + uri.protocol = url.slice(0, doubleSlash); + withoutProtocol = url.slice(doubleSlash+3); + firstSlash = withoutProtocol.indexOf('/'); + + if(firstSlash === -1) { + uri.host = uri.path; + uri.path = ""; + } else { + uri.host = withoutProtocol.slice(0, firstSlash); + uri.path = withoutProtocol.slice(firstSlash); + } + + + uri.origin = uri.protocol + "://" + uri.host; + + uri.directory = EPUBJS.core.folder(uri.path); + + uri.base = uri.origin + uri.directory; + // return origin; + } else { + uri.path = url; + uri.directory = EPUBJS.core.folder(url); + uri.base = uri.directory; + } + + //-- Filename + uri.filename = url.replace(uri.base, ''); + dot = uri.filename.lastIndexOf('.'); + if(dot != -1) { + uri.extension = uri.filename.slice(dot+1); + } + return uri; +}; + +//-- Parse out the folder, will return everything before the last slash + +EPUBJS.core.folder = function(url){ + + var lastSlash = url.lastIndexOf('/'); + + if(lastSlash == -1) var folder = ''; + + folder = url.slice(0, lastSlash + 1); + + return folder; + +}; + +//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 +EPUBJS.core.dataURLToBlob = function(dataURL) { + var BASE64_MARKER = ';base64,', + parts, contentType, raw, rawLength, uInt8Array; + + if (dataURL.indexOf(BASE64_MARKER) == -1) { + parts = dataURL.split(','); + contentType = parts[0].split(':')[1]; + raw = parts[1]; + + return new Blob([raw], {type: contentType}); + } + + parts = dataURL.split(BASE64_MARKER); + contentType = parts[0].split(':')[1]; + raw = window.atob(parts[1]); + rawLength = raw.length; + + uInt8Array = new Uint8Array(rawLength); + + for (var i = 0; i < rawLength; ++i) { + uInt8Array[i] = raw.charCodeAt(i); + } + + return new Blob([uInt8Array], {type: contentType}); +}; + +//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously +EPUBJS.core.addScript = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('script'); + s.type = 'text/javascript'; + s.async = false; + s.src = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.addScripts = function(srcArr, callback, target) { + var total = srcArr.length, + curr = 0, + cb = function(){ + curr++; + if(total == curr){ + if(callback) callback(); + }else{ + EPUBJS.core.addScript(srcArr[curr], cb, target); + } + }; + + EPUBJS.core.addScript(srcArr[curr], cb, target); +}; + +EPUBJS.core.addCss = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('link'); + s.type = 'text/css'; + s.rel = "stylesheet"; + s.href = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.prefixed = function(unprefixed) { + var vendors = ["Webkit", "Moz", "O", "ms" ], + prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], + upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), + length = vendors.length; + + if (typeof(document.documentElement.style[unprefixed]) != 'undefined') { + return unprefixed; + } + + for ( var i=0; i < length; i++ ) { + if (typeof(document.documentElement.style[vendors[i] + upper]) != 'undefined') { + return vendors[i] + upper; + } + } + + return unprefixed; +}; + +EPUBJS.core.resolveUrl = function(base, path) { + var url, + segments = [], + uri = EPUBJS.core.uri(path), + folders = base.split("/"), + paths; + + if(uri.host) { + return path; + } + + folders.pop(); + + paths = path.split("/"); + paths.forEach(function(p){ + if(p === ".."){ + folders.pop(); + }else{ + segments.push(p); + } + }); + + url = folders.concat(segments); + + return url.join("/"); +}; + +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript +EPUBJS.core.uuid = function() { + var d = new Date().getTime(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = (d + Math.random()*16)%16 | 0; + d = Math.floor(d/16); + return (c=='x' ? r : (r&0x7|0x8)).toString(16); + }); + return uuid; +}; + +// Fast quicksort insert for sorted array -- based on: +// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers +EPUBJS.core.insert = function(item, array, compareFunction) { + var location = EPUBJS.core.locationOf(item, array, compareFunction); + array.splice(location, 0, item); + + return location; +}; + +EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return pivot; + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared > 0 ? pivot : pivot + 1; + } + + if(compared === 0) { + return pivot; + } + if(compared === -1) { + return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); + } +}; + +EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return -1; // Not found + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared === 0 ? pivot : -1; + } + if(compared === 0) { + return pivot; // Found + } + if(compared === -1) { + return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); + } +}; + + +EPUBJS.core.queue = function(_scope){ + var _q = []; + var scope = _scope; + // Add an item to the queue + var enqueue = function(funcName, args, context) { + _q.push({ + "funcName" : funcName, + "args" : args, + "context" : context + }); + return _q; + }; + // Run one item + var dequeue = function(){ + var inwait; + if(_q.length) { + inwait = _q.shift(); + // Defer to any current tasks + // setTimeout(function(){ + scope[inwait.funcName].apply(inwait.context || scope, inwait.args); + // }, 0); + } + }; + + // Run All + var flush = function(){ + while(_q.length) { + dequeue(); + } + }; + // Clear all items in wait + var clear = function(){ + _q = []; + }; + + var length = function(){ + return _q.length; + }; + + return { + "enqueue" : enqueue, + "dequeue" : dequeue, + "flush" : flush, + "clear" : clear, + "length" : length + }; +}; + +// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js +/** + * Gets an XPath for an element which describes its hierarchical location. + */ +EPUBJS.core.getElementXPath = function(element) { + if (element && element.id) { + return '//*[@id="' + element.id + '"]'; + } else { + return EPUBJS.core.getElementTreeXPath(element); + } +}; + +EPUBJS.core.getElementTreeXPath = function(element) { + var paths = []; + var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); + var index, nodeName, tagName, pathIndex; + + if(element.nodeType === Node.TEXT_NODE){ + // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; + index = EPUBJS.core.indexOfTextNode(element) + 1; + + paths.push("text()["+index+"]"); + element = element.parentNode; + } + + // Use nodeName (instead of localName) so namespace prefix is included (if any). + for (; element && element.nodeType == 1; element = element.parentNode) + { + index = 0; + for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) + { + // Ignore document type declaration. + if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { + continue; + } + if (sibling.nodeName == element.nodeName) { + ++index; + } + } + nodeName = element.nodeName.toLowerCase(); + tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); + pathIndex = (index ? "[" + (index+1) + "]" : ""); + paths.splice(0, 0, tagName + pathIndex); + } + + return paths.length ? "./" + paths.join("/") : null; +}; + +EPUBJS.core.nsResolver = function(prefix) { + var ns = { + 'xhtml' : 'http://www.w3.org/1999/xhtml', + 'epub': 'http://www.idpf.org/2007/ops' + }; + return ns[prefix] || null; +}; + +//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 +EPUBJS.core.cleanStringForXpath = function(str) { + var parts = str.match(/[^'"]+|['"]/g); + parts = parts.map(function(part){ + if (part === "'") { + return '\"\'\"'; // output "'" + } + + if (part === '"') { + return "\'\"\'"; // output '"' + } + return "\'" + part + "\'"; + }); + return "concat(\'\'," + parts.join(",") + ")"; +}; + +EPUBJS.core.indexOfTextNode = function(textNode){ + var parent = textNode.parentNode; + var children = parent.childNodes; + var sib; + var index = -1; + for (var i = 0; i < children.length; i++) { + sib = children[i]; + if(sib.nodeType === Node.TEXT_NODE){ + index++; + } + if(sib == textNode) break; + } + + return index; +}; + +// Underscore +EPUBJS.core.defaults = function(obj) { + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + for (var prop in source) { + if (obj[prop] === void 0) obj[prop] = source[prop]; + } + } + return obj; +}; + +EPUBJS.core.extend = function(target) { + var sources = [].slice.call(arguments, 1); + sources.forEach(function (source) { + if(!source) return; + Object.getOwnPropertyNames(source).forEach(function(propName) { + Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); + }); + }); + return target; +}; + +EPUBJS.core.clone = function(obj) { + return EPUBJS.core.isArray(obj) ? obj.slice() : EPUBJS.core.extend({}, obj); +}; + +EPUBJS.core.isElement = function(obj) { + return !!(obj && obj.nodeType == 1); +}; + +EPUBJS.core.isNumber = function(n) { + return !isNaN(parseFloat(n)) && isFinite(n); +}; + +EPUBJS.core.isString = function(str) { + return (typeof str === 'string' || str instanceof String); +}; + +EPUBJS.core.isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; +}; + +// Lodash +EPUBJS.core.values = function(object) { + var index = -1; + var props, length, result; + + if(!object) return []; + + props = Object.keys(object); + length = props.length; + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; +}; + +EPUBJS.core.indexOfNode = function(node, typeId) { + var parent = node.parentNode; + var children = parent.childNodes; + var sib; + var index = -1; + for (var i = 0; i < children.length; i++) { + sib = children[i]; + if (sib.nodeType === typeId) { + index++; + } + if (sib == node) break; + } + + return index; +} + +EPUBJS.core.indexOfTextNode = function(textNode) { + return EPUBJS.core.indexOfNode(textNode, TEXT_NODE); +} + +EPUBJS.core.indexOfElementNode = function(elementNode) { + return EPUBJS.core.indexOfNode(elementNode, ELEMENT_NODE); +} + +var EPUBJS = EPUBJS || {}; +EPUBJS.reader = {}; +EPUBJS.reader.plugins = {}; //-- Attach extra Controllers as plugins (like search?) + +(function(root, $) { + + var previousReader = root.ePubReader || {}; + + var ePubReader = root.ePubReader = function(path, options) { + return new EPUBJS.Reader(path, options); + }; + + //exports to multiple environments + if (typeof define === 'function' && define.amd) { + //AMD + define(function(){ return Reader; }); + } else if (typeof module != "undefined" && module.exports) { + //Node + module.exports = ePubReader; + } + +})(window, jQuery); + +EPUBJS.Reader = function(bookPath, _options) { + var reader = this; + var book; + var plugin; + var $viewer = $("#viewer"); + var search = window.location.search; + var parameters; + + this.settings = EPUBJS.core.defaults(_options || {}, { + bookPath : bookPath, + restore : false, + reload : false, + bookmarks : undefined, + annotations : undefined, + contained : undefined, + bookKey : undefined, + styles : undefined, + sidebarReflow: false, + generatePagination: false, + history: true + }); + + // Overide options with search parameters + if(search) { + parameters = search.slice(1).split("&"); + parameters.forEach(function(p){ + var split = p.split("="); + var name = split[0]; + var value = split[1] || ''; + reader.settings[name] = decodeURIComponent(value); + }); + } + + this.setBookKey(this.settings.bookPath); //-- This could be username + path or any unique string + + if(this.settings.restore && this.isSaved()) { + this.applySavedSettings(); + } + + this.settings.styles = this.settings.styles || { + fontSize : "100%" + }; + + this.book = book = new ePub(this.settings.bookPath, this.settings); + + this.offline = false; + this.sidebarOpen = false; + if(!this.settings.bookmarks) { + this.settings.bookmarks = []; + } + + if(!this.settings.annotations) { + this.settings.annotations = []; + } + + if(this.settings.generatePagination) { + book.generatePagination($viewer.width(), $viewer.height()); + } + + this.rendition = book.renderTo("viewer", { + ignoreClass: "annotator-hl", + width: "100%", + height: "100%" + }); + + if(this.settings.previousLocationCfi) { + this.displayed = this.rendition.display(this.settings.previousLocationCfi); + } else { + this.displayed = this.rendition.display(); + } + + book.ready.then(function () { + reader.ReaderController = EPUBJS.reader.ReaderController.call(reader, book); + reader.SettingsController = EPUBJS.reader.SettingsController.call(reader, book); + reader.ControlsController = EPUBJS.reader.ControlsController.call(reader, book); + reader.SidebarController = EPUBJS.reader.SidebarController.call(reader, book); + reader.BookmarksController = EPUBJS.reader.BookmarksController.call(reader, book); + reader.NotesController = EPUBJS.reader.NotesController.call(reader, book); + + window.addEventListener("hashchange", this.hashChanged.bind(this), false); + + document.addEventListener('keydown', this.adjustFontSize.bind(this), false); + + this.rendition.on("keydown", this.adjustFontSize.bind(this)); + this.rendition.on("keydown", reader.ReaderController.arrowKeys.bind(this)); + + this.rendition.on("selected", this.selectedRange.bind(this)); + }.bind(this)).then(function() { + reader.ReaderController.hideLoader(); + }.bind(this)); + + // Call Plugins + for(plugin in EPUBJS.reader.plugins) { + if(EPUBJS.reader.plugins.hasOwnProperty(plugin)) { + reader[plugin] = EPUBJS.reader.plugins[plugin].call(reader, book); + } + } + + book.loaded.metadata.then(function(meta) { + reader.MetaController = EPUBJS.reader.MetaController.call(reader, meta); + }); + + book.loaded.navigation.then(function(navigation) { + reader.TocController = EPUBJS.reader.TocController.call(reader, navigation); + }); + + window.addEventListener("beforeunload", this.unload.bind(this), false); + + return this; +}; + +EPUBJS.Reader.prototype.adjustFontSize = function(e) { + var fontSize; + var interval = 2; + var PLUS = 187; + var MINUS = 189; + var ZERO = 48; + var MOD = (e.ctrlKey || e.metaKey ); + + if(!this.settings.styles) return; + + /* + if(!this.settings.styles.fontSize) { + this.settings.styles.fontSize = "100%"; + } + + fontSize = parseInt(this.settings.styles.fontSize.slice(0, -1)); + + if(MOD && e.keyCode == PLUS) { + e.preventDefault(); + this.book.setStyle("fontSize", (fontSize + interval) + "%"); + + } + + if(MOD && e.keyCode == MINUS){ + + e.preventDefault(); + this.book.setStyle("fontSize", (fontSize - interval) + "%"); + } + + if(MOD && e.keyCode == ZERO){ + e.preventDefault(); + this.book.setStyle("fontSize", "100%"); + } + */ +}; + +EPUBJS.Reader.prototype.addBookmark = function(cfi) { + var present = this.isBookmarked(cfi); + if(present > -1 ) return; + + this.settings.bookmarks.push(cfi); + + this.trigger("reader:bookmarked", cfi); +}; + +EPUBJS.Reader.prototype.removeBookmark = function(cfi) { + var bookmark = this.isBookmarked(cfi); + if( bookmark === -1 ) return; + + this.settings.bookmarks.splice(bookmark, 1); + + this.trigger("reader:unbookmarked", bookmark); +}; + +EPUBJS.Reader.prototype.isBookmarked = function(cfi) { + var bookmarks = this.settings.bookmarks; + + return bookmarks.indexOf(cfi); +}; + +/* +EPUBJS.Reader.prototype.searchBookmarked = function(cfi) { + var bookmarks = this.settings.bookmarks, + len = bookmarks.length, + i; + + for(i = 0; i < len; i++) { + if (bookmarks[i]['cfi'] === cfi) return i; + } + return -1; +}; +*/ + +EPUBJS.Reader.prototype.clearBookmarks = function() { + this.settings.bookmarks = []; +}; + +//-- Notes +EPUBJS.Reader.prototype.addNote = function(note) { + this.settings.annotations.push(note); +}; + +EPUBJS.Reader.prototype.removeNote = function(note) { + var index = this.settings.annotations.indexOf(note); + if( index === -1 ) return; + + delete this.settings.annotations[index]; + +}; + +EPUBJS.Reader.prototype.clearNotes = function() { + this.settings.annotations = []; +}; + +//-- Settings +EPUBJS.Reader.prototype.setBookKey = function(identifier){ + if(!this.settings.bookKey) { + this.settings.bookKey = "epubjsreader:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; + } + return this.settings.bookKey; +}; + +//-- Checks if the book setting can be retrieved from localStorage +EPUBJS.Reader.prototype.isSaved = function(bookPath) { + var storedSettings; + + if(!localStorage) { + return false; + } + + storedSettings = localStorage.getItem(this.settings.bookKey); + + if(storedSettings === null) { + return false; + } else { + return true; + } +}; + +EPUBJS.Reader.prototype.removeSavedSettings = function() { + if(!localStorage) { + return false; + } + + localStorage.removeItem(this.settings.bookKey); +}; + +EPUBJS.Reader.prototype.applySavedSettings = function() { + var stored; + + if(!localStorage) { + return false; + } + + try { + stored = JSON.parse(localStorage.getItem(this.settings.bookKey)); + } catch (e) { // parsing error of localStorage + return false; + } + + if(stored) { + // Merge styles + if(stored.styles) { + this.settings.styles = EPUBJS.core.defaults(this.settings.styles || {}, stored.styles); + } + // Merge the rest + this.settings = EPUBJS.core.defaults(this.settings, stored); + return true; + } else { + return false; + } +}; + +EPUBJS.Reader.prototype.saveSettings = function(){ + if(this.book) { + this.settings.previousLocationCfi = this.rendition.currentLocation().start.cfi; + } + + if(!localStorage) { + return false; + } + + localStorage.setItem(this.settings.bookKey, JSON.stringify(this.settings)); +}; + +EPUBJS.Reader.prototype.unload = function(){ + if(this.settings.restore && localStorage) { + this.saveSettings(); + } +}; + + +EPUBJS.Reader.prototype.hashChanged = function(){ + var hash = window.location.hash.slice(1); + this.rendition.display(hash); +}; + +EPUBJS.Reader.prototype.selectedRange = function(cfiRange){ + var cfiFragment = "#"+cfiRange; + + // Update the History Location + if(this.settings.history && + window.location.hash != cfiFragment) { + // Add CFI fragment to the history + history.pushState({}, '', cfiFragment); + this.currentLocationCfi = cfiRange; + } +}; + +//-- Enable binding events to reader +RSVP.EventTarget.mixin(EPUBJS.Reader.prototype); + +EPUBJS.reader.BookmarksController = function() { + var reader = this; + var book = this.book; + var rendition = this.rendition; + + var $bookmarks = $("#bookmarksView"), + $list = $bookmarks.find("#bookmarks"); + + var docfrag = document.createDocumentFragment(); + + var show = function() { + $bookmarks.show(); + }; + + var hide = function() { + $bookmarks.hide(); + }; + + var counter = 0; + + var createBookmarkItem = function(cfi) { + var listitem = document.createElement("li"), + link = document.createElement("a"); + + listitem.id = "bookmark-"+counter; + listitem.classList.add('list_item'); + + var spineItem = book.spine.get(cfi); + var tocItem; + if (spineItem.index in book.navigation.toc) { + tocItem = book.navigation.toc[spineItem.index]; + link.textContent = tocItem.label; + } else { + link.textContent = cfi; + } + + link.href = cfi; + + link.classList.add('bookmark_link'); + + link.addEventListener("click", function(event){ + var cfi = this.getAttribute('href'); + rendition.display(cfi); + event.preventDefault(); + }, false); + + listitem.appendChild(link); + + counter++; + + return listitem; + }; + + this.settings.bookmarks.forEach(function(cfi) { + var bookmark = createBookmarkItem(cfi); + docfrag.appendChild(bookmark); + }); + + $list.append(docfrag); + + this.on("reader:bookmarked", function(cfi) { + var item = createBookmarkItem(cfi); + $list.append(item); + }); + + this.on("reader:unbookmarked", function(index) { + var $item = $("#bookmark-"+index); + $item.remove(); + }); + + return { + "show" : show, + "hide" : hide + }; +}; + +EPUBJS.reader.ControlsController = function(book) { + var reader = this; + var rendition = this.rendition; + + var $store = $("#store"), + $fullscreen = $("#fullscreen"), + $fullscreenicon = $("#fullscreenicon"), + $cancelfullscreenicon = $("#cancelfullscreenicon"), + $slider = $("#slider"), + $main = $("#main"), + $sidebar = $("#sidebar"), + $settings = $("#setting"), + $bookmark = $("#bookmark"); + /* + var goOnline = function() { + reader.offline = false; + // $store.attr("src", $icon.data("save")); + }; + + var goOffline = function() { + reader.offline = true; + // $store.attr("src", $icon.data("saved")); + }; + + var fullscreen = false; + + book.on("book:online", goOnline); + book.on("book:offline", goOffline); + */ + $slider.on("click", function () { + if(reader.sidebarOpen) { + reader.SidebarController.hide(); + $slider.addClass("icon-menu"); + $slider.removeClass("icon-right"); + } else { + reader.SidebarController.show(); + $slider.addClass("icon-right"); + $slider.removeClass("icon-menu"); + } + }); + + if(typeof screenfull !== 'undefined') { + $fullscreen.on("click", function() { + screenfull.toggle($('#container')[0]); + }); + if(screenfull.raw) { + document.addEventListener(screenfull.raw.fullscreenchange, function() { + fullscreen = screenfull.isFullscreen; + if(fullscreen) { + $fullscreen + .addClass("icon-resize-small") + .removeClass("icon-resize-full"); + } else { + $fullscreen + .addClass("icon-resize-full") + .removeClass("icon-resize-small"); + } + }); + } + } + + $settings.on("click", function() { + reader.SettingsController.show(); + }); + + $bookmark.on("click", function() { + var cfi = reader.rendition.currentLocation().start.cfi; + var bookmarked = reader.isBookmarked(cfi); + + if(bookmarked === -1) { //-- Add bookmark + reader.addBookmark(cfi); + $bookmark + .addClass("icon-bookmark") + .removeClass("icon-bookmark-empty"); + } else { //-- Remove Bookmark + reader.removeBookmark(cfi); + $bookmark + .removeClass("icon-bookmark") + .addClass("icon-bookmark-empty"); + } + + }); + + rendition.on('relocated', function(location){ + var cfi = location.start.cfi; + var cfiFragment = "#" + cfi; + //-- Check if bookmarked + var bookmarked = reader.isBookmarked(cfi); + if(bookmarked === -1) { //-- Not bookmarked + $bookmark + .removeClass("icon-bookmark") + .addClass("icon-bookmark-empty"); + } else { //-- Bookmarked + $bookmark + .addClass("icon-bookmark") + .removeClass("icon-bookmark-empty"); + } + + reader.currentLocationCfi = cfi; + + // Update the History Location + if(reader.settings.history && + window.location.hash != cfiFragment) { + // Add CFI fragment to the history + history.pushState({}, '', cfiFragment); + } + }); + + return { + + }; +}; + +EPUBJS.reader.MetaController = function(meta) { + var title = meta.title, + author = meta.creator; + + var $title = $("#book-title"), + $author = $("#chapter-title"), + $dash = $("#title-seperator"); + + document.title = title+" – "+author; + + $title.html(title); + $author.html(author); + $dash.show(); +}; + +EPUBJS.reader.NotesController = function() { + var book = this.book; + var rendition = this.rendition; + var reader = this; + var $notesView = $("#notesView"); + var $notes = $("#notes"); + var $text = $("#note-text"); + var $anchor = $("#note-anchor"); + var annotations = reader.settings.annotations; + var renderer = book.renderer; + var popups = []; + var epubcfi = new ePub.CFI(); + + var show = function() { + $notesView.show(); + }; + + var hide = function() { + $notesView.hide(); + } + + var insertAtPoint = function(e) { + var range; + var textNode; + var offset; + var doc = book.renderer.doc; + var cfi; + var annotation; + + // standard + if (doc.caretPositionFromPoint) { + range = doc.caretPositionFromPoint(e.clientX, e.clientY); + textNode = range.offsetNode; + offset = range.offset; + // WebKit + } else if (doc.caretRangeFromPoint) { + range = doc.caretRangeFromPoint(e.clientX, e.clientY); + textNode = range.startContainer; + offset = range.startOffset; + } + + if (textNode.nodeType !== 3) { + for (var i=0; i < textNode.childNodes.length; i++) { + if (textNode.childNodes[i].nodeType == 3) { + textNode = textNode.childNodes[i]; + break; + } + } + } + + // Find the end of the sentance + offset = textNode.textContent.indexOf(".", offset); + if(offset === -1){ + offset = textNode.length; // Last item + } else { + offset += 1; // After the period + } + + cfi = epubcfi.generateCfiFromTextNode(textNode, offset, book.renderer.currentChapter.cfiBase); + + annotation = { + annotatedAt: new Date(), + anchor: cfi, + body: $text.val() + } + + // add to list + reader.addNote(annotation); + + // attach + addAnnotation(annotation); + placeMarker(annotation); + + // clear + $text.val(''); + $anchor.text("Attach"); + $text.prop("disabled", false); + + rendition.off("click", insertAtPoint); + + }; + + var addAnnotation = function(annotation){ + var note = document.createElement("li"); + var link = document.createElement("a"); + + note.innerHTML = annotation.body; + // note.setAttribute("ref", annotation.anchor); + link.innerHTML = " context »"; + link.href = "#"+annotation.anchor; + link.onclick = function(){ + rendition.display(annotation.anchor); + return false; + }; + + note.appendChild(link); + $notes.append(note); + + }; + + var placeMarker = function(annotation){ + var doc = book.renderer.doc; + var marker = document.createElement("span"); + var mark = document.createElement("a"); + marker.classList.add("footnotesuperscript", "reader_generated"); + + marker.style.verticalAlign = "super"; + marker.style.fontSize = ".75em"; + // marker.style.position = "relative"; + marker.style.lineHeight = "1em"; + + // mark.style.display = "inline-block"; + mark.style.padding = "2px"; + mark.style.backgroundColor = "#fffa96"; + mark.style.borderRadius = "5px"; + mark.style.cursor = "pointer"; + + marker.id = "note-"+EPUBJS.core.uuid(); + mark.innerHTML = annotations.indexOf(annotation) + 1 + "[Reader]"; + + marker.appendChild(mark); + epubcfi.addMarker(annotation.anchor, doc, marker); + + markerEvents(marker, annotation.body); + } + + var markerEvents = function(item, txt){ + var id = item.id; + + var showPop = function(){ + var poppos, + iheight = renderer.height, + iwidth = renderer.width, + tip, + pop, + maxHeight = 225, + itemRect, + left, + top, + pos; + + + //-- create a popup with endnote inside of it + if(!popups[id]) { + popups[id] = document.createElement("div"); + popups[id].setAttribute("class", "popup"); + + pop_content = document.createElement("div"); + + popups[id].appendChild(pop_content); + + pop_content.innerHTML = txt; + pop_content.setAttribute("class", "pop_content"); + + renderer.render.document.body.appendChild(popups[id]); + + //-- TODO: will these leak memory? - Fred + popups[id].addEventListener("mouseover", onPop, false); + popups[id].addEventListener("mouseout", offPop, false); + + //-- Add hide on page change + rendition.on("locationChanged", hidePop, this); + rendition.on("locationChanged", offPop, this); + // chapter.book.on("renderer:chapterDestroy", hidePop, this); + } + + pop = popups[id]; + + + //-- get location of item + itemRect = item.getBoundingClientRect(); + left = itemRect.left; + top = itemRect.top; + + //-- show the popup + pop.classList.add("show"); + + //-- locations of popup + popRect = pop.getBoundingClientRect(); + + //-- position the popup + pop.style.left = left - popRect.width / 2 + "px"; + pop.style.top = top + "px"; + + + //-- Adjust max height + if(maxHeight > iheight / 2.5) { + maxHeight = iheight / 2.5; + pop_content.style.maxHeight = maxHeight + "px"; + } + + //-- switch above / below + if(popRect.height + top >= iheight - 25) { + pop.style.top = top - popRect.height + "px"; + pop.classList.add("above"); + }else{ + pop.classList.remove("above"); + } + + //-- switch left + if(left - popRect.width <= 0) { + pop.style.left = left + "px"; + pop.classList.add("left"); + }else{ + pop.classList.remove("left"); + } + + //-- switch right + if(left + popRect.width / 2 >= iwidth) { + //-- TEMP MOVE: 300 + pop.style.left = left - 300 + "px"; + + popRect = pop.getBoundingClientRect(); + pop.style.left = left - popRect.width + "px"; + //-- switch above / below again + if(popRect.height + top >= iheight - 25) { + pop.style.top = top - popRect.height + "px"; + pop.classList.add("above"); + }else{ + pop.classList.remove("above"); + } + + pop.classList.add("right"); + }else{ + pop.classList.remove("right"); + } + + } + + var onPop = function(){ + popups[id].classList.add("on"); + } + + var offPop = function(){ + popups[id].classList.remove("on"); + } + + var hidePop = function(){ + setTimeout(function(){ + popups[id].classList.remove("show"); + }, 100); + } + + var openSidebar = function(){ + reader.ReaderController.slideOut(); + show(); + }; + + item.addEventListener("mouseover", showPop, false); + item.addEventListener("mouseout", hidePop, false); + item.addEventListener("click", openSidebar, false); + + } + $anchor.on("click", function(e){ + + $anchor.text("Cancel"); + $text.prop("disabled", "true"); + // listen for selection + rendition.on("click", insertAtPoint); + + }); + + annotations.forEach(function(note) { + addAnnotation(note); + }); + + /* + renderer.registerHook("beforeChapterDisplay", function(callback, renderer){ + var chapter = renderer.currentChapter; + annotations.forEach(function(note) { + var cfi = epubcfi.parse(note.anchor); + if(cfi.spinePos === chapter.spinePos) { + try { + placeMarker(note); + } catch(e) { + console.log("anchoring failed", note.anchor); + } + } + }); + callback(); + }, true); + */ + + return { + "show" : show, + "hide" : hide + }; +}; + +EPUBJS.reader.ReaderController = function(book) { + var $main = $("#main"), + $divider = $("#divider"), + $loader = $("#loader"), + $next = $("#next"), + $prev = $("#prev"); + var reader = this; + var book = this.book; + var rendition = this.rendition; + var slideIn = function() { + var currentPosition = rendition.currentLocation().start.cfi; + if (reader.settings.sidebarReflow){ + $main.removeClass('single'); + $main.one("transitionend", function(){ + rendition.resize(); + }); + } else { + $main.removeClass("closed"); + } + }; + + var slideOut = function() { + var location = rendition.currentLocation(); + if (!location) { + return; + } + var currentPosition = location.start.cfi; + if (reader.settings.sidebarReflow){ + $main.addClass('single'); + $main.one("transitionend", function(){ + rendition.resize(); + }); + } else { + $main.addClass("closed"); + } + }; + + var showLoader = function() { + $loader.show(); + hideDivider(); + }; + + var hideLoader = function() { + $loader.hide(); + + //-- If the book is using spreads, show the divider + // if(book.settings.spreads) { + // showDivider(); + // } + }; + + var showDivider = function() { + $divider.addClass("show"); + }; + + var hideDivider = function() { + $divider.removeClass("show"); + }; + + var keylock = false; + + var arrowKeys = function(e) { + if(e.keyCode == 37) { + + if(book.package.metadata.direction === "rtl") { + rendition.next(); + } else { + rendition.prev(); + } + + $prev.addClass("active"); + + keylock = true; + setTimeout(function(){ + keylock = false; + $prev.removeClass("active"); + }, 100); + + e.preventDefault(); + } + if(e.keyCode == 39) { + + if(book.package.metadata.direction === "rtl") { + rendition.prev(); + } else { + rendition.next(); + } + + $next.addClass("active"); + + keylock = true; + setTimeout(function(){ + keylock = false; + $next.removeClass("active"); + }, 100); + + e.preventDefault(); + } + } + + document.addEventListener('keydown', arrowKeys, false); + + $next.on("click", function(e){ + + if(book.package.metadata.direction === "rtl") { + rendition.prev(); + } else { + rendition.next(); + } + + e.preventDefault(); + }); + + $prev.on("click", function(e){ + + if(book.package.metadata.direction === "rtl") { + rendition.next(); + } else { + rendition.prev(); + } + + e.preventDefault(); + }); + + rendition.on("layout", function(props){ + if(props.spread === true) { + showDivider(); + } else { + hideDivider(); + } + }); + + rendition.on('relocated', function(location){ + if (location.atStart) { + $prev.addClass("disabled"); + } + if (location.atEnd) { + $next.addClass("disabled"); + } + }); + + return { + "slideOut" : slideOut, + "slideIn" : slideIn, + "showLoader" : showLoader, + "hideLoader" : hideLoader, + "showDivider" : showDivider, + "hideDivider" : hideDivider, + "arrowKeys" : arrowKeys + }; +}; + +EPUBJS.reader.SettingsController = function() { + var book = this.book; + var reader = this; + var $settings = $("#settings-modal"), + $overlay = $(".overlay"); + + var show = function() { + $settings.addClass("md-show"); + }; + + var hide = function() { + $settings.removeClass("md-show"); + }; + + var $sidebarReflowSetting = $('#sidebarReflow'); + + $sidebarReflowSetting.on('click', function() { + reader.settings.sidebarReflow = !reader.settings.sidebarReflow; + }); + + $settings.find(".closer").on("click", function() { + hide(); + }); + + $overlay.on("click", function() { + hide(); + }); + + return { + "show" : show, + "hide" : hide + }; +}; +EPUBJS.reader.SidebarController = function(book) { + var reader = this; + + var $sidebar = $("#sidebar"), + $panels = $("#panels"); + + var activePanel = "Toc"; + + var changePanelTo = function(viewName) { + var controllerName = viewName + "Controller"; + + if(activePanel == viewName || typeof reader[controllerName] === 'undefined' ) return; + reader[activePanel+ "Controller"].hide(); + reader[controllerName].show(); + activePanel = viewName; + + $panels.find('.active').removeClass("active"); + $panels.find("#show-" + viewName ).addClass("active"); + }; + + var getActivePanel = function() { + return activePanel; + }; + + var show = function() { + reader.sidebarOpen = true; + reader.ReaderController.slideOut(); + $sidebar.addClass("open"); + } + + var hide = function() { + reader.sidebarOpen = false; + reader.ReaderController.slideIn(); + $sidebar.removeClass("open"); + } + + $panels.find(".show_view").on("click", function(event) { + var view = $(this).data("view"); + + changePanelTo(view); + event.preventDefault(); + }); + + return { + 'show' : show, + 'hide' : hide, + 'getActivePanel' : getActivePanel, + 'changePanelTo' : changePanelTo + }; +}; +EPUBJS.reader.TocController = function(toc) { + var book = this.book; + var rendition = this.rendition; + + var $list = $("#tocView"), + docfrag = document.createDocumentFragment(); + + var currentChapter = false; + + var generateTocItems = function(toc, level) { + var container = document.createElement("ul"); + + if(!level) level = 1; + + toc.forEach(function(chapter) { + var listitem = document.createElement("li"), + link = document.createElement("a"); + toggle = document.createElement("a"); + + var subitems; + + listitem.id = "toc-"+chapter.id; + listitem.classList.add('list_item'); + + link.textContent = chapter.label; + link.href = chapter.href; + + link.classList.add('toc_link'); + + listitem.appendChild(link); + + if(chapter.subitems && chapter.subitems.length > 0) { + level++; + subitems = generateTocItems(chapter.subitems, level); + toggle.classList.add('toc_toggle'); + + listitem.insertBefore(toggle, link); + listitem.appendChild(subitems); + } + + + container.appendChild(listitem); + + }); + + return container; + }; + + var onShow = function() { + $list.show(); + }; + + var onHide = function() { + $list.hide(); + }; + + var chapterChange = function(e) { + var id = e.id, + $item = $list.find("#toc-"+id), + $current = $list.find(".currentChapter"), + $open = $list.find('.openChapter'); + + if($item.length){ + + if($item != $current && $item.has(currentChapter).length > 0) { + $current.removeClass("currentChapter"); + } + + $item.addClass("currentChapter"); + + // $open.removeClass("openChapter"); + $item.parents('li').addClass("openChapter"); + } + }; + + rendition.on('renderered', chapterChange); + + var tocitems = generateTocItems(toc); + + docfrag.appendChild(tocitems); + + $list.append(docfrag); + $list.find(".toc_link").on("click", function(event){ + var url = this.getAttribute('href'); + + event.preventDefault(); + + //-- Provide the Book with the url to show + // The Url must be found in the books manifest + rendition.display(url); + + $list.find(".currentChapter") + .addClass("openChapter") + .removeClass("currentChapter"); + + $(this).parent('li').addClass("currentChapter"); + + }); + + $list.find(".toc_toggle").on("click", function(event){ + var $el = $(this).parent('li'), + open = $el.hasClass("openChapter"); + + event.preventDefault(); + if(open){ + $el.removeClass("openChapter"); + } else { + $el.addClass("openChapter"); + } + }); + + return { + "show" : onShow, + "hide" : onHide + }; +}; + +//# sourceMappingURL=reader.js.map diff --git a/epub.js/js/reader.js.map b/epub.js/js/reader.js.map new file mode 100644 index 0000000..bee76df --- /dev/null +++ b/epub.js/js/reader.js.map @@ -0,0 +1,89 @@ +{ + "version": 3, + "file": "reader.js", + "sources": [ + "node_modules/rsvp/dist/config/versionTemplate.txt", + "node_modules/rsvp/dist/lib/rsvp/events.js", + "node_modules/rsvp/dist/lib/rsvp/config.js", + "node_modules/rsvp/dist/lib/rsvp/utils.js", + "node_modules/rsvp/dist/lib/rsvp/instrument.js", + "node_modules/rsvp/dist/lib/rsvp/promise/resolve.js", + "node_modules/rsvp/dist/lib/rsvp/-internal.js", + "node_modules/rsvp/dist/lib/rsvp/then.js", + "node_modules/rsvp/dist/lib/rsvp/enumerator.js", + "node_modules/rsvp/dist/lib/rsvp/promise/all.js", + "node_modules/rsvp/dist/lib/rsvp/promise/race.js", + "node_modules/rsvp/dist/lib/rsvp/promise/reject.js", + "node_modules/rsvp/dist/lib/rsvp/promise.js", + "node_modules/rsvp/dist/lib/rsvp/node.js", + "node_modules/rsvp/dist/lib/rsvp/all.js", + "node_modules/rsvp/dist/lib/rsvp/all-settled.js", + "node_modules/rsvp/dist/lib/rsvp/race.js", + "node_modules/rsvp/dist/lib/rsvp/promise-hash.js", + "node_modules/rsvp/dist/lib/rsvp/hash.js", + "node_modules/rsvp/dist/lib/rsvp/hash-settled.js", + "node_modules/rsvp/dist/lib/rsvp/rethrow.js", + "node_modules/rsvp/dist/lib/rsvp/defer.js", + "node_modules/rsvp/dist/lib/rsvp/map.js", + "node_modules/rsvp/dist/lib/rsvp/resolve.js", + "node_modules/rsvp/dist/lib/rsvp/reject.js", + "node_modules/rsvp/dist/lib/rsvp/filter.js", + "node_modules/rsvp/dist/lib/rsvp/asap.js", + "node_modules/rsvp/dist/lib/rsvp/platform.js", + "node_modules/rsvp/dist/lib/rsvp.js", + "src/core.js", + "src/reader.js", + "src/controllers/bookmarks_controller.js", + "src/controllers/controls_controller.js", + "src/controllers/meta_controller.js", + "src/controllers/notes_controller.js", + "src/controllers/reader_controller.js", + "src/controllers/settings_controller.js", + "src/controllers/sidebar_controller.js", + "src/controllers/toc_controller.js" + ], + "names": [], + "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACNA;AAAsC;AACc;AACjB;AACpB;AACV;AACF;AAAA;AAES;AACX;AA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B;AACiB;AAC5C;AAED;AAAmC;AACU;AAC5C;AAED;AACA;AAAmB;AACQ;AACpB;AACmB;AACwC;AAC9D;AACH;AAED;AAA8B;AAAA;AAAA;AAI9B;AAAyC;AACX;AAC7B;AC7BD;AAAe;AAEf;AAAyB;AACA;AACkB;AAChB;AAAA;AAEO;AAAA;AAEY;AACU;AAC/B;AACmB;AACrC;AAAA;AAE4C;AAC9C;AACgB;AACZ;AACR;AAED;AAA8D;AACvC;AACJ;AACN;AACc;AACN;AACK;AACG;AACI;AACN;AACL;AACyD;AACrE;AACU;AACjB;AAAA;ACpCH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgCA;AAA+C;AAAA;AAEtB;AAAA;AAEyD;AAChE;AACf;AAAA;AAE0C;AACjB;AACX;AAAA;ACpCjB;AAA0B;AACqD;AAC9E;AAEM;AAAkB;AAEzB;AACA;AACO;AAAiB;AAExB;AAAuC;AAEvC;AAAiC;AAC3B;AACkB;AACN;AACe;AACP;AACvB;AACF;AAED;AAAoE;AAC9D;AACqD;AAC7C;AACD;AACV;AACF;AAED;AAAwD;AACtB;AACX;AACkC;AACvC;AACH;AACR;AACa;AACU;AACa;AAC9B;AACmB;AACzB;AACkB;AACP;AACH;AACR;AACa;AAAA;AAEU;AAC8B;AAAA;AAElC;AACN;AACS;AACxB;AACS;AACb;AAED;AAA8C;AACT;AACE;AACI;AACd;AACS;AAC7B;AAC2C;AACtB;AACa;AAC9B;AACmB;AACzB;AACkB;AACY;AAC9B;AACJ;AACF;AAED;AAAkE;AACkF;AAAA;AAE/H;AACyB;AACR;AACI;AACV;AACD;AACyB;AAC/C;AAC2B;AACjC;AACF;AAED;AAAwC;AACf;AACG;AACU;AACkB;AAC/C;AACmB;AACzB;AACF;AAEM;AAAmC;AAClB;AACc;AACnC;AAAA;AAEgB;AAClB;AAED;AAAwC;AACN;AACvB;AACR;AAAA;AAEuB;AACG;AAAA;AAEY;AACd;AACY;AAClC;AACI;AAC0B;AAChC;AACF;AAEM;AAAiC;AACN;AACvB;AACR;AACyB;AACD;AACe;AACzC;AAED;AAAqE;AAC7B;AACN;AAAA;AAET;AAAA;AAEK;AACoB;AACH;AAAA;AAEV;AACH;AAC/B;AACF;AAED;AAAiC;AACQ;AACV;AAAA;AAEN;AACiD;AACvE;AAAA;AAE6B;AACrB;AACR;AAAA;AAEiB;AACG;AACQ;AAAA;AAEmB;AACvB;AACa;AAAA;AAEzB;AACwC;AAC5C;AACY;AAClB;AACF;AAAA;AAE+B;AACjC;AAED;AAAuB;AACH;AACnB;AAED;AAAwC;AAExC;AAAoC;AAC9B;AACsB;AACd;AACgB;AACH;AACxB;AACF;AAED;AAAiE;AACxB;AACrB;AACC;AAAA;AAEF;AACoB;AAAA;AAEJ;AACT;AACD;AACS;AACM;AAC3B;AACR;AACI;AACU;AAChB;AAAA;AAE+B;AAAA;AAEe;AACrB;AACM;AACP;AACO;AACN;AACK;AACN;AACxB;AACF;AAEM;AAA8C;AAC9B;AACjB;AACwB;AACV;AACL;AACR;AACe;AACQ;AACL;AACL;AACL;AACR;AACe;AACQ;AACvB;AACO;AACS;AACpB;AAAA;AC1PY;AAAiD;AAC5C;AACQ;AAAA;AAEuD;AACpB;AAC7C;AACf;AAAA;AAEsB;AAAA;AAEyB;AACpB;AAAA;AAE8B;AAAA;AAEnC;AACgC;AAChD;AAC4D;AACxC;AAC+B;AACrD;AACJ;AAAA;AAEY;AAAA;ACnBf;AAA6B;AACmC;AACpB;AACI;AACR;AAAA;AAEF;AACnC;AAAA;AAE+D;AAClC;AACV;AACI;AACQ;AAAA;AAEP;AACI;AACW;AACrC;AACD;AAAA;AAE2D;AAClC;AACE;AAAA;AAEoC;AAChC;AAC9B;AACD;AAAA;AAEkF;AAChD;AACV;AAAA;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;AAAA;AAGD;AAAgG;AACxC;AACxB;AACG;AACU;AACH;AACrC;AACF;AACF;AAED;AACA;AAEA;AAAwC;AAC5B;AACA;AACM;AACQ;AAChB;AACc;AACZ;AACA;AACc;AACR;AACJ;AACQ;AACA;AACd;AACE;AACQ;AACF;AACN;AAGV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A;AC3EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC9oBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AClUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC/GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC/RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A", + "sourceRoot": "../", + "sourcesContent": [ + "/*!\n * @overview RSVP - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2016 Yehuda Katz, Tom Dale, Stefan Penner and contributors\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE\n * @version 3.6.2\n */\n", + "function indexOf(callbacks, callback) {\n for (var i = 0, l = callbacks.length; i < l; i++) {\n if (callbacks[i] === callback) {\n return i;\n }\n }\n\n return -1;\n}\n\nfunction callbacksFor(object) {\n var callbacks = object._promiseCallbacks;\n\n if (!callbacks) {\n callbacks = object._promiseCallbacks = {};\n }\n\n return callbacks;\n}\n\n/**\n @class RSVP.EventTarget\n*/\nexport default {\n\n /**\n `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For\n Example:\n ```javascript\n let object = {};\n RSVP.EventTarget.mixin(object);\n object.on('finished', function(event) {\n // handle event\n });\n object.trigger('finished', { detail: value });\n ```\n `EventTarget.mixin` also works with prototypes:\n ```javascript\n let Person = function() {};\n RSVP.EventTarget.mixin(Person.prototype);\n let yehuda = new Person();\n let tom = new Person();\n yehuda.on('poke', function(event) {\n console.log('Yehuda says OW');\n });\n tom.on('poke', function(event) {\n console.log('Tom says OW');\n });\n yehuda.trigger('poke');\n tom.trigger('poke');\n ```\n @method mixin\n @for RSVP.EventTarget\n @private\n @param {Object} object object to extend with EventTarget methods\n */\n mixin: function (object) {\n object['on'] = this['on'];\n object['off'] = this['off'];\n object['trigger'] = this['trigger'];\n object._promiseCallbacks = undefined;\n return object;\n },\n\n\n /**\n Registers a callback to be executed when `eventName` is triggered\n ```javascript\n object.on('event', function(eventInfo){\n // handle the event\n });\n object.trigger('event');\n ```\n @method on\n @for RSVP.EventTarget\n @private\n @param {String} eventName name of the event to listen for\n @param {Function} callback function to be called when the event is triggered.\n */\n on: function (eventName, callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function');\n }\n\n var allCallbacks = callbacksFor(this),\n callbacks = void 0;\n\n callbacks = allCallbacks[eventName];\n\n if (!callbacks) {\n callbacks = allCallbacks[eventName] = [];\n }\n\n if (indexOf(callbacks, callback) === -1) {\n callbacks.push(callback);\n }\n },\n\n\n /**\n You can use `off` to stop firing a particular callback for an event:\n ```javascript\n function doStuff() { // do stuff! }\n object.on('stuff', doStuff);\n object.trigger('stuff'); // doStuff will be called\n // Unregister ONLY the doStuff callback\n object.off('stuff', doStuff);\n object.trigger('stuff'); // doStuff will NOT be called\n ```\n If you don't pass a `callback` argument to `off`, ALL callbacks for the\n event will not be executed when the event fires. For example:\n ```javascript\n let callback1 = function(){};\n let callback2 = function(){};\n object.on('stuff', callback1);\n object.on('stuff', callback2);\n object.trigger('stuff'); // callback1 and callback2 will be executed.\n object.off('stuff');\n object.trigger('stuff'); // callback1 and callback2 will not be executed!\n ```\n @method off\n @for RSVP.EventTarget\n @private\n @param {String} eventName event to stop listening to\n @param {Function} callback optional argument. If given, only the function\n given will be removed from the event's callback queue. If no `callback`\n argument is given, all callbacks will be removed from the event's callback\n queue.\n */\n off: function (eventName, callback) {\n var allCallbacks = callbacksFor(this),\n callbacks = void 0,\n index = void 0;\n\n if (!callback) {\n allCallbacks[eventName] = [];\n return;\n }\n\n callbacks = allCallbacks[eventName];\n\n index = indexOf(callbacks, callback);\n\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n },\n\n\n /**\n Use `trigger` to fire custom events. For example:\n ```javascript\n object.on('foo', function(){\n console.log('foo event happened!');\n });\n object.trigger('foo');\n // 'foo event happened!' logged to the console\n ```\n You can also pass a value as a second argument to `trigger` that will be\n passed as an argument to all event listeners for the event:\n ```javascript\n object.on('foo', function(value){\n console.log(value.name);\n });\n object.trigger('foo', { name: 'bar' });\n // 'bar' logged to the console\n ```\n @method trigger\n @for RSVP.EventTarget\n @private\n @param {String} eventName name of the event to be triggered\n @param {*} options optional value to be passed to any event handlers for\n the given `eventName`\n */\n trigger: function (eventName, options, label) {\n var allCallbacks = callbacksFor(this),\n callbacks = void 0,\n callback = void 0;\n\n if (callbacks = allCallbacks[eventName]) {\n // Don't cache the callbacks.length since it may grow\n for (var i = 0; i < callbacks.length; i++) {\n callback = callbacks[i];\n\n callback(options, label);\n }\n }\n }\n};", + "import EventTarget from './events';\n\nvar config = {\n instrument: false\n};\n\nEventTarget['mixin'](config);\n\nfunction configure(name, value) {\n if (arguments.length === 2) {\n config[name] = value;\n } else {\n return config[name];\n }\n}\n\nexport { config, configure };", + "export function objectOrFunction(x) {\n var type = typeof x;\n return x !== null && (type === 'object' || type === 'function');\n}\n\nexport function isFunction(x) {\n return typeof x === 'function';\n}\n\nexport function isObject(x) {\n return x !== null && typeof x === 'object';\n}\n\nexport function isMaybeThenable(x) {\n return x !== null && typeof x === 'object';\n}\n\nvar _isArray = void 0;\nif (Array.isArray) {\n _isArray = Array.isArray;\n} else {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n}\n\nexport var isArray = _isArray;\n\n// Date.now is not available in browsers < IE9\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility\nexport var now = Date.now || function () {\n return new Date().getTime();\n};", + "import { config } from './config';\nimport { now } from './utils';\n\nvar queue = [];\n\nfunction scheduleFlush() {\n setTimeout(function () {\n for (var i = 0; i < queue.length; i++) {\n var entry = queue[i];\n\n var payload = entry.payload;\n\n payload.guid = payload.key + payload.id;\n payload.childGuid = payload.key + payload.childId;\n if (payload.error) {\n payload.stack = payload.error.stack;\n }\n\n config['trigger'](entry.name, entry.payload);\n }\n queue.length = 0;\n }, 50);\n}\n\nexport default function instrument(eventName, promise, child) {\n if (1 === queue.push({\n name: eventName,\n payload: {\n key: promise._guidKey,\n id: promise._id,\n eventName: eventName,\n detail: promise._result,\n childId: child && child._id,\n label: promise._label,\n timeStamp: now(),\n error: config[\"instrument-with-stack\"] ? new Error(promise._label) : null\n } })) {\n scheduleFlush();\n }\n}", + "import { noop, resolve as _resolve } from '../-internal';\n\n/**\n `RSVP.Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new RSVP.Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = RSVP.Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {*} object value that the returned promise will be resolved with\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nexport default function resolve(object, label) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop, label);\n _resolve(promise, object);\n return promise;\n}", + "import { objectOrFunction, isFunction } from './utils';\nimport originalThen from './then';\nimport originalResolve from './promise/resolve';\nimport instrument from './instrument';\n\nimport { config } from './config';\nimport Promise from './promise';\n\nfunction withOwnPromise() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nexport function noop() {}\n\nexport var PENDING = void 0;\nexport var FULFILLED = 1;\nexport var REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nexport function getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n config.async(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n resolve(promise, value, undefined);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n thenable._onError = null;\n reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n if (thenable !== value) {\n resolve(promise, value, undefined);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n}\n\nexport function handleMaybeThenable(promise, maybeThenable, then) {\n var isOwnThenable = maybeThenable.constructor === promise.constructor && then === originalThen && promise.constructor.resolve === originalResolve;\n\n if (isOwnThenable) {\n handleOwnThenable(promise, maybeThenable);\n } else if (then === GET_THEN_ERROR) {\n reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (isFunction(then)) {\n handleForeignThenable(promise, maybeThenable, then);\n } else {\n fulfill(promise, maybeThenable);\n }\n}\n\nexport function resolve(promise, value) {\n if (promise === value) {\n fulfill(promise, value);\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nexport function publishRejection(promise) {\n if (promise._onError) {\n promise._onError(promise._result);\n }\n\n publish(promise);\n}\n\nexport function fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length === 0) {\n if (config.instrument) {\n instrument('fulfilled', promise);\n }\n } else {\n config.async(publish, promise);\n }\n}\n\nexport function reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n config.async(publishRejection, promise);\n}\n\nexport function subscribe(parent, child, onFulfillment, onRejection) {\n var subscribers = parent._subscribers;\n var length = subscribers.length;\n\n parent._onError = null;\n\n subscribers[length] = child;\n subscribers[length + FULFILLED] = onFulfillment;\n subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n config.async(publish, parent);\n }\n}\n\nexport function publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (config.instrument) {\n instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);\n }\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = void 0,\n callback = void 0,\n result = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, result);\n } else {\n callback(result);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, result) {\n try {\n return callback(result);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nexport function invokeCallback(state, promise, callback, result) {\n var hasCallback = isFunction(callback);\n var value = void 0,\n error = void 0;\n\n if (hasCallback) {\n value = tryCatch(callback, result);\n\n if (value === TRY_CATCH_ERROR) {\n error = value.error;\n value.error = null; // release\n } else if (value === promise) {\n reject(promise, withOwnPromise());\n return;\n }\n } else {\n value = result;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && error === undefined) {\n resolve(promise, value);\n } else if (error !== undefined) {\n reject(promise, error);\n } else if (state === FULFILLED) {\n fulfill(promise, value);\n } else if (state === REJECTED) {\n reject(promise, value);\n }\n}\n\nexport function initializePromise(promise, resolver) {\n var resolved = false;\n try {\n resolver(function (value) {\n if (resolved) {\n return;\n }\n resolved = true;\n resolve(promise, value);\n }, function (reason) {\n if (resolved) {\n return;\n }\n resolved = true;\n reject(promise, reason);\n });\n } catch (e) {\n reject(promise, e);\n }\n}", + "import { config } from './config';\nimport instrument from './instrument';\nimport { noop, subscribe, FULFILLED, REJECTED, PENDING, invokeCallback } from './-internal';\n\nexport default function then(onFulfillment, onRejection, label) {\n var parent = this;\n var state = parent._state;\n\n if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {\n config.instrument && instrument('chained', parent, parent);\n return parent;\n }\n\n parent._onError = null;\n\n var child = new parent.constructor(noop, label);\n var result = parent._result;\n\n config.instrument && instrument('chained', parent, child);\n\n if (state === PENDING) {\n subscribe(parent, child, onFulfillment, onRejection);\n } else {\n var callback = state === FULFILLED ? onFulfillment : onRejection;\n config.async(function () {\n return invokeCallback(state, child, callback, result);\n });\n }\n\n return child;\n}", + "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nimport { isArray, isMaybeThenable } from './utils';\n\nimport { noop, resolve, handleMaybeThenable, reject, fulfill, subscribe, FULFILLED, REJECTED, PENDING, getThen } from './-internal';\n\nimport Promise from './promise';\nimport originalThen from './then';\nimport originalResolve from './promise/resolve';\n\nvar Enumerator = function () {\n function Enumerator(Constructor, input, abortOnReject, label) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop, label);\n this._abortOnReject = abortOnReject;\n\n this._init.apply(this, arguments);\n }\n\n Enumerator.prototype._init = function _init(Constructor, input) {\n var len = input.length || 0;\n this.length = len;\n this._remaining = len;\n this._result = new Array(len);\n\n this._enumerate(input);\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n };\n\n Enumerator.prototype._enumerate = function _enumerate(input) {\n var length = this.length;\n var promise = this.promise;\n\n for (var i = 0; promise._state === PENDING && i < length; i++) {\n this._eachEntry(input[i], i);\n }\n };\n\n Enumerator.prototype._settleMaybeThenable = function _settleMaybeThenable(entry, i) {\n var c = this._instanceConstructor;\n var resolve = c.resolve;\n\n if (resolve === originalResolve) {\n var then = getThen(entry);\n\n if (then === originalThen && entry._state !== PENDING) {\n entry._onError = null;\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof then !== 'function') {\n this._remaining--;\n this._result[i] = this._makeResult(FULFILLED, i, entry);\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve) {\n return resolve(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve(entry), i);\n }\n };\n\n Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {\n if (isMaybeThenable(entry)) {\n this._settleMaybeThenable(entry, i);\n } else {\n this._remaining--;\n this._result[i] = this._makeResult(FULFILLED, i, entry);\n }\n };\n\n Enumerator.prototype._settledAt = function _settledAt(state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n if (this._abortOnReject && state === REJECTED) {\n reject(promise, value);\n } else {\n this._remaining--;\n this._result[i] = this._makeResult(state, i, value);\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n }\n }\n };\n\n Enumerator.prototype._makeResult = function _makeResult(state, i, value) {\n return value;\n };\n\n Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n };\n\n return Enumerator;\n}();\n\nexport default Enumerator;\n\n\nexport function makeSettledResult(state, position, value) {\n if (state === FULFILLED) {\n return {\n state: 'fulfilled',\n value: value\n };\n } else {\n return {\n state: 'rejected',\n reason: value\n };\n }\n}", + "import Enumerator from '../enumerator';\nimport { isArray } from '../utils';\n\n/**\n `RSVP.Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `RSVP.all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error(\"2\"));\n let promise3 = RSVP.reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nexport default function all(entries, label) {\n if (!isArray(entries)) {\n return this.reject(new TypeError(\"Promise.all must be called with an array\"), label);\n }\n return new Enumerator(this, entries, true /* abort on reject */, label).promise;\n}", + "import { isArray } from \"../utils\";\n\nimport { noop, resolve, reject, subscribe, PENDING } from '../-internal';\n\n/**\n `RSVP.Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n RSVP.Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `RSVP.Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n RSVP.Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n RSVP.Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} entries array of promises to observe\n @param {String} label optional string for describing the promise returned.\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nexport default function race(entries, label) {\n /*jshint validthis:true */\n var Constructor = this;\n\n var promise = new Constructor(noop, label);\n\n if (!isArray(entries)) {\n reject(promise, new TypeError('Promise.race must be called with an array'));\n return promise;\n }\n\n for (var i = 0; promise._state === PENDING && i < entries.length; i++) {\n subscribe(Constructor.resolve(entries[i]), undefined, function (value) {\n return resolve(promise, value);\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n\n return promise;\n}", + "import { noop, reject as _reject } from '../-internal';\n\n/**\n `RSVP.Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new RSVP.Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = RSVP.Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {*} reason value that the returned promise will be rejected with.\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nexport default function reject(reason, label) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop, label);\n _reject(promise, reason);\n return promise;\n}", + "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nimport { config } from './config';\nimport instrument from './instrument';\nimport then from './then';\nimport { isFunction, now } from './utils';\n\nimport { noop, initializePromise } from './-internal';\n\nimport all from './promise/all';\nimport race from './promise/race';\nimport Resolve from './promise/resolve';\nimport Reject from './promise/reject';\n\nvar guidKey = 'rsvp_' + now() + '-';\nvar counter = 0;\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise’s eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class RSVP.Promise\n @param {function} resolver\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @constructor\n*/\n\nvar Promise = function () {\n function Promise(resolver, label) {\n this._id = counter++;\n this._label = label;\n this._state = undefined;\n this._result = undefined;\n this._subscribers = [];\n\n config.instrument && instrument('created', this);\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n }\n\n Promise.prototype._onError = function _onError(reason) {\n var _this = this;\n\n config.after(function () {\n if (_this._onError) {\n config.trigger('error', reason, _this._label);\n }\n });\n };\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn\\'t find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n\n\n Promise.prototype.catch = function _catch(onRejection, label) {\n return this.then(undefined, onRejection, label);\n };\n\n /**\n `finally` will be invoked regardless of the promise's fate just as native\n try/catch/finally behaves\n \n Synchronous example:\n \n ```js\n findAuthor() {\n if (Math.random() > 0.5) {\n throw new Error();\n }\n return new Author();\n }\n \n try {\n return findAuthor(); // succeed or fail\n } catch(error) {\n return findOtherAuthor();\n } finally {\n // always runs\n // doesn't affect the return value\n }\n ```\n \n Asynchronous example:\n \n ```js\n findAuthor().catch(function(reason){\n return findOtherAuthor();\n }).finally(function(){\n // author was either found, or not\n });\n ```\n \n @method finally\n @param {Function} callback\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n\n\n Promise.prototype.finally = function _finally(callback, label) {\n var promise = this;\n var constructor = promise.constructor;\n\n return promise.then(function (value) {\n return constructor.resolve(callback()).then(function () {\n return value;\n });\n }, function (reason) {\n return constructor.resolve(callback()).then(function () {\n throw reason;\n });\n }, label);\n };\n\n return Promise;\n}();\n\n;\n\nPromise.cast = Resolve; // deprecated\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = Resolve;\nPromise.reject = Reject;\n\nPromise.prototype._guidKey = guidKey;\n\n/**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n\n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n\n Chaining\n --------\n\n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n\n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n\n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we\\'re unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we\\'re unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n\n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n\n Assimilation\n ------------\n\n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n\n If the assimliated promise rejects, then the downstream promise will also reject.\n\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n\n Simple Example\n --------------\n\n Synchronous Example\n\n ```javascript\n let result;\n\n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n\n Errback Example\n\n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n\n Promise Example;\n\n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n\n Advanced Example\n --------------\n\n Synchronous Example\n\n ```javascript\n let author, books;\n\n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n\n Errback Example\n\n ```js\n\n function foundBooks(books) {\n\n }\n\n function failure(reason) {\n\n }\n\n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n\n Promise Example;\n\n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n\n @method then\n @param {Function} onFulfillment\n @param {Function} onRejection\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n*/\nPromise.prototype.then = then;\n\nexport default Promise;", + "import Promise from './promise';\nimport { noop, resolve, reject } from './-internal';\nimport { isArray } from './utils';\n\nfunction Result() {\n this.value = undefined;\n}\n\nvar ERROR = new Result();\nvar GET_THEN_ERROR = new Result();\n\nfunction getThen(obj) {\n try {\n return obj.then;\n } catch (error) {\n ERROR.value = error;\n return ERROR;\n }\n}\n\nfunction tryApply(f, s, a) {\n try {\n f.apply(s, a);\n } catch (error) {\n ERROR.value = error;\n return ERROR;\n }\n}\n\nfunction makeObject(_, argumentNames) {\n var obj = {};\n var length = _.length;\n var args = new Array(length);\n\n for (var x = 0; x < length; x++) {\n args[x] = _[x];\n }\n\n for (var i = 0; i < argumentNames.length; i++) {\n var name = argumentNames[i];\n obj[name] = args[i + 1];\n }\n\n return obj;\n}\n\nfunction arrayResult(_) {\n var length = _.length;\n var args = new Array(length - 1);\n\n for (var i = 1; i < length; i++) {\n args[i - 1] = _[i];\n }\n\n return args;\n}\n\nfunction wrapThenable(then, promise) {\n return {\n then: function (onFulFillment, onRejection) {\n return then.call(promise, onFulFillment, onRejection);\n }\n };\n}\n\n/**\n `RSVP.denodeify` takes a 'node-style' function and returns a function that\n will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the\n browser when you'd prefer to use promises over using callbacks. For example,\n `denodeify` transforms the following:\n\n ```javascript\n let fs = require('fs');\n\n fs.readFile('myfile.txt', function(err, data){\n if (err) return handleError(err);\n handleData(data);\n });\n ```\n\n into:\n\n ```javascript\n let fs = require('fs');\n let readFile = RSVP.denodeify(fs.readFile);\n\n readFile('myfile.txt').then(handleData, handleError);\n ```\n\n If the node function has multiple success parameters, then `denodeify`\n just returns the first one:\n\n ```javascript\n let request = RSVP.denodeify(require('request'));\n\n request('http://example.com').then(function(res) {\n // ...\n });\n ```\n\n However, if you need all success parameters, setting `denodeify`'s\n second parameter to `true` causes it to return all success parameters\n as an array:\n\n ```javascript\n let request = RSVP.denodeify(require('request'), true);\n\n request('http://example.com').then(function(result) {\n // result[0] -> res\n // result[1] -> body\n });\n ```\n\n Or if you pass it an array with names it returns the parameters as a hash:\n\n ```javascript\n let request = RSVP.denodeify(require('request'), ['res', 'body']);\n\n request('http://example.com').then(function(result) {\n // result.res\n // result.body\n });\n ```\n\n Sometimes you need to retain the `this`:\n\n ```javascript\n let app = require('express')();\n let render = RSVP.denodeify(app.render.bind(app));\n ```\n\n The denodified function inherits from the original function. It works in all\n environments, except IE 10 and below. Consequently all properties of the original\n function are available to you. However, any properties you change on the\n denodeified function won't be changed on the original function. Example:\n\n ```javascript\n let request = RSVP.denodeify(require('request')),\n cookieJar = request.jar(); // <- Inheritance is used here\n\n request('http://example.com', {jar: cookieJar}).then(function(res) {\n // cookieJar.cookies holds now the cookies returned by example.com\n });\n ```\n\n Using `denodeify` makes it easier to compose asynchronous operations instead\n of using callbacks. For example, instead of:\n\n ```javascript\n let fs = require('fs');\n\n fs.readFile('myfile.txt', function(err, data){\n if (err) { ... } // Handle error\n fs.writeFile('myfile2.txt', data, function(err){\n if (err) { ... } // Handle error\n console.log('done')\n });\n });\n ```\n\n you can chain the operations together using `then` from the returned promise:\n\n ```javascript\n let fs = require('fs');\n let readFile = RSVP.denodeify(fs.readFile);\n let writeFile = RSVP.denodeify(fs.writeFile);\n\n readFile('myfile.txt').then(function(data){\n return writeFile('myfile2.txt', data);\n }).then(function(){\n console.log('done')\n }).catch(function(error){\n // Handle error\n });\n ```\n\n @method denodeify\n @static\n @for RSVP\n @param {Function} nodeFunc a 'node-style' function that takes a callback as\n its last argument. The callback expects an error to be passed as its first\n argument (if an error occurred, otherwise null), and the value from the\n operation as its second argument ('function(err, value){ }').\n @param {Boolean|Array} [options] An optional paramter that if set\n to `true` causes the promise to fulfill with the callback's success arguments\n as an array. This is useful if the node function has multiple success\n paramters. If you set this paramter to an array with names, the promise will\n fulfill with a hash with these names as keys and the success parameters as\n values.\n @return {Function} a function that wraps `nodeFunc` to return an\n `RSVP.Promise`\n @static\n*/\nexport default function denodeify(nodeFunc, options) {\n var fn = function () {\n var self = this;\n var l = arguments.length;\n var args = new Array(l + 1);\n var promiseInput = false;\n\n for (var i = 0; i < l; ++i) {\n var arg = arguments[i];\n\n if (!promiseInput) {\n // TODO: clean this up\n promiseInput = needsPromiseInput(arg);\n if (promiseInput === GET_THEN_ERROR) {\n var p = new Promise(noop);\n reject(p, GET_THEN_ERROR.value);\n return p;\n } else if (promiseInput && promiseInput !== true) {\n arg = wrapThenable(promiseInput, arg);\n }\n }\n args[i] = arg;\n }\n\n var promise = new Promise(noop);\n\n args[l] = function (err, val) {\n if (err) reject(promise, err);else if (options === undefined) resolve(promise, val);else if (options === true) resolve(promise, arrayResult(arguments));else if (isArray(options)) resolve(promise, makeObject(arguments, options));else resolve(promise, val);\n };\n\n if (promiseInput) {\n return handlePromiseInput(promise, args, nodeFunc, self);\n } else {\n return handleValueInput(promise, args, nodeFunc, self);\n }\n };\n\n fn.__proto__ = nodeFunc;\n\n return fn;\n}\n\nfunction handleValueInput(promise, args, nodeFunc, self) {\n var result = tryApply(nodeFunc, self, args);\n if (result === ERROR) {\n reject(promise, result.value);\n }\n return promise;\n}\n\nfunction handlePromiseInput(promise, args, nodeFunc, self) {\n return Promise.all(args).then(function (args) {\n var result = tryApply(nodeFunc, self, args);\n if (result === ERROR) {\n reject(promise, result.value);\n }\n return promise;\n });\n}\n\nfunction needsPromiseInput(arg) {\n if (arg && typeof arg === 'object') {\n if (arg.constructor === Promise) {\n return true;\n } else {\n return getThen(arg);\n }\n } else {\n return false;\n }\n}", + "import Promise from \"./promise\";\n\n/**\n This is a convenient alias for `RSVP.Promise.all`.\n\n @method all\n @static\n @for RSVP\n @param {Array} array Array of promises.\n @param {String} label An optional label. This is useful\n for tooling.\n*/\nexport default function all(array, label) {\n return Promise.all(array, label);\n}", + "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nimport { default as Enumerator, makeSettledResult } from './enumerator';\nimport Promise from './promise';\nimport { isArray } from './utils';\n\nvar AllSettled = function (_Enumerator) {\n _inherits(AllSettled, _Enumerator);\n\n function AllSettled(Constructor, entries, label) {\n return _possibleConstructorReturn(this, _Enumerator.call(this, Constructor, entries, false /* don't abort on reject */, label));\n }\n\n return AllSettled;\n}(Enumerator);\n\nAllSettled.prototype._makeResult = makeSettledResult;\n\n/**\n`RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing\na fail-fast method, it waits until all the promises have returned and\nshows you all the results. This is useful if you want to handle multiple\npromises' failure states together as a set.\n Returns a promise that is fulfilled when all the given promises have been\nsettled. The return promise is fulfilled with an array of the states of\nthe promises passed into the `promises` array argument.\n Each state object will either indicate fulfillment or rejection, and\nprovide the corresponding value or reason. The states will take one of\nthe following formats:\n ```javascript\n{ state: 'fulfilled', value: value }\n or\n{ state: 'rejected', reason: reason }\n```\n Example:\n ```javascript\nlet promise1 = RSVP.Promise.resolve(1);\nlet promise2 = RSVP.Promise.reject(new Error('2'));\nlet promise3 = RSVP.Promise.reject(new Error('3'));\nlet promises = [ promise1, promise2, promise3 ];\n RSVP.allSettled(promises).then(function(array){\n // array == [\n // { state: 'fulfilled', value: 1 },\n // { state: 'rejected', reason: Error },\n // { state: 'rejected', reason: Error }\n // ]\n // Note that for the second item, reason.message will be '2', and for the\n // third item, reason.message will be '3'.\n}, function(error) {\n // Not run. (This block would only be called if allSettled had failed,\n // for instance if passed an incorrect argument type.)\n});\n```\n @method allSettled\n@static\n@for RSVP\n@param {Array} entries\n@param {String} label - optional string that describes the promise.\nUseful for tooling.\n@return {Promise} promise that is fulfilled with an array of the settled\nstates of the constituent promises.\n*/\n\nexport default function allSettled(entries, label) {\n if (!isArray(entries)) {\n return Promise.reject(new TypeError(\"Promise.allSettled must be called with an array\"), label);\n }\n\n return new AllSettled(Promise, entries, label).promise;\n}", + "import Promise from './promise';\n\n/**\n This is a convenient alias for `RSVP.Promise.race`.\n\n @method race\n @static\n @for RSVP\n @param {Array} array Array of promises.\n @param {String} label An optional label. This is useful\n for tooling.\n */\nexport default function race(array, label) {\n return Promise.race(array, label);\n}", + "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nimport Enumerator from './enumerator';\nimport { PENDING, FULFILLED, fulfill } from './-internal';\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar PromiseHash = function (_Enumerator) {\n _inherits(PromiseHash, _Enumerator);\n\n function PromiseHash(Constructor, object) {\n var abortOnReject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var label = arguments[3];\n return _possibleConstructorReturn(this, _Enumerator.call(this, Constructor, object, abortOnReject, label));\n }\n\n PromiseHash.prototype._init = function _init(Constructor, object) {\n this._result = {};\n\n this._enumerate(object);\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n };\n\n PromiseHash.prototype._enumerate = function _enumerate(input) {\n var promise = this.promise;\n var results = [];\n\n for (var key in input) {\n if (hasOwnProperty.call(input, key)) {\n results.push({\n position: key,\n entry: input[key]\n });\n }\n }\n\n var length = results.length;\n this._remaining = length;\n var result = void 0;\n\n for (var i = 0; promise._state === PENDING && i < length; i++) {\n result = results[i];\n this._eachEntry(result.entry, result.position);\n }\n };\n\n return PromiseHash;\n}(Enumerator);\n\nexport default PromiseHash;", + "import Promise from './promise';\nimport PromiseHash from './promise-hash';\nimport { isObject } from './utils';\n\n/**\n `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array\n for its `promises` argument.\n\n Returns a promise that is fulfilled when all the given promises have been\n fulfilled, or rejected if any of them become rejected. The returned promise\n is fulfilled with a hash that has the same key names as the `promises` object\n argument. If any of the values in the object are not promises, they will\n simply be copied over to the fulfilled object.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.resolve(1),\n yourPromise: RSVP.resolve(2),\n theirPromise: RSVP.resolve(3),\n notAPromise: 4\n };\n\n RSVP.hash(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: 1,\n // yourPromise: 2,\n // theirPromise: 3,\n // notAPromise: 4\n // }\n });\n ````\n\n If any of the `promises` given to `RSVP.hash` are rejected, the first promise\n that is rejected will be given as the reason to the rejection handler.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.resolve(1),\n rejectedPromise: RSVP.reject(new Error('rejectedPromise')),\n anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')),\n };\n\n RSVP.hash(promises).then(function(hash){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === 'rejectedPromise'\n });\n ```\n\n An important note: `RSVP.hash` is intended for plain JavaScript objects that\n are just a set of keys and values. `RSVP.hash` will NOT preserve prototype\n chains.\n\n Example:\n\n ```javascript\n function MyConstructor(){\n this.example = RSVP.resolve('Example');\n }\n\n MyConstructor.prototype = {\n protoProperty: RSVP.resolve('Proto Property')\n };\n\n let myObject = new MyConstructor();\n\n RSVP.hash(myObject).then(function(hash){\n // protoProperty will not be present, instead you will just have an\n // object that looks like:\n // {\n // example: 'Example'\n // }\n //\n // hash.hasOwnProperty('protoProperty'); // false\n // 'undefined' === typeof hash.protoProperty\n });\n ```\n\n @method hash\n @static\n @for RSVP\n @param {Object} object\n @param {String} label optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all properties of `promises`\n have been fulfilled, or rejected if any of them become rejected.\n*/\nexport default function hash(object, label) {\n if (!isObject(object)) {\n return Promise.reject(new TypeError(\"Promise.hash must be called with an object\"), label);\n }\n\n return new PromiseHash(Promise, object, label).promise;\n}", + "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nimport Promise from './promise';\nimport PromiseHash from './promise-hash';\nimport { isObject } from './utils';\nimport { makeSettledResult } from './enumerator';\n\nvar HashSettled = function (_PromiseHash) {\n _inherits(HashSettled, _PromiseHash);\n\n function HashSettled(Constructor, object, label) {\n return _possibleConstructorReturn(this, _PromiseHash.call(this, Constructor, object, false, label));\n }\n\n return HashSettled;\n}(PromiseHash);\n\nHashSettled.prototype._makeResult = makeSettledResult;\n\n/**\n `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object\n instead of an array for its `promises` argument.\n\n Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method,\n but like `RSVP.allSettled`, `hashSettled` waits until all the\n constituent promises have returned and then shows you all the results\n with their states and values/reasons. This is useful if you want to\n handle multiple promises' failure states together as a set.\n\n Returns a promise that is fulfilled when all the given promises have been\n settled, or rejected if the passed parameters are invalid.\n\n The returned promise is fulfilled with a hash that has the same key names as\n the `promises` object argument. If any of the values in the object are not\n promises, they will be copied over to the fulfilled object and marked with state\n 'fulfilled'.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.Promise.resolve(1),\n yourPromise: RSVP.Promise.resolve(2),\n theirPromise: RSVP.Promise.resolve(3),\n notAPromise: 4\n };\n\n RSVP.hashSettled(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: { state: 'fulfilled', value: 1 },\n // yourPromise: { state: 'fulfilled', value: 2 },\n // theirPromise: { state: 'fulfilled', value: 3 },\n // notAPromise: { state: 'fulfilled', value: 4 }\n // }\n });\n ```\n\n If any of the `promises` given to `RSVP.hash` are rejected, the state will\n be set to 'rejected' and the reason for rejection provided.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.Promise.resolve(1),\n rejectedPromise: RSVP.Promise.reject(new Error('rejection')),\n anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')),\n };\n\n RSVP.hashSettled(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: { state: 'fulfilled', value: 1 },\n // rejectedPromise: { state: 'rejected', reason: Error },\n // anotherRejectedPromise: { state: 'rejected', reason: Error },\n // }\n // Note that for rejectedPromise, reason.message == 'rejection',\n // and for anotherRejectedPromise, reason.message == 'more rejection'.\n });\n ```\n\n An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that\n are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype\n chains.\n\n Example:\n\n ```javascript\n function MyConstructor(){\n this.example = RSVP.Promise.resolve('Example');\n }\n\n MyConstructor.prototype = {\n protoProperty: RSVP.Promise.resolve('Proto Property')\n };\n\n let myObject = new MyConstructor();\n\n RSVP.hashSettled(myObject).then(function(hash){\n // protoProperty will not be present, instead you will just have an\n // object that looks like:\n // {\n // example: { state: 'fulfilled', value: 'Example' }\n // }\n //\n // hash.hasOwnProperty('protoProperty'); // false\n // 'undefined' === typeof hash.protoProperty\n });\n ```\n\n @method hashSettled\n @for RSVP\n @param {Object} object\n @param {String} label optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when when all properties of `promises`\n have been settled.\n @static\n*/\n\nexport default function hashSettled(object, label) {\n if (!isObject(object)) {\n return Promise.reject(new TypeError(\"RSVP.hashSettled must be called with an object\"), label);\n }\n\n return new HashSettled(Promise, object, false, label).promise;\n}", + "/**\n `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event\n loop in order to aid debugging.\n\n Promises A+ specifies that any exceptions that occur with a promise must be\n caught by the promises implementation and bubbled to the last handler. For\n this reason, it is recommended that you always specify a second rejection\n handler function to `then`. However, `RSVP.rethrow` will throw the exception\n outside of the promise, so it bubbles up to your console if in the browser,\n or domain/cause uncaught exception in Node. `rethrow` will also throw the\n error again so the error can be handled by the promise per the spec.\n\n ```javascript\n function throws(){\n throw new Error('Whoops!');\n }\n\n let promise = new RSVP.Promise(function(resolve, reject){\n throws();\n });\n\n promise.catch(RSVP.rethrow).then(function(){\n // Code here doesn't run because the promise became rejected due to an\n // error!\n }, function (err){\n // handle the error here\n });\n ```\n\n The 'Whoops' error will be thrown on the next turn of the event loop\n and you can watch for it in your console. You can also handle it using a\n rejection handler given to `.then` or `.catch` on the returned promise.\n\n @method rethrow\n @static\n @for RSVP\n @param {Error} reason reason the promise became rejected.\n @throws Error\n @static\n*/\nexport default function rethrow(reason) {\n setTimeout(function () {\n throw reason;\n });\n throw reason;\n}", + "import Promise from \"./promise\";\n\n/**\n `RSVP.defer` returns an object similar to jQuery's `$.Deferred`.\n `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s\n interface. New code should use the `RSVP.Promise` constructor instead.\n\n The object returned from `RSVP.defer` is a plain object with three properties:\n\n * promise - an `RSVP.Promise`.\n * reject - a function that causes the `promise` property on this object to\n become rejected\n * resolve - a function that causes the `promise` property on this object to\n become fulfilled.\n\n Example:\n\n ```javascript\n let deferred = RSVP.defer();\n\n deferred.resolve(\"Success!\");\n\n deferred.promise.then(function(value){\n // value here is \"Success!\"\n });\n ```\n\n @method defer\n @static\n @for RSVP\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Object}\n */\n\nexport default function defer(label) {\n var deferred = { resolve: undefined, reject: undefined };\n\n deferred.promise = new Promise(function (resolve, reject) {\n deferred.resolve = resolve;\n deferred.reject = reject;\n }, label);\n\n return deferred;\n}", + "import Promise from './promise';\n\nimport { isFunction, isArray } from './utils';\n\n/**\n `RSVP.map` is similar to JavaScript's native `map` method, except that it\n waits for all promises to become fulfilled before running the `mapFn` on\n each item in given to `promises`. `RSVP.map` returns a promise that will\n become fulfilled with the result of running `mapFn` on the values the promises\n become fulfilled with.\n\n For example:\n\n ```javascript\n\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n let mapFn = function(item){\n return item + 1;\n };\n\n RSVP.map(promises, mapFn).then(function(result){\n // result is [ 2, 3, 4 ]\n });\n ```\n\n If any of the `promises` given to `RSVP.map` are rejected, the first promise\n that is rejected will be given as an argument to the returned promise's\n rejection handler. For example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error('2'));\n let promise3 = RSVP.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n let mapFn = function(item){\n return item + 1;\n };\n\n RSVP.map(promises, mapFn).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === '2'\n });\n ```\n\n `RSVP.map` will also wait if a promise is returned from `mapFn`. For example,\n say you want to get all comments from a set of blog posts, but you need\n the blog posts first because they contain a url to those comments.\n\n ```javscript\n\n let mapFn = function(blogPost){\n // getComments does some ajax and returns an RSVP.Promise that is fulfilled\n // with some comments data\n return getComments(blogPost.comments_url);\n };\n\n // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled\n // with some blog post data\n RSVP.map(getBlogPosts(), mapFn).then(function(comments){\n // comments is the result of asking the server for the comments\n // of all blog posts returned from getBlogPosts()\n });\n ```\n\n @method map\n @static\n @for RSVP\n @param {Array} promises\n @param {Function} mapFn function to be called on each fulfilled promise.\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled with the result of calling\n `mapFn` on each fulfilled promise or value when they become fulfilled.\n The promise will be rejected if any of the given `promises` become rejected.\n @static\n*/\nexport default function map(promises, mapFn, label) {\n if (!isArray(promises)) {\n return Promise.reject(new TypeError(\"RSVP.map must be called with an array\"), label);\n }\n\n if (!isFunction(mapFn)) {\n return Promise.reject(new TypeError(\"RSVP.map expects a function as a second argument\"), label);\n }\n\n return Promise.all(promises, label).then(function (values) {\n var length = values.length;\n var results = new Array(length);\n\n for (var i = 0; i < length; i++) {\n results[i] = mapFn(values[i]);\n }\n\n return Promise.all(results, label);\n });\n}", + "import Promise from './promise';\n\n/**\n This is a convenient alias for `RSVP.Promise.resolve`.\n\n @method resolve\n @static\n @for RSVP\n @param {*} value value that the returned promise will be resolved with\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nexport default function resolve(value, label) {\n return Promise.resolve(value, label);\n}", + "import Promise from './promise';\n\n/**\n This is a convenient alias for `RSVP.Promise.reject`.\n\n @method reject\n @static\n @for RSVP\n @param {*} reason value that the returned promise will be rejected with.\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nexport default function reject(reason, label) {\n return Promise.reject(reason, label);\n}", + "import Promise from './promise';\nimport { isFunction, isArray, isObject } from './utils';\n\n/**\n `RSVP.filter` is similar to JavaScript's native `filter` method, except that it\n waits for all promises to become fulfilled before running the `filterFn` on\n each item in given to `promises`. `RSVP.filter` returns a promise that will\n become fulfilled with the result of running `filterFn` on the values the\n promises become fulfilled with.\n\n For example:\n\n ```javascript\n\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n\n let promises = [promise1, promise2, promise3];\n\n let filterFn = function(item){\n return item > 1;\n };\n\n RSVP.filter(promises, filterFn).then(function(result){\n // result is [ 2, 3 ]\n });\n ```\n\n If any of the `promises` given to `RSVP.filter` are rejected, the first promise\n that is rejected will be given as an argument to the returned promise's\n rejection handler. For example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error('2'));\n let promise3 = RSVP.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n let filterFn = function(item){\n return item > 1;\n };\n\n RSVP.filter(promises, filterFn).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === '2'\n });\n ```\n\n `RSVP.filter` will also wait for any promises returned from `filterFn`.\n For instance, you may want to fetch a list of users then return a subset\n of those users based on some asynchronous operation:\n\n ```javascript\n\n let alice = { name: 'alice' };\n let bob = { name: 'bob' };\n let users = [ alice, bob ];\n\n let promises = users.map(function(user){\n return RSVP.resolve(user);\n });\n\n let filterFn = function(user){\n // Here, Alice has permissions to create a blog post, but Bob does not.\n return getPrivilegesForUser(user).then(function(privs){\n return privs.can_create_blog_post === true;\n });\n };\n RSVP.filter(promises, filterFn).then(function(users){\n // true, because the server told us only Alice can create a blog post.\n users.length === 1;\n // false, because Alice is the only user present in `users`\n users[0] === bob;\n });\n ```\n\n @method filter\n @static\n @for RSVP\n @param {Array} promises\n @param {Function} filterFn - function to be called on each resolved value to\n filter the final results.\n @param {String} label optional string describing the promise. Useful for\n tooling.\n @return {Promise}\n*/\n\nfunction resolveAll(promises, label) {\n return Promise.all(promises, label);\n}\n\nfunction resolveSingle(promise, label) {\n return Promise.resolve(promise, label).then(function (promises) {\n return resolveAll(promises, label);\n });\n}\n\nexport default function filter(promises, filterFn, label) {\n if (!isArray(promises) && !(isObject(promises) && promises.then !== undefined)) {\n return Promise.reject(new TypeError(\"RSVP.filter must be called with an array or promise\"), label);\n }\n\n if (!isFunction(filterFn)) {\n return Promise.reject(new TypeError(\"RSVP.filter expects function as a second argument\"), label);\n }\n\n var promise = isArray(promises) ? resolveAll(promises, label) : resolveSingle(promises, label);\n return promise.then(function (values) {\n var length = values.length;\n var filtered = new Array(length);\n\n for (var i = 0; i < length; i++) {\n filtered[i] = filterFn(values[i]);\n }\n\n return resolveAll(filtered, label).then(function (filtered) {\n var results = new Array(length);\n var newLength = 0;\n\n for (var _i = 0; _i < length; _i++) {\n if (filtered[_i]) {\n results[newLength] = values[_i];\n newLength++;\n }\n }\n\n results.length = newLength;\n\n return results;\n });\n });\n}", + "var len = 0;\nvar vertxNext = void 0;\nexport default function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 1, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n scheduleFlush();\n }\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n var nextTick = process.nextTick;\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // setImmediate should be used instead instead\n var version = process.versions.node.match(/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/);\n if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {\n nextTick = setImmediate;\n }\n return function () {\n return nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n return node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n return function () {\n return setTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\n\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertex() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = void 0;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertex();\n} else {\n scheduleFlush = useSetTimeout();\n}", + "var platform = void 0;\n\n/* global self */\nif (typeof self === 'object') {\n platform = self;\n\n /* global global */\n} else if (typeof global === 'object') {\n platform = global;\n} else {\n throw new Error('no global: `self` or `global` found');\n}\n\nexport default platform;", + "var _asap$cast$Promise$Ev;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nimport Promise from './rsvp/promise';\nimport EventTarget from './rsvp/events';\nimport denodeify from './rsvp/node';\nimport all from './rsvp/all';\nimport allSettled from './rsvp/all-settled';\nimport race from './rsvp/race';\nimport hash from './rsvp/hash';\nimport hashSettled from './rsvp/hash-settled';\nimport rethrow from './rsvp/rethrow';\nimport defer from './rsvp/defer';\nimport { config, configure } from './rsvp/config';\nimport map from './rsvp/map';\nimport resolve from './rsvp/resolve';\nimport reject from './rsvp/reject';\nimport filter from './rsvp/filter';\nimport asap from './rsvp/asap';\n\n// defaults\nconfig.async = asap;\nconfig.after = function (cb) {\n return setTimeout(cb, 0);\n};\nvar cast = resolve;\n\nvar async = function (callback, arg) {\n return config.async(callback, arg);\n};\n\nfunction on() {\n config['on'].apply(config, arguments);\n}\n\nfunction off() {\n config['off'].apply(config, arguments);\n}\n\n// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`\nif (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {\n var callbacks = window['__PROMISE_INSTRUMENTATION__'];\n configure('instrument', true);\n for (var eventName in callbacks) {\n if (callbacks.hasOwnProperty(eventName)) {\n on(eventName, callbacks[eventName]);\n }\n }\n}\n\nimport platform from './rsvp/platform';\n// the default export here is for backwards compat:\n// https://github.com/tildeio/rsvp.js/issues/434\nexport default (_asap$cast$Promise$Ev = {\n asap: asap,\n cast: cast,\n Promise: Promise,\n EventTarget: EventTarget,\n all: all,\n allSettled: allSettled,\n race: race,\n hash: hash,\n hashSettled: hashSettled,\n rethrow: rethrow,\n defer: defer,\n denodeify: denodeify,\n configure: configure,\n on: on,\n off: off,\n resolve: resolve,\n reject: reject,\n map: map\n}, _defineProperty(_asap$cast$Promise$Ev, 'async', async), _defineProperty(_asap$cast$Promise$Ev, 'filter', filter), _asap$cast$Promise$Ev);\n\nexport { asap, cast, Promise, EventTarget, all, allSettled, race, hash, hashSettled, rethrow, defer, denodeify, configure, on, off, resolve, reject, map, async, filter };", + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + ] +} \ No newline at end of file diff --git a/epub.js/js/reader.min.map b/epub.js/js/reader.min.map new file mode 100644 index 0000000..6a23446 --- /dev/null +++ b/epub.js/js/reader.min.map @@ -0,0 +1 @@ +{"version":3,"file":"reader.min.js","sources":["../../reader_src/reader.js","../../reader_src/controllers/bookmarks_controller.js","../../reader_src/controllers/controls_controller.js","../../reader_src/controllers/meta_controller.js","../../reader_src/controllers/notes_controller.js","../../reader_src/controllers/reader_controller.js","../../reader_src/controllers/settings_controller.js","../../reader_src/controllers/sidebar_controller.js","../../reader_src/controllers/toc_controller.js"],"names":["EPUBJS","reader","plugins","root","ePubReader","path","options","Reader","define","amd","module","exports","window","jQuery","bookPath","_options","book","plugin","parameters","this","$viewer","$","search","location","settings","core","defaults","restore","reload","bookmarks","undefined","annotations","contained","bookKey","styles","sidebarReflow","generatePagination","history","slice","split","forEach","p","name","value","decodeURIComponent","setBookKey","isSaved","applySavedSettings","fontSize","Book","previousLocationCfi","gotoCfi","offline","sidebarOpen","width","height","renderTo","ReaderController","call","SettingsController","ControlsController","SidebarController","BookmarksController","NotesController","hasOwnProperty","ready","all","then","hideLoader","getMetadata","meta","MetaController","getToc","toc","TocController","addEventListener","unload","bind","hashChanged","document","adjustFontSize","on","arrowKeys","selectedRange","prototype","e","interval","PLUS","MINUS","ZERO","MOD","ctrlKey","metaKey","parseInt","keyCode","preventDefault","setStyle","addBookmark","cfi","present","isBookmarked","push","trigger","removeBookmark","bookmark","splice","indexOf","clearBookmarks","addNote","note","removeNote","index","clearNotes","identifier","VERSION","host","storedSettings","localStorage","getItem","removeSavedSettings","removeItem","stored","JSON","parse","saveSettings","getCurrentLocationCfi","setItem","stringify","hash","goto","range","epubcfi","EpubCFI","generateCfiFromRangeAnchor","renderer","currentChapter","cfiBase","cfiFragment","pushState","currentLocationCfi","RSVP","EventTarget","mixin","$bookmarks","$list","find","docfrag","createDocumentFragment","show","hide","counter","createBookmarkItem","listitem","createElement","link","id","classList","add","textContent","href","event","getAttribute","appendChild","append","item","$item","remove","$fullscreen","$slider","$settings","$bookmark","goOnline","goOffline","fullscreen","addClass","removeClass","screenfull","toggle","raw","fullscreenchange","isFullscreen","bookmarked","title","bookTitle","author","creator","$title","$author","$dash","html","$notesView","$notes","$text","$anchor","popups","insertAtPoint","textNode","offset","annotation","doc","caretPositionFromPoint","clientX","clientY","offsetNode","caretRangeFromPoint","startContainer","startOffset","nodeType","i","childNodes","length","generateCfiFromTextNode","annotatedAt","Date","anchor","body","val","addAnnotation","placeMarker","text","prop","off","innerHTML","onclick","marker","mark","style","verticalAlign","lineHeight","padding","backgroundColor","borderRadius","cursor","uuid","addMarker","markerEvents","txt","showPop","pop","itemRect","left","top","iheight","iwidth","maxHeight","setAttribute","pop_content","render","onPop","offPop","hidePop","getBoundingClientRect","popRect","setTimeout","openSidebar","slideOut","registerHook","callback","chapter","spinePos","console","log","$main","$divider","$loader","$next","$prev","slideIn","currentPosition","one","showLoader","hideDivider","showDivider","keylock","metadata","direction","nextPage","prevPage","bool","$overlay","$sidebarReflowSetting","$sidebar","$panels","activePanel","changePanelTo","viewName","controllerName","getActivePanel","view","data","generateTocItems","level","container","subitems","label","insertBefore","onShow","onHide","chapterChange","$current","has","parents","tocitems","url","parent","$el","open","hasClass"],"mappings":"AAAAA,OAAOC,UACPD,OAAOC,OAAOC,WAEd,SAAUC,GAET,GAEIC,IAFiBD,EAAKC,eAETD,EAAKC,WAAa,SAASC,EAAMC,GACjD,MAAO,IAAIN,QAAOO,OAAOF,EA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B,CAAA,GAAIsE,GAAKtE,EAAEsE,GACTU,EAAQrB,EAAMC,KAAK,QAAQU,GAC3BgJ,EAAW3J,EAAMC,KAAK,kBACdD,GAAMC,KAAK,gBAElBoB,EAAM6C,SAEL7C,GAASsI,GAAYtI,EAAMuI,IAAIrK,GAAgB2E,OAAS,GAC1DyF,EAAS5H,YAAY,kBAGtBV,EAAMS,SAAS,kBAGfT,EAAMwI,QAAQ,MAAM/H,SAAS,gBAI/B9J,GAAKiE,GAAG,4BAA6ByN,EAErC,IAAII,GAAWZ,EAAiBzN,EAkChC,OAhCAyE,GAAQgB,YAAY4I,GAEpB9J,EAAMmB,OAAOjB,GACbF,EAAMC,KAAK,aAAahE,GAAG,QAAS,SAAS+E,GAC3C,GAAI+I,GAAM5R,KAAK8I,aAAa,OAE5BD,GAAMjE,iBAIN/E,EAAKiH,KAAK8K,GAEV/J,EAAMC,KAAK,mBACR6B,SAAS,eACTC,YAAY,kBAEf1J,EAAEF,MAAM6R,OAAO,MAAMlI,SAAS,oBAIhC9B,EAAMC,KAAK,eAAehE,GAAG,QAAS,SAAS+E,GAC7C,GAAIiJ,GAAM5R,EAAEF,MAAM6R,OAAO,MACvBE,EAAOD,EAAIE,SAAS,cAEtBnJ,GAAMjE,iBACHmN,EACFD,EAAIlI,YAAY,eAEhBkI,EAAInI,SAAS,kBAKf1B,KAASoJ,EACTnJ,KAASoJ"} \ No newline at end of file diff --git a/epub.js/libs/fileStorage.min.js b/epub.js/libs/fileStorage.min.js deleted file mode 100644 index 6fc082b..0000000 --- a/epub.js/libs/fileStorage.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! fileStorage - v0.1.0 - 2013-03-28 */var fileStorage = fileStorage || {}; -fileStorage.core=fileStorage.core||{},fileStorage.core.dataURLToBlob=function(e){var t=";base64,";if(e.indexOf(t)==-1){var n=e.split(","),r=n[0].split(":")[1],i=n[1];return new Blob([i],{type:r})}var n=e.split(t),r=n[0].split(":")[1],i=window.atob(n[1]),s=i.length,o=new Uint8Array(s);for(var u=0;u=y&&0===e[y];y++);for(z=y,y>A&&(A=y),x=B;0!==x&&0===e[x];x--);for(v=x,A>x&&(A=x),n[0]=A,H=1<y;y++,H<<=1)if((H-=e[y])<0)return m;if((H-=e[x])<0)return m;for(e[x]+=H,h[1]=y=0,D=1,G=2;0!==--x;)h[G]=y+=e[D],G++,D++;x=0,D=0;do 0!==(y=a[b+D])&&(s[h[y]++]=x),D++;while(++x=z;z++)for(t=e[z];0!==t--;){for(;z>F+A;){if(w++,F+=A,I=v-F,I=I>A?A:I,(u=1<<(y=z-F))>t+1&&(u-=t+1,G=z,I>y))for(;++yq)return m;g[w]=E=r[0],r[0]+=I,0!==w?(h[w]=x,f[0]=y,f[1]=A,y=x>>>F-A,f[2]=E-g[w-1]-y,p.set(f,3*(g[w-1]+y))):l[0]=E}for(f[1]=z-F,D>=c?f[0]=192:s[D]>>F;I>y;y+=u)p.set(f,3*(E+y));for(y=1<>>=1)x^=y;for(x^=y,C=(1<b;b++)d[b]=0;for(b=0;B+1>b;b++)e[b]=0;for(b=0;3>b;b++)f[b]=0;g.set(e.subarray(0,B),0),h.set(e.subarray(0,B+1),0)}var c,d,e,f,g,h,j=this;j.inflate_trees_bits=function(e,f,g,h,i){var j;return b(19),c[0]=0,j=a(e,0,19,19,null,null,g,f,h,c,d),j==m?i.msg="oversubscribed dynamic bit lengths tree":(j==o||0===f[0])&&(i.msg="incomplete dynamic bit lengths tree",j=m),j},j.inflate_trees_dynamic=function(e,f,g,h,j,k,l,p,q){var r;return b(288),c[0]=0,r=a(g,0,e,257,x,y,k,h,p,c,d),r!=i||0===h[0]?(r==m?q.msg="oversubscribed literal/length tree":r!=n&&(q.msg="incomplete literal/length tree",r=m),r):(b(288),r=a(g,e,f,0,z,A,l,j,p,c,d),r!=i||0===j[0]&&e>257?(r==m?q.msg="oversubscribed distance tree":r==o?(q.msg="incomplete distance tree",r=m):r!=n&&(q.msg="empty distance tree with lengths",r=m),r):i)}}function c(){function a(a,b,c,d,e,f,g,h){var k,l,n,o,q,r,s,t,u,v,w,x,y,z,A,B;s=h.next_in_index,t=h.avail_in,q=g.bitb,r=g.bitk,u=g.write,v=ur;)t--,q|=(255&h.read_byte(s++))<>=l[B+1],r-=l[B+1],0!==(16&o)){for(o&=15,y=l[B+2]+(q&p[o]),q>>=o,r-=o;15>r;)t--,q|=(255&h.read_byte(s++))<>=l[B+1],r-=l[B+1],0!==(16&o)){for(o&=15;o>r;)t--,q|=(255&h.read_byte(s++))<>=o,r-=o,v-=y,u>=z)A=u-z,u-A>0&&2>u-A?(g.window[u++]=g.window[A++],g.window[u++]=g.window[A++],y-=2):(g.window.set(g.window.subarray(A,A+2),u),u+=2,A+=2,y-=2);else{A=u-z;do A+=g.end;while(0>A);if(o=g.end-A,y>o){if(y-=o,u-A>0&&o>u-A){do g.window[u++]=g.window[A++];while(0!==--o)}else g.window.set(g.window.subarray(A,A+o),u),u+=o,A+=o,o=0;A=0}}if(u-A>0&&y>u-A){do g.window[u++]=g.window[A++];while(0!==--y)}else g.window.set(g.window.subarray(A,A+y),u),u+=y,A+=y,y=0;break}if(0!==(64&o))return h.msg="invalid distance code",y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,m;k+=l[B+2],k+=q&p[o],B=3*(n+k),o=l[B]}break}if(0!==(64&o))return 0!==(32&o)?(y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,j):(h.msg="invalid literal/length code",y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,m);if(k+=l[B+2],k+=q&p[o],B=3*(n+k),0===(o=l[B])){q>>=l[B+1],r-=l[B+1],g.window[u++]=l[B+2],v--;break}}else q>>=l[B+1],r-=l[B+1],g.window[u++]=l[B+2],v--}while(v>=258&&t>=10);return y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,i}var b,c,d,e,f=this,g=0,h=0,k=0,n=0,o=0,q=0,r=0,s=0,t=0,u=0;f.init=function(a,f,g,h,i,j){b=C,r=a,s=f,d=g,t=h,e=i,u=j,c=null},f.proc=function(f,v,w){var x,y,z,A,B,M,N,O=0,P=0,Q=0;for(Q=v.next_in_index,A=v.avail_in,O=f.bitb,P=f.bitk,B=f.write,M=B=258&&A>=10&&(f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,w=a(r,s,d,t,e,u,f,v),Q=v.next_in_index,A=v.avail_in,O=f.bitb,P=f.bitk,B=f.write,M=BP;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>>=c[y+1],P-=c[y+1],z=c[y],0===z){n=c[y+2],b=I;break}if(0!==(16&z)){o=15&z,g=c[y+2],b=E;break}if(0===(64&z)){k=z,h=y/3+c[y+2];break}if(0!==(32&z)){b=J;break}return b=L,v.msg="invalid literal/length code",w=m,f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);case E:for(x=o;x>P;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>=x,P-=x,k=s,c=e,h=u,b=F;case F:for(x=k;x>P;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>=c[y+1],P-=c[y+1],z=c[y],0!==(16&z)){o=15&z,q=c[y+2],b=G;break}if(0===(64&z)){k=z,h=y/3+c[y+2];break}return b=L,v.msg="invalid distance code",w=m,f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);case G:for(x=o;x>P;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>=x,P-=x,b=H;case H:for(N=B-q;0>N;)N+=f.end;for(;0!==g;){if(0===M&&(B==f.end&&0!==f.read&&(B=0,M=B7&&(P-=8,A++,Q--),f.write=B,w=f.inflate_flush(v,w),B=f.write,M=Ba.avail_out&&(c=a.avail_out),0!==c&&b==o&&(b=i),a.avail_out-=c,a.total_out+=c,a.next_out.set(f.window.subarray(e,e+c),d),d+=c,e+=c,e==f.end&&(e=0,f.write==f.end&&(f.write=0),c=f.write-e,c>a.avail_out&&(c=a.avail_out),0!==c&&b==o&&(b=i),a.avail_out-=c,a.total_out+=c,a.next_out.set(f.window.subarray(e,e+c),d),d+=c,e+=c),a.next_out_index=d,f.read=e,b},f.proc=function(a,c){var d,o,q,w,y,z,A,B;for(w=a.next_in_index,y=a.avail_in,o=f.bitb,q=f.bitk,z=f.write,A=zq;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>1){case 0:o>>>=3,q-=3,d=7&q,o>>>=d,q-=d,g=O;break;case 1:var C=[],D=[],E=[[]],F=[[]];b.inflate_trees_fixed(C,D,E,F),t.init(C[0],D[0],E[0],0,F[0],0),o>>>=3,q-=3,g=T;break;case 2:o>>>=3,q-=3,g=Q;break;case 3:return o>>>=3,q-=3,g=W,a.msg="invalid block type",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c)}break;case O:for(;32>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>16&65535)!=(65535&o))return g=W,a.msg="invalid stored block lengths",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);h=65535&o,o=q=0,g=0!==h?P:0!==u?U:N;break;case P:if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);if(0===A&&(z==f.end&&0!==f.read&&(z=0,A=zy&&(d=y),d>A&&(d=A),f.window.set(a.read_buf(w,d),z),w+=d,y-=d,z+=d,A-=d,0!==(h-=d))break;g=0!==u?U:N;break;case Q:for(;14>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<29||(d>>5&31)>29)return g=W,a.msg="too many length or distance symbols",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);if(d=258+(31&d)+(d>>5&31),!e||e.lengthB;B++)e[B]=0;o>>>=14,q-=14,n=0,g=R;case R:for(;4+(k>>>10)>n;){for(;3>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>=3,q-=3}for(;19>n;)e[M[n++]]=0;if(r[0]=7,d=x.inflate_trees_bits(e,r,s,v,a),d!=i)return c=d,c==m&&(e=null,g=W),f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);n=0,g=S;case S:for(;;){if(d=k,!(258+(31&d)+(d>>5&31)>n))break;var G,H;for(d=r[0];d>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<H)o>>>=d,q-=d,e[n++]=H;else{for(B=18==H?7:H-14,G=18==H?11:3;d+B>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>=d,q-=d,G+=o&p[B],o>>>=B,q-=B,B=n,d=k,B+G>258+(31&d)+(d>>5&31)||16==H&&1>B)return e=null,g=W,a.msg="invalid bit length repeat",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);H=16==H?e[B-1]:0;do e[B++]=H;while(0!==--G);n=B}}s[0]=-1;var I=[],J=[],K=[],L=[];if(I[0]=9,J[0]=6,d=k,d=x.inflate_trees_dynamic(257+(31&d),1+(d>>5&31),e,I,J,K,L,v,a),d!=i)return d==m&&(e=null,g=W),c=d,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);t.init(I[0],J[0],v,K[0],v,L[0]),g=T;case T:if(f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,(c=t.proc(f,a,c))!=j)return f.inflate_flush(a,c);if(c=i,t.free(a),w=a.next_in_index,y=a.avail_in,o=f.bitb,q=f.bitk,z=f.write,A=ze||e>15?(b.inflateEnd(c),l):(b.wbits=e,c.istate.blocks=new d(c,1<>4)+8>a.istate.wbits){a.istate.mode=gb,a.msg="invalid window size",a.istate.marker=5;break}a.istate.mode=$;case $:if(0===a.avail_in)return c;if(c=b,a.avail_in--,a.total_in++,d=255&a.read_byte(a.next_in_index++),((a.istate.method<<8)+d)%31!==0){a.istate.mode=gb,a.msg="incorrect header check",a.istate.marker=5;break}if(0===(d&X)){a.istate.mode=eb;break}a.istate.mode=_;case _:if(0===a.avail_in)return c;c=b,a.avail_in--,a.total_in++,a.istate.need=(255&a.read_byte(a.next_in_index++))<<24&4278190080,a.istate.mode=ab;case ab:if(0===a.avail_in)return c;c=b,a.avail_in--,a.total_in++,a.istate.need+=(255&a.read_byte(a.next_in_index++))<<16&16711680,a.istate.mode=bb;case bb:if(0===a.avail_in)return c;c=b,a.avail_in--,a.total_in++,a.istate.need+=(255&a.read_byte(a.next_in_index++))<<8&65280,a.istate.mode=cb;case cb:return 0===a.avail_in?c:(c=b,a.avail_in--,a.total_in++,a.istate.need+=255&a.read_byte(a.next_in_index++),a.istate.mode=db,k);case db:return a.istate.mode=gb,a.msg="need dictionary",a.istate.marker=0,l;case eb:if(c=a.istate.blocks.proc(a,c),c==m){a.istate.mode=gb,a.istate.marker=0;break}if(c==i&&(c=b),c!=j)return c;c=b,a.istate.blocks.reset(a,a.istate.was),a.istate.mode=fb;case fb:return j;case gb:return m;default:return l}},b.inflateSetDictionary=function(a,b,c){var d=0,e=c;return a&&a.istate&&a.istate.mode==db?(e>=1<e;)b.read_byte(d)==hb[e]?e++:e=0!==b.read_byte(d)?0:4-e,d++,c--;return b.total_in+=d-b.next_in_index,b.next_in_index=d,b.avail_in=c,b.istate.marker=e,4!=e?m:(f=b.total_in,g=b.total_out,a(b),b.total_in=f,b.total_out=g,b.istate.mode=eb,i)},b.inflateSyncPoint=function(a){return a&&a.istate&&a.istate.blocks?a.istate.blocks.sync_point():l}}function f(){}function g(){var a=this,b=new f,c=512,d=r,e=new Uint8Array(c),g=!1;b.inflateInit(),b.next_out=e,a.append=function(a,f){var h,k,l=[],m=0,n=0,p=0;if(0!==a.length){b.next_in_index=0,b.next_in=a,b.avail_in=a.length;do{if(b.next_out_index=0,b.avail_out=c,0!==b.avail_in||g||(b.next_in_index=0,g=!0),h=b.inflate(d),g&&h==o)return-1;if(h!=i&&h!=j)throw"inflating: "+b.msg;if((g||h==j)&&b.avail_in==a.length)return-1;b.next_out_index&&l.push(b.next_out_index==c?new Uint8Array(e):new Uint8Array(e.subarray(0,b.next_out_index))),p+=b.next_out_index,f&&b.next_in_index>0&&b.next_in_index!=m&&(f(b.next_in_index),m=b.next_in_index)}while(b.avail_in>0||0===b.avail_out);return k=new Uint8Array(p),l.forEach(function(a){k.set(a,n),n+=a.length}),k}},a.flush=function(){b.inflateEnd()}}var h=15,i=0,j=1,k=2,l=-2,m=-3,n=-4,o=-5,p=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],q=1440,r=0,s=4,t=9,u=5,v=[96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,192,80,7,10,0,8,96,0,8,32,0,9,160,0,8,0,0,8,128,0,8,64,0,9,224,80,7,6,0,8,88,0,8,24,0,9,144,83,7,59,0,8,120,0,8,56,0,9,208,81,7,17,0,8,104,0,8,40,0,9,176,0,8,8,0,8,136,0,8,72,0,9,240,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,200,81,7,13,0,8,100,0,8,36,0,9,168,0,8,4,0,8,132,0,8,68,0,9,232,80,7,8,0,8,92,0,8,28,0,9,152,84,7,83,0,8,124,0,8,60,0,9,216,82,7,23,0,8,108,0,8,44,0,9,184,0,8,12,0,8,140,0,8,76,0,9,248,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,196,81,7,11,0,8,98,0,8,34,0,9,164,0,8,2,0,8,130,0,8,66,0,9,228,80,7,7,0,8,90,0,8,26,0,9,148,84,7,67,0,8,122,0,8,58,0,9,212,82,7,19,0,8,106,0,8,42,0,9,180,0,8,10,0,8,138,0,8,74,0,9,244,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,204,81,7,15,0,8,102,0,8,38,0,9,172,0,8,6,0,8,134,0,8,70,0,9,236,80,7,9,0,8,94,0,8,30,0,9,156,84,7,99,0,8,126,0,8,62,0,9,220,82,7,27,0,8,110,0,8,46,0,9,188,0,8,14,0,8,142,0,8,78,0,9,252,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,194,80,7,10,0,8,97,0,8,33,0,9,162,0,8,1,0,8,129,0,8,65,0,9,226,80,7,6,0,8,89,0,8,25,0,9,146,83,7,59,0,8,121,0,8,57,0,9,210,81,7,17,0,8,105,0,8,41,0,9,178,0,8,9,0,8,137,0,8,73,0,9,242,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,202,81,7,13,0,8,101,0,8,37,0,9,170,0,8,5,0,8,133,0,8,69,0,9,234,80,7,8,0,8,93,0,8,29,0,9,154,84,7,83,0,8,125,0,8,61,0,9,218,82,7,23,0,8,109,0,8,45,0,9,186,0,8,13,0,8,141,0,8,77,0,9,250,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,198,81,7,11,0,8,99,0,8,35,0,9,166,0,8,3,0,8,131,0,8,67,0,9,230,80,7,7,0,8,91,0,8,27,0,9,150,84,7,67,0,8,123,0,8,59,0,9,214,82,7,19,0,8,107,0,8,43,0,9,182,0,8,11,0,8,139,0,8,75,0,9,246,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,206,81,7,15,0,8,103,0,8,39,0,9,174,0,8,7,0,8,135,0,8,71,0,9,238,80,7,9,0,8,95,0,8,31,0,9,158,84,7,99,0,8,127,0,8,63,0,9,222,82,7,27,0,8,111,0,8,47,0,9,190,0,8,15,0,8,143,0,8,79,0,9,254,96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,193,80,7,10,0,8,96,0,8,32,0,9,161,0,8,0,0,8,128,0,8,64,0,9,225,80,7,6,0,8,88,0,8,24,0,9,145,83,7,59,0,8,120,0,8,56,0,9,209,81,7,17,0,8,104,0,8,40,0,9,177,0,8,8,0,8,136,0,8,72,0,9,241,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,201,81,7,13,0,8,100,0,8,36,0,9,169,0,8,4,0,8,132,0,8,68,0,9,233,80,7,8,0,8,92,0,8,28,0,9,153,84,7,83,0,8,124,0,8,60,0,9,217,82,7,23,0,8,108,0,8,44,0,9,185,0,8,12,0,8,140,0,8,76,0,9,249,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,197,81,7,11,0,8,98,0,8,34,0,9,165,0,8,2,0,8,130,0,8,66,0,9,229,80,7,7,0,8,90,0,8,26,0,9,149,84,7,67,0,8,122,0,8,58,0,9,213,82,7,19,0,8,106,0,8,42,0,9,181,0,8,10,0,8,138,0,8,74,0,9,245,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,205,81,7,15,0,8,102,0,8,38,0,9,173,0,8,6,0,8,134,0,8,70,0,9,237,80,7,9,0,8,94,0,8,30,0,9,157,84,7,99,0,8,126,0,8,62,0,9,221,82,7,27,0,8,110,0,8,46,0,9,189,0,8,14,0,8,142,0,8,78,0,9,253,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,195,80,7,10,0,8,97,0,8,33,0,9,163,0,8,1,0,8,129,0,8,65,0,9,227,80,7,6,0,8,89,0,8,25,0,9,147,83,7,59,0,8,121,0,8,57,0,9,211,81,7,17,0,8,105,0,8,41,0,9,179,0,8,9,0,8,137,0,8,73,0,9,243,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,203,81,7,13,0,8,101,0,8,37,0,9,171,0,8,5,0,8,133,0,8,69,0,9,235,80,7,8,0,8,93,0,8,29,0,9,155,84,7,83,0,8,125,0,8,61,0,9,219,82,7,23,0,8,109,0,8,45,0,9,187,0,8,13,0,8,141,0,8,77,0,9,251,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,199,81,7,11,0,8,99,0,8,35,0,9,167,0,8,3,0,8,131,0,8,67,0,9,231,80,7,7,0,8,91,0,8,27,0,9,151,84,7,67,0,8,123,0,8,59,0,9,215,82,7,19,0,8,107,0,8,43,0,9,183,0,8,11,0,8,139,0,8,75,0,9,247,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,207,81,7,15,0,8,103,0,8,39,0,9,175,0,8,7,0,8,135,0,8,71,0,9,239,80,7,9,0,8,95,0,8,31,0,9,159,84,7,99,0,8,127,0,8,63,0,9,223,82,7,27,0,8,111,0,8,47,0,9,191,0,8,15,0,8,143,0,8,79,0,9,255],w=[80,5,1,87,5,257,83,5,17,91,5,4097,81,5,5,89,5,1025,85,5,65,93,5,16385,80,5,3,88,5,513,84,5,33,92,5,8193,82,5,9,90,5,2049,86,5,129,192,5,24577,80,5,2,87,5,385,83,5,25,91,5,6145,81,5,7,89,5,1537,85,5,97,93,5,24577,80,5,4,88,5,769,84,5,49,92,5,12289,82,5,13,90,5,3073,86,5,193,192,5,24577],x=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],y=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,112,112],z=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],A=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],B=15;b.inflate_trees_fixed=function(a,b,c,d){return a[0]=t,b[0]=u,c[0]=v,d[0]=w,i};var C=0,D=1,E=2,F=3,G=4,H=5,I=6,J=7,K=8,L=9,M=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],N=0,O=1,P=2,Q=3,R=4,S=5,T=6,U=7,V=8,W=9,X=32,Y=8,Z=0,$=1,_=2,ab=3,bb=4,cb=5,db=6,eb=7,fb=12,gb=13,hb=[0,0,255,255];f.prototype={inflateInit:function(a){var b=this;return b.istate=new e,a||(a=h),b.istate.inflateInit(b,a)},inflate:function(a){var b=this;return b.istate?b.istate.inflate(b,a):l},inflateEnd:function(){var a=this;if(!a.istate)return l;var b=a.istate.inflateEnd(a);return a.istate=null,b},inflateSync:function(){var a=this;return a.istate?a.istate.inflateSync(a):l},inflateSetDictionary:function(a,b){var c=this;return c.istate?c.istate.inflateSetDictionary(c,a,b):l},read_byte:function(a){var b=this;return b.next_in.subarray(a,a+1)[0]},read_buf:function(a,b){var c=this;return c.next_in.subarray(a,a+b)}};var ib;a.zip?a.zip.Inflater=g:(ib=new g,a.addEventListener("message",function(b){var c=b.data;c.append&&a.postMessage({onappend:!0,data:ib.append(c.data,function(b){a.postMessage({progress:!0,current:b})})}),c.flush&&(ib.flush(),a.postMessage({onflush:!0}))},!1))}(this); -//# sourceMappingURL=inflate.map \ No newline at end of file diff --git a/epub.js/libs/inflate.map b/epub.js/libs/inflate.map deleted file mode 100644 index dc48317..0000000 --- a/epub.js/libs/inflate.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inflate.js","sources":["../../libs/zip/inflate.js"],"names":["obj","InfTree","huft_build","b","bindex","n","s","d","e","t","m","hp","hn","v","a","f","g","h","i","j","k","l","mask","p","q","w","xp","y","z","c","Z_OK","BMAX","Z_DATA_ERROR","x","u","MANY","r","set","Z_BUF_ERROR","initWorkArea","vsize","Int32Array","length","subarray","that","this","inflate_trees_bits","bb","tb","result","msg","inflate_trees_dynamic","nl","nd","bl","bd","tl","td","cplens","cplext","Z_MEM_ERROR","cpdist","cpdext","InfCodes","inflate_fast","tl_index","td_index","tp","tp_index","ml","md","tp_index_t_3","next_in_index","avail_in","bitb","bitk","write","read","end","inflate_mask","read_byte","window","total_in","Z_STREAM_END","mode","tree","ltree","dtree","len","tree_index","need","lit","get","dist","lbits","dbits","ltree_index","dtree_index","init","START","proc","tindex","WASH","BADCODE","LEN","inflate_flush","LIT","LENEXT","DIST","DISTEXT","COPY","END","Z_STREAM_ERROR","free","InfBlocks","blens","TYPE","left","table","index","codes","last","hufts","check","inftree","Uint8Array","reset","CODES","next_out_index","avail_out","total_out","next_out","LENS","inflate_trees_fixed","TABLE","BADBLOCKS","STORED","DRY","read_buf","BTREE","border","DTREE","bl_","bd_","tl_","td_","DONELOCKS","set_dictionary","start","sync_point","Inflate","inflateReset","istate","BLOCKS","blocks","method","was","marker","wbits","inflateEnd","inflateInit","inflate","next_in","Z_FINISH","METHOD","Z_DEFLATED","BAD","FLAG","PRESET_DICT","DICT4","DICT3","DICT2","DICT1","DICT0","Z_NEED_DICT","DONE","inflateSetDictionary","dictionary","dictLength","inflateSync","mark","inflateSyncPoint","ZStream","Inflater","bufsize","flush","Z_NO_FLUSH","buf","nomoreinput","append","data","onprogress","err","array","buffers","lastIndex","bufferIndex","bufferSize","push","forEach","chunk","MAX_BITS","fixed_bl","fixed_bd","fixed_tl","fixed_td","prototype","bits","ret","size","inflater","zip","addEventListener","event","message","postMessage","onappend","current","progress","onflush"],"mappings":"CAmCA,SAAUA,GAqFT,QAASC,KAUR,QAASC,GAAWC,EAEpBC,EAAQC,EACRC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,GAWC,GAAIC,GACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,CAIJL,GAAI,EACJL,EAAIb,CACJ,GACCwB,GAAE1B,EAAEC,EAASmB,MACbA,IACAL,UACc,IAANA,EAET,IAAIW,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AOC,IACX,OAAKD,GAAK4G,OAEH5G,EAAK4G,OAAO2B,YAAYvI,GADvBoE,GAGTgE,qBAAuB,SAASC,EAAYC,GAC3C,GAAItI,GAAOC,IACX,OAAKD,GAAK4G,OAEH5G,EAAK4G,OAAOwB,qBAAqBpI,EAAMqI,EAAYC,GADlDlE,GAGThC,UAAY,SAASoE,GACpB,GAAIxG,GAAOC,IACX,OAAOD,GAAKsH,QAAQvH,SAASyG,EAAOA,EAAQ,GAAG,IAEhDV,SAAW,SAASU,EAAO6D,GAC1B,GAAIrK,GAAOC,IACX,OAAOD,GAAKsH,QAAQvH,SAASyG,EAAOA,EAAQ6D,IA6D9C,IAAIC,GAEAlN,GAAImN,IACPnN,EAAImN,IAAI5B,SAAWA,GAEnB2B,GAAW,GAAI3B,GACfvL,EAAIoN,iBAAiB,UAAW,SAASC,GACxC,GAAIC,GAAUD,EAAMvB,IAEhBwB,GAAQzB,QACX7L,EAAIuN,aACHC,UAAW,EACX1B,KAAOoB,GAASrB,OAAOyB,EAAQxB,KAAM,SAAS2B,GAC7CzN,EAAIuN,aACHG,UAAW,EACXD,QAAUA,QAIVH,EAAQ7B,QACXyB,GAASzB,QACTzL,EAAIuN,aACHI,SAAU,OAGV,KAGF9K"} \ No newline at end of file diff --git a/epub.js/libs/jquery-2.1.0.min.js b/epub.js/libs/jquery-2.1.0.min.js deleted file mode 100644 index cbe6abe..0000000 --- a/epub.js/libs/jquery-2.1.0.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m=a.document,n="2.1.0",o=function(a,b){return new o.fn.init(a,b)},p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};o.fn=o.prototype={jquery:n,constructor:o,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=o.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return o.each(this,a,b)},map:function(a){return this.pushStack(o.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},o.extend=o.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||o.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(o.isPlainObject(d)||(e=o.isArray(d)))?(e?(e=!1,f=c&&o.isArray(c)?c:[]):f=c&&o.isPlainObject(c)?c:{},g[b]=o.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},o.extend({expando:"jQuery"+(n+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===o.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isPlainObject:function(a){if("object"!==o.type(a)||a.nodeType||o.isWindow(a))return!1;try{if(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=o.trim(a),a&&(1===a.indexOf("use strict")?(b=m.createElement("script"),b.text=a,m.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":k.call(a)},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?o.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),o.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||o.guid++,f):void 0},now:Date.now,support:l}),o.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=o.type(a);return"function"===c||o.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);o.find=t,o.expr=t.selectors,o.expr[":"]=o.expr.pseudos,o.unique=t.uniqueSort,o.text=t.getText,o.isXMLDoc=t.isXML,o.contains=t.contains;var u=o.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(o.isFunction(b))return o.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return o.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return o.filter(b,a,c);b=o.filter(b,a)}return o.grep(a,function(a){return g.call(b,a)>=0!==c})}o.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?o.find.matchesSelector(d,a)?[d]:[]:o.find.matches(a,o.grep(b,function(a){return 1===a.nodeType}))},o.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(o(a).filter(function(){for(b=0;c>b;b++)if(o.contains(e[b],this))return!0}));for(b=0;c>b;b++)o.find(a,e[b],d);return d=this.pushStack(c>1?o.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?o(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=o.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof o?b[0]:b,o.merge(this,o.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:m,!0)),v.test(c[1])&&o.isPlainObject(b))for(c in b)o.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=m.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=m,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):o.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(o):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),o.makeArray(a,this))};A.prototype=o.fn,y=o(m);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};o.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&o(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),o.fn.extend({has:function(a){var b=o(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(o.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?o(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&o.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?o.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(o(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(o.unique(o.merge(this.get(),o(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}o.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return o.dir(a,"parentNode")},parentsUntil:function(a,b,c){return o.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return o.dir(a,"nextSibling")},prevAll:function(a){return o.dir(a,"previousSibling")},nextUntil:function(a,b,c){return o.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return o.dir(a,"previousSibling",c)},siblings:function(a){return o.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return o.sibling(a.firstChild)},contents:function(a){return a.contentDocument||o.merge([],a.childNodes)}},function(a,b){o.fn[a]=function(c,d){var e=o.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=o.filter(d,e)),this.length>1&&(C[a]||o.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return o.each(a.match(E)||[],function(a,c){b[c]=!0}),b}o.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):o.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){o.each(b,function(b,c){var d=o.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&o.each(arguments,function(a,b){var c;while((c=o.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?o.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},o.extend({Deferred:function(a){var b=[["resolve","done",o.Callbacks("once memory"),"resolved"],["reject","fail",o.Callbacks("once memory"),"rejected"],["notify","progress",o.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return o.Deferred(function(c){o.each(b,function(b,f){var g=o.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&o.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?o.extend(a,d):d}},e={};return d.pipe=d.then,o.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&o.isFunction(a.promise)?e:0,g=1===f?a:o.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&o.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;o.fn.ready=function(a){return o.ready.promise().done(a),this},o.extend({isReady:!1,readyWait:1,holdReady:function(a){a?o.readyWait++:o.ready(!0)},ready:function(a){(a===!0?--o.readyWait:o.isReady)||(o.isReady=!0,a!==!0&&--o.readyWait>0||(H.resolveWith(m,[o]),o.fn.trigger&&o(m).trigger("ready").off("ready")))}});function I(){m.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),o.ready()}o.ready.promise=function(b){return H||(H=o.Deferred(),"complete"===m.readyState?setTimeout(o.ready):(m.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},o.ready.promise();var J=o.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===o.type(c)){e=!0;for(h in c)o.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,o.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(o(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};o.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=o.expando+Math.random()}K.uid=1,K.accepts=o.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,o.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(o.isEmptyObject(f))o.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,o.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{o.isArray(b)?d=b.concat(b.map(o.camelCase)):(e=o.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!o.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?o.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}o.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),o.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length; -while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=o.camelCase(d.slice(5)),P(f,d,e[d]));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=o.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),o.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||o.isArray(c)?d=L.access(a,b,o.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=o.queue(a,b),d=c.length,e=c.shift(),f=o._queueHooks(a,b),g=function(){o.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:o.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),o.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";l.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return m.activeElement}catch(a){}}o.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=o.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof o!==U&&o.event.triggered!==b.type?o.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n&&(l=o.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=o.event.special[n]||{},k=o.extend({type:n,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&o.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),o.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n){l=o.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||o.removeEvent(a,n,r.handle),delete i[n])}else for(n in i)o.event.remove(a,n+b[j],c,d,!0);o.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,p=[d||m],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||m,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+o.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[o.expando]?b:new o.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:o.makeArray(c,[b]),n=o.event.special[q]||{},e||!n.trigger||n.trigger.apply(d,c)!==!1)){if(!e&&!n.noBubble&&!o.isWindow(d)){for(i=n.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||m)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:n.bindType||q,l=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),l&&l.apply(g,c),l=k&&g[k],l&&l.apply&&o.acceptData(g)&&(b.result=l.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||n._default&&n._default.apply(p.pop(),c)!==!1||!o.acceptData(d)||k&&o.isFunction(d[q])&&!o.isWindow(d)&&(h=d[k],h&&(d[k]=null),o.event.triggered=q,d[q](),o.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=o.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=o.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=o.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((o.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?o(e,this).index(i)>=0:o.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return o.nodeName(a,"table")&&o.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)o.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=o.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&o.nodeName(a,b)?o.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}o.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=o.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||o.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,n=a.length;n>m;m++)if(e=a[m],e||0===e)if("object"===o.type(e))o.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;o.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===o.inArray(e,d))&&(i=o.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f,g,h=o.event.special,i=0;void 0!==(c=a[i]);i++){if(o.acceptData(c)&&(f=c[L.expando],f&&(b=L.cache[f]))){if(d=Object.keys(b.events||{}),d.length)for(g=0;void 0!==(e=d[g]);g++)h[e]?o.event.remove(c,e):o.removeEvent(c,e,b.handle);L.cache[f]&&delete L.cache[f]}delete M.cache[c[M.expando]]}}}),o.fn.extend({text:function(a){return J(this,function(a){return void 0===a?o.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?o.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||o.cleanData(ob(c)),c.parentNode&&(b&&o.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(o.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return o.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(o.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,o.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,n=k-1,p=a[0],q=o.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(c=o.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=o.map(ob(c,"script"),kb),g=f.length;k>j;j++)h=c,j!==n&&(h=o.clone(h,!0,!0),g&&o.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,o.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&o.contains(i,h)&&(h.src?o._evalUrl&&o._evalUrl(h.src):o.globalEval(h.textContent.replace(hb,"")))}return this}}),o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){o.fn[a]=function(a){for(var c,d=[],e=o(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),o(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d=o(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:o.css(d[0],"display");return d.detach(),e}function tb(a){var b=m,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||o("