diff --git a/server/src/main/resources/static/epub/epub.js b/server/src/main/resources/static/epub/epub.js index 04da2f97..cbac6b86 100644 --- a/server/src/main/resources/static/epub/epub.js +++ b/server/src/main/resources/static/epub/epub.js @@ -1,16780 +1 @@ -(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 +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("JSZip")):"function"==typeof define&&define.amd?define(["JSZip"],e):"object"==typeof exports?exports.ePub=e(require("JSZip")):t.ePub=e(t.JSZip)}(window,(function(t){return function(t){var e={};function i(n){if(e[n])return e[n].exports;var s=e[n]={i:n,l:!1,exports:{}};return t[n].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)i.d(n,s,function(e){return t[e]}.bind(null,s));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="/dist/",i(i.s=30)}([function(t,e,i){"use strict";i.r(e),i.d(e,"requestAnimationFrame",(function(){return s})),i.d(e,"uuid",(function(){return o})),i.d(e,"documentHeight",(function(){return a})),i.d(e,"isElement",(function(){return h})),i.d(e,"isNumber",(function(){return l})),i.d(e,"isFloat",(function(){return c})),i.d(e,"prefixed",(function(){return u})),i.d(e,"defaults",(function(){return d})),i.d(e,"extend",(function(){return f})),i.d(e,"insert",(function(){return p})),i.d(e,"locationOf",(function(){return g})),i.d(e,"indexOfSorted",(function(){return m})),i.d(e,"bounds",(function(){return v})),i.d(e,"borders",(function(){return y})),i.d(e,"nodeBounds",(function(){return b})),i.d(e,"windowBounds",(function(){return w})),i.d(e,"indexOfNode",(function(){return x})),i.d(e,"indexOfTextNode",(function(){return E})),i.d(e,"indexOfElementNode",(function(){return S})),i.d(e,"isXml",(function(){return N})),i.d(e,"createBlob",(function(){return _})),i.d(e,"createBlobUrl",(function(){return T})),i.d(e,"revokeBlobUrl",(function(){return C})),i.d(e,"createBase64Url",(function(){return O})),i.d(e,"type",(function(){return I})),i.d(e,"parse",(function(){return R})),i.d(e,"qs",(function(){return k})),i.d(e,"qsa",(function(){return A})),i.d(e,"qsp",(function(){return L})),i.d(e,"sprint",(function(){return j})),i.d(e,"treeWalker",(function(){return D})),i.d(e,"walk",(function(){return P})),i.d(e,"blob2base64",(function(){return M})),i.d(e,"defer",(function(){return z})),i.d(e,"querySelectorByType",(function(){return B})),i.d(e,"findChildren",(function(){return q})),i.d(e,"parents",(function(){return F})),i.d(e,"filterChildren",(function(){return U})),i.d(e,"getParentByTagName",(function(){return W})),i.d(e,"RangeObject",(function(){return H}));var n=i(15);const s="undefined"!=typeof window&&(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame),r="undefined"!=typeof URL?URL:"undefined"!=typeof window?window.URL||window.webkitURL||window.mozURL:void 0;function o(){var t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:7&i|8).toString(16)}))}function a(){return Math.max(document.documentElement.clientHeight,document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight)}function h(t){return!(!t||1!=t.nodeType)}function l(t){return!isNaN(parseFloat(t))&&isFinite(t)}function c(t){let e=parseFloat(t);return!1!==l(t)&&("string"==typeof t&&t.indexOf(".")>-1||Math.floor(e)!==e)}function u(t){var e=["-webkit-","-webkit-","-moz-","-o-","-ms-"],i=t.toLowerCase(),n=["Webkit","webkit","Moz","O","ms"].length;if("undefined"==typeof document||void 0!==document.body.style[i])return t;for(var s=0;se?1:t=0?h:h+1:0===r?h:-1===r?g(t,e,i,h,a):g(t,e,i,o,h))}function m(t,e,i,n,s){var r,o=n||0,a=s||e.length,h=parseInt(o+(a-o)/2);return i||(i=function(t,e){return t>e?1:t-1}function _(t,e){return new Blob([t],{type:e})}function T(t,e){var i=_(t,e);return r.createObjectURL(i)}function C(t){return r.revokeObjectURL(t)}function O(t,e){if("string"==typeof t)return"data:"+e+";base64,"+btoa(t)}function I(t){return Object.prototype.toString.call(t).slice(8,-1)}function R(t,e,i){var s;return s="undefined"==typeof DOMParser||i?n.DOMParser:DOMParser,65279===t.charCodeAt(0)&&(t=t.slice(1)),(new s).parseFromString(t,e)}function k(t,e){var i;if(!t)throw new Error("No Element Provided");return void 0!==t.querySelector?t.querySelector(e):(i=t.getElementsByTagName(e)).length?i[0]:void 0}function A(t,e){return void 0!==t.querySelector?t.querySelectorAll(e):t.getElementsByTagName(e)}function L(t,e,i){var n,s;if(void 0!==t.querySelector){for(var r in e+="[",i)e+=r+"~='"+i[r]+"'";return e+="]",t.querySelector(e)}if(n=t.getElementsByTagName(e),s=Array.prototype.slice.call(n,0).filter((function(t){for(var e in i)if(t.getAttribute(e)===i[e])return!0;return!1})))return s[0]}function j(t,e){void 0!==(t.ownerDocument||t).createTreeWalker?D(t,e,NodeFilter.SHOW_TEXT):P(t,(function(t){t&&3===t.nodeType&&e(t)}))}function D(t,e,i){var n=document.createTreeWalker(t,i,null,!1);let s;for(;s=n.nextNode();)e(s)}function P(t,e){if(e(t))return!0;if(t=t.firstChild)do{if(P(t,e))return!0;t=t.nextSibling}while(t)}function M(t){return new Promise((function(e,i){var n=new FileReader;n.readAsDataURL(t),n.onloadend=function(){e(n.result)}}))}function z(){this.resolve=null,this.reject=null,this.id=o(),this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e}),Object.freeze(this)}function B(t,e,i){var n;if(void 0!==t.querySelector&&(n=t.querySelector(`${e}[*|type="${i}"]`)),n&&0!==n.length)return n;n=A(t,e);for(var s=0;s1&&(e=n[1],i.terminal=this.parseTerminal(e)),""===s[0]&&s.shift(),i.steps=s.map(function(t){return this.parseStep(t)}.bind(this)),i}parseStep(t){var e,i,n,s,r;if((s=t.match(/\[(.*)\]/))&&s[1]&&(r=s[1]),i=parseInt(t),!isNaN(i))return i%2==0?(e="element",n=i/2-1):(e="text",n=(i-1)/2),{type:e,index:n,id:r||null}}parseTerminal(t){var e,i,s=t.match(/\[(.*)\]/);return s&&s[1]?(e=parseInt(t.split("[")[0]),i=s[1]):e=parseInt(t),Object(n.isNumber)(e)||(e=null),{offset:e,assertion:i}}getChapterComponent(t){return t.split("!")[0]}getPathComponent(t){var e=t.split("!");if(e[1]){return e[1].split(",")[0]}}getRange(t){var e=t.split(",");return 3===e.length&&[e[1],e[2]]}getCharecterOffsetComponent(t){return t.split(":")[1]||""}joinSteps(t){return t?t.map((function(t){var e="";return"element"===t.type&&(e+=2*(t.index+1)),"text"===t.type&&(e+=1+2*t.index),t.id&&(e+="["+t.id+"]"),e})).join("/"):""}segmentString(t){var e="/";return e+=this.joinSteps(t.steps),t.terminal&&null!=t.terminal.offset&&(e+=":"+t.terminal.offset),t.terminal&&null!=t.terminal.assertion&&(e+="["+t.terminal.assertion+"]"),e}toString(){var t="epubcfi(";return t+=this.segmentString(this.base),t+="!",t+=this.segmentString(this.path),this.range&&this.start&&(t+=",",t+=this.segmentString(this.start)),this.range&&this.end&&(t+=",",t+=this.segmentString(this.end)),t+=")"}compare(t,e){var i,n,r,o;if("string"==typeof t&&(t=new s(t)),"string"==typeof e&&(e=new s(e)),t.spinePos>e.spinePos)return 1;if(t.spinePosn[a].index)return 1;if(i[a].indexo.offset?1:r.offset=0&&(s.terminal.offset=e,"text"!=s.steps[s.steps.length-1].type&&s.steps.push({type:"text",index:0})),s}equalStep(t,e){return!(!t||!e)&&(t.index===e.index&&t.id===e.id&&t.type===e.type)}fromRange(t,e,i){var n={range:!1,base:{},path:{},start:null,end:null},s=t.startContainer,r=t.endContainer,o=t.startOffset,a=t.endOffset,h=!1;if(i&&(h=null!=s.ownerDocument.querySelector("."+i)),"string"==typeof e?(n.base=this.parseComponent(e),n.spinePos=n.base.steps[1].index):"object"==typeof e&&(n.base=e),t.collapsed)h&&(o=this.patchOffset(s,o,i)),n.path=this.pathTo(s,o,i);else{n.range=!0,h&&(o=this.patchOffset(s,o,i)),n.start=this.pathTo(s,o,i),h&&(a=this.patchOffset(r,a,i)),n.end=this.pathTo(r,a,i),n.path={steps:[],terminal:null};var l,c=n.start.steps.length;for(l=0;l0&&3===s&&3===r?o[n]=a:e===s&&(a+=1,o[n]=a),r=s;return o}position(t){var e,i;return 1===t.nodeType?((e=t.parentNode.children)||(e=Object(n.findChildren)(t.parentNode)),i=Array.prototype.indexOf.call(e,t)):i=(e=this.textNodes(t.parentNode)).indexOf(t),i}filteredPosition(t,e){var i,n;return 1===t.nodeType?(i=t.parentNode.children,n=this.normalizedMap(i,1,e)):(i=t.parentNode.childNodes,t.parentNode.classList.contains(e)&&(i=(t=t.parentNode).parentNode.childNodes),n=this.normalizedMap(i,3,e)),n[Array.prototype.indexOf.call(i,t)]}stepsToXpath(t){var e=[".","*"];return t.forEach((function(t){var i=t.index+1;t.id?e.push("*[position()="+i+" and @id='"+t.id+"']"):"text"===t.type?e.push("text()["+i+"]"):e.push("*["+i+"]")})),e.join("/")}stepsToQuerySelector(t){var e=["html"];return t.forEach((function(t){var i=t.index+1;t.id?e.push("#"+t.id):"text"===t.type||e.push("*:nth-child("+i+")")})),e.join(">")}textNodes(t,e){return Array.prototype.slice.call(t.childNodes).filter((function(t){return 3===t.nodeType||!(!e||!t.classList.contains(e))}))}walkToNode(t,e,i){var s,r,o=e||document,a=o.documentElement,h=t.length;for(r=0;r(r=(s=a[t]).textContent.length))){o=1===s.nodeType?s.childNodes[0]:s;break}e-=r}}return{container:o,offset:e}}toRange(t,e){var i,s,r,o,a,h,l,c,u=t||document,d=!!e&&null!=u.querySelector("."+e);if(i=void 0!==u.createRange?u.createRange():new n.RangeObject,this.range?(s=this.start,h=this.path.steps.concat(s.steps),o=this.findNode(h,u,d?e:null),r=this.end,l=this.path.steps.concat(r.steps),a=this.findNode(l,u,d?e:null)):(s=this.path,h=this.path.steps,o=this.findNode(this.path.steps,u,d?e:null)),!o)return console.log("No startContainer found for",this.toString()),null;try{null!=s.terminal.offset?i.setStart(o,s.terminal.offset):i.setStart(o,0)}catch(t){c=this.fixMiss(h,s.terminal.offset,u,d?e:null),i.setStart(c.container,c.offset)}if(a)try{null!=r.terminal.offset?i.setEnd(a,r.terminal.offset):i.setEnd(a,0)}catch(t){c=this.fixMiss(l,this.end.terminal.offset,u,d?e:null),i.setEnd(c.container,c.offset)}return i}isCfiString(t){return"string"==typeof t&&0===t.indexOf("epubcfi(")&&")"===t[t.length-1]}generateChapterComponent(t,e,i){var n="/"+2*(t+1)+"/";return n+=2*(parseInt(e)+1),i&&(n+="["+i+"]"),n}collapse(t){this.range&&(this.range=!1,t?(this.path.steps=this.path.steps.concat(this.start.steps),this.path.terminal=this.start.terminal):(this.path.steps=this.path.steps.concat(this.end.steps),this.path.terminal=this.end.terminal))}}e.a=s},function(t,e,i){"use strict";var n,s,r,o,a,h,l,c=i(31),u=i(45),d=Function.prototype.apply,f=Function.prototype.call,p=Object.create,g=Object.defineProperty,m=Object.defineProperties,v=Object.prototype.hasOwnProperty,y={configurable:!0,enumerable:!1,writable:!0};s=function(t,e){var i,s;return u(e),s=this,n.call(this,t,i=function(){r.call(s,t,i),d.call(e,this,arguments)}),i.__eeOnceListener__=e,this},a={on:n=function(t,e){var i;return u(e),v.call(this,"__ee__")?i=this.__ee__:(i=y.value=p(null),g(this,"__ee__",y),y.value=null),i[t]?"object"==typeof i[t]?i[t].push(e):i[t]=[i[t],e]:i[t]=e,this},once:s,off:r=function(t,e){var i,n,s,r;if(u(e),!v.call(this,"__ee__"))return this;if(!(i=this.__ee__)[t])return this;if("object"==typeof(n=i[t]))for(r=0;s=n[r];++r)s!==e&&s.__eeOnceListener__!==e||(2===n.length?i[t]=n[r?0:1]:n.splice(r,1));else n!==e&&n.__eeOnceListener__!==e||delete i[t];return this},emit:o=function(t){var e,i,n,s,r;if(v.call(this,"__ee__")&&(s=this.__ee__[t]))if("object"==typeof s){for(i=arguments.length,r=new Array(i-1),e=1;e-1&&(t=new URL(t).pathname),e=this.parse(t),this.path=t,this.isDirectory(t)?this.directory=t:this.directory=e.dir+"/",this.filename=e.base,this.extension=e.ext.slice(1)}parse(t){return s.a.parse(t)}isAbsolute(t){return s.a.isAbsolute(t||this.path)}isDirectory(t){return"/"===t.charAt(t.length-1)}resolve(t){return s.a.resolve(this.directory,t)}relative(t){return t&&t.indexOf("://")>-1?t:s.a.relative(this.directory,t)}splitPath(t){return this.splitPathRe.exec(t).slice(1)}toString(){return this.path}}},function(t,e,i){"use strict";var n=i(4),s=i(7),r=i.n(s);e.a=class{constructor(t,e){var i=t.indexOf("://")>-1,s=t;if(this.Url=void 0,this.href=t,this.protocol="",this.origin="",this.hash="",this.hash="",this.search="",this.base=e,!i&&!1!==e&&"string"!=typeof e&&window&&window.location&&(this.base=window.location.href),i||this.base)try{this.base?this.Url=new URL(t,this.base):this.Url=new URL(t),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,s=this.Url.pathname+(this.Url.search?this.Url.search:"")}catch(t){this.Url=void 0,this.base&&(s=new n.a(this.base).resolve(s))}this.Path=new n.a(s),this.directory=this.Path.directory,this.filename=this.Path.filename,this.extension=this.Path.extension}path(){return this.Path}resolve(t){var e;return t.indexOf("://")>-1?t:(e=r.a.resolve(this.directory,t),this.origin+e)}relative(t){return r.a.relative(t,this.directory)}toString(){return this.href}}},function(t,e,i){"use strict";e.a=class{constructor(t){this.context=t||this,this.hooks=[]}register(){for(var t=0;t2){for(var a=n.length-1,h=a;h>=0&&47!==n.charCodeAt(h);--h);if(h!==a){n=-1===h?"":n.slice(0,h),s=o,r=0;continue}}else if(2===n.length||1===n.length){n="",s=o,r=0;continue}e&&(n.length>0?n+="/..":n="..")}else n.length>0?n+="/"+t.slice(s+1,o):n=t.slice(s+1,o);s=o,r=0}else 46===i&&-1!==r?++r:r=-1}return n}var o={resolve:function(){for(var t,e="",i=!1,o=arguments.length-1;o>=-1&&!i;o--){var a;o>=0?a=arguments[o]:(void 0===t&&(t=n.cwd()),a=t),s(a),0!==a.length&&(e=a+"/"+e,i=47===a.charCodeAt(0))}return e=r(e,!i),i?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(t){if(s(t),0===t.length)return".";var e=47===t.charCodeAt(0),i=47===t.charCodeAt(t.length-1);return 0!==(t=r(t,!e)).length||e||(t="."),t.length>0&&i&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return s(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var t,e=0;e0&&(void 0===t?t=i:t+="/"+i)}return void 0===t?".":o.normalize(t)},relative:function(t,e){if(s(t),s(e),t===e)return"";if((t=o.resolve(t))===(e=o.resolve(e)))return"";for(var i=1;il){if(47===e.charCodeAt(a+u))return e.slice(a+u+1);if(0===u)return e.slice(a+u)}else r>l&&(47===t.charCodeAt(i+u)?c=u:0===u&&(c=0));break}var d=t.charCodeAt(i+u);if(d!==e.charCodeAt(a+u))break;47===d&&(c=u)}var f="";for(u=i+c+1;u<=n;++u)u!==n&&47!==t.charCodeAt(u)||(0===f.length?f+="..":f+="/..");return f.length>0?f+e.slice(a+c):(a+=c,47===e.charCodeAt(a)&&++a,e.slice(a))},_makeLong:function(t){return t},dirname:function(t){if(s(t),0===t.length)return".";for(var e=t.charCodeAt(0),i=47===e,n=-1,r=!0,o=t.length-1;o>=1;--o)if(47===(e=t.charCodeAt(o))){if(!r){n=o;break}}else r=!1;return-1===n?i?"/":".":i&&1===n?"//":t.slice(0,n)},basename:function(t,e){if(void 0!==e&&"string"!=typeof e)throw new TypeError('"ext" argument must be a string');s(t);var i,n=0,r=-1,o=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var a=e.length-1,h=-1;for(i=t.length-1;i>=0;--i){var l=t.charCodeAt(i);if(47===l){if(!o){n=i+1;break}}else-1===h&&(o=!1,h=i+1),a>=0&&(l===e.charCodeAt(a)?-1==--a&&(r=i):(a=-1,r=h))}return n===r?r=h:-1===r&&(r=t.length),t.slice(n,r)}for(i=t.length-1;i>=0;--i)if(47===t.charCodeAt(i)){if(!o){n=i+1;break}}else-1===r&&(o=!1,r=i+1);return-1===r?"":t.slice(n,r)},extname:function(t){s(t);for(var e=-1,i=0,n=-1,r=!0,o=0,a=t.length-1;a>=0;--a){var h=t.charCodeAt(a);if(47!==h)-1===n&&(r=!1,n=a+1),46===h?-1===e?e=a:1!==o&&(o=1):-1!==e&&(o=-1);else if(!r){i=a+1;break}}return-1===e||-1===n||0===o||1===o&&e===n-1&&e===i+1?"":t.slice(e,n)},format:function(t){if(null===t||"object"!=typeof t)throw new TypeError('Parameter "pathObject" must be an object, not '+typeof t);return function(t,e){var i=e.dir||e.root,n=e.base||(e.name||"")+(e.ext||"");return i?i===e.root?i+n:i+t+n:n}("/",t)},parse:function(t){s(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;var i,n=t.charCodeAt(0),r=47===n;r?(e.root="/",i=1):i=0;for(var o=-1,a=0,h=-1,l=!0,c=t.length-1,u=0;c>=i;--c)if(47!==(n=t.charCodeAt(c)))-1===h&&(l=!1,h=c+1),46===n?-1===o?o=c:1!==u&&(u=1):-1!==o&&(u=-1);else if(!l){a=c+1;break}return-1===o||-1===h||0===u||1===u&&o===h-1&&o===a+1?-1!==h&&(e.base=e.name=0===a&&r?t.slice(1,h):t.slice(a,h)):(0===a&&r?(e.name=t.slice(1,o),e.base=t.slice(1,h)):(e.name=t.slice(a,o),e.base=t.slice(a,h)),e.ext=t.slice(o,h)),a>0?e.dir=t.slice(0,a-1):r&&(e.dir="/"),e},sep:"/",delimiter:":",posix:null};t.exports=o},function(t,e,i){"use strict";i.d(e,"a",(function(){return r})),i.d(e,"b",(function(){return o})),i.d(e,"d",(function(){return a})),i.d(e,"c",(function(){return h})),i.d(e,"e",(function(){return l}));var n=i(0),s=i(5);i(4);function r(t,e){var i,s,r=e.url,o=r.indexOf("://")>-1;t&&(s=Object(n.qs)(t,"head"),(i=Object(n.qs)(s,"base"))||(i=t.createElement("base"),s.insertBefore(i,s.firstChild)),!o&&window&&window.location&&(r=window.location.origin+r),i.setAttribute("href",r))}function o(t,e){var i,s,r=e.canonical;t&&(i=Object(n.qs)(t,"head"),(s=Object(n.qs)(i,"link[rel='canonical']"))?s.setAttribute("href",r):((s=t.createElement("link")).setAttribute("rel","canonical"),s.setAttribute("href",r),i.appendChild(s)))}function a(t,e){var i,s,r=e.idref;t&&(i=Object(n.qs)(t,"head"),(s=Object(n.qs)(i,"link[property='dc.identifier']"))?s.setAttribute("content",r):((s=t.createElement("meta")).setAttribute("name","dc.identifier"),s.setAttribute("content",r),i.appendChild(s)))}function h(t,e){var i=t.querySelectorAll("a[href]");if(i.length)for(var r=Object(n.qs)(t.ownerDocument,"base"),o=r?r.getAttribute("href"):void 0,a=function(t){var i=t.getAttribute("href");if(0!==i.indexOf("mailto:"))if(i.indexOf("://")>-1)t.setAttribute("target","_blank");else{var n;try{n=new s.a(i,o)}catch(t){}t.onclick=function(){return n&&n.hash?e(n.Path.path+n.hash):e(n?n.Path.path:i),!1}}}.bind(this),h=0;h{this._q.length?this.dequeue().then(function(){this.run()}.bind(this)):(this.defered.resolve(),this.running=void 0)}),1==this.paused&&(this.paused=!1),this.defered.promise}flush(){return this.running?this.running:this._q.length?(this.running=this.dequeue().then(function(){return this.running=void 0,this.flush()}.bind(this)),this.running):void 0}clear(){this._q=[]}length(){return this._q.length}pause(){this.paused=!0}stop(){this._q=[],this.running=!1,this.paused=!0}}},function(t,e,i){"use strict";var n=i(3),s=i.n(n),r=i(0);function o(){var t="reverse",e=function(){var t=document.createElement("div");t.dir="rtl",t.style.position="fixed",t.style.width="1px",t.style.height="1px",t.style.top="0px",t.style.left="0px",t.style.overflow="hidden";var e=document.createElement("div");e.style.width="2px";var i=document.createElement("span");i.style.width="1px",i.style.display="inline-block";var n=document.createElement("span");return n.style.width="1px",n.style.display="inline-block",e.appendChild(i),e.appendChild(n),t.appendChild(e),t}();return document.body.appendChild(e),e.scrollLeft>0?t="default":"undefined"!=typeof Element&&Element.prototype.scrollIntoView?(e.children[0].children[1].scrollIntoView(),e.scrollLeft<0&&(t="negative")):(e.scrollLeft=1,0===e.scrollLeft&&(t="negative")),document.body.removeChild(e),t}var a=i(11),h=i(9),l=i(28),c=i.n(l);var u=class{constructor(t){this.settings=t||{},this.id="epubjs-container-"+Object(r.uuid)(),this.container=this.create(this.settings),this.settings.hidden&&(this.wrapper=this.wrap(this.container))}create(t){let e=t.height,i=t.width,n=t.overflow||!1,s=t.axis||"vertical",o=t.direction;Object(r.extend)(this.settings,t),t.height&&Object(r.isNumber)(t.height)&&(e=t.height+"px"),t.width&&Object(r.isNumber)(t.width)&&(i=t.width+"px");let a=document.createElement("div");return a.id=this.id,a.classList.add("epub-container"),a.style.wordSpacing="0",a.style.lineHeight="0",a.style.verticalAlign="top",a.style.position="relative","horizontal"===s&&(a.style.display="flex",a.style.flexDirection="row",a.style.flexWrap="nowrap"),i&&(a.style.width=i),e&&(a.style.height=e),n&&("scroll"===n&&"vertical"===s?(a.style["overflow-y"]=n,a.style["overflow-x"]="hidden"):"scroll"===n&&"horizontal"===s?(a.style["overflow-y"]="hidden",a.style["overflow-x"]=n):a.style.overflow=n),o&&(a.dir=o,a.style.direction=o),o&&this.settings.fullsize&&(document.body.style.direction=o),a}wrap(t){var e=document.createElement("div");return e.style.visibility="hidden",e.style.overflow="hidden",e.style.width="0",e.style.height="0",e.appendChild(t),e}getElement(t){var e;if(Object(r.isElement)(t)?e=t:"string"==typeof t&&(e=document.getElementById(t)),!e)throw new Error("Not an Element");return e}attachTo(t){var e,i=this.getElement(t);if(i)return e=this.settings.hidden?this.wrapper:this.container,i.appendChild(e),this.element=i,i}getContainer(){return this.container}onResize(t){Object(r.isNumber)(this.settings.width)&&Object(r.isNumber)(this.settings.height)||(this.resizeFunc=c()(t,50),window.addEventListener("resize",this.resizeFunc,!1))}onOrientationChange(t){this.orientationChangeFunc=t,window.addEventListener("orientationchange",this.orientationChangeFunc,!1)}size(t,e){var i;let n=t||this.settings.width,s=e||this.settings.height;null===t?(i=this.element.getBoundingClientRect()).width&&(t=Math.floor(i.width),this.container.style.width=t+"px"):Object(r.isNumber)(t)?this.container.style.width=t+"px":this.container.style.width=t,null===e?(i=i||this.element.getBoundingClientRect()).height&&(e=i.height,this.container.style.height=e+"px"):Object(r.isNumber)(e)?this.container.style.height=e+"px":this.container.style.height=e,Object(r.isNumber)(t)||(t=this.container.clientWidth),Object(r.isNumber)(e)||(e=this.container.clientHeight),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};let o=Object(r.windowBounds)(),a=window.getComputedStyle(document.body),h=parseFloat(a["padding-left"])||0,l=parseFloat(a["padding-right"])||0,c=parseFloat(a["padding-top"])||0,u=parseFloat(a["padding-bottom"])||0;return n||(t=o.width-h-l),(this.settings.fullsize&&!s||!s)&&(e=o.height-c-u),{width:t-this.containerPadding.left-this.containerPadding.right,height:e-this.containerPadding.top-this.containerPadding.bottom}}bounds(){let t;return"visible"!==this.container.style.overflow&&(t=this.container&&this.container.getBoundingClientRect()),t&&t.width&&t.height?t:Object(r.windowBounds)()}getSheet(){var t=document.createElement("style");return t.appendChild(document.createTextNode("")),document.head.appendChild(t),t.sheet}addStyleRules(t,e){var i="#"+this.id+" ",n="";this.sheet||(this.sheet=this.getSheet()),e.forEach((function(t){for(var e in t)t.hasOwnProperty(e)&&(n+=e+":"+t[e]+";")})),this.sheet.insertRule(i+t+" {"+n+"}",0)}axis(t){"horizontal"===t?(this.container.style.display="flex",this.container.style.flexDirection="row",this.container.style.flexWrap="nowrap"):this.container.style.display="block",this.settings.axis=t}direction(t){this.container&&(this.container.dir=t,this.container.style.direction=t),this.settings.fullsize&&(document.body.style.direction=t),this.settings.dir=t}overflow(t){this.container&&("scroll"===t&&"vertical"===this.settings.axis?(this.container.style["overflow-y"]=t,this.container.style["overflow-x"]="hidden"):"scroll"===t&&"horizontal"===this.settings.axis?(this.container.style["overflow-y"]="hidden",this.container.style["overflow-x"]=t):this.container.style.overflow=t),this.settings.overflow=t}destroy(){this.element&&(this.settings.hidden?this.wrapper:this.container,this.element.contains(this.container)&&this.element.removeChild(this.container),window.removeEventListener("resize",this.resizeFunc),window.removeEventListener("orientationChange",this.orientationChangeFunc))}};var d=class{constructor(t){this.container=t,this._views=[],this.length=0,this.hidden=!1}all(){return this._views}first(){return this._views[0]}last(){return this._views[this._views.length-1]}indexOf(t){return this._views.indexOf(t)}slice(){return this._views.slice.apply(this._views,arguments)}get(t){return this._views[t]}append(t){return this._views.push(t),this.container&&this.container.appendChild(t.element),this.length++,t}prepend(t){return this._views.unshift(t),this.container&&this.container.insertBefore(t.element,this.container.firstChild),this.length++,t}insert(t,e){return this._views.splice(e,0,t),this.container&&(e-1&&this._views.splice(e,1),this.destroy(t),this.length--}destroy(t){t.destroy(),this.container&&this.container.removeChild(t.element),t=null}forEach(){return this._views.forEach.apply(this._views,arguments)}clear(){var t,e=this.length;if(this.length){for(var i=0;i1){if(t||0===e.index)return;if(n=e.next(),n&&!n.properties.includes("page-spread-left"))return i.call(this,n)}}display(t,e){var i=new r.defer,n=i.promise;(e===t.href||Object(r.isNumber)(e))&&(e=void 0);var s=this.views.find(t);if(s&&t&&"pre-paginated"!==this.layout.name){let t=s.offset();if("ltr"===this.settings.direction)this.scrollTo(t.left,t.top,!0);else{let e=s.width();this.scrollTo(t.left+e,t.top,!0)}if(e){let t=s.locationOf(e),i=s.width();this.moveTo(t,i)}return i.resolve(),n}this.clear();let o=!1;return"pre-paginated"===this.layout.name&&2===this.layout.divisor&&t.properties.includes("page-spread-right")&&(o=!0),this.add(t,o).then(function(t){if(e){let i=t.locationOf(e),n=t.width();this.moveTo(i,n)}}.bind(this),t=>{i.reject(t)}).then(function(){return this.handleNextPrePaginated(o,t,this.add)}.bind(this)).then(function(){this.views.show(),i.resolve()}.bind(this)),n}afterDisplayed(t){this.emit(f.c.MANAGERS.ADDED,t)}afterResized(t){this.emit(f.c.MANAGERS.RESIZE,t.section)}moveTo(t,e){var i=0,n=0;this.isPaginated?((i=Math.floor(t.left/this.layout.delta)*this.layout.delta)+this.layout.delta>this.container.scrollWidth&&(i=this.container.scrollWidth-this.layout.delta),(n=Math.floor(t.top/this.layout.delta)*this.layout.delta)+this.layout.delta>this.container.scrollHeight&&(n=this.container.scrollHeight-this.layout.delta)):n=t.top,"rtl"===this.settings.direction&&(i+=this.layout.delta,i-=e),this.scrollTo(i,n,!0)}add(t,e){var i=this.createView(t,e);return this.views.append(i),i.onDisplayed=this.afterDisplayed.bind(this),i.onResize=this.afterResized.bind(this),i.on(f.c.VIEWS.AXIS,t=>{this.updateAxis(t)}),i.on(f.c.VIEWS.WRITING_MODE,t=>{this.updateWritingMode(t)}),i.display(this.request)}append(t,e){var i=this.createView(t,e);return this.views.append(i),i.onDisplayed=this.afterDisplayed.bind(this),i.onResize=this.afterResized.bind(this),i.on(f.c.VIEWS.AXIS,t=>{this.updateAxis(t)}),i.on(f.c.VIEWS.WRITING_MODE,t=>{this.updateWritingMode(t)}),i.display(this.request)}prepend(t,e){var i=this.createView(t,e);return i.on(f.c.VIEWS.RESIZED,t=>{this.counter(t)}),this.views.prepend(i),i.onDisplayed=this.afterDisplayed.bind(this),i.onResize=this.afterResized.bind(this),i.on(f.c.VIEWS.AXIS,t=>{this.updateAxis(t)}),i.on(f.c.VIEWS.WRITING_MODE,t=>{this.updateWritingMode(t)}),i.display(this.request)}counter(t){"vertical"===this.settings.axis?this.scrollBy(0,t.heightDelta,!0):this.scrollBy(t.widthDelta,0,!0)}next(){var t;let e=this.settings.direction;if(this.views.length){if(!this.isPaginated||"horizontal"!==this.settings.axis||e&&"ltr"!==e)if(this.isPaginated&&"horizontal"===this.settings.axis&&"rtl"===e)this.scrollLeft=this.container.scrollLeft,"default"===this.settings.rtlScrollType?this.container.scrollLeft>0?this.scrollBy(this.layout.delta,0,!0):t=this.views.last().section.next():this.container.scrollLeft+-1*this.layout.delta>-1*this.container.scrollWidth?this.scrollBy(this.layout.delta,0,!0):t=this.views.last().section.next();else if(this.isPaginated&&"vertical"===this.settings.axis){this.scrollTop=this.container.scrollTop,this.container.scrollTop+this.container.offsetHeightt).then(function(){this.isPaginated||"horizontal"!==this.settings.axis||"rtl"!==this.settings.direction||"default"!==this.settings.rtlScrollType||this.scrollTo(this.container.scrollWidth,0,!0),this.views.show()}.bind(this))}}}prev(){var t;let e=this.settings.direction;if(this.views.length){if(!this.isPaginated||"horizontal"!==this.settings.axis||e&&"ltr"!==e)if(this.isPaginated&&"horizontal"===this.settings.axis&&"rtl"===e)this.scrollLeft=this.container.scrollLeft,"default"===this.settings.rtlScrollType?this.container.scrollLeft+this.container.offsetWidth0?this.scrollBy(0,-this.layout.height,!0):t=this.views.first().section.prev()}else t=this.views.first().section.prev();else this.scrollLeft=this.container.scrollLeft,this.container.scrollLeft>0?this.scrollBy(-this.layout.delta,0,!0):t=this.views.first().section.prev();if(t){this.clear(),this.updateLayout();let e=!1;return"pre-paginated"===this.layout.name&&2===this.layout.divisor&&"object"!=typeof t.prev()&&(e=!0),this.prepend(t,e).then(function(){var e;if("pre-paginated"===this.layout.name&&this.layout.divisor>1&&(e=t.prev()))return this.prepend(e)}.bind(this),t=>t).then(function(){this.isPaginated&&"horizontal"===this.settings.axis&&("rtl"===this.settings.direction?"default"===this.settings.rtlScrollType?this.scrollTo(0,0,!0):this.scrollTo(-1*this.container.scrollWidth+this.layout.delta,0,!0):this.scrollTo(this.container.scrollWidth-this.layout.delta,0,!0)),this.views.show()}.bind(this))}}}current(){var t=this.visible();return t.length?t[t.length-1]:null}clear(){this.views&&(this.views.hide(),this.scrollTo(0,0,!0),this.views.clear())}currentLocation(){return this.updateLayout(),this.isPaginated&&"horizontal"===this.settings.axis?this.location=this.paginatedLocation():this.location=this.scrolledLocation(),this.location}scrolledLocation(){let t=this.visible(),e=this.container.getBoundingClientRect(),i=e.height{let o,a,h,l,{index:c,href:u}=t.section,d=t.position(),f=t.width(),p=t.height();s?(o=r+e.top-d.top+0,a=o+i-0,l=this.layout.count(p,i).pages,h=i):(o=r+e.left-d.left+0,a=o+n-0,l=this.layout.count(f,n).pages,h=n);let g=Math.ceil(o/h),m=[],v=Math.ceil(a/h);if("rtl"===this.settings.direction&&!s){let t=g;g=l-v,v=l-t}m=[];for(var y=g;y<=v;y++){let t=y+1;m.push(t)}return{index:c,href:u,pages:m,totalPages:l,mapping:this.mapping.page(t.contents,t.section.cfiBase,o,a)}})}paginatedLocation(){let t=this.visible(),e=this.container.getBoundingClientRect(),i=0,n=0;return this.settings.fullsize&&(i=window.scrollX),t.map(t=>{let s,r,o,a,{index:h,href:l}=t.section,c=t.position(),u=t.width();"rtl"===this.settings.direction?(s=e.right-i,a=Math.min(Math.abs(s-c.left),this.layout.width)-n,o=c.width-(c.right-s)-n,r=o-a):(s=e.left+i,a=Math.min(c.right-s,this.layout.width)-n,r=s-c.left+n,o=r+a),n+=a;let d=this.mapping.page(t.contents,t.section.cfiBase,r,o),f=this.layout.count(u).pages,p=Math.floor(r/this.layout.pageWidth),g=[],m=Math.floor(o/this.layout.pageWidth);if(p<0&&(p=0,m+=1),"rtl"===this.settings.direction){let t=p;p=f-m,m=f-t}for(var v=p+1;v<=m;v++){let t=v;g.push(t)}return{index:h,href:l,pages:g,totalPages:f,mapping:d}})}isVisible(t,e,i,n){var s=t.position(),r=n||this.bounds();return"horizontal"===this.settings.axis&&s.right>r.left-e&&s.leftr.top-e&&s.top0&&"pre-paginated"===this.layout.name&&this.display(this.views.first().section)}updateLayout(){this.stage&&(this._stageSize=this.stage.size(),this.isPaginated?(this.layout.calculate(this._stageSize.width,this._stageSize.height,this.settings.gap),this.settings.offset=this.layout.delta/this.layout.divisor):this.layout.calculate(this._stageSize.width,this._stageSize.height),this.viewSettings.width=this.layout.width,this.viewSettings.height=this.layout.height,this.setLayout(this.layout))}setLayout(t){this.viewSettings.layout=t,this.mapping=new a.a(t.props,this.settings.direction,this.settings.axis),this.views&&this.views.forEach((function(e){e&&e.setLayout(t)}))}updateWritingMode(t){this.writingMode=t}updateAxis(t,e){(e||t!==this.settings.axis)&&(this.settings.axis=t,this.stage&&this.stage.axis(t),this.viewSettings.axis=t,this.mapping&&(this.mapping=new a.a(this.layout.props,this.settings.direction,this.settings.axis)),this.layout&&("vertical"===t?this.layout.spread("none"):this.layout.spread(this.layout.settings.spread)))}updateFlow(t,e="auto"){let i="paginated"===t||"auto"===t;this.isPaginated=i,"scrolled-doc"===t||"scrolled-continuous"===t||"scrolled"===t?this.updateAxis("vertical"):this.updateAxis("horizontal"),this.viewSettings.flow=t,this.settings.overflow?this.overflow=this.settings.overflow:this.overflow=i?"hidden":e,this.stage&&this.stage.overflow(this.overflow),this.updateLayout()}getContents(){var t=[];return this.views?(this.views.forEach((function(e){const i=e&&e.contents;i&&t.push(i)})),t):t}direction(t="ltr"){this.settings.direction=t,this.stage&&this.stage.direction(t),this.viewSettings.direction=t,this.updateLayout()}isRendered(){return this.rendered}}s()(p.prototype);e.a=p},function(t,e,i){"use strict";var n=i(2),s=i(0);e.a=class{constructor(t,e,i,n=!1){this.layout=t,this.horizontal="horizontal"===i,this.direction=e||"ltr",this._dev=n}section(t){var e=this.findRanges(t);return this.rangeListToCfiList(t.section.cfiBase,e)}page(t,e,i,s){var r,o=!(!t||!t.document)&&t.document.body;if(o){if(r=this.rangePairToCfiPair(e,{start:this.findStart(o,i,s),end:this.findEnd(o,i,s)}),!0===this._dev){let e=t.document,i=new n.a(r.start).toRange(e),s=new n.a(r.end).toRange(e),o=e.defaultView.getSelection(),a=e.createRange();o.removeAllRanges(),a.setStart(i.startContainer,i.startOffset),a.setEnd(s.endContainer,s.endOffset),o.addRange(a)}return r}}walk(t,e){if(!t||t.nodeType!==Node.TEXT_NODE){var i=function(t){return t.data.trim().length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT},n=i;n.acceptNode=i;for(var s,r,o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,n,!1);(s=o.nextNode())&&!(r=e(s)););return r}}findRanges(t){for(var e,i,n=[],s=t.contents.scrollWidth(),r=Math.ceil(s/this.layout.spreadWidth)*this.layout.divisor,o=this.layout.columnWidth,a=this.layout.gap,h=0;h{var n,r,h,l,c;if(c=Object(s.nodeBounds)(t),this.horizontal&&"ltr"===this.direction){if(n=this.horizontal?c.left:c.top,r=this.horizontal?c.right:c.bottom,n>=e&&n<=i)return t;if(r>e)return t;a=t,o.push(t)}else if(this.horizontal&&"rtl"===this.direction){if(n=c.left,(r=c.right)<=i&&r>=e)return t;if(n=e&&h<=i)return t;if(l>e)return t;a=t,o.push(t)}}))return this.findTextStartRange(r,e,i);return this.findTextStartRange(a,e,i)}findEnd(t,e,i){for(var n,r,o=[t],a=t;o.length;)if(n=o.shift(),r=this.walk(n,t=>{var n,r,h,l,c;if(c=Object(s.nodeBounds)(t),this.horizontal&&"ltr"===this.direction){if(n=Math.round(c.left),r=Math.round(c.right),n>i&&a)return a;if(r>i)return t;a=t,o.push(t)}else if(this.horizontal&&"rtl"===this.direction){if(n=Math.round(this.horizontal?c.left:c.top),(r=Math.round(this.horizontal?c.right:c.bottom))i&&a)return a;if(l>i)return t;a=t,o.push(t)}}))return this.findTextEndRange(r,e,i);return this.findTextEndRange(a,e,i)}findTextStartRange(t,e,i){for(var n,s,r=this.splitTextNodeIntoRanges(t),o=0;o=e)return n}else if(this.horizontal&&"rtl"===this.direction){if(s.right<=i)return n}else if(s.top>=e)return n;return r[0]}findTextEndRange(t,e,i){for(var n,s,r,o,a,h,l,c=this.splitTextNodeIntoRanges(t),u=0;ui&&n)return n;if(a>i)return s}else if(this.horizontal&&"rtl"===this.direction){if(o=r.left,(a=r.right)i&&n)return n;if(l>i)return s}n=s}return c[c.length-1]}splitTextNodeIntoRanges(t,e){var i,n=[],s=(t.textContent||"").trim(),r=t.ownerDocument,o=e||" ",a=s.indexOf(o);if(-1===a||t.nodeType!=Node.TEXT_NODE)return(i=r.createRange()).selectNodeContents(t),[i];for((i=r.createRange()).setStart(t,0),i.setEnd(t,a),n.push(i),i=!1;-1!=a;)(a=s.indexOf(o,a+1))>0&&(i&&(i.setEnd(t,a),n.push(i)),(i=r.createRange()).setStart(t,a+1));return i&&(i.setEnd(t,s.length),n.push(i)),n}rangePairToCfiPair(t,e){var i=e.start,s=e.end;return i.collapse(!0),s.collapse(!1),{start:new n.a(i,t).toString(),end:new n.a(s,t).toString()}}rangeListToCfiList(t,e){for(var i,n=[],s=0;s{"visible"===document.visibilityState&&!1===this.active?(this.active=!0,this.resizeListeners()):(this.active=!1,clearTimeout(this.expanding))})}transitionListeners(){let t=this.content;t.style.transitionProperty="font, font-size, font-size-adjust, font-stretch, font-variation-settings, font-weight, width, height",t.style.transitionDuration="0.001ms",t.style.transitionTimingFunction="linear",t.style.transitionDelay="0",this._resizeCheck=this.resizeCheck.bind(this),this.document.addEventListener("transitionend",this._resizeCheck)}mediaQueryListeners(){for(var t=this.document.styleSheets,e=function(t){t.matches&&!this._expanding&&setTimeout(this.expand.bind(this),1)}.bind(this),i=0;i{requestAnimationFrame(this.resizeCheck.bind(this))}),this.observer.observe(this.document.documentElement)}mutationObservers(){this.observer=new MutationObserver(t=>{this.resizeCheck()});this.observer.observe(this.document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})}imageLoadListeners(){for(var t,e=this.document.querySelectorAll("img"),i=0;i0?(e.setStart(t,s.startOffset-2),e.setEnd(t,s.startOffset),i=e.getBoundingClientRect()):i=t.parentNode.getBoundingClientRect()}catch(t){console.error(t,t.stack)}}else i=s.getBoundingClientRect()}}else if("string"==typeof t&&t.indexOf("#")>-1){let e=t.substring(t.indexOf("#")+1),n=this.document.getElementById(e);if(n)if(d){let t=new Range;t.selectNode(n),i=t.getBoundingClientRect()}else i=n.getBoundingClientRect()}return i&&(n.left=i.left,n.top=i.top),n}addStylesheet(t){return new Promise(function(e,i){var n,s=!1;this.document?(n=this.document.querySelector("link[href='"+t+"']"))?e(!0):((n=this.document.createElement("link")).type="text/css",n.rel="stylesheet",n.href=t,n.onload=n.onreadystatechange=function(){s||this.readyState&&"complete"!=this.readyState||(s=!0,setTimeout(()=>{e(!0)},1))},this.document.head.appendChild(n)):e(!1)}.bind(this))}_getStylesheetNode(t){var e;return t="epubjs-inserted-css-"+(t||""),!!this.document&&((e=this.document.getElementById(t))||((e=this.document.createElement("style")).id=t,this.document.head.appendChild(e)),e)}addStylesheetCss(t,e){return!(!this.document||!t)&&(this._getStylesheetNode(e).innerHTML=t,!0)}addStylesheetRules(t,e){var i;if(this.document&&t&&0!==t.length)if(i=this._getStylesheetNode(e).sheet,"[object Array]"===Object.prototype.toString.call(t))for(var n=0,s=t.length;n{const n=t[e];if(Array.isArray(n))n.forEach(t=>{const n=Object.keys(t).map(e=>`${e}:${t[e]}`).join(";");i.insertRule(`${e}{${n}}`,i.cssRules.length)});else{const t=Object.keys(n).map(t=>`${t}:${n[t]}`).join(";");i.insertRule(`${e}{${t}}`,i.cssRules.length)}})}}addScript(t){return new Promise(function(e,i){var n,s=!1;this.document?((n=this.document.createElement("script")).type="text/javascript",n.async=!0,n.src=t,n.onload=n.onreadystatechange=function(){s||this.readyState&&"complete"!=this.readyState||(s=!0,setTimeout((function(){e(!0)}),1))},this.document.head.appendChild(n)):e(!1)}.bind(this))}addClass(t){var e;this.document&&(e=this.content||this.document.body)&&e.classList.add(t)}removeClass(t){var e;this.document&&(e=this.content||this.document.body)&&e.classList.remove(t)}addEventListeners(){this.document&&(this._triggerEvent=this.triggerEvent.bind(this),l.a.forEach((function(t){this.document.addEventListener(t,this._triggerEvent,{passive:!0})}),this))}removeEventListeners(){this.document&&(l.a.forEach((function(t){this.document.removeEventListener(t,this._triggerEvent,{passive:!0})}),this),this._triggerEvent=void 0)}triggerEvent(t){this.emit(t.type,t)}addSelectionListeners(){this.document&&(this._onSelectionChange=this.onSelectionChange.bind(this),this.document.addEventListener("selectionchange",this._onSelectionChange,{passive:!0}))}removeSelectionListeners(){this.document&&(this.document.removeEventListener("selectionchange",this._onSelectionChange,{passive:!0}),this._onSelectionChange=void 0)}onSelectionChange(t){this.selectionEndTimeout&&clearTimeout(this.selectionEndTimeout),this.selectionEndTimeout=setTimeout(function(){var t=this.window.getSelection();this.triggerSelectedEvent(t)}.bind(this),250)}triggerSelectedEvent(t){var e,i;t&&t.rangeCount>0&&((e=t.getRangeAt(0)).collapsed||(i=new o.a(e,this.cfiBase).toString(),this.emit(l.c.CONTENTS.SELECTED,i),this.emit(l.c.CONTENTS.SELECTED_RANGE,e)))}range(t,e){return new o.a(t).toRange(this.document,e)}cfiFromRange(t,e){return new o.a(t,this.cfiBase,e).toString()}cfiFromNode(t,e){return new o.a(t,this.cfiBase,e).toString()}map(t){return new a.a(t).section()}size(t,e){var i={scale:1,scalable:"no"};this.layoutStyle("scrolling"),t>=0&&(this.width(t),i.width=t,this.css("padding","0 "+t/12+"px")),e>=0&&(this.height(e),i.height=e),this.css("margin","0"),this.css("box-sizing","border-box"),this.viewport(i)}columns(t,e,i,n,s){let o=Object(r.prefixed)("column-axis"),a=Object(r.prefixed)("column-gap"),h=Object(r.prefixed)("column-width"),l=Object(r.prefixed)("column-fill"),c=0===this.writingMode().indexOf("vertical")?"vertical":"horizontal";this.layoutStyle("paginated"),"rtl"===s&&"horizontal"===c&&this.direction(s),this.width(t),this.height(e),this.viewport({width:t,height:e,scale:1,scalable:"no"}),this.css("overflow-y","hidden"),this.css("margin","0",!0),"vertical"===c?(this.css("padding-top",n/2+"px",!0),this.css("padding-bottom",n/2+"px",!0),this.css("padding-left","20px"),this.css("padding-right","20px"),this.css(o,"vertical")):(this.css("padding-top","20px"),this.css("padding-bottom","20px"),this.css("padding-left",n/2+"px",!0),this.css("padding-right",n/2+"px",!0),this.css(o,"horizontal")),this.css("box-sizing","border-box"),this.css("max-width","inherit"),this.css(l,"auto"),this.css(a,n+"px"),this.css(h,i+"px"),this.css("-webkit-line-box-contain","block glyphs replaced")}scaler(t,e,i){var n="scale("+t+")",s="";this.css("transform-origin","top left"),(e>=0||i>=0)&&(s=" translate("+(e||0)+"px, "+(i||0)+"px )"),this.css("transform",n+s)}fit(t,e,i){var n=this.viewport(),s=parseInt(n.width),r=parseInt(n.height),o=t/s,a=e/r,h=o{this.emit(l.c.CONTENTS.LINK_CLICKED,t)})}writingMode(t){let e=Object(r.prefixed)("writing-mode");return t&&this.documentElement&&(this.documentElement.style[e]=t),this.window.getComputedStyle(this.documentElement)[e]||""}layoutStyle(t){return t&&(this._layoutStyle=t,navigator.epubReadingSystem.layoutStyle=this._layoutStyle),this._layoutStyle||"paginated"}epubReadingSystem(t,e){return navigator.epubReadingSystem={name:t,version:e,layoutStyle:this.layoutStyle(),hasFeature:function(t){switch(t){case"dom-manipulation":case"layout-changes":case"touch-events":case"mouse-events":case"keyboard-events":return!0;case"spine-scripting":default:return!1}}},navigator.epubReadingSystem}destroy(){this.removeListeners()}}s()(f.prototype),e.a=f},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Underline=e.Highlight=e.Mark=e.Pane=void 0;var n=function(){function t(t,e){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:document.body;l(this,t),this.target=e,this.element=s.default.createElement("svg"),this.marks=[],this.element.style.position="absolute",this.element.setAttribute("pointer-events","none"),r.default.proxyMouse(this.target,this.marks),this.container=i,this.container.appendChild(this.element),this.render()}return n(t,[{key:"addMark",value:function(t){var e=s.default.createElement("g");return this.element.appendChild(e),t.bind(e,this.container),this.marks.push(t),t.render(),t}},{key:"removeMark",value:function(t){var e=this.marks.indexOf(t);if(-1!==e){var i=t.unbind();this.element.removeChild(i),this.marks.splice(e,1)}}},{key:"render",value:function(){var t,e,i,n;!function(t,e){t.style.setProperty("top",e.top+"px","important"),t.style.setProperty("left",e.left+"px","important"),t.style.setProperty("height",e.height+"px","important"),t.style.setProperty("width",e.width+"px","important")}(this.element,(t=this.target,e=this.container,i=e.getBoundingClientRect(),n=t.getBoundingClientRect(),{top:n.top-i.top,left:n.left-i.left,height:t.scrollHeight,width:t.scrollWidth}));var s=!0,r=!1,o=void 0;try{for(var a,h=this.marks[Symbol.iterator]();!(s=(a=h.next()).done);s=!0){a.value.render()}}catch(t){r=!0,o=t}finally{try{!s&&h.return&&h.return()}finally{if(r)throw o}}}}]),t}();var c=e.Mark=function(){function t(){l(this,t),this.element=null}return n(t,[{key:"bind",value:function(t,e){this.element=t,this.container=e}},{key:"unbind",value:function(){var t=this.element;return this.element=null,t}},{key:"render",value:function(){}},{key:"dispatchEvent",value:function(t){this.element&&this.element.dispatchEvent(t)}},{key:"getBoundingClientRect",value:function(){return this.element.getBoundingClientRect()}},{key:"getClientRects",value:function(){for(var t=[],e=this.element.firstChild;e;)t.push(e.getBoundingClientRect()),e=e.nextSibling;return t}},{key:"filteredRanges",value:function(){var t=Array.from(this.range.getClientRects());return t.filter((function(e){for(var i=0;i=n.left&&s.top>=n.top&&s.bottom<=n.bottom)return!1}var n,s;return!0}))}}]),t}(),u=e.Highlight=function(t){function e(t,i,n,s){l(this,e);var r=a(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return r.range=t,r.className=i,r.data=n||{},r.attributes=s||{},r}return h(e,t),n(e,[{key:"bind",value:function(t,i){for(var n in function t(e,i,n){null===e&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,i);if(void 0===s){var r=Object.getPrototypeOf(e);return null===r?void 0:t(r,i,n)}if("value"in s)return s.value;var o=s.get;return void 0!==o?o.call(n):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"bind",this).call(this,t,i),this.data)this.data.hasOwnProperty(n)&&(this.element.dataset[n]=this.data[n]);for(var n in this.attributes)this.attributes.hasOwnProperty(n)&&this.element.setAttribute(n,this.attributes[n]);this.className&&this.element.classList.add(this.className)}},{key:"render",value:function(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);for(var t=this.element.ownerDocument.createDocumentFragment(),e=this.filteredRanges(),i=this.element.getBoundingClientRect(),n=this.container.getBoundingClientRect(),r=0,o=e.length;r=0&&(this._minSpreadWidth=e),this._spread}calculate(t,e,i){var n,s,r,o,a=1,h=i||0,l=t,c=e,u=Math.floor(l/12);a=this._spread&&l>=this._minSpreadWidth?2:1,"reflowable"!==this.name||"paginated"!==this._flow||i>=0||(h=u%2==0?u:u-1),"pre-paginated"===this.name&&(h=0),a>1?r=(n=l/a-h)+h:(n=l,r=l),"pre-paginated"===this.name&&a>1&&(l=n),s=n*a+h,o=l,this.width=l,this.height=c,this.spreadWidth=s,this.pageWidth=r,this.delta=o,this.columnWidth=n,this.gap=h,this.divisor=a,this.update({width:l,height:c,spreadWidth:s,pageWidth:r,delta:o,columnWidth:n,gap:h,divisor:a})}format(t,e,i){return"pre-paginated"===this.name?t.fit(this.columnWidth,this.height,e):"paginated"===this._flow?t.columns(this.width,this.height,this.columnWidth,this.gap,this.settings.direction):i&&"horizontal"===i?t.size(null,this.height):t.size(this.width,null)}count(t,e){let i,n;return"pre-paginated"===this.name?(i=1,n=1):"paginated"===this._flow?(e=e||this.delta,i=Math.ceil(t/e),n=i*this.divisor):(e=e||this.height,i=Math.ceil(t/e),n=i),{spreads:i,pages:n}}update(t){if(Object.keys(t).forEach(e=>{this.props[e]===t[e]&&delete t[e]}),Object.keys(t).length>0){let e=Object(r.extend)(this.props,t);this.emit(l.c.LAYOUT.UPDATED,e,t)}}}s()(c.prototype);var u=c,d=i(5);var f=class{constructor(t){this.rendition=t,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))}register(){if(0!==arguments.length)return 1===arguments.length&&"object"==typeof arguments[0]?this.registerThemes(arguments[0]):1===arguments.length&&"string"==typeof arguments[0]?this.default(arguments[0]):2===arguments.length&&"string"==typeof arguments[1]?this.registerUrl(arguments[0],arguments[1]):2===arguments.length&&"object"==typeof arguments[1]?this.registerRules(arguments[0],arguments[1]):void 0}default(t){if(t)return"string"==typeof t?this.registerUrl("default",t):"object"==typeof t?this.registerRules("default",t):void 0}registerThemes(t){for(var e in t)t.hasOwnProperty(e)&&("string"==typeof t[e]?this.registerUrl(e,t[e]):this.registerRules(e,t[e]))}registerCss(t,e){this._themes[t]={serialized:e},(this._injected[t]||"default"==t)&&this.update(t)}registerUrl(t,e){var i=new d.a(e);this._themes[t]={url:i.toString()},(this._injected[t]||"default"==t)&&this.update(t)}registerRules(t,e){this._themes[t]={rules:e},(this._injected[t]||"default"==t)&&this.update(t)}select(t){var e=this._current;this._current=t,this.update(t),this.rendition.getContents().forEach(i=>{i.removeClass(e),i.addClass(t)})}update(t){this.rendition.getContents().forEach(e=>{this.add(t,e)})}inject(t){var e,i=[],n=this._themes;for(var s in n)!n.hasOwnProperty(s)||s!==this._current&&"default"!==s||(((e=n[s]).rules&&Object.keys(e.rules).length>0||e.url&&-1===i.indexOf(e.url))&&this.add(s,t),this._injected.push(s));"default"!=this._current&&t.addClass(this._current)}add(t,e){var i=this._themes[t];i&&e&&(i.url?e.addStylesheet(i.url):i.serialized?(e.addStylesheetCss(i.serialized,t),i.injected=!0):i.rules&&(e.addStylesheetRules(i.rules,t),i.injected=!0))}override(t,e,i){var n=this.rendition.getContents();this._overrides[t]={value:e,priority:!0===i},n.forEach(e=>{e.css(t,this._overrides[t].value,this._overrides[t].priority)})}removeOverride(t){var e=this.rendition.getContents();delete this._overrides[t],e.forEach(e=>{e.css(t)})}overrides(t){var e=this._overrides;for(var i in e)e.hasOwnProperty(i)&&t.css(i,e[i].value,e[i].priority)}fontSize(t){this.override("font-size",t)}font(t){this.override("font-family",t,!0)}destroy(){this.rendition=void 0,this._themes=void 0,this._overrides=void 0,this._current=void 0,this._injected=void 0}};i(12);class p{constructor({type:t,cfiRange:e,data:i,sectionIndex:n,cb:s,className:r,styles:o}){this.type=t,this.cfiRange=e,this.data=i,this.sectionIndex=n,this.mark=void 0,this.cb=s,this.className=r,this.styles=o}update(t){this.data=t}attach(t){let e,{cfiRange:i,data:n,type:s,mark:r,cb:o,className:a,styles:h}=this;return"highlight"===s?e=t.highlight(i,n,o,a,h):"underline"===s?e=t.underline(i,n,o,a,h):"mark"===s&&(e=t.mark(i,n,o)),this.mark=e,this.emit(l.c.ANNOTATION.ATTACH,e),e}detach(t){let e,{cfiRange:i,type:n}=this;return t&&("highlight"===n?e=t.unhighlight(i):"underline"===n?e=t.ununderline(i):"mark"===n&&(e=t.unmark(i))),this.mark=void 0,this.emit(l.c.ANNOTATION.DETACH,e),e}text(){}}s()(p.prototype);var g=class{constructor(t){this.rendition=t,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(t,e,i,n,s,r){let o=encodeURI(e+t),h=new a.a(e).spinePos,l=new p({type:t,cfiRange:e,data:i,sectionIndex:h,cb:n,className:s,styles:r});return this._annotations[o]=l,h in this._annotationsBySectionIndex?this._annotationsBySectionIndex[h].push(o):this._annotationsBySectionIndex[h]=[o],this.rendition.views().forEach(t=>{l.sectionIndex===t.index&&l.attach(t)}),l}remove(t,e){let i=encodeURI(t+e);if(i in this._annotations){let t=this._annotations[i];if(e&&t.type!==e)return;this.rendition.views().forEach(e=>{this._removeFromAnnotationBySectionIndex(t.sectionIndex,i),t.sectionIndex===e.index&&t.detach(e)}),delete this._annotations[i]}}_removeFromAnnotationBySectionIndex(t,e){this._annotationsBySectionIndex[t]=this._annotationsAt(t).filter(t=>t!==e)}_annotationsAt(t){return this._annotationsBySectionIndex[t]}highlight(t,e,i,n,s){return this.add("highlight",t,e,i,n,s)}underline(t,e,i,n,s){return this.add("underline",t,e,i,n,s)}mark(t,e,i){return this.add("mark",t,e,i)}each(){return this._annotations.forEach.apply(this._annotations,arguments)}inject(t){let e=t.index;if(e in this._annotationsBySectionIndex){this._annotationsBySectionIndex[e].forEach(e=>{this._annotations[e].attach(t)})}}clear(t){let e=t.index;if(e in this._annotationsBySectionIndex){this._annotationsBySectionIndex[e].forEach(e=>{this._annotations[e].detach(t)})}}show(){}hide(){}},m=i(20),v=i(10),y=i(22);class b{constructor(t,e){this.settings=Object(r.extend)(this.settings||{},{width:null,height:null,ignoreClass:"",manager:"default",view:"iframe",flow:null,layout:null,spread:null,minSpreadWidth:800,stylesheet:null,resizeOnOrientationChange:!0,script:null,snap:!1,defaultDirection:"ltr",allowScriptedContent:!1,allowPopups:!1}),Object(r.extend)(this.settings,e),"object"==typeof this.settings.manager&&(this.manager=this.settings.manager),this.book=t,this.hooks={},this.hooks.display=new o.a(this),this.hooks.serialize=new o.a(this),this.hooks.content=new o.a(this),this.hooks.unloaded=new o.a(this),this.hooks.layout=new o.a(this),this.hooks.render=new o.a(this),this.hooks.show=new o.a(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)),this.settings.stylesheet&&this.book.spine.hooks.content.register(this.injectStylesheet.bind(this)),this.settings.script&&this.book.spine.hooks.content.register(this.injectScript.bind(this)),this.themes=new f(this),this.annotations=new g(this),this.epubcfi=new a.a,this.q=new h.a(this),this.location=void 0,this.q.enqueue(this.book.opened),this.starting=new r.defer,this.started=this.starting.promise,this.q.enqueue(this.start)}setManager(t){this.manager=t}requireManager(t){return"string"==typeof t&&"default"===t?v.a:"string"==typeof t&&"continuous"===t?y.a:t}requireView(t){return"string"==typeof t&&"iframe"===t?m.a:t}start(){switch(this.settings.layout||"pre-paginated"!==this.book.package.metadata.layout&&"true"!==this.book.displayOptions.fixedLayout||(this.settings.layout="pre-paginated"),this.book.package.metadata.spread){case"none":this.settings.spread="none";break;case"both":this.settings.spread=!0}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||this.settings.defaultDirection),this.settings.globalLayoutProperties=this.determineLayoutProperties(this.book.package.metadata),this.flow(this.settings.globalLayoutProperties.flow),this.layout(this.settings.globalLayoutProperties),this.manager.on(l.c.MANAGERS.ADDED,this.afterDisplayed.bind(this)),this.manager.on(l.c.MANAGERS.REMOVED,this.afterRemoved.bind(this)),this.manager.on(l.c.MANAGERS.RESIZED,this.onResized.bind(this)),this.manager.on(l.c.MANAGERS.ORIENTATION_CHANGE,this.onOrientationChange.bind(this)),this.manager.on(l.c.MANAGERS.SCROLLED,this.reportLocation.bind(this)),this.emit(l.c.RENDITION.STARTED),this.starting.resolve()}attachTo(t){return this.q.enqueue(function(){this.manager.render(t,{width:this.settings.width,height:this.settings.height}),this.emit(l.c.RENDITION.ATTACHED)}.bind(this))}display(t){return this.displaying&&this.displaying.resolve(),this.q.enqueue(this._display,t)}_display(t){if(this.book){this.epubcfi.isCfiString(t);var e,i=new r.defer,n=i.promise;return this.displaying=i,this.book.locations.length()&&Object(r.isFloat)(t)&&(t=this.book.locations.cfiFromPercentage(parseFloat(t))),(e=this.book.spine.get(t))?(this.manager.display(e,t).then(()=>{i.resolve(e),this.displaying=void 0,this.emit(l.c.RENDITION.DISPLAYED,e),this.reportLocation()},t=>{this.emit(l.c.RENDITION.DISPLAY_ERROR,t)}),n):(i.reject(new Error("No Section Found")),n)}}afterDisplayed(t){t.on(l.c.VIEWS.MARK_CLICKED,(e,i)=>this.triggerMarkEvent(e,i,t.contents)),this.hooks.render.trigger(t,this).then(()=>{t.contents?this.hooks.content.trigger(t.contents,this).then(()=>{this.emit(l.c.RENDITION.RENDERED,t.section,t)}):this.emit(l.c.RENDITION.RENDERED,t.section,t)})}afterRemoved(t){this.hooks.unloaded.trigger(t,this).then(()=>{this.emit(l.c.RENDITION.REMOVED,t.section,t)})}onResized(t,e){this.emit(l.c.RENDITION.RESIZED,{width:t.width,height:t.height},e),this.location&&this.location.start&&this.display(e||this.location.start.cfi)}onOrientationChange(t){this.emit(l.c.RENDITION.ORIENTATION_CHANGE,t)}moveTo(t){this.manager.moveTo(t)}resize(t,e,i){t&&(this.settings.width=t),e&&(this.settings.height=e),this.manager.resize(t,e,i)}clear(){this.manager.clear()}next(){return this.q.enqueue(this.manager.next.bind(this.manager)).then(this.reportLocation.bind(this))}prev(){return this.q.enqueue(this.manager.prev.bind(this.manager)).then(this.reportLocation.bind(this))}determineLayoutProperties(t){var e=this.settings.layout||t.layout||"reflowable",i=this.settings.spread||t.spread||"auto",n=this.settings.orientation||t.orientation||"auto",s=this.settings.flow||t.flow||"auto",r=t.viewport||"",o=this.settings.minSpreadWidth||t.minSpreadWidth||800,a=this.settings.direction||t.direction||"ltr";return(0===this.settings.width||this.settings.width>0)&&(0===this.settings.height||this.settings.height),{layout:e,spread:i,orientation:n,flow:s,viewport:r,minSpreadWidth:o,direction:a}}flow(t){var e=t;"scrolled"!==t&&"scrolled-doc"!==t&&"scrolled-continuous"!==t||(e="scrolled"),"auto"!==t&&"paginated"!==t||(e="paginated"),this.settings.flow=t,this._layout&&this._layout.flow(e),this.manager&&this._layout&&this.manager.applyLayout(this._layout),this.manager&&this.manager.updateFlow(e),this.manager&&this.manager.isRendered()&&this.location&&(this.manager.clear(),this.display(this.location.start.cfi))}layout(t){return t&&(this._layout=new u(t),this._layout.spread(t.spread,this.settings.minSpreadWidth),this._layout.on(l.c.LAYOUT.UPDATED,(t,e)=>{this.emit(l.c.RENDITION.LAYOUT,t,e)})),this.manager&&this._layout&&this.manager.applyLayout(this._layout),this._layout}spread(t,e){this.settings.spread=t,e&&(this.settings.minSpreadWidth=e),this._layout&&this._layout.spread(t,e),this.manager&&this.manager.isRendered()&&this.manager.updateLayout()}direction(t){this.settings.direction=t||"ltr",this.manager&&this.manager.direction(this.settings.direction),this.manager&&this.manager.isRendered()&&this.location&&(this.manager.clear(),this.display(this.location.start.cfi))}reportLocation(){return this.q.enqueue(function(){requestAnimationFrame(function(){var t=this.manager.currentLocation();if(t&&t.then&&"function"==typeof t.then)t.then(function(t){let e=this.located(t);e&&e.start&&e.end&&(this.location=e,this.emit(l.c.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(l.c.RENDITION.RELOCATED,this.location))}.bind(this));else if(t){let e=this.located(t);if(!e||!e.start||!e.end)return;this.location=e,this.emit(l.c.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(l.c.RENDITION.RELOCATED,this.location)}}.bind(this))}.bind(this))}currentLocation(){var t=this.manager.currentLocation();if(t&&t.then&&"function"==typeof t.then)t.then(function(t){return this.located(t)}.bind(this));else if(t){return this.located(t)}}located(t){if(!t.length)return{};let e=t[0],i=t[t.length-1],n={start:{index:e.index,href:e.href,cfi:e.mapping.start,displayed:{page:e.pages[0]||1,total:e.totalPages}},end:{index:i.index,href:i.href,cfi:i.mapping.end,displayed:{page:i.pages[i.pages.length-1]||1,total:i.totalPages}}},s=this.book.locations.locationFromCfi(e.mapping.start),r=this.book.locations.locationFromCfi(i.mapping.end);null!=s&&(n.start.location=s,n.start.percentage=this.book.locations.percentageFromLocation(s)),null!=r&&(n.end.location=r,n.end.percentage=this.book.locations.percentageFromLocation(r));let o=this.book.pageList.pageFromCfi(e.mapping.start),a=this.book.pageList.pageFromCfi(i.mapping.end);return-1!=o&&(n.start.page=o),-1!=a&&(n.end.page=a),i.index===this.book.spine.last().index&&n.end.displayed.page>=n.end.displayed.total&&(n.atEnd=!0),e.index===this.book.spine.first().index&&1===n.start.displayed.page&&(n.atStart=!0),n}destroy(){this.manager&&this.manager.destroy(),this.book=void 0}passEvents(t){l.a.forEach(e=>{t.on(e,e=>this.triggerViewEvent(e,t))}),t.on(l.c.CONTENTS.SELECTED,e=>this.triggerSelectedEvent(e,t))}triggerViewEvent(t,e){this.emit(t.type,t,e)}triggerSelectedEvent(t,e){this.emit(l.c.RENDITION.SELECTED,t,e)}triggerMarkEvent(t,e,i){this.emit(l.c.RENDITION.MARK_CLICKED,t,e,i)}getRange(t,e){var i=new a.a(t),n=this.manager.visible().filter((function(t){if(i.spinePos===t.index)return!0}));if(n.length)return n[0].contents.range(i,e)}adjustImages(t){if("pre-paginated"===this._layout.name)return new Promise((function(t){t()}));let e=t.window.getComputedStyle(t.content,null),i=.95*(t.content.offsetHeight-(parseFloat(e.paddingTop)+parseFloat(e.paddingBottom))),n=parseFloat(e.paddingLeft)+parseFloat(e.paddingRight);return t.addStylesheetRules({img:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-n+"px":"100%")+"!important","max-height":i+"px!important","object-fit":"contain","page-break-inside":"avoid","break-inside":"avoid","box-sizing":"border-box"},svg:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-n+"px":"100%")+"!important","max-height":i+"px!important","page-break-inside":"avoid","break-inside":"avoid"}}),new Promise((function(t,e){setTimeout((function(){t()}),1)}))}getContents(){return this.manager?this.manager.getContents():[]}views(){return(this.manager?this.manager.views:void 0)||[]}handleLinks(t){t&&t.on(l.c.CONTENTS.LINK_CLICKED,t=>{let e=this.book.path.relative(t);this.display(e)})}injectStylesheet(t,e){let i=t.createElement("link");i.setAttribute("type","text/css"),i.setAttribute("rel","stylesheet"),i.setAttribute("href",this.settings.stylesheet),t.getElementsByTagName("head")[0].appendChild(i)}injectScript(t,e){let i=t.createElement("script");i.setAttribute("type","text/javascript"),i.setAttribute("src",this.settings.script),i.textContent=" ",t.getElementsByTagName("head")[0].appendChild(i)}injectIdentifier(t,e){let i=this.book.packaging.metadata.identifier,n=t.createElement("meta");n.setAttribute("name","dc.relation.ispartof"),i&&n.setAttribute("content",i),t.getElementsByTagName("head")[0].appendChild(n)}}s()(b.prototype);e.a=b},function(t,e){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(t){"object"==typeof window&&(i=window)}t.exports=i},function(t,e,i){"use strict";var n=i(38)();t.exports=function(t){return t!==n&&null!==t}},function(t,e){t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},function(t,e,i){"use strict";var n,s,r,o=i(3),a=i.n(o),h=i(0),l=i(2),c=i(12),u=i(1),d=i(13);class f{constructor(t,e){const i=f.ViewMap.get(t.href);i&&i.destroy(),f.ViewMap.set(t.href,this),this.settings=Object(h.extend)({ignoreClass:"",axis:void 0,direction:void 0,width:0,height:0,layout:void 0,globalLayoutProperties:{},method:void 0,forceRight:!1,allowScriptedContent:!1,allowPopups:!1},e||{}),this.id="epubjs-view-"+Object(h.uuid)(),this.section=t,this.index=t.index,this.element=this.container(this.settings.axis),this.added=!1,this.displayed=!1,this.rendered=!1,this.fixedWidth=0,this.fixedHeight=0,this.epubcfi=new l.a,this.layout=this.settings.layout,this.pane=void 0,this.highlights={},this.underlines={},this.marks={},this.loading=void 0}container(t){var e=document.createElement("div");return e.classList.add("epub-view"),e.style.height="0px",e.style.width="0px",e.style.overflow="hidden",e.style.position="relative",e.style.display="block",e.style.flex=t&&"horizontal"==t?"none":"initial",e}create(){return this.iframe||(this.element||(this.element=this.createContainer()),this.iframe=document.createElement("iframe"),this.iframe.id=this.id,this.iframe.scrolling="no",this.iframe.style.overflow="hidden",this.iframe.seamless="seamless",this.iframe.style.border="none",this.iframe.sandbox="allow-same-origin",this.settings.allowScriptedContent&&(this.iframe.sandbox+=" allow-scripts"),this.settings.allowPopups&&(this.iframe.sandbox+=" allow-popups"),this.iframe.setAttribute("enable-annotation","true"),this.resizing=!0,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.added=!0,this.elementBounds=Object(h.bounds)(this.element),"srcdoc"in this.iframe?this.supportsSrcdoc=!0:this.supportsSrcdoc=!1,this.settings.method||(this.settings.method=this.supportsSrcdoc?"srcdoc":"write")),this.iframe}render(t,e){return this.create(),this.size(),this.sectionRender||(this.sectionRender=this.section.render(t)),this.sectionRender.then(function(t){return this.load(t)}.bind(this)).then(function(){let t,e=this.contents.writingMode();return t="scrolled"===this.settings.flow?0===e.indexOf("vertical")?"horizontal":"vertical":0===e.indexOf("vertical")?"vertical":"horizontal",0===e.indexOf("vertical")&&"paginated"===this.settings.flow&&(this.layout.delta=this.layout.height),this.setAxis(t),this.emit(u.c.VIEWS.AXIS,t),this.setWritingMode(e),this.emit(u.c.VIEWS.WRITING_MODE,e),this.layout.format(this.contents,this.section,this.axis),this.addListeners(),new Promise((t,e)=>{this.expand(),this.settings.forceRight&&(this.element.style.marginLeft=this.width()+"px"),t()})}.bind(this),function(t){return this.emit(u.c.VIEWS.LOAD_ERROR,t),new Promise((e,i)=>{i(t)})}.bind(this)).then(function(){this.emit(u.c.VIEWS.RENDERED,this.section)}.bind(this))}reset(){this.iframe&&(this.iframe.style.width="0",this.iframe.style.height="0",this._width=0,this._height=0,this._textWidth=void 0,this._contentWidth=void 0,this._textHeight=void 0,this._contentHeight=void 0),this._needsReframe=!0}size(t,e){var i=t||this.settings.width,n=e||this.settings.height;"pre-paginated"===this.layout.name?this.lock("both",i,n):"horizontal"===this.settings.axis?this.lock("height",i,n):this.lock("width",i,n),this.settings.width=i,this.settings.height=n}lock(t,e,i){var n,s=Object(h.borders)(this.element);n=this.iframe?Object(h.borders)(this.iframe):{width:0,height:0},"width"==t&&Object(h.isNumber)(e)&&(this.lockedWidth=e-s.width-n.width),"height"==t&&Object(h.isNumber)(i)&&(this.lockedHeight=i-s.height-n.height),"both"===t&&Object(h.isNumber)(e)&&Object(h.isNumber)(i)&&(this.lockedWidth=e-s.width-n.width,this.lockedHeight=i-s.height-n.height),this.displayed&&this.iframe&&this.expand()}expand(t){var e,i=this.lockedWidth,n=this.lockedHeight;this.iframe&&!this._expanding&&(this._expanding=!0,"pre-paginated"===this.layout.name?(i=this.layout.columnWidth,n=this.layout.height):"horizontal"===this.settings.axis?((i=this.contents.textWidth())%this.layout.pageWidth>0&&(i=Math.ceil(i/this.layout.pageWidth)*this.layout.pageWidth),this.settings.forceEvenPages&&(e=i/this.layout.pageWidth,this.layout.divisor>1&&"reflowable"===this.layout.name&&e%2>0&&(i+=this.layout.pageWidth))):"vertical"===this.settings.axis&&(n=this.contents.textHeight(),"paginated"===this.settings.flow&&n%this.layout.height>0&&(n=Math.ceil(n/this.layout.height)*this.layout.height)),(this._needsReframe||i!=this._width||n!=this._height)&&this.reframe(i,n),this._expanding=!1)}reframe(t,e){var i;Object(h.isNumber)(t)&&(this.element.style.width=t+"px",this.iframe.style.width=t+"px",this._width=t),Object(h.isNumber)(e)&&(this.element.style.height=e+"px",this.iframe.style.height=e+"px",this._height=e),i={width:t,height:e,widthDelta:this.prevBounds?t-this.prevBounds.width:t,heightDelta:this.prevBounds?e-this.prevBounds.height:e},this.pane&&this.pane.render(),requestAnimationFrame(()=>{let t;for(let e in this.marks)this.marks.hasOwnProperty(e)&&(t=this.marks[e],this.placeMark(t.element,t.range))}),this.onResize(this,i),this.emit(u.c.VIEWS.RESIZED,i),this.prevBounds=i,this.elementBounds=Object(h.bounds)(this.element)}load(t){this.loading&&this.loading.reject("cancel");var e=this.loading=new h.defer,i=e.promise;if(!this.iframe)return e.reject(new Error("No Iframe Available")),i;if(this.iframe.onload=function(t){this.onLoad(t,e)}.bind(this),"blobUrl"===this.settings.method)this.blobUrl=Object(h.createBlobUrl)(t,"application/xhtml+xml"),this.iframe.src=this.blobUrl,this.element.appendChild(this.iframe);else if("srcdoc"===this.settings.method)this.iframe.srcdoc=t,this.element.appendChild(this.iframe);else{if(this.element.appendChild(this.iframe),this.document=this.iframe.contentDocument,!this.document)return e.reject(new Error("No Document Available")),i;if(this.iframe.contentDocument.open(),window.MSApp&&MSApp.execUnsafeLocalFunction){var n=this;MSApp.execUnsafeLocalFunction((function(){n.iframe.contentDocument.write(t)}))}else this.iframe.contentDocument.write(t);this.iframe.contentDocument.close()}return i}onLoad(t,e){this.window=this.iframe.contentWindow,this.document=this.iframe.contentDocument,this.contents=new c.a(this.document,this.document.body,this.section.cfiBase,this.section.index),this.rendering=!1;var i=this.document.querySelector("link[rel='canonical']");i?i.setAttribute("href",this.section.canonical):((i=this.document.createElement("link")).setAttribute("rel","canonical"),i.setAttribute("href",this.section.canonical),this.document.querySelector("head").appendChild(i)),this.contents.on(u.c.CONTENTS.EXPAND,()=>{this.displayed&&this.iframe&&(this.expand(),this.contents&&this.layout.format(this.contents))}),this.contents.on(u.c.CONTENTS.RESIZE,t=>{this.displayed&&this.iframe&&(this.expand(),this.contents&&this.layout.format(this.contents))}),e.resolve(this.contents)}setLayout(t){this.layout=t,this.contents&&(this.layout.format(this.contents),this.expand())}setAxis(t){this.settings.axis=t,this.element.style.flex="horizontal"==t?"none":"initial",this.size()}setWritingMode(t){this.writingMode=t}addListeners(){}removeListeners(t){}display(t){var e=new h.defer;return this.displayed?e.resolve(this):this.render(t).then(function(){this.emit(u.c.VIEWS.DISPLAYED,this),this.onDisplayed(this),this.displayed=!0,e.resolve(this)}.bind(this),(function(t){e.reject(t,this)})),e.promise}show(){this.element.style.visibility="visible",this.iframe&&(this.iframe.style.visibility="visible",this.iframe.style.transform="translateZ(0)",this.iframe.offsetWidth,this.iframe.style.transform=null),this.emit(u.c.VIEWS.SHOWN,this)}hide(){this.element.style.visibility="hidden",this.iframe.style.visibility="hidden",this.stopExpanding=!0,this.emit(u.c.VIEWS.HIDDEN,this)}offset(){return{top:this.element.offsetTop,left:this.element.offsetLeft}}width(){return this._width}height(){return this._height}position(){return this.element.getBoundingClientRect()}locationOf(t){this.iframe.getBoundingClientRect();var e=this.contents.locationOf(t,this.settings.ignoreClass);return{left:e.left,top:e.top}}onDisplayed(t){}onResize(t,e){}bounds(t){return!t&&this.elementBounds||(this.elementBounds=Object(h.bounds)(this.element)),this.elementBounds}highlight(t,e={},i,n="epubjs-hl",s={}){if(!this.contents)return;const r=Object.assign({fill:"yellow","fill-opacity":"0.3","mix-blend-mode":"multiply"},s);let o=this.contents.range(t),a=()=>{this.emit(u.c.VIEWS.MARK_CLICKED,t,e)};e.epubcfi=t,this.pane||(this.pane=new d.Pane(this.iframe,this.element));let h=new d.Highlight(o,n,e,r),l=this.pane.addMark(h);return this.highlights[t]={mark:l,element:l.element,listeners:[a,i]},l.element.setAttribute("ref",n),l.element.addEventListener("click",a),l.element.addEventListener("touchstart",a),i&&(l.element.addEventListener("click",i),l.element.addEventListener("touchstart",i)),l}underline(t,e={},i,n="epubjs-ul",s={}){if(!this.contents)return;const r=Object.assign({stroke:"black","stroke-opacity":"0.3","mix-blend-mode":"multiply"},s);let o=this.contents.range(t),a=()=>{this.emit(u.c.VIEWS.MARK_CLICKED,t,e)};e.epubcfi=t,this.pane||(this.pane=new d.Pane(this.iframe,this.element));let h=new d.Underline(o,n,e,r),l=this.pane.addMark(h);return this.underlines[t]={mark:l,element:l.element,listeners:[a,i]},l.element.setAttribute("ref",n),l.element.addEventListener("click",a),l.element.addEventListener("touchstart",a),i&&(l.element.addEventListener("click",i),l.element.addEventListener("touchstart",i)),l}mark(t,e={},i){if(!this.contents)return;if(t in this.marks){return this.marks[t]}let n=this.contents.range(t);if(!n)return;let s=n.commonAncestorContainer,r=1===s.nodeType?s:s.parentNode,o=i=>{this.emit(u.c.VIEWS.MARK_CLICKED,t,e)};n.collapsed&&1===s.nodeType?(n=new Range,n.selectNodeContents(s)):n.collapsed&&(n=new Range,n.selectNodeContents(r));let a=this.document.createElement("a");return a.setAttribute("ref","epubjs-mk"),a.style.position="absolute",a.dataset.epubcfi=t,e&&Object.keys(e).forEach(t=>{a.dataset[t]=e[t]}),i&&(a.addEventListener("click",i),a.addEventListener("touchstart",i)),a.addEventListener("click",o),a.addEventListener("touchstart",o),this.placeMark(a,n),this.element.appendChild(a),this.marks[t]={element:a,range:n,listeners:[o,i]},r}placeMark(t,e){let i,n,s;if("pre-paginated"===this.layout.name||"horizontal"!==this.settings.axis){let t=e.getBoundingClientRect();i=t.top,n=t.right}else{let t,o=e.getClientRects();for(var r=0;r!=o.length;r++)t=o[r],(!s||t.left{t&&(e.element.removeEventListener("click",t),e.element.removeEventListener("touchstart",t))}),delete this.highlights[t])}ununderline(t){let e;t in this.underlines&&(e=this.underlines[t],this.pane.removeMark(e.mark),e.listeners.forEach(t=>{t&&(e.element.removeEventListener("click",t),e.element.removeEventListener("touchstart",t))}),delete this.underlines[t])}unmark(t){let e;t in this.marks&&(e=this.marks[t],this.element.removeChild(e.element),e.listeners.forEach(t=>{t&&(e.element.removeEventListener("click",t),e.element.removeEventListener("touchstart",t))}),delete this.marks[t])}destroy(){for(let t in this.highlights)this.unhighlight(t);for(let t in this.underlines)this.ununderline(t);for(let t in this.marks)this.unmark(t);this.blobUrl&&Object(h.revokeBlobUrl)(this.blobUrl),this.displayed&&(this.displayed=!1,this.removeListeners(),this.contents.destroy(),this.stopExpanding=!0,this.element.removeChild(this.iframe),this.pane&&(this.pane.element.remove(),this.pane=void 0),this.iframe=void 0,this.contents=void 0,this._textWidth=null,this._textHeight=null,this._width=null,this._height=null),this.loading&&this.loading.reject("cancel")}}n=f,s="ViewMap",r=new Map,s in n?Object.defineProperty(n,s,{value:r,enumerable:!0,configurable:!0,writable:!0}):n[s]=r,a()(f.prototype),e.a=f},function(t,e,i){var n=i(19),s=i(51),r=i(53),o=Math.max,a=Math.min;t.exports=function(t,e,i){var h,l,c,u,d,f,p=0,g=!1,m=!1,v=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function y(e){var i=h,n=l;return h=l=void 0,p=e,u=t.apply(n,i)}function b(t){return p=t,d=setTimeout(x,e),g?y(t):u}function w(t){var i=t-f;return void 0===f||i>=e||i<0||m&&t-p>=c}function x(){var t=s();if(w(t))return E(t);d=setTimeout(x,function(t){var i=e-(t-f);return m?a(i,c-(t-p)):i}(t))}function E(t){return d=void 0,v&&h?y(t):(h=l=void 0,u)}function S(){var t=s(),i=w(t);if(h=arguments,l=this,f=t,i){if(void 0===d)return b(f);if(m)return clearTimeout(d),d=setTimeout(x,e),y(f)}return void 0===d&&(d=setTimeout(x,e)),u}return e=r(e)||0,n(i)&&(g=!!i.leading,c=(m="maxWait"in i)?o(r(i.maxWait)||0,e):c,v="trailing"in i?!!i.trailing:v),S.cancel=function(){void 0!==d&&clearTimeout(d),p=0,h=f=l=d=void 0},S.flush=function(){return void 0===d?u:E(s())},S}},function(t,e,i){"use strict";var n=i(0),s=i(10),r=i(1),o=i(3),a=i.n(o);const h=Math.PI/2,l={easeOutSine:function(t){return Math.sin(t*h)},easeInOutSine:function(t){return-.5*(Math.cos(Math.PI*t)-1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*Math.pow(t,5):.5*(Math.pow(t-2,5)+2)},easeInCubic:function(t){return Math.pow(t,3)}};class c{constructor(t,e){this.settings=Object(n.extend)({duration:80,minVelocity:.2,minDistance:10,easing:l.easeInCubic},e||{}),this.supportsTouch=this.supportsTouch(),this.supportsTouch&&this.setup(t)}setup(t){this.manager=t,this.layout=this.manager.layout,this.fullsize=this.manager.settings.fullsize,this.fullsize?(this.element=this.manager.stage.element,this.scroller=window,this.disableScroll()):(this.element=this.manager.stage.container,this.scroller=this.element,this.element.style.WebkitOverflowScrolling="touch"),this.manager.settings.offset=this.layout.width,this.manager.settings.afterScrolledTimeout=2*this.settings.duration,this.isVertical="vertical"===this.manager.settings.axis,this.manager.isPaginated&&!this.isVertical&&(this.touchCanceler=!1,this.resizeCanceler=!1,this.snapping=!1,this.scrollLeft,this.scrollTop,this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0,this.addListeners())}supportsTouch(){return!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch)}disableScroll(){this.element.style.overflow="hidden"}enableScroll(){this.element.style.overflow=""}addListeners(){this._onResize=this.onResize.bind(this),window.addEventListener("resize",this._onResize),this._onScroll=this.onScroll.bind(this),this.scroller.addEventListener("scroll",this._onScroll),this._onTouchStart=this.onTouchStart.bind(this),this.scroller.addEventListener("touchstart",this._onTouchStart,{passive:!0}),this.on("touchstart",this._onTouchStart),this._onTouchMove=this.onTouchMove.bind(this),this.scroller.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.on("touchmove",this._onTouchMove),this._onTouchEnd=this.onTouchEnd.bind(this),this.scroller.addEventListener("touchend",this._onTouchEnd,{passive:!0}),this.on("touchend",this._onTouchEnd),this._afterDisplayed=this.afterDisplayed.bind(this),this.manager.on(r.c.MANAGERS.ADDED,this._afterDisplayed)}removeListeners(){window.removeEventListener("resize",this._onResize),this._onResize=void 0,this.scroller.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,this.scroller.removeEventListener("touchstart",this._onTouchStart,{passive:!0}),this.off("touchstart",this._onTouchStart),this._onTouchStart=void 0,this.scroller.removeEventListener("touchmove",this._onTouchMove,{passive:!0}),this.off("touchmove",this._onTouchMove),this._onTouchMove=void 0,this.scroller.removeEventListener("touchend",this._onTouchEnd,{passive:!0}),this.off("touchend",this._onTouchEnd),this._onTouchEnd=void 0,this.manager.off(r.c.MANAGERS.ADDED,this._afterDisplayed),this._afterDisplayed=void 0}afterDisplayed(t){let e=t.contents;["touchstart","touchmove","touchend"].forEach(t=>{e.on(t,t=>this.triggerViewEvent(t,e))})}triggerViewEvent(t,e){this.emit(t.type,t,e)}onScroll(t){this.scrollLeft=this.fullsize?window.scrollX:this.scroller.scrollLeft,this.scrollTop=this.fullsize?window.scrollY:this.scroller.scrollTop}onResize(t){this.resizeCanceler=!0}onTouchStart(t){let{screenX:e,screenY:i}=t.touches[0];this.fullsize&&this.enableScroll(),this.touchCanceler=!0,this.startTouchX||(this.startTouchX=e,this.startTouchY=i,this.startTime=this.now()),this.endTouchX=e,this.endTouchY=i,this.endTime=this.now()}onTouchMove(t){let{screenX:e,screenY:i}=t.touches[0],n=Math.abs(i-this.endTouchY);this.touchCanceler=!0,!this.fullsize&&n<10&&(this.element.scrollLeft-=e-this.endTouchX),this.endTouchX=e,this.endTouchY=i,this.endTime=this.now()}onTouchEnd(t){this.fullsize&&this.disableScroll(),this.touchCanceler=!1;let e=this.wasSwiped();0!==e?this.snap(e):this.snap(),this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0}wasSwiped(){let t=this.layout.pageWidth*this.layout.divisor,e=this.endTouchX-this.startTouchX,i=Math.abs(e),n=e/(this.endTime-this.startTime),s=this.settings.minVelocity;return i<=this.settings.minDistance||i>=t?0:n>s?-1:n<-s?1:void 0}needsSnap(){return this.scrollLeft%(this.layout.pageWidth*this.layout.divisor)!=0}snap(t=0){let e=this.scrollLeft,i=this.layout.pageWidth*this.layout.divisor,n=Math.round(e/i)*i;return t&&(n+=t*i),this.smoothScrollTo(n)}smoothScrollTo(t){const e=new n.defer,i=this.scrollLeft,s=this.now(),r=this.settings.duration,o=this.settings.easing;return this.snapping=!0,function n(){const a=this.now(),h=Math.min(1,(a-s)/r);if(o(h),this.touchCanceler||this.resizeCanceler)return this.resizeCanceler=!1,this.snapping=!1,void e.resolve();h<1?(window.requestAnimationFrame(n.bind(this)),this.scrollTo(i+(t-i)*h,0)):(this.scrollTo(t,0),this.snapping=!1,e.resolve())}.call(this),e.promise}scrollTo(t=0,e=0){this.fullsize?window.scroll(t,e):(this.scroller.scrollLeft=t,this.scroller.scrollTop=e)}now(){return"now"in window.performance?performance.now():(new Date).getTime()}destroy(){this.scroller&&(this.fullsize&&this.enableScroll(),this.removeListeners(),this.scroller=void 0)}}a()(c.prototype);var u=c,d=i(21),f=i.n(d);class p extends s.a{constructor(t){super(t),this.name="continuous",this.settings=Object(n.extend)(this.settings||{},{infinite:!0,overflow:void 0,axis:void 0,writingMode:void 0,flow:"scrolled",offset:500,offsetDelta:250,width:void 0,height:void 0,snap:!1,afterScrolledTimeout:10,allowScriptedContent:!1,allowPopups:!1}),Object(n.extend)(this.settings,t.settings||{}),"undefined"!=t.settings.gap&&0===t.settings.gap&&(this.settings.gap=t.settings.gap),this.viewSettings={ignoreClass:this.settings.ignoreClass,axis:this.settings.axis,flow:this.settings.flow,layout:this.layout,width:0,height:0,forceEvenPages:!1,allowScriptedContent:this.settings.allowScriptedContent,allowPopups:this.settings.allowPopups},this.scrollTop=0,this.scrollLeft=0}display(t,e){return s.a.prototype.display.call(this,t,e).then(function(){return this.fill()}.bind(this))}fill(t){var e=t||new n.defer;return this.q.enqueue(()=>this.check()).then(t=>{t?this.fill(e):e.resolve()}),e.promise}moveTo(t){var e=0,i=0;this.isPaginated?(e=Math.floor(t.left/this.layout.delta)*this.layout.delta,this.settings.offsetDelta):(i=t.top,t.top,this.settings.offsetDelta),(e>0||i>0)&&this.scrollBy(e,i,!0)}afterResized(t){this.emit(r.c.MANAGERS.RESIZE,t.section)}removeShownListeners(t){t.onDisplayed=function(){}}add(t){var e=this.createView(t);return this.views.append(e),e.on(r.c.VIEWS.RESIZED,t=>{e.expanded=!0}),e.on(r.c.VIEWS.AXIS,t=>{this.updateAxis(t)}),e.on(r.c.VIEWS.WRITING_MODE,t=>{this.updateWritingMode(t)}),e.onDisplayed=this.afterDisplayed.bind(this),e.onResize=this.afterResized.bind(this),e.display(this.request)}append(t){var e=this.createView(t);return e.on(r.c.VIEWS.RESIZED,t=>{e.expanded=!0}),e.on(r.c.VIEWS.AXIS,t=>{this.updateAxis(t)}),e.on(r.c.VIEWS.WRITING_MODE,t=>{this.updateWritingMode(t)}),this.views.append(e),e.onDisplayed=this.afterDisplayed.bind(this),e}prepend(t){var e=this.createView(t);return e.on(r.c.VIEWS.RESIZED,t=>{this.counter(t),e.expanded=!0}),e.on(r.c.VIEWS.AXIS,t=>{this.updateAxis(t)}),e.on(r.c.VIEWS.WRITING_MODE,t=>{this.updateWritingMode(t)}),this.views.prepend(e),e.onDisplayed=this.afterDisplayed.bind(this),e}counter(t){"vertical"===this.settings.axis?this.scrollBy(0,t.heightDelta,!0):this.scrollBy(t.widthDelta,0,!0)}update(t){for(var e,i=this.bounds(),s=this.views.all(),r=s.length,o=[],a=void 0!==t?t:this.settings.offset||0,h=new n.defer,l=[],c=0;c{e.hide()});l.push(t)}o.push(e)}else this.q.enqueue(e.destroy.bind(e)),clearTimeout(this.trimTimeout),this.trimTimeout=setTimeout(function(){this.q.enqueue(this.trim.bind(this))}.bind(this),250);return l.length?Promise.all(l).catch(t=>{h.reject(t)}):(h.resolve(),h.promise)}check(t,e){var i=new n.defer,s=[],r="horizontal"===this.settings.axis,o=this.settings.offset||0;t&&r&&(o=t),e&&!r&&(o=e);var a=this._bounds;let h=r?this.scrollLeft:this.scrollTop,l=r?Math.floor(a.width):a.height,c=r?this.container.scrollWidth:this.container.scrollHeight,u=this.writingMode&&0===this.writingMode.indexOf("vertical")?"vertical":"horizontal",d=this.settings.rtlScrollType,f="rtl"===this.settings.direction;this.settings.fullsize?(r&&f&&"negative"===d||!r&&f&&"default"===d)&&(h*=-1):(f&&"default"===d&&"horizontal"===u&&(h=c-l-h),f&&"negative"===d&&"horizontal"===u&&(h*=-1));let p=()=>{let t=this.views.first(),e=t&&t.section.prev();e&&s.push(this.prepend(e))},g=h-o;h+l+o>=c&&(()=>{let t=this.views.last(),e=t&&t.section.next();e&&s.push(this.append(e))})(),g<0&&p();let m=s.map(t=>t.display(this.request));return s.length?Promise.all(m).then(()=>this.check()).then(()=>this.update(o),t=>t):(this.q.enqueue(function(){this.update()}.bind(this)),i.resolve(!1),i.promise)}trim(){for(var t=new n.defer,e=this.views.displayed(),i=e[0],s=e[e.length-1],r=this.views.indexOf(i),o=this.views.indexOf(s),a=this.views.slice(0,r),h=this.views.slice(o+1),l=0;l=43)}})).catch((function(){return!1}))}(t).then((function(t){return u=t}))}function g(t){var e=d[t.name],i={};i.promise=new o((function(t,e){i.resolve=t,i.reject=e})),e.deferredOperations.push(i),e.dbReady?e.dbReady=e.dbReady.then((function(){return i.promise})):e.dbReady=i.promise}function m(t){var e=d[t.name].deferredOperations.pop();if(e)return e.resolve(),e.promise}function v(t,e){var i=d[t.name].deferredOperations.pop();if(i)return i.reject(e),i.promise}function y(t,e){return new o((function(i,n){if(d[t.name]=d[t.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},t.db){if(!e)return i(t.db);g(t),t.db.close()}var r=[t.name];e&&r.push(t.version);var o=s.open.apply(s,r);e&&(o.onupgradeneeded=function(e){var i=o.result;try{i.createObjectStore(t.storeName),e.oldVersion<=1&&i.createObjectStore("local-forage-detect-blob-support")}catch(i){if("ConstraintError"!==i.name)throw i;console.warn('The database "'+t.name+'" has been upgraded from version '+e.oldVersion+" to version "+e.newVersion+', but the storage "'+t.storeName+'" already exists.')}}),o.onerror=function(t){t.preventDefault(),n(o.error)},o.onsuccess=function(){var e=o.result;e.onversionchange=function(t){t.target.close()},i(e),m(t)}}))}function b(t){return y(t,!1)}function w(t){return y(t,!0)}function x(t,e){if(!t.db)return!0;var i=!t.db.objectStoreNames.contains(t.storeName),n=t.versiont.db.version;if(n&&(t.version!==e&&console.warn('The database "'+t.name+"\" can't be downgraded from version "+t.db.version+" to version "+t.version+"."),t.version=t.db.version),s||i){if(i){var r=t.db.version+1;r>t.version&&(t.version=r)}return!0}return!1}function E(t){return r([function(t){for(var e=t.length,i=new ArrayBuffer(e),n=new Uint8Array(i),s=0;s0&&(!t.db||"InvalidStateError"===s.name||"NotFoundError"===s.name))return o.resolve().then((function(){if(!t.db||"NotFoundError"===s.name&&!t.db.objectStoreNames.contains(t.storeName)&&t.version<=t.db.version)return t.db&&(t.version=t.db.version+1),w(t)})).then((function(){return function(t){g(t);for(var e=d[t.name],i=e.forages,n=0;n>4,c[h++]=(15&n)<<4|s>>2,c[h++]=(3&s)<<6|63&r;return l}function L(t){var e,i=new Uint8Array(t),n="";for(e=0;e>2],n+=C[(3&i[e])<<4|i[e+1]>>4],n+=C[(15&i[e+1])<<2|i[e+2]>>6],n+=C[63&i[e+2]];return i.length%3==2?n=n.substring(0,n.length-1)+"=":i.length%3==1&&(n=n.substring(0,n.length-2)+"=="),n}var j={serialize:function(t,e){var i="";if(t&&(i=k.call(t)),t&&("[object ArrayBuffer]"===i||t.buffer&&"[object ArrayBuffer]"===k.call(t.buffer))){var n,s="__lfsc__:";t instanceof ArrayBuffer?(n=t,s+="arbf"):(n=t.buffer,"[object Int8Array]"===i?s+="si08":"[object Uint8Array]"===i?s+="ui08":"[object Uint8ClampedArray]"===i?s+="uic8":"[object Int16Array]"===i?s+="si16":"[object Uint16Array]"===i?s+="ur16":"[object Int32Array]"===i?s+="si32":"[object Uint32Array]"===i?s+="ui32":"[object Float32Array]"===i?s+="fl32":"[object Float64Array]"===i?s+="fl64":e(new Error("Failed to get type for BinaryArray"))),e(s+L(n))}else if("[object Blob]"===i){var r=new FileReader;r.onload=function(){var i="~~local_forage_type~"+t.type+"~"+L(this.result);e("__lfsc__:blob"+i)},r.readAsArrayBuffer(t)}else try{e(JSON.stringify(t))}catch(i){console.error("Couldn't convert value into a JSON string: ",t),e(null,i)}},deserialize:function(t){if("__lfsc__:"!==t.substring(0,I))return JSON.parse(t);var e,i=t.substring(R),n=t.substring(I,R);if("blob"===n&&O.test(i)){var s=i.match(O);e=s[1],i=i.substring(s[0].length)}var o=A(i);switch(n){case"arbf":return o;case"blob":return r([o],{type:e});case"si08":return new Int8Array(o);case"ui08":return new Uint8Array(o);case"uic8":return new Uint8ClampedArray(o);case"si16":return new Int16Array(o);case"ur16":return new Uint16Array(o);case"si32":return new Int32Array(o);case"ui32":return new Uint32Array(o);case"fl32":return new Float32Array(o);case"fl64":return new Float64Array(o);default:throw new Error("Unkown type: "+n)}},stringToBuffer:A,bufferToString:L};function D(t,e,i,n){t.executeSql("CREATE TABLE IF NOT EXISTS "+e.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],i,n)}function P(t,e,i,n,s,r){t.executeSql(i,n,s,(function(t,o){o.code===o.SYNTAX_ERR?t.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[e.storeName],(function(t,a){a.rows.length?r(t,o):D(t,e,(function(){t.executeSql(i,n,s,r)}),r)}),r):r(t,o)}),r)}function M(t,e,i,n){var s=this;t=l(t);var r=new o((function(r,o){s.ready().then((function(){void 0===e&&(e=null);var a=e,h=s._dbInfo;h.serializer.serialize(e,(function(e,l){l?o(l):h.db.transaction((function(i){P(i,h,"INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[t,e],(function(){r(a)}),(function(t,e){o(e)}))}),(function(e){if(e.code===e.QUOTA_ERR){if(n>0)return void r(M.apply(s,[t,a,i,n-1]));o(e)}}))}))})).catch(o)}));return a(r,i),r}function z(t){return new o((function(e,i){t.transaction((function(n){n.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],(function(i,n){for(var s=[],r=0;r0}var U={_driver:"localStorageWrapper",_initStorage:function(t){var e={};if(t)for(var i in t)e[i]=t[i];return e.keyPrefix=q(t,this._defaultConfig),F()?(this._dbInfo=e,e.serializer=j,o.resolve()):o.reject()},_support:function(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&!!localStorage.setItem}catch(t){return!1}}(),iterate:function(t,e){var i=this,n=i.ready().then((function(){for(var e=i._dbInfo,n=e.keyPrefix,s=n.length,r=localStorage.length,o=1,a=0;a=0;i--){var n=localStorage.key(i);0===n.indexOf(t)&&localStorage.removeItem(n)}}));return a(i,t),i},length:function(t){var e=this.keys().then((function(t){return t.length}));return a(e,t),e},key:function(t,e){var i=this,n=i.ready().then((function(){var e,n=i._dbInfo;try{e=localStorage.key(t)}catch(t){e=null}return e&&(e=e.substring(n.keyPrefix.length)),e}));return a(n,e),n},keys:function(t){var e=this,i=e.ready().then((function(){for(var t=e._dbInfo,i=localStorage.length,n=[],s=0;s=0;e--){var i=localStorage.key(e);0===i.indexOf(t)&&localStorage.removeItem(i)}})):o.reject("Invalid arguments"),e),n}},W=function(t,e){for(var i,n,s=t.length,r=0;r=0,i=new("undefined"==typeof XMLSerializer||e?d.DOMParser:XMLSerializer);return this.output=i.serializeToString(t),this.output}.bind(this)).then(function(){return this.hooks.serialize.trigger(this.output,this)}.bind(this)).then(function(){e.resolve(this.output)}.bind(this)).catch((function(t){e.reject(t)})),i}find(t){var e=this,i=[],n=t.toLowerCase();return Object(r.sprint)(e.document,(function(t){!function(t){for(var s,r,o,a=t.textContent.toLowerCase(),h=e.document.createRange(),l=-1;-1!=r;)-1!=(r=a.indexOf(n,l+1))&&((h=e.document.createRange()).setStart(t,r),h.setEnd(t,r+n.length),s=e.cfiFromRange(h),o=t.textContent.length<150?t.textContent:"..."+(o=t.textContent.substring(r-75,r+75))+"...",i.push({cfi:s,excerpt:o})),l=r}(t)})),i}search(t,e=5){if(void 0===document.createTreeWalker)return this.find(t);let i=[];const n=this,s=t.toLowerCase(),r=function(t){const e=t.reduce((t,e)=>t+e.textContent,"").toLowerCase().indexOf(s);if(-1!=e){const r=0,o=e+s.length;let a=0,h=0;if(et+e.textContent.length,0);u.setEnd(c,d>o?o:o-d),s=n.cfiFromRange(u);let f=t.slice(0,a+1).reduce((t,e)=>t+e.textContent,"");f.length>150&&(f=f.substring(e-75,e+75),f="..."+f+"..."),i.push({cfi:s,excerpt:f})}}},o=document.createTreeWalker(n.document,NodeFilter.SHOW_TEXT,null,!1);let a,h=[];for(;a=o.nextNode();)h.push(a),h.length==e&&(r(h.slice(0,e)),h=h.slice(1,e));return h.length>0&&r(h),i}reconcileLayoutSettings(t){var e={layout:t.layout,spread:t.spread,orientation:t.orientation};return this.properties.forEach((function(t){var i,n,s=t.replace("rendition:",""),r=s.indexOf("-");-1!=r&&(i=s.slice(0,r),n=s.slice(r+1),e[i]=n)})),e}cfiFromRange(t){return new h.a(t,this.cfiBase).toString()}cfiFromElement(t){return new h.a(t,this.cfiBase).toString()}unload(){this.document=void 0,this.contents=void 0,this.output=void 0}destroy(){this.unload(),this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks=void 0,this.idref=void 0,this.linear=void 0,this.properties=void 0,this.index=void 0,this.href=void 0,this.url=void 0,this.next=void 0,this.prev=void 0,this.cfiBase=void 0}};var p=class{constructor(){this.spineItems=[],this.spineByHref={},this.spineById={},this.hooks={},this.hooks.serialize=new l.a,this.hooks.content=new l.a,this.hooks.content.register(c.a),this.hooks.content.register(c.b),this.hooks.content.register(c.d),this.epubcfi=new h.a,this.loaded=!1,this.items=void 0,this.manifest=void 0,this.spineNodeIndex=void 0,this.baseUrl=void 0,this.length=void 0}unpack(t,e,i){this.items=t.spine,this.manifest=t.manifest,this.spineNodeIndex=t.spineNodeIndex,this.baseUrl=t.baseUrl||t.basePath||"",this.length=this.items.length,this.items.forEach((t,n)=>{var s,r=this.manifest[t.idref];t.index=n,t.cfiBase=this.epubcfi.generateChapterComponent(this.spineNodeIndex,t.index,t.id),t.href&&(t.url=e(t.href,!0),t.canonical=i(t.href)),r&&(t.href=r.href,t.url=e(t.href,!0),t.canonical=i(t.href),r.properties.length&&t.properties.push.apply(t.properties,r.properties)),"yes"===t.linear?(t.prev=function(){let e=t.index;for(;e>0;){let t=this.get(e-1);if(t&&t.linear)return t;e-=1}}.bind(this),t.next=function(){let e=t.index;for(;e-1)return delete this.spineByHref[t.href],delete this.spineById[t.idref],this.spineItems.splice(e,1)}each(){return this.spineItems.forEach.apply(this.spineItems,arguments)}first(){let t=0;do{let e=this.get(t);if(e&&e.linear)return e;t+=1}while(t=0)}destroy(){this.each(t=>t.destroy()),this.spineItems=void 0,this.spineByHref=void 0,this.spineById=void 0,this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks=void 0,this.epubcfi=void 0,this.loaded=!1,this.items=void 0,this.manifest=void 0,this.spineNodeIndex=void 0,this.baseUrl=void 0,this.length=void 0}},g=i(9),m=i(1);class v{constructor(t,e,i){this.spine=t,this.request=e,this.pause=i||100,this.q=new g.a(this),this.epubcfi=new h.a,this._locations=[],this._locationsWords=[],this.total=0,this.break=150,this._current=0,this._wordCounter=0,this.currentLocation="",this._currentCfi="",this.processingTimeout=void 0}generate(t){return t&&(this.break=t),this.q.pause(),this.spine.each(function(t){t.linear&&this.q.enqueue(this.process.bind(this),t)}.bind(this)),this.q.run().then(function(){return this.total=this._locations.length-1,this._currentCfi&&(this.currentLocation=this._currentCfi),this._locations}.bind(this))}createRange(){return{startContainer:void 0,startOffset:void 0,endContainer:void 0,endOffset:void 0}}process(t){return t.load(this.request).then(function(e){var i=new r.defer,n=this.parse(e,t.cfiBase);return this._locations=this._locations.concat(n),t.unload(),this.processingTimeout=setTimeout(()=>i.resolve(n),this.pause),i.promise}.bind(this))}parse(t,e,i){var n,s,o=[],a=t.ownerDocument,l=Object(r.qs)(a,"body"),c=0,u=i||this.break;if(Object(r.sprint)(l,function(t){var i,r=t.length,a=0;if(0===t.textContent.trim().length)return!1;for(0==c&&((n=this.createRange()).startContainer=t,n.startOffset=0),(i=u-c)>r&&(c+=r,a=r);a=r)c+=r-a,a=r;else{a+=i,n.endContainer=t,n.endOffset=a;let s=new h.a(n,e).toString();o.push(s),c=0}s=t}.bind(this)),n&&n.startContainer&&s){n.endContainer=s,n.endOffset=s.length;let t=new h.a(n,e).toString();o.push(t),c=0}return o}generateFromWords(t,e,i){var n=t?new h.a(t):void 0;return this.q.pause(),this._locationsWords=[],this._wordCounter=0,this.spine.each(function(t){t.linear&&(n?t.index>=n.spinePos&&this.q.enqueue(this.processWords.bind(this),t,e,n,i):this.q.enqueue(this.processWords.bind(this),t,e,n,i))}.bind(this)),this.q.run().then(function(){return this._currentCfi&&(this.currentLocation=this._currentCfi),this._locationsWords}.bind(this))}processWords(t,e,i,n){return n&&this._locationsWords.length>=n?Promise.resolve():t.load(this.request).then(function(s){var o=new r.defer,a=this.parseWords(s,t,e,i),h=n-this._locationsWords.length;return this._locationsWords=this._locationsWords.concat(a.length>=n?a.slice(0,h):a),t.unload(),this.processingTimeout=setTimeout(()=>o.resolve(a),this.pause),o.promise}.bind(this))}countWords(t){return(t=(t=(t=t.replace(/(^\s*)|(\s*$)/gi,"")).replace(/[ ]{2,}/gi," ")).replace(/\n /,"\n")).split(" ").length}parseWords(t,e,i,n){var s,o=e.cfiBase,a=[],l=t.ownerDocument,c=Object(r.qs)(l,"body"),u=i,d=!n||n.spinePos!==e.index;n&&e.index===n.spinePos&&(s=n.findNode(n.range?n.path.steps.concat(n.start.steps):n.path.steps,t.ownerDocument));return Object(r.sprint)(c,function(t){if(!d){if(t!==s)return!1;d=!0}if(t.textContent.length<10&&0===t.textContent.trim().length)return!1;var e,i=this.countWords(t.textContent),n=0;if(0===i)return!1;for((e=u-this._wordCounter)>i&&(this._wordCounter+=i,n=i);n=i)this._wordCounter+=i-n,n=i;else{n+=e;let i=new h.a(t,o);a.push({cfi:i.toString(),wordCount:this._wordCounter}),this._wordCounter=0}t}.bind(this)),a}locationFromCfi(t){let e;return h.a.prototype.isCfiString(t)&&(t=new h.a(t)),0===this._locations.length?-1:(e=Object(r.locationOf)(t,this._locations,this.epubcfi.compare),e>this.total?this.total:e)}percentageFromCfi(t){if(0===this._locations.length)return null;var e=this.locationFromCfi(t);return this.percentageFromLocation(e)}percentageFromLocation(t){return t&&this.total?t/this.total:0}cfiFromLocation(t){var e=-1;return"number"!=typeof t&&(t=parseInt(t)),t>=0&&t1&&console.warn("Normalize cfiFromPercentage value to between 0 - 1"),t>=1){let t=new h.a(this._locations[this.total]);return t.collapse(),t.toString()}return e=Math.ceil(this.total*t),this.cfiFromLocation(e)}load(t){return this._locations="string"==typeof t?JSON.parse(t):t,this.total=this._locations.length-1,this._locations}save(){return JSON.stringify(this._locations)}getCurrent(){return this._current}setCurrent(t){var e;if("string"==typeof t)this._currentCfi=t;else{if("number"!=typeof t)return;this._current=t}0!==this._locations.length&&("string"==typeof t?(e=this.locationFromCfi(t),this._current=e):e=t,this.emit(m.c.LOCATIONS.CHANGED,{percentage:this.percentageFromLocation(e)}))}get currentLocation(){return this._current}set currentLocation(t){this.setCurrent(t)}length(){return this._locations.length}destroy(){this.spine=void 0,this.request=void 0,this.pause=void 0,this.q.stop(),this.q=void 0,this.epubcfi=void 0,this._locations=void 0,this.total=void 0,this.break=void 0,this._current=void 0,this.currentLocation=void 0,this._currentCfi=void 0,clearTimeout(this.processingTimeout)}}s()(v.prototype);var y=v,b=i(7),w=i.n(b);var x=class{constructor(t){this.packagePath="",this.directory="",this.encoding="",t&&this.parse(t)}parse(t){var e;if(!t)throw new Error("Container File Not Found");if(!(e=Object(r.qs)(t,"rootfile")))throw new Error("No RootFile Found");this.packagePath=e.getAttribute("full-path"),this.directory=w.a.dirname(this.packagePath),this.encoding=t.xmlEncoding}destroy(){this.packagePath=void 0,this.directory=void 0,this.encoding=void 0}};var E=class{constructor(t){this.manifest={},this.navPath="",this.ncxPath="",this.coverPath="",this.spineNodeIndex=0,this.spine=[],this.metadata={},t&&this.parse(t)}parse(t){var e,i,n;if(!t)throw new Error("Package File Not Found");if(!(e=Object(r.qs)(t,"metadata")))throw new Error("No Metadata Found");if(!(i=Object(r.qs)(t,"manifest")))throw new Error("No Manifest Found");if(!(n=Object(r.qs)(t,"spine")))throw new Error("No Spine Found");return this.manifest=this.parseManifest(i),this.navPath=this.findNavPath(i),this.ncxPath=this.findNcxPath(i,n),this.coverPath=this.findCoverPath(t),this.spineNodeIndex=Object(r.indexOfElementNode)(n),this.spine=this.parseSpine(n,this.manifest),this.uniqueIdentifier=this.findUniqueIdentifier(t),this.metadata=this.parseMetadata(e),this.metadata.direction=n.getAttribute("page-progression-direction"),{metadata:this.metadata,spine:this.spine,manifest:this.manifest,navPath:this.navPath,ncxPath:this.ncxPath,coverPath:this.coverPath,spineNodeIndex:this.spineNodeIndex}}parseMetadata(t){var e={};return e.title=this.getElementText(t,"title"),e.creator=this.getElementText(t,"creator"),e.description=this.getElementText(t,"description"),e.pubdate=this.getElementText(t,"date"),e.publisher=this.getElementText(t,"publisher"),e.identifier=this.getElementText(t,"identifier"),e.language=this.getElementText(t,"language"),e.rights=this.getElementText(t,"rights"),e.modified_date=this.getPropertyText(t,"dcterms:modified"),e.layout=this.getPropertyText(t,"rendition:layout"),e.orientation=this.getPropertyText(t,"rendition:orientation"),e.flow=this.getPropertyText(t,"rendition:flow"),e.viewport=this.getPropertyText(t,"rendition:viewport"),e.media_active_class=this.getPropertyText(t,"media:active-class"),e.spread=this.getPropertyText(t,"rendition:spread"),e}parseManifest(t){var e={},i=Object(r.qsa)(t,"item");return Array.prototype.slice.call(i).forEach((function(t){var i=t.getAttribute("id"),n=t.getAttribute("href")||"",s=t.getAttribute("media-type")||"",r=t.getAttribute("media-overlay")||"",o=t.getAttribute("properties")||"";e[i]={href:n,type:s,overlay:r,properties:o.length?o.split(" "):[]}})),e}parseSpine(t,e){var i=[],n=Object(r.qsa)(t,"itemref");return Array.prototype.slice.call(n).forEach((function(t,e){var n=t.getAttribute("idref"),s=t.getAttribute("properties")||"",r=s.length?s.split(" "):[],o={id:t.getAttribute("id"),idref:n,linear:t.getAttribute("linear")||"yes",properties:r,index:e};i.push(o)})),i}findUniqueIdentifier(t){var e=t.documentElement.getAttribute("unique-identifier");if(!e)return"";var i=t.getElementById(e);return i&&"identifier"===i.localName&&"http://purl.org/dc/elements/1.1/"===i.namespaceURI&&i.childNodes.length>0?i.childNodes[0].nodeValue.trim():""}findNavPath(t){var e=Object(r.qsp)(t,"item",{properties:"nav"});return!!e&&e.getAttribute("href")}findNcxPath(t,e){var i,n=Object(r.qsp)(t,"item",{"media-type":"application/x-dtbncx+xml"});return n||(i=e.getAttribute("toc"))&&(n=t.querySelector("#"+i)),!!n&&n.getAttribute("href")}findCoverPath(t){Object(r.qs)(t,"package").getAttribute("version");var e=Object(r.qsp)(t,"item",{properties:"cover-image"});if(e)return e.getAttribute("href");var i=Object(r.qsp)(t,"meta",{name:"cover"});if(i){var n=i.getAttribute("content"),s=t.getElementById(n);return s?s.getAttribute("href"):""}return!1}getElementText(t,e){var i,n=t.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/",e);return n&&0!==n.length&&(i=n[0]).childNodes.length?i.childNodes[0].nodeValue:""}getPropertyText(t,e){var i=Object(r.qsp)(t,"meta",{property:e});return i&&i.childNodes.length?i.childNodes[0].nodeValue:""}load(t){this.metadata=t.metadata;let e=t.readingOrder||t.spine;return this.spine=e.map((t,e)=>(t.index=e,t.linear=t.linear||"yes",t)),t.resources.forEach((t,e)=>{this.manifest[e]=t,t.rel&&"cover"===t.rel[0]&&(this.coverPath=t.href)}),this.spineNodeIndex=0,this.toc=t.toc.map((t,e)=>(t.label=t.title,t)),{metadata:this.metadata,spine:this.spine,manifest:this.manifest,navPath:this.navPath,ncxPath:this.ncxPath,coverPath:this.coverPath,spineNodeIndex:this.spineNodeIndex,toc:this.toc}}destroy(){this.manifest=void 0,this.navPath=void 0,this.ncxPath=void 0,this.coverPath=void 0,this.spineNodeIndex=void 0,this.spine=void 0,this.metadata=void 0}};var S=class{constructor(t){this.toc=[],this.tocByHref={},this.tocById={},this.landmarks=[],this.landmarksByType={},this.length=0,t&&this.parse(t)}parse(t){let e,i,n=t.nodeType;n&&(e=Object(r.qs)(t,"html"),i=Object(r.qs)(t,"ncx")),n?e?(this.toc=this.parseNav(t),this.landmarks=this.parseLandmarks(t)):i&&(this.toc=this.parseNcx(t)):this.toc=this.load(t),this.length=0,this.unpack(this.toc)}unpack(t){for(var e,i=0;i(t.label=t.title,t.subitems=t.children?this.load(t.children):[],t))}forEach(t){return this.toc.forEach(t)}},N={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","omdoc+xml":"omdoc",oxps:"oxps","vnd.amazon.ebook":"azw",widget:"wgt","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"}},_=function(){var t,e,i,n,s={};for(t in N)if(N.hasOwnProperty(t))for(e in N[t])if(N[t].hasOwnProperty(e))if("string"==typeof(i=N[t][e]))s[i]=t+"/"+e;else for(n=0;nObject(r.blob2base64)(t)).then(t=>Object(r.createBase64Url)(t,i)):this.settings.request(t,"blob").then(t=>Object(r.createBlobUrl)(t,i))}replacements(){if("none"===this.settings.replacements)return new Promise(function(t){t(this.urls)}.bind(this));var t=this.urls.map(t=>{var e=this.settings.resolver(t);return this.createUrl(e).catch(t=>(console.error(t),null))});return Promise.all(t).then(t=>(this.replacementUrls=t.filter(t=>"string"==typeof t),t))}replaceCss(t,e){var i=[];return t=t||this.settings.archive,e=e||this.settings.resolver,this.cssUrls.forEach(function(n){var s=this.createCssFile(n,t,e).then(function(t){var e=this.urls.indexOf(n);e>-1&&(this.replacementUrls[e]=t)}.bind(this));i.push(s)}.bind(this)),Promise.all(i)}createCssFile(t){if(w.a.isAbsolute(t))return new Promise((function(t){t()}));var e,i=this.settings.resolver(t);e=this.settings.archive?this.settings.archive.getText(i):this.settings.request(i,"text");var n=this.urls.map(t=>{var e=this.settings.resolver(t);return new a.a(i).relative(e)});return e?e.then(t=>(t=Object(c.e)(t,n,this.replacementUrls),"base64"===this.settings.replacements?Object(r.createBase64Url)(t,"text/css"):Object(r.createBlobUrl)(t,"text/css")),t=>new Promise((function(t){t()}))):new Promise((function(t){t()}))}relativeTo(t,e){return e=e||this.settings.resolver,this.urls.map(function(i){var n=e(i);return new a.a(t).relative(n)}.bind(this))}get(t){var e=this.urls.indexOf(t);if(-1!==e)return this.replacementUrls.length?new Promise(function(t,i){t(this.replacementUrls[e])}.bind(this)):this.createUrl(t)}substitute(t,e){var i;return i=e?this.relativeTo(e):this.urls,Object(c.e)(t,i,this.replacementUrls)}destroy(){this.settings=void 0,this.manifest=void 0,this.resources=void 0,this.replacementUrls=void 0,this.html=void 0,this.assets=void 0,this.css=void 0,this.urls=void 0,this.cssUrls=void 0}};var O=class{constructor(t){this.pages=[],this.locations=[],this.epubcfi=new h.a,this.firstPage=0,this.lastPage=0,this.totalPages=0,this.toc=void 0,this.ncx=void 0,t&&(this.pageList=this.parse(t)),this.pageList&&this.pageList.length&&this.process(this.pageList)}parse(t){var e=Object(r.qs)(t,"html"),i=Object(r.qs)(t,"ncx");return e?this.parseNav(t):i?this.parseNcx(t):void 0}parseNav(t){var e,i,n=Object(r.querySelectorByType)(t,"nav","page-list"),s=n?Object(r.qsa)(n,"li"):[],o=s.length,a=[];if(!s||0===o)return a;for(e=0;e1&&e[1],href:s,packageUrl:i,page:a}):{href:s,page:a}}process(t){t.forEach((function(t){this.pages.push(t.page),t.cfi&&this.locations.push(t.cfi)}),this),this.firstPage=parseInt(this.pages[0]),this.lastPage=parseInt(this.pages[this.pages.length-1]),this.totalPages=this.lastPage-this.firstPage}pageFromCfi(t){var e=-1;if(0===this.locations.length)return-1;var i=Object(r.indexOfSorted)(t,this.locations,this.epubcfi.compare);return-1!=i?e=this.pages[i]:void 0!==(e=(i=Object(r.locationOf)(t,this.locations,this.epubcfi.compare))-1>=0?this.pages[i-1]:this.pages[0])||(e=-1),e}cfiFromPage(t){var e=-1;"number"!=typeof t&&(t=parseInt(t));var i=this.pages.indexOf(t);return-1!=i&&(e=this.locations[i]),e}pageFromPercentage(t){return Math.round(this.totalPages*t)}percentageFromPage(t){var e=(t-this.firstPage)/this.totalPages;return Math.round(1e3*e)/1e3}percentageFromCfi(t){var e=this.pageFromCfi(t);return this.percentageFromPage(e)}destroy(){this.pages=void 0,this.locations=void 0,this.epubcfi=void 0,this.pageList=void 0,this.toc=void 0,this.ncx=void 0}},I=i(16),R=i(29),k=i.n(R);var A=class{constructor(){this.zip=void 0,this.urlCache={},this.checkRequirements()}checkRequirements(){try{this.zip=new k.a}catch(t){throw new Error("JSZip lib not loaded")}}open(t,e){return this.zip.loadAsync(t,{base64:e})}openUrl(t,e){return u(t,"binary").then(function(t){return this.zip.loadAsync(t,{base64:e})}.bind(this))}request(t,e){var i,n=new r.defer,s=new a.a(t);return e||(e=s.extension),(i="blob"==e?this.getBlob(t):this.getText(t))?i.then(function(t){let i=this.handleResponse(t,e);n.resolve(i)}.bind(this)):n.reject({message:"File not found in the epub: "+t,stack:(new Error).stack}),n.promise}handleResponse(t,e){return"json"==e?JSON.parse(t):Object(r.isXml)(e)?Object(r.parse)(t,"text/xml"):"xhtml"==e?Object(r.parse)(t,"application/xhtml+xml"):"html"==e||"htm"==e?Object(r.parse)(t,"text/html"):t}getBlob(t,e){var i=window.decodeURIComponent(t.substr(1)),n=this.zip.file(i);if(n)return e=e||T.lookup(n.name),n.async("uint8array").then((function(t){return new Blob([t],{type:e})}))}getText(t,e){var i=window.decodeURIComponent(t.substr(1)),n=this.zip.file(i);if(n)return n.async("string").then((function(t){return t}))}getBase64(t,e){var i=window.decodeURIComponent(t.substr(1)),n=this.zip.file(i);if(n)return e=e||T.lookup(n.name),n.async("base64").then((function(t){return"data:"+e+";base64,"+t}))}createUrl(t,e){var i,n,s=new r.defer,o=window.URL||window.webkitURL||window.mozURL,a=e&&e.base64;return t in this.urlCache?(s.resolve(this.urlCache[t]),s.promise):(a?(n=this.getBase64(t))&&n.then(function(e){this.urlCache[t]=e,s.resolve(e)}.bind(this)):(n=this.getBlob(t))&&n.then(function(e){i=o.createObjectURL(e),this.urlCache[t]=i,s.resolve(i)}.bind(this)),n||s.reject({message:"File not found in the epub: "+t,stack:(new Error).stack}),s.promise)}revokeUrl(t){var e=window.URL||window.webkitURL||window.mozURL,i=this.urlCache[t];i&&e.revokeObjectURL(i)}destroy(){var t=window.URL||window.webkitURL||window.mozURL;for(let e in this.urlCache)t.revokeObjectURL(e);this.zip=void 0,this.urlCache={}}},L=i(23),j=i.n(L);class D{constructor(t,e,i){this.urlCache={},this.storage=void 0,this.name=t,this.requester=e||u,this.resolver=i,this.online=!0,this.checkRequirements(),this.addListeners()}checkRequirements(){try{let t;void 0===j.a&&(t=j.a),this.storage=t.createInstance({name:this.name})}catch(t){throw new Error("localForage lib not loaded")}}addListeners(){this._status=this.status.bind(this),window.addEventListener("online",this._status),window.addEventListener("offline",this._status)}removeListeners(){window.removeEventListener("online",this._status),window.removeEventListener("offline",this._status),this._status=void 0}status(t){let e=navigator.onLine;this.online=e,e?this.emit("online",this):this.emit("offline",this)}add(t,e){let i=t.resources.map(t=>{let{href:i}=t,n=this.resolver(i),s=window.encodeURIComponent(n);return this.storage.getItem(s).then(t=>!t||e?this.requester(n,"binary").then(t=>this.storage.setItem(s,t)):t)});return Promise.all(i)}put(t,e,i){let n=window.encodeURIComponent(t);return this.storage.getItem(n).then(s=>s||this.requester(t,"binary",e,i).then(t=>this.storage.setItem(n,t)))}request(t,e,i,n){return this.online?this.requester(t,e,i,n).then(e=>(this.put(t),e)):this.retrieve(t,e)}retrieve(t,e){new r.defer;var i=new a.a(t);return e||(e=i.extension),("blob"==e?this.getBlob(t):this.getText(t)).then(i=>{var n,s=new r.defer;return i?(n=this.handleResponse(i,e),s.resolve(n)):s.reject({message:"File not found in storage: "+t,stack:(new Error).stack}),s.promise})}handleResponse(t,e){return"json"==e?JSON.parse(t):Object(r.isXml)(e)?Object(r.parse)(t,"text/xml"):"xhtml"==e?Object(r.parse)(t,"application/xhtml+xml"):"html"==e||"htm"==e?Object(r.parse)(t,"text/html"):t}getBlob(t,e){let i=window.encodeURIComponent(t);return this.storage.getItem(i).then((function(i){if(i)return e=e||T.lookup(t),new Blob([i],{type:e})}))}getText(t,e){let i=window.encodeURIComponent(t);return e=e||T.lookup(t),this.storage.getItem(i).then((function(t){var i,n=new r.defer,s=new FileReader;if(t)return i=new Blob([t],{type:e}),s.addEventListener("loadend",()=>{n.resolve(s.result)}),s.readAsText(i,e),n.promise}))}getBase64(t,e){let i=window.encodeURIComponent(t);return e=e||T.lookup(t),this.storage.getItem(i).then(t=>{var i,n=new r.defer,s=new FileReader;if(t)return i=new Blob([t],{type:e}),s.addEventListener("loadend",()=>{n.resolve(s.result)}),s.readAsDataURL(i,e),n.promise})}createUrl(t,e){var i,n,s=new r.defer,o=window.URL||window.webkitURL||window.mozURL,a=e&&e.base64;return t in this.urlCache?(s.resolve(this.urlCache[t]),s.promise):(a?(n=this.getBase64(t))&&n.then(function(e){this.urlCache[t]=e,s.resolve(e)}.bind(this)):(n=this.getBlob(t))&&n.then(function(e){i=o.createObjectURL(e),this.urlCache[t]=i,s.resolve(i)}.bind(this)),n||s.reject({message:"File not found in storage: "+t,stack:(new Error).stack}),s.promise)}revokeUrl(t){var e=window.URL||window.webkitURL||window.mozURL,i=this.urlCache[t];i&&e.revokeObjectURL(i)}destroy(){var t=window.URL||window.webkitURL||window.mozURL;for(let e in this.urlCache)t.revokeObjectURL(e);this.urlCache={},this.removeListeners()}}s()(D.prototype);var P=D;var M=class{constructor(t){this.interactive="",this.fixedLayout="",this.openToSpread="",this.orientationLock="",t&&this.parse(t)}parse(t){if(!t)return this;const e=Object(r.qs)(t,"display_options");if(!e)return this;return Object(r.qsa)(e,"option").forEach(t=>{let e="";switch(t.childNodes.length&&(e=t.childNodes[0].nodeValue),t.attributes.name.value){case"interactive":this.interactive=e;break;case"fixed-layout":this.fixedLayout=e;break;case"open-to-spread":this.openToSpread=e;break;case"orientation-lock":this.orientationLock=e}}),this}destroy(){this.interactive=void 0,this.fixedLayout=void 0,this.openToSpread=void 0,this.orientationLock=void 0}};const z="binary",B="base64",q="epub",F="opf",U="json",W="directory";class H{constructor(t,e){void 0===e&&"string"!=typeof t&&t instanceof Blob==!1&&t instanceof ArrayBuffer==!1&&(e=t,t=void 0),this.settings=Object(r.extend)(this.settings||{},{requestMethod:void 0,requestCredentials:void 0,requestHeaders:void 0,encoding:void 0,replacements:void 0,canonical:void 0,openAs:void 0,store:void 0}),Object(r.extend)(this.settings,e),this.opening=new r.defer,this.opened=this.opening.promise,this.isOpen=!1,this.loading={manifest:new r.defer,spine:new r.defer,metadata:new r.defer,cover:new r.defer,navigation:new r.defer,pageList:new r.defer,resources:new r.defer,displayOptions:new r.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,displayOptions:this.loading.displayOptions.promise},this.ready=Promise.all([this.loaded.manifest,this.loaded.spine,this.loaded.metadata,this.loaded.cover,this.loaded.navigation,this.loaded.resources,this.loaded.displayOptions]),this.isRendered=!1,this.request=this.settings.requestMethod||u,this.spine=new p,this.locations=new y(this.spine,this.load.bind(this)),this.navigation=void 0,this.pageList=void 0,this.url=void 0,this.path=void 0,this.archived=!1,this.archive=void 0,this.storage=void 0,this.resources=void 0,this.rendition=void 0,this.container=void 0,this.packaging=void 0,this.displayOptions=void 0,this.settings.store&&this.store(this.settings.store),t&&this.open(t,this.settings.openAs).catch(e=>{var i=new Error("Cannot load book at "+t);this.emit(m.c.BOOK.OPEN_FAILED,i)})}open(t,e){var i,n=e||this.determineType(t);return n===z?(this.archived=!0,this.url=new o.a("/",""),i=this.openEpub(t)):n===B?(this.archived=!0,this.url=new o.a("/",""),i=this.openEpub(t,n)):n===q?(this.archived=!0,this.url=new o.a("/",""),i=this.request(t,"binary",this.settings.requestCredentials,this.settings.requestHeaders).then(this.openEpub.bind(this))):n==F?(this.url=new o.a(t),i=this.openPackaging(this.url.Path.toString())):n==U?(this.url=new o.a(t),i=this.openManifest(this.url.Path.toString())):(this.url=new o.a(t),i=this.openContainer("META-INF/container.xml").then(this.openPackaging.bind(this))),i}openEpub(t,e){return this.unarchive(t,e||this.settings.encoding).then(()=>this.openContainer("META-INF/container.xml")).then(t=>this.openPackaging(t))}openContainer(t){return this.load(t).then(t=>(this.container=new x(t),this.resolve(this.container.packagePath)))}openPackaging(t){return this.path=new a.a(t),this.load(t).then(t=>(this.packaging=new E(t),this.unpack(this.packaging)))}openManifest(t){return this.path=new a.a(t),this.load(t).then(t=>(this.packaging=new E,this.packaging.load(t),this.unpack(this.packaging)))}load(t){var e=this.resolve(t);return this.archived?this.archive.request(e):this.request(e,null,this.settings.requestCredentials,this.settings.requestHeaders)}resolve(t,e){if(t){var i=t;return t.indexOf("://")>-1?t:(this.path&&(i=this.path.resolve(t)),0!=e&&this.url&&(i=this.url.resolve(i)),i)}}canonical(t){return t?this.settings.canonical?this.settings.canonical(t):this.resolve(t,!0):""}determineType(t){var e;return"base64"===this.settings.encoding?B:"string"!=typeof t?z:((e=new o.a(t).path().extension)&&(e=e.replace(/\?.*$/,"")),e?"epub"===e?q:"opf"===e?F:"json"===e?U:void 0:W)}unpack(t){this.package=t,""===this.packaging.metadata.layout?this.load(this.url.resolve("META-INF/com.apple.ibooks.display-options.xml")).then(t=>{this.displayOptions=new M(t),this.loading.displayOptions.resolve(this.displayOptions)}).catch(t=>{this.displayOptions=new M,this.loading.displayOptions.resolve(this.displayOptions)}):(this.displayOptions=new M,this.loading.displayOptions.resolve(this.displayOptions)),this.spine.unpack(this.packaging,this.resolve.bind(this),this.canonical.bind(this)),this.resources=new C(this.packaging.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.packaging).then(()=>{this.loading.navigation.resolve(this.navigation)}),this.packaging.coverPath&&(this.cover=this.resolve(this.packaging.coverPath)),this.loading.manifest.resolve(this.packaging.manifest),this.loading.metadata.resolve(this.packaging.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=!0,this.archived||this.settings.replacements&&"none"!=this.settings.replacements?this.replacements().then(()=>{this.loaded.displayOptions.then(()=>{this.opening.resolve(this)})}).catch(t=>{console.error(t)}):this.loaded.displayOptions.then(()=>{this.opening.resolve(this)})}loadNavigation(t){let e=t.navPath||t.ncxPath,i=t.toc;return i?new Promise((e,n)=>{this.navigation=new S(i),t.pageList&&(this.pageList=new O(t.pageList)),e(this.navigation)}):e?this.load(e,"xml").then(t=>(this.navigation=new S(t),this.pageList=new O(t),this.navigation)):new Promise((t,e)=>{this.navigation=new S,this.pageList=new O,t(this.navigation)})}section(t){return this.spine.get(t)}renderTo(t,e){return this.rendition=new I.a(this,e),this.rendition.attachTo(t),this.rendition}setRequestCredentials(t){this.settings.requestCredentials=t}setRequestHeaders(t){this.settings.requestHeaders=t}unarchive(t,e){return this.archive=new A,this.archive.open(t,e)}store(t){let e=this.settings.replacements&&"none"!==this.settings.replacements,i=this.url,n=this.settings.requestMethod||u.bind(this);return this.storage=new P(t,n,this.resolve.bind(this)),this.request=this.storage.request.bind(this.storage),this.opened.then(()=>{this.archived&&(this.storage.requester=this.archive.request.bind(this.archive));let t=(t,e)=>{e.output=this.resources.substitute(t,e.url)};this.resources.settings.replacements=e||"blobUrl",this.resources.replacements().then(()=>this.resources.replaceCss()),this.storage.on("offline",()=>{this.url=new o.a("/",""),this.spine.hooks.serialize.register(t)}),this.storage.on("online",()=>{this.url=i,this.spine.hooks.serialize.deregister(t)})}),this.storage}coverUrl(){return this.loaded.cover.then(()=>this.cover?this.archived?this.archive.createUrl(this.cover):this.cover:null)}replacements(){return this.spine.hooks.serialize.register((t,e)=>{e.output=this.resources.substitute(t,e.url)}),this.resources.replacements().then(()=>this.resources.replaceCss())}getRange(t){var e=new h.a(t),i=this.spine.get(e.spinePos),n=this.load.bind(this);return i?i.load(n).then((function(t){return e.toRange(i.document)})):new Promise((t,e)=>{e("CFI could not be found")})}key(t){var e=t||this.packaging.metadata.identifier||this.url.filename;return`epubjs:${m.b}:${e}`}destroy(){this.opened=void 0,this.loading=void 0,this.loaded=void 0,this.ready=void 0,this.isOpen=!1,this.isRendered=!1,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.displayOptions&&this.displayOptions.destroy(),this.spine=void 0,this.locations=void 0,this.pageList=void 0,this.archive=void 0,this.resources=void 0,this.container=void 0,this.packaging=void 0,this.rendition=void 0,this.navigation=void 0,this.url=void 0,this.path=void 0,this.archived=!1}}s()(H.prototype);e.a=H},function(t,e,i){var n=i(14).NAMESPACE;function s(t){return""!==t}function r(t,e){return t.hasOwnProperty(e)||(t[e]=!0),t}function o(t){if(!t)return[];var e=function(t){return t?t.split(/[\t\n\f\r ]+/).filter(s):[]}(t);return Object.keys(e.reduce(r,{}))}function a(t,e){for(var i in t)e[i]=t[i]}function h(t,e){var i=t.prototype;if(!(i instanceof e)){function n(){}n.prototype=e.prototype,a(i,n=new n),t.prototype=i=n}i.constructor!=t&&("function"!=typeof t&&console.error("unknown Class:"+t),i.constructor=t)}var l={},c=l.ELEMENT_NODE=1,u=l.ATTRIBUTE_NODE=2,d=l.TEXT_NODE=3,f=l.CDATA_SECTION_NODE=4,p=l.ENTITY_REFERENCE_NODE=5,g=l.ENTITY_NODE=6,m=l.PROCESSING_INSTRUCTION_NODE=7,v=l.COMMENT_NODE=8,y=l.DOCUMENT_NODE=9,b=l.DOCUMENT_TYPE_NODE=10,w=l.DOCUMENT_FRAGMENT_NODE=11,x=l.NOTATION_NODE=12,E={},S={},N=(E.INDEX_SIZE_ERR=(S[1]="Index size error",1),E.DOMSTRING_SIZE_ERR=(S[2]="DOMString size error",2),E.HIERARCHY_REQUEST_ERR=(S[3]="Hierarchy request error",3)),_=(E.WRONG_DOCUMENT_ERR=(S[4]="Wrong document",4),E.INVALID_CHARACTER_ERR=(S[5]="Invalid character",5),E.NO_DATA_ALLOWED_ERR=(S[6]="No data allowed",6),E.NO_MODIFICATION_ALLOWED_ERR=(S[7]="No modification allowed",7),E.NOT_FOUND_ERR=(S[8]="Not found",8)),T=(E.NOT_SUPPORTED_ERR=(S[9]="Not supported",9),E.INUSE_ATTRIBUTE_ERR=(S[10]="Attribute in use",10));E.INVALID_STATE_ERR=(S[11]="Invalid state",11),E.SYNTAX_ERR=(S[12]="Syntax error",12),E.INVALID_MODIFICATION_ERR=(S[13]="Invalid modification",13),E.NAMESPACE_ERR=(S[14]="Invalid namespace",14),E.INVALID_ACCESS_ERR=(S[15]="Invalid access",15);function C(t,e){if(e instanceof Error)var i=e;else i=this,Error.call(this,S[t]),this.message=S[t],Error.captureStackTrace&&Error.captureStackTrace(this,C);return i.code=t,e&&(this.message=this.message+": "+e),i}function O(){}function I(t,e){this._node=t,this._refresh=e,R(this)}function R(t){var e=t._node._inc||t._node.ownerDocument._inc;if(t._inc!=e){var i=t._refresh(t._node);at(t,"length",i.length),a(i,t),t._inc=e}}function k(){}function A(t,e){for(var i=t.length;i--;)if(t[i]===e)return i}function L(t,e,i,s){if(s?e[A(e,s)]=i:e[e.length++]=i,t){i.ownerElement=t;var r=t.ownerDocument;r&&(s&&q(r,t,s),function(t,e,i){t&&t._inc++,i.namespaceURI===n.XMLNS&&(e._nsMap[i.prefix?i.localName:""]=i.value)}(r,t,i))}}function j(t,e,i){var n=A(e,i);if(!(n>=0))throw C(_,new Error(t.tagName+"@"+i));for(var s=e.length-1;n"==t&&">")||"&"==t&&"&"||'"'==t&&"""||"&#"+t.charCodeAt()+";"}function z(t,e){if(e(t))return!0;if(t=t.firstChild)do{if(z(t,e))return!0}while(t=t.nextSibling)}function B(){}function q(t,e,i,s){t&&t._inc++,i.namespaceURI===n.XMLNS&&delete e._nsMap[i.prefix?i.localName:""]}function F(t,e,i){if(t&&t._inc){t._inc++;var n=e.childNodes;if(i)n[n.length++]=i;else{for(var s=e.firstChild,r=0;s;)n[r++]=s,s=s.nextSibling;n.length=r}}}function U(t,e){var i=e.previousSibling,n=e.nextSibling;return i?i.nextSibling=n:t.firstChild=n,n?n.previousSibling=i:t.lastChild=i,F(t.ownerDocument,t),e}function W(t,e,i){var n=e.parentNode;if(n&&n.removeChild(e),e.nodeType===w){var s=e.firstChild;if(null==s)return e;var r=e.lastChild}else s=r=e;var o=i?i.previousSibling:t.lastChild;s.previousSibling=o,r.nextSibling=i,o?o.nextSibling=s:t.firstChild=s,null==i?t.lastChild=r:i.previousSibling=r;do{s.parentNode=t}while(s!==r&&(s=s.nextSibling));return F(t.ownerDocument||t,t),e.nodeType==w&&(e.firstChild=e.lastChild=null),e}function H(){this._nsMap={}}function V(){}function X(){}function G(){}function Y(){}function $(){}function K(){}function Z(){}function J(){}function Q(){}function tt(){}function et(){}function it(){}function nt(t,e){var i=[],n=9==this.nodeType&&this.documentElement||this,s=n.prefix,r=n.namespaceURI;if(r&&null==s&&null==(s=n.lookupPrefix(r)))var o=[{namespace:r,prefix:null}];return ot(this,i,t,e,o),i.join("")}function st(t,e,i){var s=t.prefix||"",r=t.namespaceURI;if(!r)return!1;if("xml"===s&&r===n.XML||r===n.XMLNS)return!1;for(var o=i.length;o--;){var a=i[o];if(a.prefix===s)return a.namespace!==r}return!0}function rt(t,e,i){t.push(" ",e,'="',i.replace(/[<&"]/g,M),'"')}function ot(t,e,i,s,r){if(r||(r=[]),s){if(!(t=s(t)))return;if("string"==typeof t)return void e.push(t)}switch(t.nodeType){case c:var o=t.attributes,a=o.length,h=t.firstChild,l=t.tagName,g=l;if(!(i=n.isHTML(t.namespaceURI)||i)&&!t.prefix&&t.namespaceURI){for(var x,E=0;E=0;S--){if(""===(N=r[S]).prefix&&N.namespace===t.namespaceURI){x=N.namespace;break}}if(x!==t.namespaceURI)for(S=r.length-1;S>=0;S--){var N;if((N=r[S]).namespace===t.namespaceURI){N.prefix&&(g=N.prefix+":"+l);break}}}e.push("<",g);for(var _=0;_"),i&&/^script$/i.test(l))for(;h;)h.data?e.push(h.data):ot(h,e,i,s,r.slice()),h=h.nextSibling;else for(;h;)ot(h,e,i,s,r.slice()),h=h.nextSibling;e.push("")}else e.push("/>");return;case y:case w:for(h=t.firstChild;h;)ot(h,e,i,s,r.slice()),h=h.nextSibling;return;case u:return rt(e,t.name,t.value);case d:return e.push(t.data.replace(/[<&]/g,M).replace(/]]>/g,"]]>"));case f:return e.push("");case v:return e.push("\x3c!--",t.data,"--\x3e");case b:var I=t.publicId,R=t.systemId;if(e.push("");else if(R&&"."!=R)e.push(" SYSTEM ",R,">");else{var k=t.internalSubset;k&&e.push(" [",k,"]"),e.push(">")}return;case m:return e.push("");case p:return e.push("&",t.nodeName,";");default:e.push("??",t.nodeName)}}function at(t,e,i){t[e]=i}C.prototype=Error.prototype,a(E,C),O.prototype={length:0,item:function(t){return this[t]||null},toString:function(t,e){for(var i=[],n=0;n0},lookupPrefix:function(t){for(var e=this;e;){var i=e._nsMap;if(i)for(var n in i)if(i[n]==t)return n;e=e.nodeType==u?e.ownerDocument:e.parentNode}return null},lookupNamespaceURI:function(t){for(var e=this;e;){var i=e._nsMap;if(i&&t in i)return i[t];e=e.nodeType==u?e.ownerDocument:e.parentNode}return null},isDefaultNamespace:function(t){return null==this.lookupPrefix(t)}},a(l,P),a(l,P.prototype),B.prototype={nodeName:"#document",nodeType:y,doctype:null,documentElement:null,_inc:1,insertBefore:function(t,e){if(t.nodeType==w){for(var i=t.firstChild;i;){var n=i.nextSibling;this.insertBefore(i,e),i=n}return t}return null==this.documentElement&&t.nodeType==c&&(this.documentElement=t),W(this,t,e),t.ownerDocument=this,t},removeChild:function(t){return this.documentElement==t&&(this.documentElement=null),U(this,t)},importNode:function(t,e){return function t(e,i,n){var s;switch(i.nodeType){case c:(s=i.cloneNode(!1)).ownerDocument=e;case w:break;case u:n=!0}s||(s=i.cloneNode(!1));if(s.ownerDocument=e,s.parentNode=null,n)for(var r=i.firstChild;r;)s.appendChild(t(e,r,n)),r=r.nextSibling;return s}(this,t,e)},getElementById:function(t){var e=null;return z(this.documentElement,(function(i){if(i.nodeType==c&&i.getAttribute("id")==t)return e=i,!0})),e},getElementsByClassName:function(t){var e=o(t);return new I(this,(function(i){var n=[];return e.length>0&&z(i.documentElement,(function(s){if(s!==i&&s.nodeType===c){var r=s.getAttribute("class");if(r){var a=t===r;if(!a){var h=o(r);a=e.every((l=h,function(t){return l&&-1!==l.indexOf(t)}))}a&&n.push(s)}}var l})),n}))},createElement:function(t){var e=new H;return e.ownerDocument=this,e.nodeName=t,e.tagName=t,e.localName=t,e.childNodes=new O,(e.attributes=new k)._ownerElement=e,e},createDocumentFragment:function(){var t=new tt;return t.ownerDocument=this,t.childNodes=new O,t},createTextNode:function(t){var e=new G;return e.ownerDocument=this,e.appendData(t),e},createComment:function(t){var e=new Y;return e.ownerDocument=this,e.appendData(t),e},createCDATASection:function(t){var e=new $;return e.ownerDocument=this,e.appendData(t),e},createProcessingInstruction:function(t,e){var i=new et;return i.ownerDocument=this,i.tagName=i.target=t,i.nodeValue=i.data=e,i},createAttribute:function(t){var e=new V;return e.ownerDocument=this,e.name=t,e.nodeName=t,e.localName=t,e.specified=!0,e},createEntityReference:function(t){var e=new Q;return e.ownerDocument=this,e.nodeName=t,e},createElementNS:function(t,e){var i=new H,n=e.split(":"),s=i.attributes=new k;return i.childNodes=new O,i.ownerDocument=this,i.nodeName=e,i.tagName=e,i.namespaceURI=t,2==n.length?(i.prefix=n[0],i.localName=n[1]):i.localName=e,s._ownerElement=i,i},createAttributeNS:function(t,e){var i=new V,n=e.split(":");return i.ownerDocument=this,i.nodeName=e,i.name=e,i.namespaceURI=t,i.specified=!0,2==n.length?(i.prefix=n[0],i.localName=n[1]):i.localName=e,i}},h(B,P),H.prototype={nodeType:c,hasAttribute:function(t){return null!=this.getAttributeNode(t)},getAttribute:function(t){var e=this.getAttributeNode(t);return e&&e.value||""},getAttributeNode:function(t){return this.attributes.getNamedItem(t)},setAttribute:function(t,e){var i=this.ownerDocument.createAttribute(t);i.value=i.nodeValue=""+e,this.setAttributeNode(i)},removeAttribute:function(t){var e=this.getAttributeNode(t);e&&this.removeAttributeNode(e)},appendChild:function(t){return t.nodeType===w?this.insertBefore(t,null):function(t,e){var i=e.parentNode;if(i){var n=t.lastChild;i.removeChild(e);n=t.lastChild}return n=t.lastChild,e.parentNode=t,e.previousSibling=n,e.nextSibling=null,n?n.nextSibling=e:t.firstChild=e,t.lastChild=e,F(t.ownerDocument,t,e),e}(this,t)},setAttributeNode:function(t){return this.attributes.setNamedItem(t)},setAttributeNodeNS:function(t){return this.attributes.setNamedItemNS(t)},removeAttributeNode:function(t){return this.attributes.removeNamedItem(t.nodeName)},removeAttributeNS:function(t,e){var i=this.getAttributeNodeNS(t,e);i&&this.removeAttributeNode(i)},hasAttributeNS:function(t,e){return null!=this.getAttributeNodeNS(t,e)},getAttributeNS:function(t,e){var i=this.getAttributeNodeNS(t,e);return i&&i.value||""},setAttributeNS:function(t,e,i){var n=this.ownerDocument.createAttributeNS(t,e);n.value=n.nodeValue=""+i,this.setAttributeNode(n)},getAttributeNodeNS:function(t,e){return this.attributes.getNamedItemNS(t,e)},getElementsByTagName:function(t){return new I(this,(function(e){var i=[];return z(e,(function(n){n===e||n.nodeType!=c||"*"!==t&&n.tagName!=t||i.push(n)})),i}))},getElementsByTagNameNS:function(t,e){return new I(this,(function(i){var n=[];return z(i,(function(s){s===i||s.nodeType!==c||"*"!==t&&s.namespaceURI!==t||"*"!==e&&s.localName!=e||n.push(s)})),n}))}},B.prototype.getElementsByTagName=H.prototype.getElementsByTagName,B.prototype.getElementsByTagNameNS=H.prototype.getElementsByTagNameNS,h(H,P),V.prototype.nodeType=u,h(V,P),X.prototype={data:"",substringData:function(t,e){return this.data.substring(t,t+e)},appendData:function(t){t=this.data+t,this.nodeValue=this.data=t,this.length=t.length},insertData:function(t,e){this.replaceData(t,0,e)},appendChild:function(t){throw new Error(S[N])},deleteData:function(t,e){this.replaceData(t,e,"")},replaceData:function(t,e,i){i=this.data.substring(0,t)+i+this.data.substring(t+e),this.nodeValue=this.data=i,this.length=i.length}},h(X,P),G.prototype={nodeName:"#text",nodeType:d,splitText:function(t){var e=this.data,i=e.substring(t);e=e.substring(0,t),this.data=this.nodeValue=e,this.length=e.length;var n=this.ownerDocument.createTextNode(i);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}},h(G,X),Y.prototype={nodeName:"#comment",nodeType:v},h(Y,X),$.prototype={nodeName:"#cdata-section",nodeType:f},h($,X),K.prototype.nodeType=b,h(K,P),Z.prototype.nodeType=x,h(Z,P),J.prototype.nodeType=g,h(J,P),Q.prototype.nodeType=p,h(Q,P),tt.prototype.nodeName="#document-fragment",tt.prototype.nodeType=w,h(tt,P),et.prototype.nodeType=m,h(et,P),it.prototype.serializeToString=function(t,e,i){return nt.call(t,e,i)},P.prototype.toString=nt;try{if(Object.defineProperty){Object.defineProperty(I.prototype,"length",{get:function(){return R(this),this.$$length}}),Object.defineProperty(P.prototype,"textContent",{get:function(){return function t(e){switch(e.nodeType){case c:case w:var i=[];for(e=e.firstChild;e;)7!==e.nodeType&&8!==e.nodeType&&i.push(t(e)),e=e.nextSibling;return i.join("");default:return e.nodeValue}}(this)},set:function(t){switch(this.nodeType){case c:case w:for(;this.firstChild;)this.removeChild(this.firstChild);(t||String(t))&&this.appendChild(this.ownerDocument.createTextNode(t));break;default:this.data=t,this.value=t,this.nodeValue=t}}}),at=function(t,e,i){t["$$"+e]=i}}}catch(t){}e.DocumentType=K,e.DOMException=C,e.DOMImplementation=D,e.Element=H,e.Node=P,e.NodeList=O,e.XMLSerializer=it},function(t,e,i){var n=i(52),s="object"==typeof self&&self&&self.Object===Object&&self,r=n||s||Function("return this")();t.exports=r},function(t,e,i){var n=i(26).Symbol;t.exports=n},function(t,e,i){var n=i(21),s=i(19);t.exports=function(t,e,i){var r=!0,o=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return s(i)&&(r="leading"in i?!!i.leading:r,o="trailing"in i?!!i.trailing:o),n(t,e,{leading:r,maxWait:e,trailing:o})}},function(e,i){e.exports=t},function(t,e,i){"use strict";i.r(e),function(t){var n=i(24),s=i(16),r=i(2),o=i(12),a=i(0),h=i(1);i(20),i(10),i(22);function l(t,e){return new n.a(t,e)}l.VERSION=h.b,void 0!==t&&(t.EPUBJS_VERSION=h.b),l.Book=n.a,l.Rendition=s.a,l.Contents=o.a,l.CFI=r.a,l.utils=a,e.default=l}.call(this,i(17))},function(t,e,i){"use strict";var n=i(32),s=i(40),r=i(41),o=i(42);(t.exports=function(t,e){var i,r,a,h,l;return arguments.length<2||"string"!=typeof t?(h=e,e=t,t=null):h=arguments[2],null==t?(i=a=!0,r=!1):(i=o.call(t,"c"),r=o.call(t,"e"),a=o.call(t,"w")),l={value:e,configurable:i,enumerable:r,writable:a},h?n(s(h),l):l}).gs=function(t,e,i){var a,h,l,c;return"string"!=typeof t?(l=i,i=e,e=t,t=null):l=arguments[3],null==e?e=void 0:r(e)?null==i?i=void 0:r(i)||(l=i,i=void 0):(l=e,e=i=void 0),null==t?(a=!0,h=!1):(a=o.call(t,"c"),h=o.call(t,"e")),c={get:e,set:i,configurable:a,enumerable:h},l?n(s(l),c):c}},function(t,e,i){"use strict";t.exports=i(33)()?Object.assign:i(34)},function(t,e,i){"use strict";t.exports=function(){var t,e=Object.assign;return"function"==typeof e&&(e(t={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),t.foo+t.bar+t.trzy==="razdwatrzy")}},function(t,e,i){"use strict";var n=i(35),s=i(39),r=Math.max;t.exports=function(t,e){var i,o,a,h=r(arguments.length,2);for(t=Object(s(t)),a=function(n){try{t[n]=e[n]}catch(t){i||(i=t)}},o=1;o-1}},function(t,e,i){"use strict";t.exports=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}},function(t,e,i){var n=i(14),s=i(25),r=i(47),o=i(48),a=s.DOMImplementation,h=n.NAMESPACE,l=o.ParseError,c=o.XMLReader;function u(t){this.options=t||{locator:{}}}function d(){this.cdata=!1}function f(t,e){e.lineNumber=t.lineNumber,e.columnNumber=t.columnNumber}function p(t){if(t)return"\n@"+(t.systemId||"")+"#[line:"+t.lineNumber+",col:"+t.columnNumber+"]"}function g(t,e,i){return"string"==typeof t?t.substr(e,i):t.length>=e+i||e?new java.lang.String(t,e,i)+"":t}function m(t,e){t.currentElement?t.currentElement.appendChild(e):t.doc.appendChild(e)}u.prototype.parseFromString=function(t,e){var i=this.options,n=new c,s=i.domBuilder||new d,o=i.errorHandler,a=i.locator,l=i.xmlns||{},u=/\/x?html?$/.test(e),f=u?r.HTML_ENTITIES:r.XML_ENTITIES;return a&&s.setDocumentLocator(a),n.errorHandler=function(t,e,i){if(!t){if(e instanceof d)return e;t=e}var n={},s=t instanceof Function;function r(e){var r=t[e];!r&&s&&(r=2==t.length?function(i){t(e,i)}:t),n[e]=r&&function(t){r("[xmldom "+e+"]\t"+t+p(i))}||function(){}}return i=i||{},r("warning"),r("error"),r("fatalError"),n}(o,s,a),n.domBuilder=i.domBuilder||s,u&&(l[""]=h.HTML),l.xml=l.xml||h.XML,t&&"string"==typeof t?n.parse(t,l,f):n.errorHandler.error("invalid doc source"),s.doc},d.prototype={startDocument:function(){this.doc=(new a).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(t,e,i,n){var s=this.doc,r=s.createElementNS(t,i||e),o=n.length;m(this,r),this.currentElement=r,this.locator&&f(this.locator,r);for(var a=0;a",lt:"<",quot:'"'}),e.HTML_ENTITIES=n({lt:"<",gt:">",amp:"&",quot:'"',apos:"'",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",times:"×",divide:"÷",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",euro:"€",trade:"™",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"}),e.entityMap=e.HTML_ENTITIES},function(t,e,i){var n=i(14).NAMESPACE,s=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,r=new RegExp("[\\-\\.0-9"+s.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),o=new RegExp("^"+s.source+r.source+"*(?::"+s.source+r.source+"*)?$");function a(t,e){this.message=t,this.locator=e,Error.captureStackTrace&&Error.captureStackTrace(this,a)}function h(){}function l(t,e){return e.lineNumber=t.lineNumber,e.columnNumber=t.columnNumber,e}function c(t,e,i,s,r,o){function a(t,e,n){i.attributeNames.hasOwnProperty(t)&&o.fatalError("Attribute "+t+" redefined"),i.addValue(t,e,n)}for(var h,l=++e,c=0;;){var u=t.charAt(l);switch(u){case"=":if(1===c)h=t.slice(e,l),c=3;else{if(2!==c)throw new Error("attribute equal must after attrName");c=3}break;case"'":case'"':if(3===c||1===c){if(1===c&&(o.warning('attribute value must after "="'),h=t.slice(e,l)),e=l+1,!((l=t.indexOf(u,e))>0))throw new Error("attribute value no end '"+u+"' match");a(h,d=t.slice(e,l).replace(/&#?\w+;/g,r),e-1),c=5}else{if(4!=c)throw new Error('attribute value must after "="');a(h,d=t.slice(e,l).replace(/&#?\w+;/g,r),e),o.warning('attribute "'+h+'" missed start quot('+u+")!!"),e=l+1,c=5}break;case"/":switch(c){case 0:i.setTagName(t.slice(e,l));case 5:case 6:case 7:c=7,i.closed=!0;case 4:case 1:case 2:break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),0==c&&i.setTagName(t.slice(e,l)),l;case">":switch(c){case 0:i.setTagName(t.slice(e,l));case 5:case 6:case 7:break;case 4:case 1:"/"===(d=t.slice(e,l)).slice(-1)&&(i.closed=!0,d=d.slice(0,-1));case 2:2===c&&(d=h),4==c?(o.warning('attribute "'+d+'" missed quot(")!'),a(h,d.replace(/&#?\w+;/g,r),e)):(n.isHTML(s[""])&&d.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+d+'" missed value!! "'+d+'" instead!!'),a(d,d,e));break;case 3:throw new Error("attribute value missed!!")}return l;case"€":u=" ";default:if(u<=" ")switch(c){case 0:i.setTagName(t.slice(e,l)),c=6;break;case 1:h=t.slice(e,l),c=2;break;case 4:var d=t.slice(e,l).replace(/&#?\w+;/g,r);o.warning('attribute "'+d+'" missed quot(")!!'),a(h,d,e);case 5:c=6}else switch(c){case 2:i.tagName;n.isHTML(s[""])&&h.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+h+'" missed value!! "'+h+'" instead2!!'),a(h,h,e),e=l,c=1;break;case 5:o.warning('attribute space is required"'+h+'"!!');case 6:c=1,e=l;break;case 3:c=4,e=l;break;case 7:throw new Error("elements closed character '/' and '>' must be connected to")}}l++}}function u(t,e,i){for(var s=t.tagName,r=null,o=t.length;o--;){var a=t[o],h=a.qName,l=a.value;if((f=h.indexOf(":"))>0)var c=a.prefix=h.slice(0,f),u=h.slice(f+1),d="xmlns"===c&&u;else u=h,c=null,d="xmlns"===h&&"";a.localName=u,!1!==d&&(null==r&&(r={},p(i,i={})),i[d]=r[d]=l,a.uri=n.XMLNS,e.startPrefixMapping(d,l))}for(o=t.length;o--;){(c=(a=t[o]).prefix)&&("xml"===c&&(a.uri=n.XML),"xmlns"!==c&&(a.uri=i[c||""]))}var f;(f=s.indexOf(":"))>0?(c=t.prefix=s.slice(0,f),u=t.localName=s.slice(f+1)):(c=null,u=t.localName=s);var g=t.uri=i[c||""];if(e.startElement(g,u,s,t),!t.closed)return t.currentNSMap=i,t.localNSMap=r,!0;if(e.endElement(g,u,s),r)for(c in r)e.endPrefixMapping(c)}function d(t,e,i,n,s){if(/^(?:script|textarea)$/i.test(i)){var r=t.indexOf("",e),o=t.substring(e+1,r);if(/[&<]/.test(o))return/^script$/i.test(i)?(s.characters(o,0,o.length),r):(o=o.replace(/&#?\w+;/g,n),s.characters(o,0,o.length),r)}return e+1}function f(t,e,i,n){var s=n[i];return null==s&&((s=t.lastIndexOf(""))e?(i.comment(t,e+4,s-e-4),s+3):(n.error("Unclosed comment"),-1):-1;default:if("CDATA["==t.substr(e+3,6)){var s=t.indexOf("]]>",e+9);return i.startCDATA(),i.characters(t,e+9,s-e-9),i.endCDATA(),s+3}var r=function(t,e){var i,n=[],s=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;s.lastIndex=e,s.exec(t);for(;i=s.exec(t);)if(n.push(i),i[1])return n}(t,e),o=r.length;if(o>1&&/!doctype/i.test(r[0][0])){var a=r[1][0],h=!1,l=!1;o>3&&(/^public$/i.test(r[2][0])?(h=r[3][0],l=o>4&&r[4][0]):/^system$/i.test(r[2][0])&&(l=r[3][0]));var c=r[o-1];return i.startDTD(a,h,l),i.endDTD(),c.index+c[0].length}}return-1}function m(t,e,i){var n=t.indexOf("?>",e);if(n){var s=t.substring(e,n).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(s){s[0].length;return i.processingInstruction(s[1],s[2]),n+2}return-1}return-1}function v(){this.attributeNames={}}a.prototype=new Error,a.prototype.name=a.name,h.prototype={parse:function(t,e,i){var s=this.domBuilder;s.startDocument(),p(e,e={}),function(t,e,i,s,r){function o(t){var e=t.slice(1,-1);return e in i?i[e]:"#"===e.charAt(0)?function(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}(parseInt(e.substr(1).replace("x","0x"))):(r.error("entity not found:"+t),t)}function h(e){if(e>N){var i=t.substring(N,e).replace(/&#?\w+;/g,o);x&&p(N),s.characters(i,0,e-N),N=e}}function p(e,i){for(;e>=b&&(i=w.exec(t));)y=i.index,b=y+i[0].length,x.lineNumber++;x.columnNumber=e-y+1}var y=0,b=0,w=/.*(?:\r\n?|\n)|.*$/g,x=s.locator,E=[{currentNSMap:e}],S={},N=0;for(;;){try{var _=t.indexOf("<",N);if(_<0){if(!t.substr(N).match(/^\s*$/)){var T=s.doc,C=T.createTextNode(t.substr(N));T.appendChild(C),s.currentElement=C}return}switch(_>N&&h(_),t.charAt(_+1)){case"/":var O=t.indexOf(">",_+3),I=t.substring(_+2,O).replace(/[ \t\n\r]+$/g,""),R=E.pop();O<0?(I=t.substring(_+2).replace(/[\s<].*/,""),r.error("end tag name: "+I+" is not complete:"+R.tagName),O=_+1+I.length):I.match(/\sN?N=O:h(Math.max(_,N)+1)}}(t,e,i,s,this.errorHandler),s.endDocument()}},v.prototype={setTagName:function(t){if(!o.test(t))throw new Error("invalid tagName:"+t);this.tagName=t},addValue:function(t,e,i){if(!o.test(t))throw new Error("invalid attribute:"+t);this.attributeNames[t]=this.length,this[this.length++]={qName:t,value:e,offset:i}},length:0,getLocalName:function(t){return this[t].localName},getLocator:function(t){return this[t].locator},getQName:function(t){return this[t].qName},getURI:function(t){return this[t].uri},getValue:function(t){return this[t].value}},e.XMLReader=h,e.ParseError=a},function(t,e,i){"use strict";function n(t){return document.createElementNS("http://www.w3.org/2000/svg",t)}Object.defineProperty(e,"__esModule",{value:!0}),e.createElement=n,e.default={createElement:n}},function(t,e,i){"use strict";function n(t,e){function i(i){for(var n=e.length-1;n>=0;n--){var o=e[n],a=i.clientX,h=i.clientY;if(i.touches&&i.touches.length&&(a=i.touches[0].clientX,h=i.touches[0].clientY),r(o,t,a,h)){o.dispatchEvent(s(i));break}}}if("iframe"===t.nodeName||"IFRAME"===t.nodeName)try{this.target=t.contentDocument}catch(e){this.target=t}else this.target=t;for(var n=["mouseup","mousedown","click","touchstart"],o=0;oi&&a>e}if(!r(t.getBoundingClientRect(),i,n))return!1;for(var o=t.getClientRects(),a=0,h=o.length;a