From e1937f3c7c1d5b4bc647a1272d83bb6719a9db29 Mon Sep 17 00:00:00 2001 From: j Date: Mon, 28 Jan 2019 23:25:51 +0530 Subject: [PATCH] update epub.js, layout fixes --- epub.js/js/epub.js | 9254 +++++++++++++++++++++++++++++++++------- epub.js/js/epub.min.js | 2 +- 2 files changed, 7808 insertions(+), 1448 deletions(-) diff --git a/epub.js/js/epub.js b/epub.js/js/epub.js index 87ce87a..646e339 100644 --- a/epub.js/js/epub.js +++ b/epub.js/js/epub.js @@ -7,7 +7,7 @@ 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__) { +})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_42__, __WEBPACK_EXTERNAL_MODULE_72__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; @@ -99,6 +99,7 @@ exports.locationOf = locationOf; exports.indexOfSorted = indexOfSorted; exports.bounds = bounds; exports.borders = borders; +exports.nodeBounds = nodeBounds; exports.windowBounds = windowBounds; exports.indexOfNode = indexOfNode; exports.indexOfTextNode = indexOfTextNode; @@ -170,6 +171,7 @@ function documentHeight() { /** * Checks if a node is an element + * @param {object} obj * @returns {boolean} * @memberof Core */ @@ -178,6 +180,7 @@ function isElement(obj) { } /** + * @param {any} n * @returns {boolean} * @memberof Core */ @@ -186,16 +189,27 @@ function isNumber(n) { } /** + * @param {any} n * @returns {boolean} * @memberof Core */ function isFloat(n) { var f = parseFloat(n); - return f === n && isNumber(n) && Math.floor(f) !== n; + + if (isNumber(n) === false) { + return false; + } + + if (typeof n === "string" && n.indexOf(".") > -1) { + return true; + } + + return Math.floor(f) !== f; } /** * Get a prefixed css property + * @param {string} unprefixed * @returns {string} * @memberof Core */ @@ -407,6 +421,26 @@ function borders(el) { }; } +/** + * Find the bounds of any node + * allows for getting bounds of text nodes by wrapping them in a range + * @param {node} node + * @returns {BoundingClientRect} + * @memberof Core + */ +function nodeBounds(node) { + var elPos = void 0; + var doc = node.ownerDocument; + if (node.nodeType == Node.TEXT_NODE) { + var elRange = doc.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + } else { + elPos = node.getBoundingClientRect(); + } + return elPos; +} + /** * Find the equivelent of getBoundingClientRect of a browser window * @returns {{ width: Number, height: Number, top: Number, left: Number, right: Number, bottom: Number }} @@ -429,7 +463,9 @@ function windowBounds() { /** * Gets the index of a node in its parent - * @private + * @param {Node} node + * @param {string} typeId + * @return {number} index * @memberof Core */ function indexOfNode(node, typeId) { @@ -560,7 +596,7 @@ function parse(markup, mime, forceXMLDom) { var Parser; if (typeof DOMParser === "undefined" || forceXMLDom) { - Parser = __webpack_require__(16).DOMParser; + Parser = __webpack_require__(42).DOMParser; } else { Parser = DOMParser; } @@ -619,7 +655,7 @@ function qsa(el, sel) { * querySelector by property * @param {element} el * @param {string} sel selector string - * @param {props[]} props + * @param {object[]} props * @returns {element[]} elements * @memberof Core */ @@ -669,6 +705,13 @@ function sprint(root, func) { } } +/** + * Create a treeWalker + * @memberof Core + * @param {element} root element to start with + * @param {function} func function to run on each element + * @param {function | object} filter funtion or object to filter with + */ function treeWalker(root, func, filter) { var treeWalker = document.createTreeWalker(root, filter, null, false); var node = void 0; @@ -1066,12 +1109,12 @@ var EpubCFI = function () { 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")) { + } else if (cfi && (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") { + } else if (cfi && (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) { + } else if (cfi && (typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && cfi instanceof EpubCFI) { return "EpubCFI"; } else { return false; @@ -1330,7 +1373,7 @@ var EpubCFI = function () { /** * Compare which of two CFIs is earlier in the text - * @returns {number} First is earlier = 1, Second is earlier = -1, They are equal = 0 + * @returns {number} First is earlier = -1, Second is earlier = 1, They are equal = 0 */ }, { @@ -2063,6 +2106,78 @@ module.exports = exports["default"]; "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var EPUBJS_VERSION = exports.EPUBJS_VERSION = "0.3"; + +// Dom events to listen for +var DOM_EVENTS = exports.DOM_EVENTS = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart", "touchmove"]; + +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", + REMOVED: "removed" + }, + 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" + }, + ANNOTATION: { + ATTACH: "attach", + DETACH: "detach" + } +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + var d = __webpack_require__(27) , callable = __webpack_require__(41) @@ -2195,71 +2310,6 @@ module.exports = exports = function (o) { 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__) { @@ -2273,7 +2323,7 @@ Object.defineProperty(exports, "__esModule", { 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 _pathWebpack = __webpack_require__(7); var _pathWebpack2 = _interopRequireDefault(_pathWebpack); @@ -2375,6 +2425,12 @@ var Path = function () { }, { key: "relative", value: function relative(what) { + var isAbsolute = what && what.indexOf("://") > -1; + + if (isAbsolute) { + return what; + } + return _pathWebpack2.default.relative(this.directory, what); } }, { @@ -2403,6 +2459,33 @@ module.exports = exports["default"]; /***/ }), /* 5 */ +/***/ (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; + + +/***/ }), +/* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2418,7 +2501,7 @@ var _path = __webpack_require__(4); var _path2 = _interopRequireDefault(_path); -var _pathWebpack = __webpack_require__(6); +var _pathWebpack = __webpack_require__(7); var _pathWebpack2 = _interopRequireDefault(_pathWebpack); @@ -2501,6 +2584,7 @@ var Url = function () { /** * Resolves a relative path to a absolute url + * @param {string} what * @returns {string} url */ @@ -2520,6 +2604,7 @@ var Url = function () { /** * Resolve a path relative to the url + * @param {string} what * @returns {string} path */ @@ -2547,7 +2632,7 @@ exports.default = Url; module.exports = exports["default"]; /***/ }), -/* 6 */ +/* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -3108,7 +3193,7 @@ module.exports = posix; /***/ }), -/* 7 */ +/* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -3125,7 +3210,7 @@ exports.substitute = substitute; var _core = __webpack_require__(0); -var _url = __webpack_require__(5); +var _url = __webpack_require__(6); var _url2 = _interopRequireDefault(_url); @@ -3223,12 +3308,18 @@ function replaceLinks(contents, fn) { } var absolute = href.indexOf("://") > -1; - var linkUrl = new _url2.default(href, location); if (absolute) { link.setAttribute("target", "_blank"); } else { + var linkUrl; + try { + linkUrl = new _url2.default(href, location); + } catch (error) { + // NOOP + } + link.onclick = function () { if (linkUrl && linkUrl.hash) { @@ -3258,33 +3349,6 @@ function substitute(content, urls, replacements) { 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__) { @@ -3292,116 +3356,6 @@ module.exports = g; "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 }); @@ -3492,7 +3446,7 @@ function request(url, type, withCredentials, headers) { responseXML = this.responseXML; } - if (this.status === 200 || responseXML) { + if (this.status === 200 || this.status === 0 || responseXML) { //-- Firefox is reporting 0 for blob urls var r; @@ -3556,6 +3510,134 @@ function request(url, type, withCredentials, headers) { exports.default = request; module.exports = exports["default"]; +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _undefined = __webpack_require__(34)(); // Support ES3 engines + +module.exports = function (val) { + return (val !== _undefined) && (val !== null); +}; + + +/***/ }), +/* 11 */ +/***/ (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]); + } + } + } + } + + /** + * Removes a function + * @example this.content.deregister(function(){...}); + */ + + }, { + key: "deregister", + value: function deregister(func) { + var hook = void 0; + for (var i = 0; i < this.hooks.length; i++) { + hook = this.hooks[i]; + if (hook === func) { + this.hooks.splice(i, 1); + break; + } + } + } + + /** + * 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"]; + /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { @@ -3765,7 +3847,7 @@ var Queue = function () { /** * Get the number of tasks in the queue - * @return {int} tasks + * @return {number} tasks */ }, { @@ -3846,13 +3928,196 @@ exports.Task = Task; "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 +}; + +/***/ }), +/* 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 _eventEmitter = __webpack_require__(3); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); @@ -3866,16 +4131,18 @@ var _mapping = __webpack_require__(19); var _mapping2 = _interopRequireDefault(_mapping); -var _replacements = __webpack_require__(7); +var _replacements = __webpack_require__(8); -var _constants = __webpack_require__(3); +var _constants = __webpack_require__(2); 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 hasNavigator = typeof navigator !== "undefined"; + +var isChrome = hasNavigator && /Chrome/.test(navigator.userAgent); +var isWebkit = hasNavigator && !isChrome && /AppleWebKit/.test(navigator.userAgent); var ELEMENT_NODE = 1; var TEXT_NODE = 3; @@ -3909,7 +4176,7 @@ var Contents = function () { this.sectionIndex = sectionIndex || 0; this.cfiBase = cfiBase || ""; - this.epubReadingSystem("epub.js", ePub.VERSION); + this.epubReadingSystem("epub.js", _constants.EPUBJS_VERSION); this.listeners(); } @@ -4022,6 +4289,7 @@ var Contents = function () { }, { key: "textWidth", value: function textWidth() { + var rect = void 0; var width = void 0; var range = this.document.createRange(); var content = this.content || this.document.body; @@ -4031,7 +4299,8 @@ var Contents = function () { range.selectNodeContents(content); // get the width of the text content - width = range.getBoundingClientRect().width; + rect = range.getBoundingClientRect(); + width = rect.width; if (border && border.width) { width += border.width; @@ -4048,6 +4317,7 @@ var Contents = function () { }, { key: "textHeight", value: function textHeight() { + var rect = void 0; var height = void 0; var range = this.document.createRange(); var content = this.content || this.document.body; @@ -4055,12 +4325,17 @@ var Contents = function () { range.selectNodeContents(content); - height = range.getBoundingClientRect().height; + rect = range.getBoundingClientRect(); + height = rect.height; if (height && border.height) { height += border.height; } + if (height && rect.top) { + height += rect.top; + } + return Math.round(height); } @@ -4358,7 +4633,6 @@ var Contents = function () { clearTimeout(this.expanding); requestAnimationFrame(this.resizeCheck.bind(this)); - this.expanding = setTimeout(this.resizeListeners.bind(this), 350); } @@ -4377,7 +4651,8 @@ var Contents = function () { body.style['transitionTimingFunction'] = "linear"; body.style['transitionDelay'] = "0"; - this.document.addEventListener('transitionend', this.resizeCheck.bind(this)); + this._resizeCheck = this.resizeCheck.bind(this); + this.document.addEventListener('transitionend', this._resizeCheck); } /** @@ -4437,9 +4712,15 @@ var Contents = function () { // pass in the target node, as well as the observer options this.observer.observe(this.document, config); } + + /** + * Test if images are loaded or add listener for when they load + * @private + */ + }, { key: "imageLoadListeners", - value: function imageLoadListeners(target) { + value: function imageLoadListeners() { var images = this.document.querySelectorAll("img"); var img; for (var i = 0; i < images.length; i++) { @@ -4458,7 +4739,7 @@ var Contents = function () { }, { key: "fontLoadListeners", - value: function fontLoadListeners(target) { + value: function fontLoadListeners() { if (!this.document || !this.document.fonts) { return; } @@ -4538,9 +4819,15 @@ var Contents = function () { var id = target.substring(target.indexOf("#") + 1); var el = this.document.getElementById(id); - if (el) { - position = el.getBoundingClientRect(); + if (isWebkit) { + // Webkit reports incorrect bounding rects in Columns + var _newRange = new Range(); + _newRange.selectNode(el); + position = _newRange.getBoundingClientRect(); + } else { + position = el.getBoundingClientRect(); + } } } @@ -4752,8 +5039,10 @@ var Contents = function () { return; } + this._triggerEvent = this.triggerEvent.bind(this); + _constants.DOM_EVENTS.forEach(function (eventName) { - this.document.addEventListener(eventName, this.triggerEvent.bind(this), false); + this.document.addEventListener(eventName, this._triggerEvent, { passive: true }); }, this); } @@ -4769,8 +5058,9 @@ var Contents = function () { return; } _constants.DOM_EVENTS.forEach(function (eventName) { - this.document.removeEventListener(eventName, this.triggerEvent, false); + this.document.removeEventListener(eventName, this._triggerEvent, { passive: true }); }, this); + this._triggerEvent = undefined; } /** @@ -4795,7 +5085,8 @@ var Contents = function () { if (!this.document) { return; } - this.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); + this._onSelectionChange = this.onSelectionChange.bind(this); + this.document.addEventListener("selectionchange", this._onSelectionChange, { passive: true }); } /** @@ -4809,7 +5100,8 @@ var Contents = function () { if (!this.document) { return; } - this.document.removeEventListener("selectionchange", this.onSelectionChange, false); + this.document.removeEventListener("selectionchange", this._onSelectionChange, { passive: true }); + this._onSelectionChange = undefined; } /** @@ -4915,7 +5207,7 @@ var Contents = function () { if (width >= 0) { this.width(width); viewport.width = width; - this.css("padding", "0 " + width / 12 + "px", true); + this.css("padding", "0 " + width / 12 + "px"); } if (height >= 0) { @@ -4969,9 +5261,15 @@ var Contents = function () { this.css("margin", "0", true); if (axis === "vertical") { - this.css("padding", gap / 2 + "px 20px", true); + this.css("padding-top", gap / 2 + "px", true); + this.css("padding-bottom", gap / 2 + "px", true); + this.css("padding-left", "20px"); + this.css("padding-right", "20px"); } else { - this.css("padding", "20px " + gap / 2 + "px", true); + this.css("padding-top", "20px"); + this.css("padding-bottom", "20px"); + this.css("padding-left", gap / 2 + "px", true); + this.css("padding-right", gap / 2 + "px", true); } this.css("box-sizing", "border-box"); @@ -5016,20 +5314,32 @@ var Contents = function () { key: "fit", value: function fit(width, height) { var viewport = this.viewport(); - var widthScale = width / parseInt(viewport.width); - var heightScale = height / parseInt(viewport.height); + var viewportWidth = parseInt(viewport.width); + var viewportHeight = parseInt(viewport.height); + var widthScale = width / viewportWidth; + var heightScale = height / viewportHeight; var scale = widthScale < heightScale ? widthScale : heightScale; - var offsetY = (height - viewport.height * scale) / 2; + // the translate does not work as intended, elements can end up unaligned + // var offsetY = (height - (viewportHeight * scale)) / 2; + // var offsetX = 0; + // if (this.sectionIndex % 2 === 1) { + // offsetX = width - (viewportWidth * scale); + // } this.layoutStyle("paginated"); - this.width(width); - this.height(height); + // scale needs width and height to be set + this.width(viewportWidth); + this.height(viewportHeight); this.overflow("hidden"); // Scale to the correct size - this.scaler(scale, 0, offsetY); + this.scaler(scale, 0, 0); + // this.scaler(scale, offsetX > 0 ? offsetX : 0, offsetY); + + // background images are not scaled by transform + this.css("background-size", viewportWidth * scale + "px " + viewportHeight * scale + "px"); this.css("background-color", "transparent"); } @@ -5147,7 +5457,7 @@ var Contents = function () { this.observer.disconnect(); } - this.document.removeEventListener('transitionend', this.resizeCheck); + this.document.removeEventListener('transitionend', this._resizeCheck); this.removeListeners(); } @@ -5167,7 +5477,7 @@ exports.default = Contents; module.exports = exports["default"]; /***/ }), -/* 14 */ +/* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -5179,7 +5489,7 @@ Object.defineProperty(exports, "__esModule", { 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 _eventEmitter = __webpack_require__(3); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); @@ -5193,15 +5503,15 @@ var _queue = __webpack_require__(12); var _queue2 = _interopRequireDefault(_queue); -var _stage = __webpack_require__(56); +var _stage = __webpack_require__(59); var _stage2 = _interopRequireDefault(_stage); -var _views = __webpack_require__(66); +var _views = __webpack_require__(69); var _views2 = _interopRequireDefault(_views); -var _constants = __webpack_require__(3); +var _constants = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -5212,6 +5522,7 @@ var DefaultViewManager = function () { _classCallCheck(this, DefaultViewManager); this.name = "default"; + this.optsSettings = options.settings; this.View = options.view; this.request = options.request; this.renditionQueue = options.queue; @@ -5224,7 +5535,8 @@ var DefaultViewManager = function () { height: undefined, axis: undefined, flow: "scrolled", - ignoreClass: "" + ignoreClass: "", + fullsize: undefined }); (0, _core.extend)(this.settings, options.settings || {}); @@ -5248,11 +5560,11 @@ var DefaultViewManager = function () { value: function render(element, size) { var tag = element.tagName; - if (tag && (tag.toLowerCase() == "body" || tag.toLowerCase() == "html")) { - this.fullsize = true; + if (typeof this.settings.fullsize === "undefined" && tag && (tag.toLowerCase() == "body" || tag.toLowerCase() == "html")) { + this.settings.fullsize = true; } - if (this.fullsize) { + if (this.settings.fullsize) { this.settings.overflow = "visible"; this.overflow = this.settings.overflow; } @@ -5266,7 +5578,7 @@ var DefaultViewManager = function () { overflow: this.overflow, hidden: this.settings.hidden, axis: this.settings.axis, - fullsize: this.fullsize, + fullsize: this.settings.fullsize, direction: this.settings.direction }); @@ -5312,26 +5624,28 @@ var DefaultViewManager = function () { this.destroy(); }.bind(this)); - if (!this.fullsize) { + if (!this.settings.fullsize) { scroller = this.container; } else { scroller = window; } - scroller.addEventListener("scroll", this.onScroll.bind(this)); + this._onScroll = this.onScroll.bind(this); + scroller.addEventListener("scroll", this._onScroll); } }, { key: "removeEventListeners", value: function removeEventListeners() { var scroller; - if (!this.fullsize) { + if (!this.settings.fullsize) { scroller = this.container; } else { scroller = window; } - scroller.removeEventListener("scroll", this.onScroll.bind(this)); + scroller.removeEventListener("scroll", this._onScroll); + this._onScroll = undefined; } }, { key: "destroy", @@ -5364,7 +5678,9 @@ var DefaultViewManager = function () { orientation = _window.orientation; - this.resize(); + if (this.optsSettings.resizeOnOrientationChange) { + this.resize(); + } // Per ampproject: // In IOS 10.3, the measured size of an element is incorrect if the @@ -5374,7 +5690,11 @@ var DefaultViewManager = function () { clearTimeout(this.orientationTimeout); this.orientationTimeout = setTimeout(function () { this.orientationTimeout = undefined; - this.resize(); + + if (this.optsSettings.resizeOnOrientationChange) { + this.resize(); + } + this.emit(_constants.EVENTS.MANAGERS.ORIENTATION_CHANGE, orientation); }.bind(this), 500); } @@ -5474,7 +5794,8 @@ var DefaultViewManager = function () { displaying.reject(err); }).then(function () { var next; - if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) { + if (this.layout.name === "pre-paginated" && this.layout.divisor > 1 && section.index > 0) { + // First page (cover) should stand alone for pre-paginated books next = section.next(); if (next) { return this.add(next); @@ -5658,7 +5979,7 @@ var DefaultViewManager = function () { } } }.bind(this), function (err) { - displaying.reject(err); + return err; }).then(function () { this.views.show(); }.bind(this)); @@ -5723,7 +6044,7 @@ var DefaultViewManager = function () { } } }.bind(this), function (err) { - displaying.reject(err); + return err; }).then(function () { if (this.isPaginated && this.settings.axis === "horizontal") { if (this.settings.direction === "rtl") { @@ -5781,7 +6102,7 @@ var DefaultViewManager = function () { var offset = 0; var used = 0; - if (this.fullsize) { + if (this.settings.fullsize) { offset = window.scrollY; } @@ -5836,7 +6157,7 @@ var DefaultViewManager = function () { var left = 0; var used = 0; - if (this.fullsize) { + if (this.settings.fullsize) { left = window.scrollX; } @@ -5942,7 +6263,7 @@ var DefaultViewManager = function () { this.ignore = true; } - if (!this.fullsize) { + if (!this.settings.fullsize) { if (x) this.container.scrollLeft += x * dir; if (y) this.container.scrollTop += y; } else { @@ -5957,7 +6278,7 @@ var DefaultViewManager = function () { this.ignore = true; } - if (!this.fullsize) { + if (!this.settings.fullsize) { this.container.scrollLeft = x; this.container.scrollTop = y; } else { @@ -5971,7 +6292,7 @@ var DefaultViewManager = function () { var scrollTop = void 0; var scrollLeft = void 0; - if (!this.fullsize) { + if (!this.settings.fullsize) { scrollTop = this.container.scrollTop; scrollLeft = this.container.scrollLeft; } else { @@ -6093,24 +6414,27 @@ var DefaultViewManager = function () { }, { key: "updateFlow", value: function updateFlow(flow) { + var defaultScrolledOverflow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "auto"; + var isPaginated = flow === "paginated" || flow === "auto"; this.isPaginated = isPaginated; if (flow === "scrolled-doc" || flow === "scrolled-continuous" || flow === "scrolled") { this.updateAxis("vertical"); + } else { + this.updateAxis("horizontal"); } this.viewSettings.flow = flow; if (!this.settings.overflow) { - this.overflow = isPaginated ? "hidden" : "auto"; + this.overflow = isPaginated ? "hidden" : defaultScrolledOverflow; } else { this.overflow = this.settings.overflow; } - // this.views.forEach(function(view){ - // view.setAxis(axis); - // }); + + this.stage && this.stage.overflow(this.overflow); this.updateLayout(); } @@ -6161,7 +6485,7 @@ exports.default = DefaultViewManager; module.exports = exports["default"]; /***/ }), -/* 15 */ +/* 16 */ /***/ (function(module, exports) { /** @@ -6198,193 +6522,1254 @@ module.exports = isObject; /***/ }), -/* 16 */ +/* 17 */ /***/ (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 + * DOM Level 2 + * Object DOMException + * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html */ -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" +function copy(src,dest){ + for(var p in src){ + dest[p] = src[p]; + } +} +/** +^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? +^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? + */ +function _extends(Class,Super){ + var pt = Class.prototype; + if(Object.create){ + var ppt = Object.create(Super.prototype) + pt.__proto__ = ppt; + } + if(!(pt instanceof Super)){ + function t(){}; + t.prototype = Super.prototype; + t = new t(); + copy(pt,t); + Class.prototype = pt = t; + } + if(pt.constructor != Class){ + if(typeof Class != 'function'){ + console.error("unknow Class:"+Class) + } + pt.constructor = Class + } +} +var htmlns = 'http://www.w3.org/1999/xhtml' ; +// Node Types +var NodeType = {} +var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; +var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; +var TEXT_NODE = NodeType.TEXT_NODE = 3; +var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; +var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; +var ENTITY_NODE = NodeType.ENTITY_NODE = 6; +var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; +var COMMENT_NODE = NodeType.COMMENT_NODE = 8; +var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; +var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; +var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; +var NOTATION_NODE = NodeType.NOTATION_NODE = 12; + +// ExceptionCode +var ExceptionCode = {} +var ExceptionMessage = {}; +var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); +var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); +var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); +var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); +var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); +var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); +var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); +var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); +var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); +var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); +//level2 +var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); +var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); +var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); +var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); +var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); + + +function DOMException(code, message) { + if(message instanceof Error){ + var error = message; + }else{ + error = this; + Error.call(this, ExceptionMessage[code]); + this.message = ExceptionMessage[code]; + if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); + } + error.code = code; + if(message) this.message = this.message + ": " + message; + return error; +}; +DOMException.prototype = Error.prototype; +copy(ExceptionCode,DOMException) +/** + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 + * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. + * The items in the NodeList are accessible via an integral index, starting from 0. + */ +function NodeList() { +}; +NodeList.prototype = { + /** + * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. + * @standard level1 + */ + length:0, + /** + * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. + * @standard level1 + * @param index unsigned long + * Index into the collection. + * @return Node + * The node at the indexth position in the NodeList, or null if that is not a valid index. + */ + item: function(index) { + return this[index] || null; }, - "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"] + toString:function(isHTML,nodeFilter){ + for(var buf = [], i = 0;i=0){ + var lastIndex = list.length-1 + while(i0 || key == 'xmlns'){ +// return null; +// } + //console.log() + var i = this.length; + while(i--){ + var attr = this[i]; + //console.log(attr.nodeName,key) + if(attr.nodeName == key){ + return attr; + } + } }, - "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" + setNamedItem: function(attr) { + var el = attr.ownerElement; + if(el && el!=this._ownerElement){ + throw new DOMException(INUSE_ATTRIBUTE_ERR); + } + var oldAttr = this.getNamedItem(attr.nodeName); + _addNamedNode(this._ownerElement,this,attr,oldAttr); + return oldAttr; }, - "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" + /* returns Node */ + setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR + var el = attr.ownerElement, oldAttr; + if(el && el!=this._ownerElement){ + throw new DOMException(INUSE_ATTRIBUTE_ERR); + } + oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); + _addNamedNode(this._ownerElement,this,attr,oldAttr); + return oldAttr; }, - "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" + + /* returns Node */ + removeNamedItem: function(key) { + var attr = this.getNamedItem(key); + _removeNamedNode(this._ownerElement,this,attr); + return attr; + + + },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR + + //for level2 + removeNamedItemNS:function(namespaceURI,localName){ + var attr = this.getNamedItemNS(namespaceURI,localName); + _removeNamedNode(this._ownerElement,this,attr); + return attr; + }, + getNamedItemNS: function(namespaceURI, localName) { + var i = this.length; + while(i--){ + var node = this[i]; + if(node.localName == localName && node.namespaceURI == namespaceURI){ + return node; + } + } + return null; + } +}; +/** + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 + */ +function DOMImplementation(/* Object */ features) { + this._features = {}; + if (features) { + for (var feature in features) { + this._features = features[feature]; + } } }; -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; - } - } +DOMImplementation.prototype = { + hasFeature: function(/* string */ feature, /* string */ version) { + var versions = this._features[feature.toLowerCase()]; + if (versions && (!version || version in versions)) { + return true; + } else { + return false; + } + }, + // Introduced in DOM Level 2: + createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR + var doc = new Document(); + doc.implementation = this; + doc.childNodes = new NodeList(); + doc.doctype = doctype; + if(doctype){ + doc.appendChild(doctype); + } + if(qualifiedName){ + var root = doc.createElementNS(namespaceURI,qualifiedName); + doc.appendChild(root); + } + return doc; + }, + // Introduced in DOM Level 2: + createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR + var node = new DocumentType(); + node.name = qualifiedName; + node.nodeName = qualifiedName; + node.publicId = publicId; + node.systemId = systemId; + // Introduced in DOM Level 2: + //readonly attribute DOMString internalSubset; + + //TODO:.. + // readonly attribute NamedNodeMap entities; + // readonly attribute NamedNodeMap notations; + return node; + } +}; + + +/** + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 + */ + +function Node() { +}; + +Node.prototype = { + firstChild : null, + lastChild : null, + previousSibling : null, + nextSibling : null, + attributes : null, + parentNode : null, + childNodes : null, + ownerDocument : null, + nodeValue : null, + namespaceURI : null, + prefix : null, + localName : null, + // Modified in DOM Level 2: + insertBefore:function(newChild, refChild){//raises + return _insertBefore(this,newChild,refChild); + }, + replaceChild:function(newChild, oldChild){//raises + this.insertBefore(newChild,oldChild); + if(oldChild){ + this.removeChild(oldChild); + } + }, + removeChild:function(oldChild){ + return _removeChild(this,oldChild); + }, + appendChild:function(newChild){ + return this.insertBefore(newChild,null); + }, + hasChildNodes:function(){ + return this.firstChild != null; + }, + cloneNode:function(deep){ + return cloneNode(this.ownerDocument||this,this,deep); + }, + // Modified in DOM Level 2: + normalize:function(){ + var child = this.firstChild; + while(child){ + var next = child.nextSibling; + if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ + this.removeChild(next); + child.appendData(next.data); + }else{ + child.normalize(); + child = next; + } + } + }, + // Introduced in DOM Level 2: + isSupported:function(feature, version){ + return this.ownerDocument.implementation.hasFeature(feature,version); + }, + // Introduced in DOM Level 2: + hasAttributes:function(){ + return this.attributes.length>0; + }, + lookupPrefix:function(namespaceURI){ + var el = this; + while(el){ + var map = el._nsMap; + //console.dir(map) + if(map){ + for(var n in map){ + if(map[n] == namespaceURI){ + return n; + } + } + } + el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; + } + return null; + }, + // Introduced in DOM Level 3: + lookupNamespaceURI:function(prefix){ + var el = this; + while(el){ + var map = el._nsMap; + //console.dir(map) + if(map){ + if(prefix in map){ + return map[prefix] ; + } + } + el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; + } + return null; + }, + // Introduced in DOM Level 3: + isDefaultNamespace:function(namespaceURI){ + var prefix = this.lookupPrefix(namespaceURI); + return prefix == null; + } +}; + + +function _xmlEncoder(c){ + return c == '<' && '<' || + c == '>' && '>' || + c == '&' && '&' || + c == '"' && '"' || + '&#'+c.charCodeAt()+';' +} + + +copy(NodeType,Node); +copy(NodeType,Node.prototype); + +/** + * @param callback return true for continue,false for break + * @return boolean true: break visit; + */ +function _visitNode(node,callback){ + if(callback(node)){ + return true; + } + if(node = node.firstChild){ + do{ + if(_visitNode(node,callback)){return true} + }while(node=node.nextSibling) + } +} + + + +function Document(){ +} +function _onAddAttribute(doc,el,newAttr){ + doc && doc._inc++; + var ns = newAttr.namespaceURI ; + if(ns == 'http://www.w3.org/2000/xmlns/'){ + //update namespace + el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value + } +} +function _onRemoveAttribute(doc,el,newAttr,remove){ + doc && doc._inc++; + var ns = newAttr.namespaceURI ; + if(ns == 'http://www.w3.org/2000/xmlns/'){ + //update namespace + delete el._nsMap[newAttr.prefix?newAttr.localName:''] + } +} +function _onUpdateChild(doc,el,newChild){ + if(doc && doc._inc){ + doc._inc++; + //update childNodes + var cs = el.childNodes; + if(newChild){ + cs[cs.length++] = newChild; + }else{ + //console.log(1) + var child = el.firstChild; + var i = 0; + while(child){ + cs[i++] = child; + child =child.nextSibling; + } + cs.length = i; + } + } +} + +/** + * attributes; + * children; + * + * writeable properties: + * nodeValue,Attr:value,CharacterData:data + * prefix + */ +function _removeChild(parentNode,child){ + var previous = child.previousSibling; + var next = child.nextSibling; + if(previous){ + previous.nextSibling = next; + }else{ + parentNode.firstChild = next + } + if(next){ + next.previousSibling = previous; + }else{ + parentNode.lastChild = previous; + } + _onUpdateChild(parentNode.ownerDocument,parentNode); + return child; +} +/** + * preformance key(refChild == null) + */ +function _insertBefore(parentNode,newChild,nextChild){ + var cp = newChild.parentNode; + if(cp){ + cp.removeChild(newChild);//remove and update + } + if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ + var newFirst = newChild.firstChild; + if (newFirst == null) { + return newChild; + } + var newLast = newChild.lastChild; + }else{ + newFirst = newLast = newChild; + } + var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild; + + newFirst.previousSibling = pre; + newLast.nextSibling = nextChild; + + + if(pre){ + pre.nextSibling = newFirst; + }else{ + parentNode.firstChild = newFirst; + } + if(nextChild == null){ + parentNode.lastChild = newLast; + }else{ + nextChild.previousSibling = newLast; + } + do{ + newFirst.parentNode = parentNode; + }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) + _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode); + //console.log(parentNode.lastChild.nextSibling == null) + if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) { + newChild.firstChild = newChild.lastChild = null; + } + return newChild; +} +function _appendSingleChild(parentNode,newChild){ + var cp = newChild.parentNode; + if(cp){ + var pre = parentNode.lastChild; + cp.removeChild(newChild);//remove and update + var pre = parentNode.lastChild; + } + var pre = parentNode.lastChild; + newChild.parentNode = parentNode; + newChild.previousSibling = pre; + newChild.nextSibling = null; + if(pre){ + pre.nextSibling = newChild; + }else{ + parentNode.firstChild = newChild; + } + parentNode.lastChild = newChild; + _onUpdateChild(parentNode.ownerDocument,parentNode,newChild); + return newChild; + //console.log("__aa",parentNode.lastChild.nextSibling == null) +} +Document.prototype = { + //implementation : null, + nodeName : '#document', + nodeType : DOCUMENT_NODE, + doctype : null, + documentElement : null, + _inc : 1, + + insertBefore : function(newChild, refChild){//raises + if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ + var child = newChild.firstChild; + while(child){ + var next = child.nextSibling; + this.insertBefore(child,refChild); + child = next; + } + return newChild; + } + if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){ + this.documentElement = newChild; + } + + return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild; + }, + removeChild : function(oldChild){ + if(this.documentElement == oldChild){ + this.documentElement = null; + } + return _removeChild(this,oldChild); + }, + // Introduced in DOM Level 2: + importNode : function(importedNode,deep){ + return importNode(this,importedNode,deep); + }, + // Introduced in DOM Level 2: + getElementById : function(id){ + var rtv = null; + _visitNode(this.documentElement,function(node){ + if(node.nodeType == ELEMENT_NODE){ + if(node.getAttribute('id') == id){ + rtv = node; + return true; } } + }) + return rtv; + }, + + //document factory method: + createElement : function(tagName){ + var node = new Element(); + node.ownerDocument = this; + node.nodeName = tagName; + node.tagName = tagName; + node.childNodes = new NodeList(); + var attrs = node.attributes = new NamedNodeMap(); + attrs._ownerElement = node; + return node; + }, + createDocumentFragment : function(){ + var node = new DocumentFragment(); + node.ownerDocument = this; + node.childNodes = new NodeList(); + return node; + }, + createTextNode : function(data){ + var node = new Text(); + node.ownerDocument = this; + node.appendData(data) + return node; + }, + createComment : function(data){ + var node = new Comment(); + node.ownerDocument = this; + node.appendData(data) + return node; + }, + createCDATASection : function(data){ + var node = new CDATASection(); + node.ownerDocument = this; + node.appendData(data) + return node; + }, + createProcessingInstruction : function(target,data){ + var node = new ProcessingInstruction(); + node.ownerDocument = this; + node.tagName = node.target = target; + node.nodeValue= node.data = data; + return node; + }, + createAttribute : function(name){ + var node = new Attr(); + node.ownerDocument = this; + node.name = name; + node.nodeName = name; + node.localName = name; + node.specified = true; + return node; + }, + createEntityReference : function(name){ + var node = new EntityReference(); + node.ownerDocument = this; + node.nodeName = name; + return node; + }, + // Introduced in DOM Level 2: + createElementNS : function(namespaceURI,qualifiedName){ + var node = new Element(); + var pl = qualifiedName.split(':'); + var attrs = node.attributes = new NamedNodeMap(); + node.childNodes = new NodeList(); + node.ownerDocument = this; + node.nodeName = qualifiedName; + node.tagName = qualifiedName; + node.namespaceURI = namespaceURI; + if(pl.length == 2){ + node.prefix = pl[0]; + node.localName = pl[1]; + }else{ + //el.prefix = null; + node.localName = qualifiedName; + } + attrs._ownerElement = node; + return node; + }, + // Introduced in DOM Level 2: + createAttributeNS : function(namespaceURI,qualifiedName){ + var node = new Attr(); + var pl = qualifiedName.split(':'); + node.ownerDocument = this; + node.nodeName = qualifiedName; + node.name = qualifiedName; + node.namespaceURI = namespaceURI; + node.specified = true; + if(pl.length == 2){ + node.prefix = pl[0]; + node.localName = pl[1]; + }else{ + //el.prefix = null; + node.localName = qualifiedName; + } + return node; + } +}; +_extends(Document,Node); + + +function Element() { + this._nsMap = {}; +}; +Element.prototype = { + nodeType : ELEMENT_NODE, + hasAttribute : function(name){ + return this.getAttributeNode(name)!=null; + }, + getAttribute : function(name){ + var attr = this.getAttributeNode(name); + return attr && attr.value || ''; + }, + getAttributeNode : function(name){ + return this.attributes.getNamedItem(name); + }, + setAttribute : function(name, value){ + var attr = this.ownerDocument.createAttribute(name); + attr.value = attr.nodeValue = "" + value; + this.setAttributeNode(attr) + }, + removeAttribute : function(name){ + var attr = this.getAttributeNode(name) + attr && this.removeAttributeNode(attr); + }, + + //four real opeartion method + appendChild:function(newChild){ + if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ + return this.insertBefore(newChild,null); + }else{ + return _appendSingleChild(this,newChild); + } + }, + setAttributeNode : function(newAttr){ + return this.attributes.setNamedItem(newAttr); + }, + setAttributeNodeNS : function(newAttr){ + return this.attributes.setNamedItemNS(newAttr); + }, + removeAttributeNode : function(oldAttr){ + //console.log(this == oldAttr.ownerElement) + return this.attributes.removeNamedItem(oldAttr.nodeName); + }, + //get real attribute name,and remove it by removeAttributeNode + removeAttributeNS : function(namespaceURI, localName){ + var old = this.getAttributeNodeNS(namespaceURI, localName); + old && this.removeAttributeNode(old); + }, + + hasAttributeNS : function(namespaceURI, localName){ + return this.getAttributeNodeNS(namespaceURI, localName)!=null; + }, + getAttributeNS : function(namespaceURI, localName){ + var attr = this.getAttributeNodeNS(namespaceURI, localName); + return attr && attr.value || ''; + }, + setAttributeNS : function(namespaceURI, qualifiedName, value){ + var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); + attr.value = attr.nodeValue = "" + value; + this.setAttributeNode(attr) + }, + getAttributeNodeNS : function(namespaceURI, localName){ + return this.attributes.getNamedItemNS(namespaceURI, localName); + }, + + getElementsByTagName : function(tagName){ + return new LiveNodeList(this,function(base){ + var ls = []; + _visitNode(base,function(node){ + if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ + ls.push(node); + } + }); + return ls; + }); + }, + getElementsByTagNameNS : function(namespaceURI, localName){ + return new LiveNodeList(this,function(base){ + var ls = []; + _visitNode(base,function(node){ + if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ + ls.push(node); + } + }); + return ls; + + }); + } +}; +Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; +Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; + + +_extends(Element,Node); +function Attr() { +}; +Attr.prototype.nodeType = ATTRIBUTE_NODE; +_extends(Attr,Node); + + +function CharacterData() { +}; +CharacterData.prototype = { + data : '', + substringData : function(offset, count) { + return this.data.substring(offset, offset+count); + }, + appendData: function(text) { + text = this.data+text; + this.nodeValue = this.data = text; + this.length = text.length; + }, + insertData: function(offset,text) { + this.replaceData(offset,0,text); + + }, + appendChild:function(newChild){ + throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) + }, + deleteData: function(offset, count) { + this.replaceData(offset,count,""); + }, + replaceData: function(offset, count, text) { + var start = this.data.substring(0,offset); + var end = this.data.substring(offset+count); + text = start + text + end; + this.nodeValue = this.data = text; + this.length = text.length; + } +} +_extends(CharacterData,Node); +function Text() { +}; +Text.prototype = { + nodeName : "#text", + nodeType : TEXT_NODE, + splitText : function(offset) { + var text = this.data; + var newText = text.substring(offset); + text = text.substring(0, offset); + this.data = this.nodeValue = text; + this.length = text.length; + var newNode = this.ownerDocument.createTextNode(newText); + if(this.parentNode){ + this.parentNode.insertBefore(newNode, this.nextSibling); + } + return newNode; + } +} +_extends(Text,CharacterData); +function Comment() { +}; +Comment.prototype = { + nodeName : "#comment", + nodeType : COMMENT_NODE +} +_extends(Comment,CharacterData); + +function CDATASection() { +}; +CDATASection.prototype = { + nodeName : "#cdata-section", + nodeType : CDATA_SECTION_NODE +} +_extends(CDATASection,CharacterData); + + +function DocumentType() { +}; +DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; +_extends(DocumentType,Node); + +function Notation() { +}; +Notation.prototype.nodeType = NOTATION_NODE; +_extends(Notation,Node); + +function Entity() { +}; +Entity.prototype.nodeType = ENTITY_NODE; +_extends(Entity,Node); + +function EntityReference() { +}; +EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; +_extends(EntityReference,Node); + +function DocumentFragment() { +}; +DocumentFragment.prototype.nodeName = "#document-fragment"; +DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; +_extends(DocumentFragment,Node); + + +function ProcessingInstruction() { +} +ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; +_extends(ProcessingInstruction,Node); +function XMLSerializer(){} +XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ + return nodeSerializeToString.call(node,isHtml,nodeFilter); +} +Node.prototype.toString = nodeSerializeToString; +function nodeSerializeToString(isHtml,nodeFilter){ + var buf = []; + var refNode = this.nodeType == 9?this.documentElement:this; + var prefix = refNode.prefix; + var uri = refNode.namespaceURI; + + if(uri && prefix == null){ + //console.log(prefix) + var prefix = refNode.lookupPrefix(uri); + if(prefix == null){ + //isHTML = true; + var visibleNamespaces=[ + {namespace:uri,prefix:null} + //{namespace:uri,prefix:''} + ] + } + } + serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); + //console.log('###',this.nodeType,uri,prefix,buf.join('')) + return buf.join(''); +} +function needNamespaceDefine(node,isHTML, visibleNamespaces) { + var prefix = node.prefix||''; + var uri = node.namespaceURI; + if (!prefix && !uri){ + return false; + } + if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" + || uri == 'http://www.w3.org/2000/xmlns/'){ + return false; + } + + var i = visibleNamespaces.length + //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces) + while (i--) { + var ns = visibleNamespaces[i]; + // get namespace prefix + //console.log(node.nodeType,node.tagName,ns.prefix,prefix) + if (ns.prefix == prefix){ + return ns.namespace != uri; + } + } + //console.log(isHTML,uri,prefix=='') + //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){ + // return false; + //} + //node.flag = '11111' + //console.error(3,true,node.flag,node.prefix,node.namespaceURI) + return true; +} +function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ + if(nodeFilter){ + node = nodeFilter(node); + if(node){ + if(typeof node == 'string'){ + buf.push(node); + return; + } + }else{ + return; + } + //buf.sort.apply(attrs, attributeSorter); + } + switch(node.nodeType){ + case ELEMENT_NODE: + if (!visibleNamespaces) visibleNamespaces = []; + var startVisibleNamespaces = visibleNamespaces.length; + var attrs = node.attributes; + var len = attrs.length; + var child = node.firstChild; + var nodeName = node.tagName; + + isHTML = (htmlns === node.namespaceURI) ||isHTML + buf.push('<',nodeName); + + + + for(var i=0;i'); + //if is cdata child node + if(isHTML && /^script$/i.test(nodeName)){ + while(child){ + if(child.data){ + buf.push(child.data); + }else{ + serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); + } + child = child.nextSibling; + } + }else + { + while(child){ + serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); + child = child.nextSibling; + } + } + buf.push(''); + }else{ + buf.push('/>'); + } + // remove added visible namespaces + //visibleNamespaces.length = startVisibleNamespaces; + return; + case DOCUMENT_NODE: + case DOCUMENT_FRAGMENT_NODE: + var child = node.firstChild; + while(child){ + serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); + child = child.nextSibling; + } + return; + case ATTRIBUTE_NODE: + return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"'); + case TEXT_NODE: + return buf.push(node.data.replace(/[<&]/g,_xmlEncoder)); + case CDATA_SECTION_NODE: + return buf.push( ''); + case COMMENT_NODE: + return buf.push( ""); + case DOCUMENT_TYPE_NODE: + var pubid = node.publicId; + var sysid = node.systemId; + buf.push(''); + }else if(sysid && sysid!='.'){ + buf.push(' SYSTEM "',sysid,'">'); + }else{ + var sub = node.internalSubset; + if(sub){ + buf.push(" [",sub,"]"); + } + buf.push(">"); + } + return; + case PROCESSING_INSTRUCTION_NODE: + return buf.push( ""); + case ENTITY_REFERENCE_NODE: + return buf.push( '&',node.nodeName,';'); + //case ENTITY_NODE: + //case NOTATION_NODE: + default: + buf.push('??',node.nodeName); + } +} +function importNode(doc,node,deep){ + var node2; + switch (node.nodeType) { + case ELEMENT_NODE: + node2 = node.cloneNode(false); + node2.ownerDocument = doc; + //var attrs = node2.attributes; + //var len = attrs.length; + //for(var i=0;i 1 && this.layout.name === "reflowable" && columns % 2 > 0) { // add a blank page - width += this.layout.gap + this.layout.columnWidth; + width += this.layout.pageWidth; } } } // Expand Vertically @@ -8404,6 +9878,8 @@ var IframeView = function () { }, { key: "reframe", value: function reframe(width, height) { + var _this2 = this; + var size; if ((0, _core.isNumber)(width)) { @@ -8430,6 +9906,16 @@ var IframeView = function () { this.pane && this.pane.render(); + requestAnimationFrame(function () { + var mark = void 0; + for (var m in _this2.marks) { + if (_this2.marks.hasOwnProperty(m)) { + mark = _this2.marks[m]; + _this2.placeMark(mark.element, mark.range); + } + } + }); + this.onResize(this, size); this.emit(_constants.EVENTS.VIEWS.RESIZED, size); @@ -8457,10 +9943,14 @@ var IframeView = function () { if (this.settings.method === "blobUrl") { this.blobUrl = (0, _core.createBlobUrl)(contents, "application/xhtml+xml"); this.iframe.src = this.blobUrl; + this.element.appendChild(this.iframe); } else if (this.settings.method === "srcdoc") { this.iframe.srcdoc = contents; + this.element.appendChild(this.iframe); } else { + this.element.appendChild(this.iframe); + this.document = this.iframe.contentDocument; if (!this.document) { @@ -8478,7 +9968,7 @@ var IframeView = function () { }, { key: "onLoad", value: function onLoad(event, promise) { - var _this2 = this; + var _this3 = this; this.window = this.iframe.contentWindow; this.document = this.iframe.contentDocument; @@ -8498,19 +9988,19 @@ var IframeView = function () { } this.contents.on(_constants.EVENTS.CONTENTS.EXPAND, function () { - if (_this2.displayed && _this2.iframe) { - _this2.expand(); - if (_this2.contents) { - _this2.layout.format(_this2.contents); + if (_this3.displayed && _this3.iframe) { + _this3.expand(); + if (_this3.contents) { + _this3.layout.format(_this3.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); + if (_this3.displayed && _this3.iframe) { + _this3.expand(); + if (_this3.contents) { + _this3.layout.format(_this3.contents); } } }); @@ -8587,6 +10077,11 @@ var IframeView = function () { if (this.iframe) { this.iframe.style.visibility = "visible"; + + // Remind Safari to redraw the iframe + this.iframe.style.transform = "translateZ(0)"; + this.iframe.offsetWidth; + this.iframe.style.transform = null; } this.emit(_constants.EVENTS.VIEWS.SHOWN, this); @@ -8657,18 +10152,22 @@ var IframeView = function () { }, { key: "highlight", value: function highlight(cfiRange) { - var _this3 = this; - var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var cb = arguments[2]; + var _this4 = this; + + var className = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "epubjs-hl"; + var styles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + if (!this.contents) { return; } + var attributes = Object.assign({ "fill": "yellow", "fill-opacity": "0.3", "mix-blend-mode": "multiply" }, styles); var range = this.contents.range(cfiRange); var emitter = function emitter() { - _this3.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); + _this4.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); }; data["epubcfi"] = cfiRange; @@ -8677,12 +10176,12 @@ var IframeView = function () { 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 m = new _marksPane.Highlight(range, className, data, attributes); 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.setAttribute("ref", className); h.element.addEventListener("click", emitter); h.element.addEventListener("touchstart", emitter); @@ -8695,17 +10194,21 @@ var IframeView = function () { }, { key: "underline", value: function underline(cfiRange) { - var _this4 = this; - var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var cb = arguments[2]; + var _this5 = this; + + var className = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "epubjs-ul"; + var styles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + if (!this.contents) { return; } + var attributes = Object.assign({ "stroke": "black", "stroke-opacity": "0.3", "mix-blend-mode": "multiply" }, styles); var range = this.contents.range(cfiRange); var emitter = function emitter() { - _this4.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); + _this5.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); }; data["epubcfi"] = cfiRange; @@ -8714,12 +10217,12 @@ var IframeView = function () { 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 m = new _marksPane.Underline(range, className, data, attributes); 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.setAttribute("ref", className); h.element.addEventListener("click", emitter); h.element.addEventListener("touchstart", emitter); @@ -8732,12 +10235,11 @@ var IframeView = function () { }, { key: "mark", value: function mark(cfiRange) { - var _this5 = this; + var _this6 = this; var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var cb = arguments[2]; - if (!this.contents) { return; } @@ -8755,7 +10257,7 @@ var IframeView = function () { var parent = container.nodeType === 1 ? container : container.parentNode; var emitter = function emitter(e) { - _this5.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); + _this6.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data); }; if (range.collapsed && container.nodeType === 1) { @@ -8767,33 +10269,9 @@ var IframeView = function () { 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'); + 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; @@ -8811,12 +10289,44 @@ var IframeView = function () { mark.addEventListener("click", emitter); mark.addEventListener("touchstart", emitter); + this.placeMark(mark, range); + this.element.appendChild(mark); - this.marks[cfiRange] = { "element": mark, "listeners": [emitter, cb] }; + this.marks[cfiRange] = { "element": mark, "range": range, "listeners": [emitter, cb] }; return parent; } + }, { + key: "placeMark", + value: function placeMark(element, range) { + 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 = rect.right; + right = Math.ceil(left / this.layout.props.pageWidth) * this.layout.props.pageWidth - this.layout.gap / 2; + top = rect.top; + } + } + } + + element.style.top = top + "px"; + element.style.left = right + "px"; + } }, { key: "unhighlight", value: function unhighlight(cfiRange) { @@ -8828,6 +10338,7 @@ var IframeView = function () { item.listeners.forEach(function (l) { if (l) { item.element.removeEventListener("click", l); + item.element.removeEventListener("touchstart", l); }; }); delete this.highlights[cfiRange]; @@ -8843,6 +10354,7 @@ var IframeView = function () { item.listeners.forEach(function (l) { if (l) { item.element.removeEventListener("click", l); + item.element.removeEventListener("touchstart", l); }; }); delete this.underlines[cfiRange]; @@ -8858,6 +10370,7 @@ var IframeView = function () { item.listeners.forEach(function (l) { if (l) { item.element.removeEventListener("click", l); + item.element.removeEventListener("touchstart", l); }; }); delete this.marks[cfiRange]; @@ -8887,17 +10400,20 @@ var IframeView = function () { this.displayed = false; this.removeListeners(); + this.contents.destroy(); this.stopExpanding = true; this.element.removeChild(this.iframe); - this.iframe = null; + this.iframe = undefined; + this.contents = undefined; this._textWidth = null; this._textHeight = null; this._width = null; this._height = null; } + // this.element.style.height = "0px"; // this.element.style.width = "0px"; } @@ -8915,9 +10431,9 @@ module.exports = exports["default"]; /* 21 */ /***/ (function(module, exports, __webpack_require__) { -var isObject = __webpack_require__(15), - now = __webpack_require__(58), - toNumber = __webpack_require__(60); +var isObject = __webpack_require__(16), + now = __webpack_require__(61), + toNumber = __webpack_require__(63); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; @@ -9025,9 +10541,11 @@ function debounce(func, wait, options) { function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, - result = wait - timeSinceLastCall; + timeWaiting = wait - timeSinceLastCall; - return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; } function shouldInvoke(time) { @@ -9109,7 +10627,7 @@ module.exports = debounce; /* 22 */ /***/ (function(module, exports, __webpack_require__) { -var freeGlobal = __webpack_require__(59); +var freeGlobal = __webpack_require__(62); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; @@ -9143,15 +10661,23 @@ 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 _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 _core = __webpack_require__(0); -var _default = __webpack_require__(14); +var _default = __webpack_require__(15); var _default2 = _interopRequireDefault(_default); -var _constants = __webpack_require__(3); +var _snap = __webpack_require__(70); + +var _snap2 = _interopRequireDefault(_snap); + +var _constants = __webpack_require__(2); var _debounce = __webpack_require__(21); @@ -9183,7 +10709,9 @@ var ContinuousViewManager = function (_DefaultViewManager) { offset: 500, offsetDelta: 250, width: undefined, - height: undefined + height: undefined, + snap: false, + afterScrolledTimeout: 10 }); (0, _core.extend)(_this.settings, options.settings || {}); @@ -9247,10 +10775,10 @@ var ContinuousViewManager = function (_DefaultViewManager) { if (!this.isPaginated) { distY = offset.top; - offsetY = offset.top + this.settings.offset; + offsetY = offset.top + this.settings.offsetDelta; } else { distX = Math.floor(offset.left / this.layout.delta) * this.layout.delta; - offsetX = distX + this.settings.offset; + offsetX = distX + this.settings.offsetDelta; } if (distX > 0 || distY > 0) { @@ -9299,17 +10827,17 @@ var ContinuousViewManager = function (_DefaultViewManager) { }, { key: "append", value: function append(section) { + var _this4 = this; + 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); - }); - */ + view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) { + _this4.updateAxis(axis); + }); this.views.append(view); @@ -9320,20 +10848,18 @@ var ContinuousViewManager = function (_DefaultViewManager) { }, { key: "prepend", value: function prepend(section) { - var _this4 = this; + var _this5 = this; var view = this.createView(section); view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) { - _this4.counter(bounds); + _this5.counter(bounds); view.expanded = true; }); - /* - view.on(EVENTS.VIEWS.AXIS, (axis) => { - this.updateAxis(axis); - }); - */ + view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) { + _this5.updateAxis(axis); + }); this.views.prepend(view); @@ -9405,7 +10931,7 @@ var ContinuousViewManager = function (_DefaultViewManager) { }, { key: "check", value: function check(_offsetLeft, _offsetTop) { - var _this5 = this; + var _this6 = this; var checking = new _core.defer(); var newViews = []; @@ -9427,24 +10953,24 @@ var ContinuousViewManager = function (_DefaultViewManager) { 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 visibleLength = horizontal ? Math.floor(bounds.width) : bounds.height; var contentLength = horizontal ? this.container.scrollWidth : this.container.scrollHeight; var prepend = function prepend() { - var first = _this5.views.first(); + var first = _this6.views.first(); var prev = first && first.section.prev(); if (prev) { - newViews.push(_this5.prepend(prev)); + newViews.push(_this6.prepend(prev)); } }; var append = function append() { - var last = _this5.views.last(); + var last = _this6.views.last(); var next = last && last.section.next(); if (next) { - newViews.push(_this5.append(next)); + newViews.push(_this6.append(next)); } }; @@ -9470,12 +10996,12 @@ var ContinuousViewManager = function (_DefaultViewManager) { if (newViews.length) { return Promise.all(promises).then(function () { - if (_this5.layout.name === "pre-paginated" && _this5.layout.props.spread) { - return _this5.check(); + if (_this6.layout.name === "pre-paginated" && _this6.layout.props.spread) { + return _this6.check(); } }).then(function () { // Check to see if anything new is on screen after rendering - return _this5.update(delta); + return _this6.update(delta); }, function (err) { return err; }); @@ -9520,7 +11046,7 @@ var ContinuousViewManager = function (_DefaultViewManager) { var prevTop; var prevLeft; - if (this.settings.height) { + if (!this.settings.fullsize) { prevTop = this.container.scrollTop; prevLeft = this.container.scrollLeft; } else { @@ -9536,7 +11062,7 @@ var ContinuousViewManager = function (_DefaultViewManager) { if (this.settings.axis === "vertical") { this.scrollTo(0, prevTop - bounds.height, true); } else { - this.scrollTo(prevLeft - bounds.width, 0, true); + this.scrollTo(prevLeft - Math.floor(bounds.width), 0, true); } } } @@ -9551,6 +11077,10 @@ var ContinuousViewManager = function (_DefaultViewManager) { }.bind(this)); this.addScrollListeners(); + + if (this.isPaginated && this.settings.snap) { + this.snapper = new _snap2.default(this, this.settings.snap && _typeof(this.settings.snap) === "object" && this.settings.snap); + } } }, { key: "addScrollListeners", @@ -9559,7 +11089,7 @@ var ContinuousViewManager = function (_DefaultViewManager) { this.tick = _core.requestAnimationFrame; - if (this.settings.height) { + if (!this.settings.fullsize) { this.prevScrollTop = this.container.scrollTop; this.prevScrollLeft = this.container.scrollLeft; } else { @@ -9570,7 +11100,7 @@ var ContinuousViewManager = function (_DefaultViewManager) { this.scrollDeltaVert = 0; this.scrollDeltaHorz = 0; - if (this.settings.height) { + if (!this.settings.fullsize) { scroller = this.container; this.scrollTop = this.container.scrollTop; this.scrollLeft = this.container.scrollLeft; @@ -9580,7 +11110,8 @@ var ContinuousViewManager = function (_DefaultViewManager) { this.scrollLeft = window.scrollX; } - scroller.addEventListener("scroll", this.onScroll.bind(this)); + this._onScroll = this.onScroll.bind(this); + scroller.addEventListener("scroll", this._onScroll); this._scrolled = (0, _debounce2.default)(this.scrolled.bind(this), 30); // this.tick.call(window, this.onScroll.bind(this)); @@ -9591,13 +11122,14 @@ var ContinuousViewManager = function (_DefaultViewManager) { value: function removeEventListeners() { var scroller; - if (this.settings.height) { + if (!this.settings.fullsize) { scroller = this.container; } else { scroller = window; } - scroller.removeEventListener("scroll", this.onScroll.bind(this)); + scroller.removeEventListener("scroll", this._onScroll); + this._onScroll = undefined; } }, { key: "onScroll", @@ -9606,7 +11138,7 @@ var ContinuousViewManager = function (_DefaultViewManager) { var scrollLeft = void 0; var dir = this.settings.direction === "rtl" ? -1 : 1; - if (this.settings.height) { + if (!this.settings.fullsize) { scrollTop = this.container.scrollTop; scrollLeft = this.container.scrollLeft; } else { @@ -9636,11 +11168,14 @@ var ContinuousViewManager = function (_DefaultViewManager) { this.scrollDeltaHorz = 0; }.bind(this), 150); + clearTimeout(this.afterScrolled); + this.didScroll = false; } }, { key: "scrolled", value: function scrolled() { + this.q.enqueue(function () { this.check(); }.bind(this)); @@ -9652,11 +11187,17 @@ var ContinuousViewManager = function (_DefaultViewManager) { clearTimeout(this.afterScrolled); this.afterScrolled = setTimeout(function () { + + // Don't report scroll if we are about the snap + if (this.snapper && this.snapper.supportsTouch && this.snapper.needsSnap()) { + return; + } + this.emit(_constants.EVENTS.MANAGERS.SCROLLED, { top: this.scrollTop, left: this.scrollLeft }); - }.bind(this)); + }.bind(this), this.settings.afterScrolledTimeout); } }, { key: "next", @@ -9700,40 +11241,39 @@ var ContinuousViewManager = function (_DefaultViewManager) { this.check(); }.bind(this)); } + + // updateAxis(axis, forceUpdate){ + // + // super.updateAxis(axis, forceUpdate); + // + // if (axis === "vertical") { + // this.settings.infinite = true; + // } else { + // this.settings.infinite = false; + // } + // } + }, { - key: "updateAxis", - value: function updateAxis(axis, forceUpdate) { - - if (!this.isPaginated) { - axis = "vertical"; + key: "updateFlow", + value: function updateFlow(flow) { + if (this.rendered && this.snapper) { + this.snapper.destroy(); + this.snapper = undefined; } - if (!forceUpdate && axis === this.settings.axis) { - return; + _get(ContinuousViewManager.prototype.__proto__ || Object.getPrototypeOf(ContinuousViewManager.prototype), "updateFlow", this).call(this, flow, "scroll"); + + if (this.rendered && this.isPaginated && this.settings.snap) { + this.snapper = new _snap2.default(this, this.settings.snap && _typeof(this.settings.snap) === "object" && this.settings.snap); } + } + }, { + key: "destroy", + value: function destroy() { + _get(ContinuousViewManager.prototype.__proto__ || Object.getPrototypeOf(ContinuousViewManager.prototype), "destroy", this).call(this); - 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; + if (this.snapper) { + this.snapper.destroy(); } } }]); @@ -9767,7 +11307,7 @@ var _epubcfi = __webpack_require__(1); var _epubcfi2 = _interopRequireDefault(_epubcfi); -var _contents = __webpack_require__(13); +var _contents = __webpack_require__(14); var _contents2 = _interopRequireDefault(_contents); @@ -9775,13 +11315,17 @@ var _core = __webpack_require__(0); var utils = _interopRequireWildcard(_core); -__webpack_require__(69); +var _constants = __webpack_require__(2); + +var _urlPolyfill = __webpack_require__(76); + +var URLpolyfill = _interopRequireWildcard(_urlPolyfill); var _iframe = __webpack_require__(20); var _iframe2 = _interopRequireDefault(_iframe); -var _default = __webpack_require__(14); +var _default = __webpack_require__(15); var _default2 = _interopRequireDefault(_default); @@ -9804,10 +11348,10 @@ function ePub(url, options) { return new _book2.default(url, options); } -ePub.VERSION = "0.3"; +ePub.VERSION = _constants.EPUBJS_VERSION; if (typeof global !== "undefined") { - global.EPUBJS_VERSION = ePub.VERSION; + global.EPUBJS_VERSION = _constants.EPUBJS_VERSION; } ePub.Book = _book2.default; @@ -9818,7 +11362,7 @@ ePub.utils = utils; exports.default = ePub; module.exports = exports["default"]; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }), /* 26 */ @@ -9831,17 +11375,15 @@ 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 _eventEmitter = __webpack_require__(3); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _core = __webpack_require__(0); -var _url = __webpack_require__(5); +var _url = __webpack_require__(6); var _url2 = _interopRequireDefault(_url); @@ -9849,31 +11391,31 @@ var _path = __webpack_require__(4); var _path2 = _interopRequireDefault(_path); -var _spine = __webpack_require__(42); +var _spine = __webpack_require__(43); var _spine2 = _interopRequireDefault(_spine); -var _locations = __webpack_require__(44); +var _locations = __webpack_require__(47); var _locations2 = _interopRequireDefault(_locations); -var _container = __webpack_require__(45); +var _container = __webpack_require__(48); var _container2 = _interopRequireDefault(_container); -var _packaging = __webpack_require__(46); +var _packaging = __webpack_require__(49); var _packaging2 = _interopRequireDefault(_packaging); -var _navigation = __webpack_require__(47); +var _navigation = __webpack_require__(50); var _navigation2 = _interopRequireDefault(_navigation); -var _resources = __webpack_require__(48); +var _resources = __webpack_require__(51); var _resources2 = _interopRequireDefault(_resources); -var _pagelist = __webpack_require__(49); +var _pagelist = __webpack_require__(52); var _pagelist2 = _interopRequireDefault(_pagelist); @@ -9881,11 +11423,11 @@ var _rendition = __webpack_require__(18); var _rendition2 = _interopRequireDefault(_rendition); -var _archive = __webpack_require__(67); +var _archive = __webpack_require__(71); var _archive2 = _interopRequireDefault(_archive); -var _request2 = __webpack_require__(11); +var _request2 = __webpack_require__(9); var _request3 = _interopRequireDefault(_request2); @@ -9893,14 +11435,22 @@ var _epubcfi = __webpack_require__(1); var _epubcfi2 = _interopRequireDefault(_epubcfi); -var _constants = __webpack_require__(3); +var _store = __webpack_require__(73); + +var _store2 = _interopRequireDefault(_store); + +var _displayoptions = __webpack_require__(75); + +var _displayoptions2 = _interopRequireDefault(_displayoptions); + +var _constants = __webpack_require__(2); 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 IBOOKS_DISPLAY_OPTIONS_PATH = "META-INF/com.apple.ibooks.display-options.xml"; var INPUT_TYPE = { BINARY: "binary", @@ -9923,6 +11473,8 @@ var INPUT_TYPE = { * @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 + * @param {string} [options.openAs] optional string to determine the input type + * @param {string} [options.store=false] cache the contents in local storage, value should be the name of the reader * @returns {Book} * @example new Book("/path/to/book.epub", {}) * @example new Book({ replacements: "blobUrl" }) @@ -9935,7 +11487,7 @@ var Book = function () { _classCallCheck(this, Book); // Allow passing just options to the Book - if (typeof options === "undefined" && (typeof url === "undefined" ? "undefined" : _typeof(url)) === "object") { + if (typeof options === "undefined" && typeof url !== "string" && url instanceof Blob === false) { options = url; url = undefined; } @@ -9946,7 +11498,9 @@ var Book = function () { requestHeaders: undefined, encoding: undefined, replacements: undefined, - canonical: undefined + canonical: undefined, + openAs: undefined, + store: undefined }); (0, _core.extend)(this.settings, options); @@ -9967,7 +11521,8 @@ var Book = function () { cover: new _core.defer(), navigation: new _core.defer(), pageList: new _core.defer(), - resources: new _core.defer() + resources: new _core.defer(), + displayOptions: new _core.defer() }; this.loaded = { @@ -9977,7 +11532,8 @@ var Book = function () { cover: this.loading.cover.promise, navigation: this.loading.navigation.promise, pageList: this.loading.pageList.promise, - resources: this.loading.resources.promise + resources: this.loading.resources.promise, + displayOptions: this.loading.displayOptions.promise }; /** @@ -9985,7 +11541,7 @@ var Book = function () { * @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]); + 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]); // Queue for methods used before opening this.isRendered = false; @@ -10050,6 +11606,13 @@ var Book = function () { */ this.archive = undefined; + /** + * @member {Store} storage + * @memberof Book + * @private + */ + this.storage = undefined; + /** * @member {Resources} resources * @memberof Book @@ -10078,10 +11641,20 @@ var Book = function () { */ this.packaging = undefined; + /** + * @member {DisplayOptions} displayOptions + * @memberof DisplayOptions + * @private + */ + this.displayOptions = undefined; + // this.toc = undefined; + if (this.settings.store) { + this.store(this.settings.store); + } if (url) { - this.open(url).catch(function (error) { + this.open(url, this.settings.openAs).catch(function (error) { var err = new Error("Cannot load book at " + url); _this.emit(_constants.EVENTS.BOOK.OPEN_FAILED, err); }); @@ -10114,7 +11687,7 @@ var Book = function () { } else if (type === INPUT_TYPE.EPUB) { this.archived = true; this.url = new _url2.default("/", ""); - opening = this.request(input, "binary").then(this.openEpub.bind(this)); + opening = this.request(input, "binary", this.settings.requestCredentials).then(this.openEpub.bind(this)); } else if (type == INPUT_TYPE.OPF) { this.url = new _url2.default(input); opening = this.openPackaging(this.url.Path.toString()); @@ -10215,13 +11788,10 @@ var Book = function () { }, { key: "load", value: function load(path) { - var resolved; - + var resolved = this.resolve(path); 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); } } @@ -10325,38 +11895,52 @@ var Book = function () { } /** - * unpack the contents of the Books packageXml + * unpack the contents of the Books packaging * @private - * @param {document} packageXml XML Document + * @param {Packaging} packaging object */ }, { key: "unpack", - value: function unpack(opf) { + value: function unpack(packaging) { var _this6 = this; - this.package = opf; + this.package = packaging; //TODO: deprecated this - this.spine.unpack(this.package, this.resolve.bind(this), this.canonical.bind(this)); + if (this.packaging.metadata.layout === "") { + // rendition:layout not set - check display options if book is pre-paginated + this.load(this.url.resolve(IBOOKS_DISPLAY_OPTIONS_PATH)).then(function (xml) { + _this6.displayOptions = new _displayoptions2.default(xml); + _this6.loading.displayOptions.resolve(_this6.displayOptions); + }).catch(function (err) { + _this6.displayOptions = new _displayoptions2.default(); + _this6.loading.displayOptions.resolve(_this6.displayOptions); + }); + } else { + this.displayOptions = new _displayoptions2.default(); + this.loading.displayOptions.resolve(this.displayOptions); + } - this.resources = new _resources2.default(this.package.manifest, { + this.spine.unpack(this.packaging, this.resolve.bind(this), this.canonical.bind(this)); + + this.resources = new _resources2.default(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.package).then(function () { + this.loadNavigation(this.packaging).then(function () { // this.toc = this.navigation.toc; _this6.loading.navigation.resolve(_this6.navigation); }); - if (this.package.coverPath) { - this.cover = this.resolve(this.package.coverPath); + if (this.packaging.coverPath) { + this.cover = this.resolve(this.packaging.coverPath); } // Resolve promises - this.loading.manifest.resolve(this.package.manifest); - this.loading.metadata.resolve(this.package.metadata); + 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); @@ -10366,37 +11950,41 @@ var Book = function () { if (this.archived || this.settings.replacements && this.settings.replacements != "none") { this.replacements().then(function () { - _this6.opening.resolve(_this6); + _this6.loaded.displayOptions.then(function () { + _this6.opening.resolve(_this6); + }); }).catch(function (err) { console.error(err); }); } else { // Resolve book opened promise - this.opening.resolve(this); + this.loaded.displayOptions.then(function () { + _this6.opening.resolve(_this6); + }); } } /** * Load Navigation and PageList from package * @private - * @param {document} opf XML Document + * @param {Packaging} packaging */ }, { key: "loadNavigation", - value: function loadNavigation(opf) { + value: function loadNavigation(packaging) { var _this7 = this; - var navPath = opf.navPath || opf.ncxPath; - var toc = opf.toc; + var navPath = packaging.navPath || packaging.ncxPath; + var toc = packaging.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 + if (packaging.pageList) { + _this7.pageList = new _pagelist2.default(packaging.pageList); // TODO: handle page lists from Manifest } resolve(_this7.navigation); @@ -10485,6 +12073,64 @@ var Book = function () { return this.archive.open(input, encoding); } + /** + * Store the epubs contents + * @private + * @param {binary} input epub data + * @param {string} [encoding] + * @return {Store} + */ + + }, { + key: "store", + value: function store(name) { + var _this8 = this; + + // Use "blobUrl" or "base64" for replacements + var replacementsSetting = this.settings.replacements && this.settings.replacements !== "none"; + // Save original url + var originalUrl = this.url; + // Save original request method + var requester = this.settings.requestMethod || _request3.default.bind(this); + // Create new Store + this.storage = new _store2.default(name, requester, this.resolve.bind(this)); + // Replace request method to go through store + this.request = this.storage.request.bind(this.storage); + + this.opened.then(function () { + if (_this8.archived) { + _this8.storage.requester = _this8.archive.request.bind(_this8.archive); + } + // Substitute hook + var substituteResources = function substituteResources(output, section) { + section.output = _this8.resources.substitute(output, section.url); + }; + + // Set to use replacements + _this8.resources.settings.replacements = replacementsSetting || "blobUrl"; + // Create replacement urls + _this8.resources.replacements().then(function () { + return _this8.resources.replaceCss(); + }); + + _this8.storage.on("offline", function () { + // Remove url to use relative resolving for hrefs + _this8.url = new _url2.default("/", ""); + // Add hook to replace resources in contents + _this8.spine.hooks.serialize.register(substituteResources); + }); + + _this8.storage.on("online", function () { + // Restore original url + _this8.url = originalUrl; + // Remove hook + _this8.spine.hooks.serialize.deregister(substituteResources); + }); + }); + + return this.storage; + } + /** * Get the cover url * @return {string} coverUrl @@ -10493,14 +12139,14 @@ var Book = function () { }, { key: "coverUrl", value: function coverUrl() { - var _this8 = this; + var _this9 = this; var retrieved = this.loaded.cover.then(function (url) { - if (_this8.archived) { + if (_this9.archived) { // return this.archive.createUrl(this.cover); - return _this8.resources.get(_this8.cover); + return _this9.resources.get(_this9.cover); } else { - return _this8.cover; + return _this9.cover; } }); @@ -10516,14 +12162,14 @@ var Book = function () { }, { key: "replacements", value: function replacements() { - var _this9 = this; + var _this10 = this; this.spine.hooks.serialize.register(function (output, section) { - section.output = _this9.resources.substitute(output, section.url); + section.output = _this10.resources.substitute(output, section.url); }); return this.resources.replacements().then(function () { - return _this9.resources.replaceCss(); + return _this10.resources.replaceCss(); }); } @@ -10559,8 +12205,8 @@ var Book = function () { }, { key: "key", value: function key(identifier) { - var ident = identifier || this.package.metadata.identifier || this.url.filename; - return "epubjs:" + EPUBJS_VERSION + ":" + ident; + var ident = identifier || this.packaging.metadata.identifier || this.url.filename; + return "epubjs:" + _constants.EPUBJS_VERSION + ":" + ident; } /** @@ -10586,6 +12232,7 @@ var Book = function () { this.container && this.container.destroy(); this.packaging && this.packaging.destroy(); this.rendition && this.rendition.destroy(); + this.displayOptions && this.displayOptions.destroy(); this.spine = undefined; this.locations = undefined; @@ -10749,9 +12396,7 @@ module.exports = function (dest, src /*, …srcn*/) { "use strict"; -module.exports = __webpack_require__(32)() - ? Object.keys - : __webpack_require__(33); +module.exports = __webpack_require__(32)() ? Object.keys : __webpack_require__(33); /***/ }), @@ -10766,8 +12411,8 @@ module.exports = function () { Object.keys("primitive"); return true; } catch (e) { - return false; -} + return false; + } }; @@ -10778,13 +12423,11 @@ module.exports = function () { "use strict"; -var isValue = __webpack_require__(9); +var isValue = __webpack_require__(10); var keys = Object.keys; -module.exports = function (object) { - return keys(isValue(object) ? Object(object) : object); -}; +module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); }; /***/ }), @@ -10805,7 +12448,7 @@ module.exports = function () {}; "use strict"; -var isValue = __webpack_require__(9); +var isValue = __webpack_require__(10); module.exports = function (value) { if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); @@ -10820,7 +12463,7 @@ module.exports = function (value) { "use strict"; -var isValue = __webpack_require__(9); +var isValue = __webpack_require__(10); var forEach = Array.prototype.forEach, create = Object.create; @@ -10910,6 +12553,12 @@ module.exports = function (fn) { /***/ }), /* 42 */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_42__; + +/***/ }), +/* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10925,15 +12574,15 @@ var _epubcfi = __webpack_require__(1); var _epubcfi2 = _interopRequireDefault(_epubcfi); -var _hook = __webpack_require__(10); +var _hook = __webpack_require__(11); var _hook2 = _interopRequireDefault(_hook); -var _section = __webpack_require__(43); +var _section = __webpack_require__(44); var _section2 = _interopRequireDefault(_section); -var _replacements = __webpack_require__(7); +var _replacements = __webpack_require__(8); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -10972,8 +12621,9 @@ var Spine = function () { /** * Unpack items from a opf into spine items - * @param {Package} _package + * @param {Packaging} _package * @param {method} resolver URL resolver + * @param {method} canonical Resolve canonical url */ @@ -11052,7 +12702,7 @@ var Spine = function () { /** * Get an item from the spine - * @param {string|int} [target] + * @param {string|number} [target] * @return {Section} section * @example spine.get(); * @example spine.get(1); @@ -11168,6 +12818,12 @@ var Spine = function () { value: function each() { return this.spineItems.forEach.apply(this.spineItems, arguments); } + + /** + * Find the first Section in the Spine + * @return {Section} first section + */ + }, { key: "first", value: function first() { @@ -11182,6 +12838,12 @@ var Spine = function () { index += 1; } while (index < this.spineItems.length); } + + /** + * Find the last Section in the Spine + * @return {Section} last section + */ + }, { key: "last", value: function last() { @@ -11229,7 +12891,7 @@ exports.default = Spine; module.exports = exports["default"]; /***/ }), -/* 43 */ +/* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11247,11 +12909,11 @@ var _epubcfi = __webpack_require__(1); var _epubcfi2 = _interopRequireDefault(_epubcfi); -var _hook = __webpack_require__(10); +var _hook = __webpack_require__(11); var _hook2 = _interopRequireDefault(_hook); -var _replacements = __webpack_require__(7); +var _replacements = __webpack_require__(8); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -11295,7 +12957,7 @@ var Section = function () { /** * Load the section from its url - * @param {method} _request a request method to use for loading + * @param {method} [_request] a request method to use for loading * @return {document} a promise with the xml document */ @@ -11303,7 +12965,7 @@ var Section = function () { _createClass(Section, [{ key: "load", value: function load(_request) { - var request = _request || this.request || __webpack_require__(11); + var request = _request || this.request || __webpack_require__(9); var loading = new _core.defer(); var loaded = loading.promise; @@ -11340,7 +13002,7 @@ var Section = function () { /** * Render the contents of a section - * @param {method} _request a request method to use for loading + * @param {method} [_request] a request method to use for loading * @return {string} output a serialized XML Document */ @@ -11356,7 +13018,7 @@ var Section = function () { var isIE = userAgent.indexOf('Trident') >= 0; var Serializer; if (typeof XMLSerializer === "undefined" || isIE) { - Serializer = __webpack_require__(16).XMLSerializer; + Serializer = __webpack_require__(45).XMLSerializer; } else { Serializer = XMLSerializer; } @@ -11439,15 +13101,15 @@ var Section = function () { /** * Reconciles the current chapters layout properies with * the global layout properities. - * @param {object} global The globa layout settings object, chapter properties string + * @param {object} globalLayout The global layout settings object, chapter properties string * @return {object} layoutProperties Object with layout properties */ - value: function reconcileLayoutSettings(global) { + value: function reconcileLayoutSettings(globalLayout) { //-- Get the global defaults var settings = { - layout: global.layout, - spread: global.spread, - orientation: global.orientation + layout: globalLayout.layout, + spread: globalLayout.spread, + orientation: globalLayout.orientation }; //-- Get the chapter's display type @@ -11529,7 +13191,903 @@ exports.default = Section; module.exports = exports["default"]; /***/ }), -/* 44 */ +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +function DOMParser(options){ + this.options = options ||{locator:{}}; + +} +DOMParser.prototype.parseFromString = function(source,mimeType){ + var options = this.options; + var sax = new XMLReader(); + var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler + var errorHandler = options.errorHandler; + var locator = options.locator; + var defaultNSMap = options.xmlns||{}; + var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"} + if(locator){ + domBuilder.setDocumentLocator(locator) + } + + sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); + sax.domBuilder = options.domBuilder || domBuilder; + if(/\/x?html?$/.test(mimeType)){ + entityMap.nbsp = '\xa0'; + entityMap.copy = '\xa9'; + defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; + } + defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace'; + if(source){ + sax.parse(source,defaultNSMap,entityMap); + }else{ + sax.errorHandler.error("invalid doc source"); + } + return domBuilder.doc; +} +function buildErrorHandler(errorImpl,domBuilder,locator){ + if(!errorImpl){ + if(domBuilder instanceof DOMHandler){ + return domBuilder; + } + errorImpl = domBuilder ; + } + var errorHandler = {} + var isCallback = errorImpl instanceof Function; + locator = locator||{} + function build(key){ + var fn = errorImpl[key]; + if(!fn && isCallback){ + fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; + } + errorHandler[key] = fn && function(msg){ + fn('[xmldom '+key+']\t'+msg+_locator(locator)); + }||function(){}; + } + build('warning'); + build('error'); + build('fatalError'); + return errorHandler; +} + +//console.log('#\n\n\n\n\n\n\n####') +/** + * +ContentHandler+ErrorHandler + * +LexicalHandler+EntityResolver2 + * -DeclHandler-DTDHandler + * + * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler + * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 + * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html + */ +function DOMHandler() { + this.cdata = false; +} +function position(locator,node){ + node.lineNumber = locator.lineNumber; + node.columnNumber = locator.columnNumber; +} +/** + * @see org.xml.sax.ContentHandler#startDocument + * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html + */ +DOMHandler.prototype = { + startDocument : function() { + this.doc = new DOMImplementation().createDocument(null, null, null); + if (this.locator) { + this.doc.documentURI = this.locator.systemId; + } + }, + startElement:function(namespaceURI, localName, qName, attrs) { + var doc = this.doc; + var el = doc.createElementNS(namespaceURI, qName||localName); + var len = attrs.length; + appendElement(this, el); + this.currentElement = el; + + this.locator && position(this.locator,el) + for (var i = 0 ; i < len; i++) { + var namespaceURI = attrs.getURI(i); + var value = attrs.getValue(i); + var qName = attrs.getQName(i); + var attr = doc.createAttributeNS(namespaceURI, qName); + this.locator &&position(attrs.getLocator(i),attr); + attr.value = attr.nodeValue = value; + el.setAttributeNode(attr) + } + }, + endElement:function(namespaceURI, localName, qName) { + var current = this.currentElement + var tagName = current.tagName; + this.currentElement = current.parentNode; + }, + startPrefixMapping:function(prefix, uri) { + }, + endPrefixMapping:function(prefix) { + }, + processingInstruction:function(target, data) { + var ins = this.doc.createProcessingInstruction(target, data); + this.locator && position(this.locator,ins) + appendElement(this, ins); + }, + ignorableWhitespace:function(ch, start, length) { + }, + characters:function(chars, start, length) { + chars = _toString.apply(this,arguments) + //console.log(chars) + if(chars){ + if (this.cdata) { + var charNode = this.doc.createCDATASection(chars); + } else { + var charNode = this.doc.createTextNode(chars); + } + if(this.currentElement){ + this.currentElement.appendChild(charNode); + }else if(/^\s*$/.test(chars)){ + this.doc.appendChild(charNode); + //process xml + } + this.locator && position(this.locator,charNode) + } + }, + skippedEntity:function(name) { + }, + endDocument:function() { + this.doc.normalize(); + }, + setDocumentLocator:function (locator) { + if(this.locator = locator){// && !('lineNumber' in locator)){ + locator.lineNumber = 0; + } + }, + //LexicalHandler + comment:function(chars, start, length) { + chars = _toString.apply(this,arguments) + var comm = this.doc.createComment(chars); + this.locator && position(this.locator,comm) + appendElement(this, comm); + }, + + startCDATA:function() { + //used in characters() methods + this.cdata = true; + }, + endCDATA:function() { + this.cdata = false; + }, + + startDTD:function(name, publicId, systemId) { + var impl = this.doc.implementation; + if (impl && impl.createDocumentType) { + var dt = impl.createDocumentType(name, publicId, systemId); + this.locator && position(this.locator,dt) + appendElement(this, dt); + } + }, + /** + * @see org.xml.sax.ErrorHandler + * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html + */ + warning:function(error) { + console.warn('[xmldom warning]\t'+error,_locator(this.locator)); + }, + error:function(error) { + console.error('[xmldom error]\t'+error,_locator(this.locator)); + }, + fatalError:function(error) { + console.error('[xmldom fatalError]\t'+error,_locator(this.locator)); + throw error; + } +} +function _locator(l){ + if(l){ + return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' + } +} +function _toString(chars,start,length){ + if(typeof chars == 'string'){ + return chars.substr(start,length) + }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") + if(chars.length >= start+length || start){ + return new java.lang.String(chars,start,length)+''; + } + return chars; + } +} + +/* + * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html + * used method of org.xml.sax.ext.LexicalHandler: + * #comment(chars, start, length) + * #startCDATA() + * #endCDATA() + * #startDTD(name, publicId, systemId) + * + * + * IGNORED method of org.xml.sax.ext.LexicalHandler: + * #endDTD() + * #startEntity(name) + * #endEntity(name) + * + * + * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html + * IGNORED method of org.xml.sax.ext.DeclHandler + * #attributeDecl(eName, aName, type, mode, value) + * #elementDecl(name, model) + * #externalEntityDecl(name, publicId, systemId) + * #internalEntityDecl(name, value) + * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html + * IGNORED method of org.xml.sax.EntityResolver2 + * #resolveEntity(String name,String publicId,String baseURI,String systemId) + * #resolveEntity(publicId, systemId) + * #getExternalSubset(name, baseURI) + * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html + * IGNORED method of org.xml.sax.DTDHandler + * #notationDecl(name, publicId, systemId) {}; + * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; + */ +"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ + DOMHandler.prototype[key] = function(){return null} +}) + +/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ +function appendElement (hander,node) { + if (!hander.currentElement) { + hander.doc.appendChild(node); + } else { + hander.currentElement.appendChild(node); + } +}//appendChild and setAttributeNS are preformance key + +//if(typeof require == 'function'){ + var XMLReader = __webpack_require__(46).XMLReader; + var DOMImplementation = exports.DOMImplementation = __webpack_require__(17).DOMImplementation; + exports.XMLSerializer = __webpack_require__(17).XMLSerializer ; + exports.DOMParser = DOMParser; +//} + + +/***/ }), +/* 46 */ +/***/ (function(module, exports) { + +//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] +//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] +//[5] Name ::= NameStartChar (NameChar)* +var nameStartChar = /[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]///\u10000-\uEFFFF +var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); +var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); +//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ +//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') + +//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE +//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE +var S_TAG = 0;//tag name offerring +var S_ATTR = 1;//attr name offerring +var S_ATTR_SPACE=2;//attr name end and space offer +var S_EQ = 3;//=space? +var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) +var S_ATTR_END = 5;//attr value end and no space(quot end) +var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) +var S_TAG_CLOSE = 7;//closed el + +function XMLReader(){ + +} + +XMLReader.prototype = { + parse:function(source,defaultNSMap,entityMap){ + var domBuilder = this.domBuilder; + domBuilder.startDocument(); + _copy(defaultNSMap ,defaultNSMap = {}) + parse(source,defaultNSMap,entityMap, + domBuilder,this.errorHandler); + domBuilder.endDocument(); + } +} +function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ + function fixedFromCharCode(code) { + // String.prototype.fromCharCode does not supports + // > 2 bytes unicode chars directly + if (code > 0xffff) { + code -= 0x10000; + var surrogate1 = 0xd800 + (code >> 10) + , surrogate2 = 0xdc00 + (code & 0x3ff); + + return String.fromCharCode(surrogate1, surrogate2); + } else { + return String.fromCharCode(code); + } + } + function entityReplacer(a){ + var k = a.slice(1,-1); + if(k in entityMap){ + return entityMap[k]; + }else if(k.charAt(0) === '#'){ + return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) + }else{ + errorHandler.error('entity not found:'+a); + return a; + } + } + function appendText(end){//has some bugs + if(end>start){ + var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); + locator&&position(start); + domBuilder.characters(xt,0,end-start); + start = end + } + } + function position(p,m){ + while(p>=lineEnd && (m = linePattern.exec(source))){ + lineStart = m.index; + lineEnd = lineStart + m[0].length; + locator.lineNumber++; + //console.log('line++:',locator,startPos,endPos) + } + locator.columnNumber = p-lineStart+1; + } + var lineStart = 0; + var lineEnd = 0; + var linePattern = /.*(?:\r\n?|\n)|.*$/g + var locator = domBuilder.locator; + + var parseStack = [{currentNSMap:defaultNSMapCopy}] + var closeMap = {}; + var start = 0; + while(true){ + try{ + var tagStart = source.indexOf('<',start); + if(tagStart<0){ + if(!source.substr(start).match(/^\s*$/)){ + var doc = domBuilder.doc; + var text = doc.createTextNode(source.substr(start)); + doc.appendChild(text); + domBuilder.currentElement = text; + } + return; + } + if(tagStart>start){ + appendText(tagStart); + } + switch(source.charAt(tagStart+1)){ + case '/': + var end = source.indexOf('>',tagStart+3); + var tagName = source.substring(tagStart+2,end); + var config = parseStack.pop(); + if(end<0){ + + tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); + //console.error('#@@@@@@'+tagName) + errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); + end = tagStart+1+tagName.length; + }else if(tagName.match(/\s + locator&&position(tagStart); + end = parseInstruction(source,tagStart,domBuilder); + break; + case '!':// start){ + start = end; + }else{ + //TODO: 这里有可能sax回退,有位置错误风险 + appendText(Math.max(tagStart,start)+1); + } + } +} +function copyLocator(f,t){ + t.lineNumber = f.lineNumber; + t.columnNumber = f.columnNumber; + return t; +} + +/** + * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); + * @return end of the elementStartPart(end of elementEndPart for selfClosed el) + */ +function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ + var attrName; + var value; + var p = ++start; + var s = S_TAG;//status + while(true){ + var c = source.charAt(p); + switch(c){ + case '=': + if(s === S_ATTR){//attrName + attrName = source.slice(start,p); + s = S_EQ; + }else if(s === S_ATTR_SPACE){ + s = S_EQ; + }else{ + //fatalError: equal must after attrName or space after attrName + throw new Error('attribute equal must after attrName'); + } + break; + case '\'': + case '"': + if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE + ){//equal + if(s === S_ATTR){ + errorHandler.warning('attribute value must after "="') + attrName = source.slice(start,p) + } + start = p+1; + p = source.indexOf(c,start) + if(p>0){ + value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); + el.add(attrName,value,start-1); + s = S_ATTR_END; + }else{ + //fatalError: no end quot match + throw new Error('attribute value no end \''+c+'\' match'); + } + }else if(s == S_ATTR_NOQUOT_VALUE){ + value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); + //console.log(attrName,value,start,p) + el.add(attrName,value,start); + //console.dir(el) + errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); + start = p+1; + s = S_ATTR_END + }else{ + //fatalError: no equal before + throw new Error('attribute value must after "="'); + } + break; + case '/': + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p)); + case S_ATTR_END: + case S_TAG_SPACE: + case S_TAG_CLOSE: + s =S_TAG_CLOSE; + el.closed = true; + case S_ATTR_NOQUOT_VALUE: + case S_ATTR: + case S_ATTR_SPACE: + break; + //case S_EQ: + default: + throw new Error("attribute invalid close char('/')") + } + break; + case ''://end document + //throw new Error('unexpected end of input') + errorHandler.error('unexpected end of input'); + if(s == S_TAG){ + el.setTagName(source.slice(start,p)); + } + return p; + case '>': + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p)); + case S_ATTR_END: + case S_TAG_SPACE: + case S_TAG_CLOSE: + break;//normal + case S_ATTR_NOQUOT_VALUE://Compatible state + case S_ATTR: + value = source.slice(start,p); + if(value.slice(-1) === '/'){ + el.closed = true; + value = value.slice(0,-1) + } + case S_ATTR_SPACE: + if(s === S_ATTR_SPACE){ + value = attrName; + } + if(s == S_ATTR_NOQUOT_VALUE){ + errorHandler.warning('attribute "'+value+'" missed quot(")!!'); + el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) + }else{ + if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ + errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') + } + el.add(value,value,start) + } + break; + case S_EQ: + throw new Error('attribute value missed!!'); + } +// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) + return p; + /*xml space '\x20' | #x9 | #xD | #xA; */ + case '\u0080': + c = ' '; + default: + if(c<= ' '){//space + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p));//tagName + s = S_TAG_SPACE; + break; + case S_ATTR: + attrName = source.slice(start,p) + s = S_ATTR_SPACE; + break; + case S_ATTR_NOQUOT_VALUE: + var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); + errorHandler.warning('attribute "'+value+'" missed quot(")!!'); + el.add(attrName,value,start) + case S_ATTR_END: + s = S_TAG_SPACE; + break; + //case S_TAG_SPACE: + //case S_EQ: + //case S_ATTR_SPACE: + // void();break; + //case S_TAG_CLOSE: + //ignore warning + } + }else{//not space +//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE +//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE + switch(s){ + //case S_TAG:void();break; + //case S_ATTR:void();break; + //case S_ATTR_NOQUOT_VALUE:void();break; + case S_ATTR_SPACE: + var tagName = el.tagName; + if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ + errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') + } + el.add(attrName,attrName,start); + start = p; + s = S_ATTR; + break; + case S_ATTR_END: + errorHandler.warning('attribute space is required"'+attrName+'"!!') + case S_TAG_SPACE: + s = S_ATTR; + start = p; + break; + case S_EQ: + s = S_ATTR_NOQUOT_VALUE; + start = p; + break; + case S_TAG_CLOSE: + throw new Error("elements closed character '/' and '>' must be connected to"); + } + } + }//end outer switch + //console.log('p++',p) + p++; + } +} +/** + * @return true if has new namespace define + */ +function appendElement(el,domBuilder,currentNSMap){ + var tagName = el.tagName; + var localNSMap = null; + //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; + var i = el.length; + while(i--){ + var a = el[i]; + var qName = a.qName; + var value = a.value; + var nsp = qName.indexOf(':'); + if(nsp>0){ + var prefix = a.prefix = qName.slice(0,nsp); + var localName = qName.slice(nsp+1); + var nsPrefix = prefix === 'xmlns' && localName + }else{ + localName = qName; + prefix = null + nsPrefix = qName === 'xmlns' && '' + } + //can not set prefix,because prefix !== '' + a.localName = localName ; + //prefix == null for no ns prefix attribute + if(nsPrefix !== false){//hack!! + if(localNSMap == null){ + localNSMap = {} + //console.log(currentNSMap,0) + _copy(currentNSMap,currentNSMap={}) + //console.log(currentNSMap,1) + } + currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; + a.uri = 'http://www.w3.org/2000/xmlns/' + domBuilder.startPrefixMapping(nsPrefix, value) + } + } + var i = el.length; + while(i--){ + a = el[i]; + var prefix = a.prefix; + if(prefix){//no prefix attribute has no namespace + if(prefix === 'xml'){ + a.uri = 'http://www.w3.org/XML/1998/namespace'; + }if(prefix !== 'xmlns'){ + a.uri = currentNSMap[prefix || ''] + + //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} + } + } + } + var nsp = tagName.indexOf(':'); + if(nsp>0){ + prefix = el.prefix = tagName.slice(0,nsp); + localName = el.localName = tagName.slice(nsp+1); + }else{ + prefix = null;//important!! + localName = el.localName = tagName; + } + //no prefix element has default namespace + var ns = el.uri = currentNSMap[prefix || '']; + domBuilder.startElement(ns,localName,tagName,el); + //endPrefixMapping and startPrefixMapping have not any help for dom builder + //localNSMap = null + if(el.closed){ + domBuilder.endElement(ns,localName,tagName); + if(localNSMap){ + for(prefix in localNSMap){ + domBuilder.endPrefixMapping(prefix) + } + } + }else{ + el.currentNSMap = currentNSMap; + el.localNSMap = localNSMap; + //parseStack.push(el); + return true; + } +} +function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ + if(/^(?:script|textarea)$/i.test(tagName)){ + var elEndStart = source.indexOf('',elStartEnd); + var text = source.substring(elStartEnd+1,elEndStart); + if(/[&<]/.test(text)){ + if(/^script$/i.test(tagName)){ + //if(!/\]\]>/.test(text)){ + //lexHandler.startCDATA(); + domBuilder.characters(text,0,text.length); + //lexHandler.endCDATA(); + return elEndStart; + //} + }//}else{//text area + text = text.replace(/&#?\w+;/g,entityReplacer); + domBuilder.characters(text,0,text.length); + return elEndStart; + //} + + } + } + return elStartEnd+1; +} +function fixSelfClosed(source,elStartEnd,tagName,closeMap){ + //if(tagName in closeMap){ + var pos = closeMap[tagName]; + if(pos == null){ + //console.log(tagName) + pos = source.lastIndexOf('') + if(pos',start+4); + //append comment source.substring(4,end)//');case $:var f=e.publicId,y=e.systemId;if(t.push('');else if(y&&'.'!=y)t.push(' SYSTEM "',y,'">');else{var v=e.internalSubset;v&&t.push(' [',v,']'),t.push('>')}return;case Z:return t.push('');case G:return t.push('&',e.nodeName,';');default:t.push('??',e.nodeName);}}function j(e,t,n){var a;switch(t.nodeType){case F:a=t.cloneNode(!1),a.ownerDocument=e;case ee:break;case H:n=!0;}if(a||(a=t.cloneNode(!1)),a.ownerDocument=e,a.parentNode=null,n)for(var i=t.firstChild;i;)a.appendChild(j(e,i,n)),i=i.nextSibling;return a}function q(e,t,a){var o=new t.constructor;for(var s in t){var n=t[s];'object'!=typeof n&&n!=o[s]&&(o[s]=n)}switch(t.childNodes&&(o.childNodes=new r),o.ownerDocument=e,o.nodeType){case F:var d=t.attributes,u=o.attributes=new l,c=d.length;u._ownerElement=o;for(var p=0;p=a.end.displayed.total&&(a.atEnd=!0),t.index===this.book.spine.first().index&&1===a.start.displayed.page&&(a.atStart=!0),a}},{key:'destroy',value:function(){this.manager&&this.manager.destroy(),this.book=void 0}},{key:'passEvents',value:function(t){var n=this;N.DOM_EVENTS.forEach(function(a){t.on(a,function(e){return n.triggerViewEvent(e,t)})}),t.on(N.EVENTS.CONTENTS.SELECTED,function(a){return n.triggerSelectedEvent(a,t)})}},{key:'triggerViewEvent',value:function(t,e){this.emit(t.type,t,e)}},{key:'triggerSelectedEvent',value:function(e,t){this.emit(N.EVENTS.RENDITION.SELECTED,e,t)}},{key:'triggerMarkEvent',value:function(e,t,n){this.emit(N.EVENTS.RENDITION.MARK_CLICKED,e,t,n)}},{key:'getRange',value:function(e,t){var n=new g.default(e),a=this.manager.visible().filter(function(e){if(n.spinePos===e.index)return!0});if(a.length)return a[0].contents.range(n,t)}},{key:'adjustImages',value:function(e){if('pre-paginated'===this._layout.name)return new Promise(function(e){e()});var t=e.window.getComputedStyle(e.content,null),n=.95*(e.content.offsetHeight-(parseFloat(t.paddingTop)+parseFloat(t.paddingBottom))),a=parseFloat(t.verticalPadding);return e.addStylesheetRules({img:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-a+'px':'100%')+'!important',"max-height":n+'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-a+'px':'100%')+'!important',"max-height":n+'px!important',"page-break-inside":'avoid',"break-inside":'avoid'}}),new Promise(function(e){setTimeout(function(){e()},1)})}},{key:'getContents',value:function(){return this.manager?this.manager.getContents():[]}},{key:'views',value:function(){var e=this.manager?this.manager.views:void 0;return e||[]}},{key:'handleLinks',value:function(e){var t=this;e&&e.on(N.EVENTS.CONTENTS.LINK_CLICKED,function(e){var n=t.book.path.relative(e);t.display(n)})}},{key:'injectStylesheet',value:function(e){var t=e.createElement('link');t.setAttribute('type','text/css'),t.setAttribute('rel','stylesheet'),t.setAttribute('href',this.settings.stylesheet),e.getElementsByTagName('head')[0].appendChild(t)}},{key:'injectScript',value:function(e){var t=e.createElement('script');t.setAttribute('type','text/javascript'),t.setAttribute('src',this.settings.script),t.textContent=' ',e.getElementsByTagName('head')[0].appendChild(t)}},{key:'injectIdentifier',value:function(e){var t=this.book.packaging.metadata.identifier,n=e.createElement('meta');n.setAttribute('name','dc.relation.ispartof'),t&&n.setAttribute('content',t),e.getElementsByTagName('head')[0].appendChild(n)}}]),e}();(0,l.default)(A.prototype),t.default=A,e.exports=t['default']},function(e,t,n){'use strict';function a(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(t,'__esModule',{value:!0});var i=function(){function e(e,t){for(var n=0,a;n=t&&r<=n)return e;if(s>t)return e;o=e,i.push(e)}else if(a.horizontal&&'rtl'===a.direction){if(r=c.left,s=c.right,s<=n&&s>=t)return e;if(r=t&&l<=n)return e;if(u>t)return e;o=e,i.push(e)}}),s)return this.findTextStartRange(s,t,n);return this.findTextStartRange(o,t,n)}},{key:'findEnd',value:function(e,t,n){for(var a=this,i=[e],o=e,s,l;i.length;)if(s=i.shift(),l=this.walk(s,function(e){var s,l,u,c,p;if(p=(0,d.nodeBounds)(e),a.horizontal&&'ltr'===a.direction){if(s=r(p.left),l=r(p.right),s>n&&o)return o;if(l>n)return e;o=e,i.push(e)}else if(a.horizontal&&'rtl'===a.direction){if(s=r(a.horizontal?p.left:p.top),l=r(a.horizontal?p.right:p.bottom),ln&&o)return o;if(c>n)return e;o=e,i.push(e)}}),l)return this.findTextEndRange(l,t,n);return this.findTextEndRange(o,t,n)}},{key:'findTextStartRange',value:function(e,t,n){for(var a=this.splitTextNodeIntoRanges(e),o=0,i,r,s,l,d;o=t)return i;}else if(this.horizontal&&'rtl'===this.direction){if(d=r.right,d<=n)return i;}else if(l=r.top,l>=t)return i;return a[0]}},{key:'findTextEndRange',value:function(e,t,n){for(var a=this.splitTextNodeIntoRanges(e),o=0,i,r,s,l,d,u,c;on&&i)return i;if(d>n)return r}else if(this.horizontal&&'rtl'===this.direction){if(l=s.left,d=s.right,dn&&i)return i;if(c>n)return r}i=r}return a[a.length-1]}},{key:'splitTextNodeIntoRanges',value:function(e,t){var n=[],a=e.textContent||'',i=a.trim(),o=e.ownerDocument,r=t||' ',s=i.indexOf(r),l;if(-1===s||e.nodeType!=Node.TEXT_NODE)return l=o.createRange(),l.selectNodeContents(e),[l];for(l=o.createRange(),l.setStart(e,0),l.setEnd(e,s),n.push(l),l=!1;-1!=s;)s=i.indexOf(r,s+1),0=t||0>n||y&&a>=x}function p(){var e=o();return c(e)?g(e):void(_=setTimeout(p,u(e)))}function g(e){return(_=void 0,v&&b)?l(e):(b=k=void 0,E)}function h(){var e=o(),n=c(e);if(b=arguments,k=this,N=e,n){if(void 0===_)return d(N);if(y)return _=setTimeout(p,t),l(N)}return void 0===_&&(_=setTimeout(p,t)),E}var m=0,f=!1,y=!1,v=!0,b,k,x,E,_,N;if('function'!=typeof e)throw new TypeError('Expected a function');return t=r(t)||0,a(n)&&(f=!!n.leading,y='maxWait'in n,x=y?s(r(n.maxWait)||0,t):x,v='trailing'in n?!!n.trailing:v),h.cancel=function(){void 0!==_&&clearTimeout(_),m=0,b=N=k=_=void 0},h.flush=function(){return void 0===_?E:g(o())},h}},function(e,t,n){var a=n(62),i='object'==typeof self&&self&&self.Object===Object&&self,o=a||i||Function('return this')();e.exports=o},function(e,t,n){var a=n(22),i=a.Symbol;e.exports=i},function(e,t,n){'use strict';function i(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function r(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t&&('object'==typeof t||'function'==typeof t)?t:e}function s(e,t){if('function'!=typeof t&&null!==t)throw new TypeError('Super expression must either be null or a function, not '+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,'__esModule',{value:!0});var d='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&'function'==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?'symbol':typeof e},u=function(){function e(e,t){for(var n=0,a;n=h&&(o&&d?m():f()),0>c-r&&(o&&d?f():m());var y=i.map(function(e){return e.displayed});return i.length?Promise.all(y).then(function(){if('pre-paginated'===n.layout.name&&n.layout.props.spread)return n.check()}).then(function(){return n.update(r)},function(e){return e}):(this.q.enqueue(function(){this.update()}.bind(this)),a.resolve(!1),a.promise)}},{key:'trim',value:function(){for(var e=new p.defer,t=this.views.displayed(),n=t[0],a=t[t.length-1],o=this.views.indexOf(n),r=this.views.indexOf(a),s=this.views.slice(0,o),l=this.views.slice(r+1),d=0;darguments.length||'string'!=typeof t?(d=n,n=t,t=null):d=arguments[2],null==t?(o=l=!0,s=!1):(o=r.call(t,'c'),s=r.call(t,'e'),l=r.call(t,'w')),u={value:n,configurable:o,enumerable:s,writable:l},d?a(i(d),u):u},s.gs=function(t,n,s){var l,d,u,p;return'string'==typeof t?u=arguments[3]:(u=s,s=n,n=t,t=null),null==n?n=void 0:o(n)?null==s?s=void 0:!o(s)&&(u=s,s=void 0):(u=n,n=s=void 0),null==t?(l=!0,d=!1):(l=r.call(t,'c'),d=r.call(t,'e')),p={get:n,set:s,configurable:l,enumerable:d},u?a(i(u),p):p}},function(e,t,n){'use strict';e.exports=n(29)()?Object.assign:n(30)},function(e){'use strict';e.exports=function(){var e=Object.assign,t;return!('function'!=typeof e)&&(t={foo:'raz'},e(t,{bar:'dwa'},{trzy:'trzy'}),'razdwatrzy'===t.foo+t.bar+t.trzy)}},function(e,t,n){'use strict';var a=n(31),o=n(35);e.exports=function(e,t){var n=s(arguments.length,2),r,l,i;for(e=Object(o(e)),i=function(n){try{e[n]=t[n]}catch(t){r||(r=t)}},l=1;l=t+n||t?new java.lang.String(e,t,n)+'':e}function d(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}a.prototype.parseFromString=function(e,t){var n=this.options,a=new u,r=n.domBuilder||new o,s=n.errorHandler,l=n.locator,d=n.xmlns||{},c={lt:'<',gt:'>',amp:'&',quot:'"',apos:'\''};return l&&r.setDocumentLocator(l),a.errorHandler=i(s,r,l),a.domBuilder=n.domBuilder||r,/\/x?html?$/.test(t)&&(c.nbsp='\xA0',c.copy='\xA9',d['']='http://www.w3.org/1999/xhtml'),d.xml=d.xml||'http://www.w3.org/XML/1998/namespace',e?a.parse(e,d,c):a.errorHandler.error('invalid doc source'),r.doc},o.prototype={startDocument:function(){this.doc=new c().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,n,a){var o=this.doc,s=o.createElementNS(e,n||t),l=a.length;d(this,s),this.currentElement=s,this.locator&&r(this.locator,s);for(var u=0;u>10),a=56320+(1023&e);return t(n,a)}return t(e)}function y(e){var t=e.slice(1,-1);return t in n?n[t]:'#'===t.charAt(0)?f(parseInt(t.substr(1).replace('x','0x'))):(m.error('entity not found:'+e),e)}function v(t){if(t>w){var n=e.substring(w,t).replace(/&#?\w+;/g,y);_&&b(w),c.characters(n,0,t-w),w=t}}function b(t,n){for(;t>=x&&(n=E.exec(e));)k=n.index,x=k+n[0].length,_.lineNumber++;_.columnNumber=t-k+1}for(var k=0,x=0,E=/.*(?:\r\n?|\n)|.*$/g,_=c.locator,N=[{currentNSMap:t}],S={},w=0;;){try{var T=e.indexOf('<',w);if(0>T){if(!e.substr(w).match(/^\s*$/)){var C=c.doc,R=C.createTextNode(e.substr(w));C.appendChild(R),c.currentElement=R}return}switch(T>w&&v(T),e.charAt(T+1)){case'/':var I=e.indexOf('>',T+3),A=e.substring(T+2,I),L=N.pop();0>I?(A=e.substring(T+2).replace(/[\s<].*/,''),m.error('end tag name: '+A+' is not complete:'+L.tagName),I=T+1+A.length):A.match(/\sw?w=I:v(s(T,w)+1)}}function o(e,n){return n.lineNumber=e.lineNumber,n.columnNumber=e.columnNumber,n}function r(e,t,n,a,i,o){for(var r=++t,l=b,s,d;;){var u=e.charAt(r);switch(u){case'=':if(l==k)s=e.slice(t,r),l=E;else if(l==x)l=E;else throw new Error('attribute equal must after attrName');break;case'\'':case'"':if(l==E||l==k){if(l==k&&(o.warning('attribute value must after "="'),s=e.slice(t,r)),t=r+1,r=e.indexOf(u,t),0=u)switch(l){case b:n.setTagName(e.slice(t,r)),l=S;break;case k:s=e.slice(t,r),l=x;break;case _:var d=e.slice(t,r).replace(/&#?\w+;/g,i);o.warning('attribute "'+d+'" missed quot(")!!'),n.add(s,d,t);case N:l=S;}else switch(l){case x:n.tagName;'http://www.w3.org/1999/xhtml'===a['']&&s.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),n.add(s,s,t),t=r,l=k;break;case N:o.warning('attribute space is required"'+s+'"!!');case S:l=k,t=r;break;case E:l=_,t=r;break;case w:throw new Error('elements closed character \'/\' and \'>\' must be connected to');}}r++}}function l(e,t,n){for(var o=e.tagName,r=null,s=e.length;s--;){var i=e[s],a=i.qName,l=i.value,d=a.indexOf(':');if(0',t),r=e.substring(t+1,o);if(/[&<]/.test(r))return /^script$/i.test(n)?(i.characters(r,0,r.length),o):(r=r.replace(/&#?\w+;/g,a),i.characters(r,0,r.length),o)}return t+1}function u(e,t,n,a){var i=a[n];return null==i&&(i=e.lastIndexOf(''),i',t+4);return o>t?(n.comment(e,t+4,o-t-4),o+3):(a.error('Unclosed comment'),-1)}return-1;default:if('CDATA['==e.substr(t+3,6)){var o=e.indexOf(']]>',t+9);return n.startCDATA(),n.characters(e,t+9,o-t-9),n.endCDATA(),o+3}var r=m(e,t),s=r.length;if(1',t);if(a){var i=e.substring(t,a).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(i){i[0].length;return n.processingInstruction(i[1],i[2]),a+2}return-1}return-1}function h(){}function i(e,t){return e.__proto__=t,e}function m(e,t){var n=[],a=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g,i;for(a.lastIndex=t,a.exec(e);i=a.exec(e);)if(n.push(i),i[1])return n}var f=/[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]/,y=new RegExp('[\\-\\.0-9'+f.source.slice(1,-1)+'\\u00B7\\u0300-\\u036F\\u203F-\\u2040]'),v=new RegExp('^'+f.source+y.source+'*(?::'+f.source+y.source+'*)?$'),b=0,k=1,x=2,E=3,_=4,N=5,S=6,w=7;n.prototype={parse:function(e,t,n){var i=this.domBuilder;i.startDocument(),c(t,t={}),a(e,t,n,i,this.errorHandler),i.endDocument()}},h.prototype={setTagName:function(e){if(!v.test(e))throw new Error('invalid tagName:'+e);this.tagName=e},add:function(e,t,n){if(!v.test(e))throw new Error('invalid attribute:'+e);this[this.length++]={qName:e,value:t,offset:n}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},i({},i.prototype)instanceof i||(i=function(e,t){function n(){}for(t in n.prototype=t,n=new n,e)n[t]=e[t];return n}),t.XMLReader=n},function(e,t,n){'use strict';function a(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}Object.defineProperty(t,'__esModule',{value:!0});var r=function(){function e(e,t){for(var n=0,a;nn&&(r+=n,i=n);i=n)r+=n-i,i=n;else{i+=o,d.endContainer=e,d.endOffset=i;var s=new c.default(d,t).toString();a.push(s),r=0}u=e}.bind(this)),d&&d.startContainer&&u){d.endContainer=u,d.endOffset=u.length;var p=new c.default(d,t).toString();a.push(p),r=0}return a}},{key:'locationFromCfi',value:function(e){var t;return(c.default.prototype.isCfiString(e)&&(e=new c.default(e)),0===this._locations.length)?-1:(t=(0,s.locationOf)(e,this._locations,this.epubcfi.compare),t>this.total?this.total:t)}},{key:'percentageFromCfi',value:function(e){if(0===this._locations.length)return null;var t=this.locationFromCfi(e);return this.percentageFromLocation(t)}},{key:'percentageFromLocation',value:function(e){return e&&this.total?e/this.total:0}},{key:'cfiFromLocation',value:function(e){var t=-1;return'number'!=typeof e&&(e=parseInt(e)),0<=e&&e=this._minSpreadWidth?2:1,'reflowable'!==this.name||'paginated'!==this._flow||0<=n||(i=0==s%2?s:s-1),'pre-paginated'===this.name&&(i=0),1=e.left&&t.top>=e.top&&t.bottom<=e.bottom}var u='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&'function'==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?'symbol':typeof e};Object.defineProperty(t,'__esModule',{value:!0}),t.Underline=t.Highlight=t.Mark=t.Pane=void 0;var c=function e(t,n,a){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(i===void 0){var o=Object.getPrototypeOf(t);return null===o?void 0:e(o,n,a)}if('value'in i)return i.value;var r=i.get;return void 0===r?void 0:r.call(a)},p=function(){function e(e,t){for(var n=0,a;nn&&r>t}var s=t.getBoundingClientRect(),r=e.getBoundingClientRect();if(!o(r,n,a))return!1;for(var l=e.getClientRects(),d=0,i=l.length;d(e/=0.5)?0.5*s(e,5):0.5*(s(e-2,5)+2)},easeInCubic:function(e){return s(e,3)}},m=function(){function e(t,n){o(this,e),this.settings=(0,u.extend)({duration:80,minVelocity:0.2,minDistance:10,easing:h.easeInCubic},n||{}),this.supportsTouch=this.supportsTouch(),this.supportsTouch&&this.setup(t)}return d(e,[{key:'setup',value:function(e){this.manager=e,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())}},{key:'supportsTouch',value:function(){return'ontouchstart'in window||window.DocumentTouch&&document instanceof DocumentTouch}},{key:'disableScroll',value:function(){this.element.style.overflow='hidden'}},{key:'enableScroll',value:function(){this.element.style.overflow=''}},{key:'addListeners',value:function(){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(c.EVENTS.MANAGERS.ADDED,this._afterDisplayed)}},{key:'removeListeners',value:function(){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(c.EVENTS.MANAGERS.ADDED,this._afterDisplayed),this._afterDisplayed=void 0}},{key:'afterDisplayed',value:function(e){var t=this,n=e.contents;['touchstart','touchmove','touchend'].forEach(function(a){n.on(a,function(e){return t.triggerViewEvent(e,n)})})}},{key:'triggerViewEvent',value:function(t,e){this.emit(t.type,t,e)}},{key:'onScroll',value:function(){this.scrollLeft=this.fullsize?window.scrollX:this.scroller.scrollLeft,this.scrollTop=this.fullsize?window.scrollY:this.scroller.scrollTop}},{key:'onResize',value:function(){this.resizeCanceler=!0}},{key:'onTouchStart',value:function(t){var e=t.touches[0],n=e.screenX,a=e.screenY;this.fullsize&&this.enableScroll(),this.touchCanceler=!0,this.startTouchX||(this.startTouchX=n,this.startTouchY=a,this.startTime=this.now()),this.endTouchX=n,this.endTouchY=a,this.endTime=this.now()}},{key:'onTouchMove',value:function(t){var e=t.touches[0],n=e.screenX,i=e.screenY,o=a(i-this.endTouchY);this.touchCanceler=!0,!this.fullsize&&10>o&&(this.element.scrollLeft-=n-this.endTouchX),this.endTouchX=n,this.endTouchY=i,this.endTime=this.now()}},{key:'onTouchEnd',value:function(){this.fullsize&&this.disableScroll(),this.touchCanceler=!1;var e=this.wasSwiped();0===e?this.snap():this.snap(e),this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0}},{key:'wasSwiped',value:function(){var e=this.layout.pageWidth*this.layout.divisor,t=this.endTouchX-this.startTouchX,n=a(t),i=this.endTime-this.startTime,o=t/i,r=this.settings.minVelocity;return n<=this.settings.minDistance||n>=e?0:o>r?-1:o<-r?1:void 0}},{key:'needsSnap',value:function(){var e=this.scrollLeft,t=this.layout.pageWidth*this.layout.divisor;return 0!=e%t}},{key:'snap',value:function(){var e=0d?(window.requestAnimationFrame(t.bind(this)),this.scrollTo(a+(e-a)*d,0)):(this.scrollTo(e,0),this.snapping=!1,n.resolve()))}var n=new u.defer,a=this.scrollLeft,o=this.now(),r=this.settings.duration,s=this.settings.easing;return this.snapping=!0,t.call(this),n.promise}},{key:'scrollTo',value:function(){var e=0=n.oldVersion&&e.createObjectStore(j)}catch(e){if('ConstraintError'===e.name)console.warn('The database "'+t.name+'" has been upgraded from version '+n.oldVersion+' to version '+n.newVersion+', but the storage "'+t.storeName+'" already exists.');else throw e}}),o.onerror=function(t){t.preventDefault(),a(o.error)},o.onsuccess=function(){n(o.result),p(t)}})}function m(e){return h(e,!1)}function f(e){return h(e,!0)}function y(e,t){if(!e.db)return!0;var n=!e.db.objectStoreNames.contains(e.storeName),a=e.versione.db.version;if(a&&(e.version!==t&&console.warn('The database "'+e.name+'" can\'t be downgraded from version '+e.db.version+' to version '+e.version+'.'),e.version=e.db.version),i||n){if(n){var o=e.db.version+1;o>e.version&&(e.version=o)}return!0}return!1}function v(t){return new B(function(n,e){var a=new FileReader;a.onerror=e,a.onloadend=function(a){var e=btoa(a.target.result||'');n({__local_forage_encoded_blob:!0,data:e,type:t.type})},a.readAsBinaryString(t)})}function b(e){var t=l(atob(e.data));return a([t],{type:e.type})}function k(e){return e&&e.__local_forage_encoded_blob}function x(e){var t=this,n=t._initReady().then(function(){var e=U[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady});return o(n,e,e),n}function E(e){c(e);for(var t=U[e.name],n=t.forages,a=0,i;a>4,u[a++]=(15&r)<<4|s>>2,u[a++]=(3&s)<<6|63&l;return d}function w(e){var t=new Uint8Array(e),n='',a;for(a=0;a>2],n+=X[(3&t[a])<<4|t[a+1]>>4],n+=X[(15&t[a+1])<<2|t[a+2]>>6],n+=X[63&t[a+2]];return 2==t.length%3?n=n.substring(0,n.length-1)+'=':1==t.length%3&&(n=n.substring(0,n.length-2)+'=='),n}function T(e,t,n,a){e.executeSql('CREATE TABLE IF NOT EXISTS '+t.storeName+' (id INTEGER PRIMARY KEY, key unique, value)',[],n,a)}function C(e,n,a,i,o,r){e.executeSql(a,i,o,function(e,s){s.code===s.SYNTAX_ERR?e.executeSql('SELECT name FROM sqlite_master WHERE type=\'table\' AND name = ?',[n.storeName],function(e,t){t.rows.length?r(e,s):T(e,n,function(){e.executeSql(a,i,o,r)},r)},r):r(e,s)},r)}function R(e,t,n,a){var o=this;e=r(e);var s=new B(function(i,r){o.ready().then(function(){void 0===t&&(t=null);var s=t,l=o._dbInfo;l.serializer.serialize(t,function(d,t){t?r(t):l.db.transaction(function(n){C(n,l,'INSERT OR REPLACE INTO '+l.storeName+' (key, value) VALUES (?, ?)',[e,d],function(){i(s)},function(e,t){r(t)})},function(t){if(t.code===t.QUOTA_ERR){if(0 \'__WebKitDatabaseInfoTable__\'',[],function(a,t){for(var o=[],r=0;re?void t(null):void n.ready().then(function(){_(n._dbInfo,W,function(i,o){if(i)return a(i);try{var r=o.objectStore(n._dbInfo.storeName),s=!1,l=r.openCursor();l.onsuccess=function(){var n=l.result;return n?void(0===e?t(n.key):s?t(n.key):(s=!0,n.advance(e))):void t(null)},l.onerror=function(){a(l.error)}}catch(t){a(t)}})})['catch'](a)});return i(a,t),a},keys:function(e){var t=this,n=new B(function(e,n){t.ready().then(function(){_(t._dbInfo,W,function(a,i){if(a)return n(a);try{var o=i.objectStore(t._dbInfo.storeName),r=o.openCursor(),s=[];r.onsuccess=function(){var t=r.result;return t?void(s.push(t.key),t['continue']()):void e(s)},r.onerror=function(){n(r.error)}}catch(t){n(t)}})})['catch'](n)});return i(n,e),n},dropInstance:function(e,t){t=s.apply(this,arguments);var n=this.config();e='function'!=typeof e&&e||{},e.name||(e.name=e.name||n.name,e.storeName=e.storeName||n.storeName);var a=this,o;if(!e.name)o=B.reject('Invalid arguments');else{var r=e.name===n.name&&a._dbInfo.db,l=r?B.resolve(a._dbInfo.db):m(e).then(function(t){var n=U[e.name],a=n.forages;n.db=t;for(var o=0;ot[0]?1:0}),e._entries&&(e._entries={});for(var n=0;n