diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..f4bf68a --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,42 @@ +module.exports = { + "env": { + "browser": true, + "commonjs": true, + "es6": true, + "node": true + }, + "globals": { + "ePub": true, + "JSZip": true + }, + "extends": "eslint:recommended", + "parserOptions": { + "sourceType": "module" + }, + "rules": { + "indent": [ + "error", + "tab", + { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } } + ], + "linebreak-style": [ + "error", + "unix" + ], + "quotes": [ + "warn", + "double" + ], + "semi": [ + "error", + "always" + ], + "no-unused-vars" : ["warn"], + "no-console" : ["warn"], + "no-unused-vars": [ + "error", + { "vars": "all", "args": "none" } + ], + "no-mixed-spaces-and-tabs": ["error", "smart-tabs"] + } +}; diff --git a/src/archive.js b/src/archive.js index a2e9e54..5a0e995 100644 --- a/src/archive.js +++ b/src/archive.js @@ -1,7 +1,7 @@ -import {defer, isXml, parse} from './utils/core'; -import request from './request'; -import mime from '../libs/mime/mime'; -import Path from './utils/path'; +import {defer, isXml, parse} from "./utils/core"; +import request from "./utils/request"; +import mime from "../libs/mime/mime"; +import Path from "./utils/path"; /** * Handles Unzipping a requesting files from an Epub Archive @@ -22,14 +22,16 @@ class Archive { */ checkRequirements(){ try { - if (typeof JSZip === 'undefined') { - let JSZip = require('jszip'); + if (typeof JSZip === "undefined") { + let JSZip = require("jszip"); + this.zip = new JSZip(); + } else { + this.zip = new JSZip(); } - this.zip = new JSZip(); } catch (e) { - console.error("JSZip lib not loaded"); + throw new Error("JSZip lib not loaded"); } - }; + } /** * Open an archive @@ -39,7 +41,7 @@ class Archive { */ open(input, isBase64){ return this.zip.loadAsync(input, {"base64": isBase64}); - }; + } /** * Load and Open an archive @@ -52,7 +54,7 @@ class Archive { .then(function(data){ return this.zip.loadAsync(data, {"base64": isBase64}); }.bind(this)); - }; + } /** * Request @@ -63,7 +65,6 @@ class Archive { request(url, type){ var deferred = new defer(); var response; - var r; var path = new Path(url); // If type isn't set, determine it from the file extension @@ -71,7 +72,7 @@ class Archive { type = path.extension; } - if(type == 'blob'){ + if(type == "blob"){ response = this.getBlob(url); } else { response = this.getText(url); @@ -89,7 +90,7 @@ class Archive { }); } return deferred.promise; - }; + } /** * Handle the response from request @@ -109,18 +110,18 @@ class Archive { r = parse(response, "text/xml"); } else - if(type == 'xhtml') { + if(type == "xhtml") { r = parse(response, "application/xhtml+xml"); } else - if(type == 'html' || type == 'htm') { + if(type == "html" || type == "htm") { r = parse(response, "text/html"); } else { r = response; } return r; - }; + } /** * Get a Blob from Archive by Url @@ -138,7 +139,7 @@ class Archive { return new Blob([uint8array], {type : mimeType}); }); } - }; + } /** * Get Text from Archive by Url @@ -155,7 +156,7 @@ class Archive { return text; }); } - }; + } /** * Get a base64 encoded result from Archive by Url @@ -173,7 +174,7 @@ class Archive { return "data:" + mimeType + ";base64," + data; }); } - }; + } /** * Create a Url from an unarchived item @@ -185,7 +186,6 @@ class Archive { var deferred = new defer(); var _URL = window.URL || window.webkitURL || window.mozURL; var tempUrl; - var blob; var response; var useBase64 = options && options.base64; @@ -232,7 +232,7 @@ class Archive { } return deferred.promise; - }; + } /** * Revoke Temp Url for a achive item @@ -242,7 +242,7 @@ class Archive { var _URL = window.URL || window.webkitURL || window.mozURL; var fromCache = this.urlCache[url]; if(fromCache) _URL.revokeObjectURL(fromCache); - }; + } } export default Archive; diff --git a/src/book.js b/src/book.js index 8ec5463..2bd4cb5 100644 --- a/src/book.js +++ b/src/book.js @@ -1,21 +1,22 @@ -import EventEmitter from 'event-emitter'; -// import path from 'path'; -import {extend, defer} from './utils/core'; -import Url from './utils/url'; -import Path from './utils/path'; -import Spine from './spine'; -import Locations from './locations'; -import Container from './container'; -import Packaging from './packaging'; -import Navigation from './navigation'; -import Resources from './resources'; -import PageList from './pagelist'; -import Rendition from './rendition'; -import Archive from './archive'; -import request from './request'; -import EpubCFI from './epubcfi'; +import EventEmitter from "event-emitter"; +// import path from "path"; +import {extend, defer} from "./utils/core"; +import Url from "./utils/url"; +import Path from "./utils/path"; +import Spine from "./spine"; +import Locations from "./locations"; +import Container from "./container"; +import Packaging from "./packaging"; +import Navigation from "./navigation"; +import Resources from "./resources"; +import PageList from "./pagelist"; +import Rendition from "./rendition"; +import Archive from "./archive"; +import request from "./utils/request"; +import EpubCFI from "./epubcfi"; const CONTAINER_PATH = "META-INF/container.xml"; +const EPUBJS_VERSION = "0.3.1"; /** * Creates a new Book @@ -45,7 +46,7 @@ class Book { requestCredentials: undefined, requestHeaders: undefined, encoding: undefined, - replacements: 'base64' + replacements: "base64" }); extend(this.settings, options); @@ -84,12 +85,14 @@ class Book { * @property {promise} ready returns after the book is loaded and parsed * @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 + ]); // Queue for methods used before opening @@ -143,12 +146,11 @@ class Book { if(url) { this.open(url).catch((error) => { var err = new Error("Cannot load book at "+ url ); - console.error(err); + // console.error(err); this.emit("openFailed", err); - console.log(error); }); } - }; + } /** * Open a epub or url @@ -172,7 +174,7 @@ class Book { } else if (type === "epub") { this.archived = true; this.url = new Url("/", ""); - opening = this.request(input, 'binary') + opening = this.request(input, "binary") .then(this.openEpub.bind(this)); } else if(type == "opf") { this.url = new Url(input); @@ -224,7 +226,6 @@ class Book { * @return {Promise} */ openPackaging(url) { - var packageUrl; this.path = new Path(url); return this.load(url) .then((xml) => { @@ -258,7 +259,7 @@ class Book { */ resolve(path, absolute) { var resolved = path; - var isAbsolute = (path.indexOf('://') > -1); + var isAbsolute = (path.indexOf("://") > -1); if (isAbsolute) { return path; @@ -309,7 +310,7 @@ class Book { if(extension === "opf"){ return "opf"; } - }; + } /** @@ -369,7 +370,7 @@ class Book { return; } - return this.load(navPath, 'xml') + return this.load(navPath, "xml") .then((xml) => { this.navigation = new Navigation(xml); this.pageList = new PageList(xml); @@ -400,7 +401,7 @@ class Book { this.rendition.attachTo(element); return this.rendition; - }; + } /** * Set if request should use withCredentials @@ -408,7 +409,7 @@ class Book { */ setRequestCredentials(credentials) { this.settings.requestCredentials = credentials; - }; + } /** * Set headers request should use @@ -416,7 +417,7 @@ class Book { */ setRequestHeaders(headers) { this.settings.requestHeaders = headers; - }; + } /** * Unarchive a zipped epub @@ -478,7 +479,7 @@ class Book { return item.load().then(function (contents) { var range = cfi.toRange(item.document); return range; - }) + }); } /** @@ -488,7 +489,7 @@ class Book { */ key(identifier) { var ident = identifier || this.package.metadata.identifier || this.url.filename; - return "epubjs:" + (EPUBJS_VERSION || ePub.VERSION) + ":" + ident; + return `epubjs:${EPUBJS_VERSION}:${ident}`; } } diff --git a/src/container.js b/src/container.js index df656e1..2d4eaa4 100644 --- a/src/container.js +++ b/src/container.js @@ -1,6 +1,5 @@ -import path from 'path-webpack'; -import {qs} from './utils/core'; -import EpubCFI from './epubcfi'; +import path from "path-webpack"; +import {qs} from "./utils/core"; /** * Handles Parsing and Accessing an Epub Container @@ -12,32 +11,30 @@ class Container { if (containerDocument) { this.parse(containerDocument); } - }; + } /** * Parse the Container XML * @param {document} containerDocument */ parse(containerDocument){ - //-- - var rootfile, fullpath, folder, encoding; + //-- + var rootfile; - if(!containerDocument) { - console.error("Container File Not Found"); - return; - } + if(!containerDocument) { + throw new Error("Container File Not Found"); + } - rootfile = qs(containerDocument, "rootfile"); + rootfile = qs(containerDocument, "rootfile"); - if(!rootfile) { - console.error("No RootFile Found"); - return; - } + if(!rootfile) { + throw new Error("No RootFile Found"); + } - this.packagePath = rootfile.getAttribute('full-path'); - this.directory = path.dirname(this.packagePath); - this.encoding = containerDocument.xmlEncoding; - }; + this.packagePath = rootfile.getAttribute("full-path"); + this.directory = path.dirname(this.packagePath); + this.encoding = containerDocument.xmlEncoding; + } } export default Container; diff --git a/src/contents.js b/src/contents.js index edf6db4..0fd723f 100644 --- a/src/contents.js +++ b/src/contents.js @@ -1,7 +1,7 @@ -import EventEmitter from 'event-emitter'; -import {isNumber, prefixed} from './utils/core'; -import EpubCFI from './epubcfi'; -import Mapping from './mapping'; +import EventEmitter from "event-emitter"; +import {isNumber, prefixed} from "./utils/core"; +import EpubCFI from "./epubcfi"; +import Mapping from "./mapping"; class Contents { @@ -19,12 +19,12 @@ class Contents { this._size = { width: 0, height: 0 - } + }; this.cfiBase = cfiBase || ""; this.listeners(); - }; + } width(w) { // var frame = this.documentElement; @@ -39,10 +39,10 @@ class Contents { // this.content.style.width = w; } - return this.window.getComputedStyle(frame)['width']; + return this.window.getComputedStyle(frame)["width"]; - }; + } height(h) { // var frame = this.documentElement; @@ -57,9 +57,9 @@ class Contents { // this.content.style.height = h; } - return this.window.getComputedStyle(frame)['height']; + return this.window.getComputedStyle(frame)["height"]; - }; + } contentWidth(w) { @@ -73,10 +73,10 @@ class Contents { content.style.width = w; } - return this.window.getComputedStyle(content)['width']; + return this.window.getComputedStyle(content)["width"]; - }; + } contentHeight(h) { @@ -90,9 +90,9 @@ class Contents { content.style.height = h; } - return this.window.getComputedStyle(content)['height']; + return this.window.getComputedStyle(content)["height"]; - }; + } textWidth() { var width; @@ -107,7 +107,7 @@ class Contents { return width; - }; + } textHeight() { var height; @@ -119,19 +119,19 @@ class Contents { height = range.getBoundingClientRect().height; return height; - }; + } scrollWidth() { var width = this.documentElement.scrollWidth; return width; - }; + } scrollHeight() { var height = this.documentElement.scrollHeight; return height; - }; + } overflow(overflow) { @@ -139,8 +139,8 @@ class Contents { this.documentElement.style.overflow = overflow; } - return this.window.getComputedStyle(this.documentElement)['overflow']; - }; + return this.window.getComputedStyle(this.documentElement)["overflow"]; + } overflowX(overflow) { @@ -148,8 +148,8 @@ class Contents { this.documentElement.style.overflowX = overflow; } - return this.window.getComputedStyle(this.documentElement)['overflowX']; - }; + return this.window.getComputedStyle(this.documentElement)["overflowX"]; + } overflowY(overflow) { @@ -157,8 +157,8 @@ class Contents { this.documentElement.style.overflowY = overflow; } - return this.window.getComputedStyle(this.documentElement)['overflowY']; - }; + return this.window.getComputedStyle(this.documentElement)["overflowY"]; + } css(property, value) { var content = this.content || this.document.body; @@ -168,31 +168,31 @@ class Contents { } return this.window.getComputedStyle(content)[property]; - }; + } viewport(options) { var width, height, scale, scalable; var $viewport = this.document.querySelector("meta[name='viewport']"); - var newContent = ''; + var newContent = ""; /* * check for the viewport size * */ if($viewport && $viewport.hasAttribute("content")) { - content = $viewport.getAttribute("content"); - contents = content.split(/\s*,\s*/); + let content = $viewport.getAttribute("content"); + let contents = content.split(/\s*,\s*/); if(contents[0]){ - width = contents[0].replace("width=", '').trim(); + width = contents[0].replace("width=", "").trim(); } if(contents[1]){ - height = contents[1].replace("height=", '').trim(); + height = contents[1].replace("height=", "").trim(); } if(contents[2]){ - scale = contents[2].replace("initial-scale=", '').trim(); + scale = contents[2].replace("initial-scale=", "").trim(); } if(contents[3]){ - scalable = contents[3].replace("user-scalable=", '').trim(); + scalable = contents[3].replace("user-scalable=", "").trim(); } } @@ -210,7 +210,7 @@ class Contents { if (!$viewport) { $viewport = this.document.createElement("meta"); $viewport.setAttribute("name", "viewport"); - this.document.querySelector('head').appendChild($viewport); + this.document.querySelector("head").appendChild($viewport); } $viewport.setAttribute("content", newContent); @@ -221,7 +221,7 @@ class Contents { width: parseInt(width), height: parseInt(height) }; - }; + } // layout(layoutFunc) { @@ -247,7 +247,7 @@ class Contents { expand() { this.emit("expand"); - }; + } listeners() { @@ -263,14 +263,14 @@ class Contents { this.resizeListeners(); - }; + } removeListeners() { this.removeEventListeners(); this.removeSelectionListeners(); - }; + } resizeListeners() { var width, height; @@ -285,43 +285,43 @@ class Contents { this._size = { width: width, height: height - } + }; this.emit("resize", this._size); } this.expanding = setTimeout(this.resizeListeners.bind(this), 350); - }; + } //https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js mediaQueryListeners() { - var sheets = this.document.styleSheets; - var mediaChangeHandler = function(m){ - if(m.matches && !this._expanding) { - setTimeout(this.expand.bind(this), 1); - // this.expand(); - } - }.bind(this); - - for (var i = 0; i < sheets.length; i += 1) { - var rules; - // Firefox errors if we access cssRules cross-domain - try { - rules = sheets[i].cssRules; - } catch (e) { - return; - } - if(!rules) return; // Stylesheets changed - for (var j = 0; j < rules.length; j += 1) { - //if (rules[j].constructor === CSSMediaRule) { - if(rules[j].media){ - var mql = this.window.matchMedia(rules[j].media.mediaText); - mql.addListener(mediaChangeHandler); - //mql.onchange = mediaChangeHandler; - } - } + var sheets = this.document.styleSheets; + var mediaChangeHandler = function(m){ + if(m.matches && !this._expanding) { + setTimeout(this.expand.bind(this), 1); + // this.expand(); } - }; + }.bind(this); + + for (var i = 0; i < sheets.length; i += 1) { + var rules; + // Firefox errors if we access cssRules cross-domain + try { + rules = sheets[i].cssRules; + } catch (e) { + return; + } + if(!rules) return; // Stylesheets changed + for (var j = 0; j < rules.length; j += 1) { + //if (rules[j].constructor === CSSMediaRule) { + if(rules[j].media){ + var mql = this.window.matchMedia(rules[j].media.mediaText); + mql.addListener(mediaChangeHandler); + //mql.onchange = mediaChangeHandler; + } + } + } + } observe(target) { var renderer = this; @@ -343,7 +343,7 @@ class Contents { observer.observe(target, config); return observer; - }; + } imageLoadListeners(target) { var images = this.document.querySelectorAll("img"); @@ -356,7 +356,7 @@ class Contents { img.onload = this.expand.bind(this); } } - }; + } fontLoadListeners(target) { if (!this.document || !this.document.fonts) { @@ -367,12 +367,12 @@ class Contents { this.expand(); }.bind(this)); - }; + } root() { if(!this.document) return null; return this.document.documentElement; - }; + } locationOf(target, ignoreClass) { var position; @@ -404,8 +404,8 @@ class Contents { } else if(typeof target === "string" && target.indexOf("#") > -1) { - id = target.substring(target.indexOf("#")+1); - el = this.document.getElementById(id); + let id = target.substring(target.indexOf("#")+1); + let el = this.document.getElementById(id); if(el) { position = el.getBoundingClientRect(); @@ -415,7 +415,7 @@ class Contents { } return targetPos; - }; + } addStylesheet(src) { return new Promise(function(resolve, reject){ @@ -428,18 +428,18 @@ class Contents { } // Check if link already exists - $stylesheet = this.document.querySelector('link[href="'+src+'"]'); + $stylesheet = this.document.querySelector("link[href='"+src+"']"); if ($stylesheet) { resolve(true); return; // already present } - $stylesheet = this.document.createElement('link'); - $stylesheet.type = 'text/css'; + $stylesheet = this.document.createElement("link"); + $stylesheet.type = "text/css"; $stylesheet.rel = "stylesheet"; $stylesheet.href = src; $stylesheet.onload = $stylesheet.onreadystatechange = function() { - if ( !ready && (!this.readyState || this.readyState == 'complete') ) { + if ( !ready && (!this.readyState || this.readyState == "complete") ) { ready = true; // Let apply setTimeout(function(){ @@ -451,7 +451,7 @@ class Contents { this.document.head.appendChild($stylesheet); }.bind(this)); - }; + } // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule addStylesheetRules(rules) { @@ -464,7 +464,7 @@ class Contents { // Check if link already exists styleEl = this.document.getElementById("#"+key); if (!styleEl) { - styleEl = this.document.createElement('style'); + styleEl = this.document.createElement("style"); styleEl.id = key; } @@ -475,22 +475,22 @@ class Contents { styleSheet = styleEl.sheet; for (var i = 0, rl = rules.length; i < rl; i++) { - var j = 1, rule = rules[i], selector = rules[i][0], propStr = ''; + var j = 1, rule = rules[i], selector = rules[i][0], propStr = ""; // If the second argument of a rule is an array of arrays, correct our variables. - if (Object.prototype.toString.call(rule[1][0]) === '[object Array]') { + if (Object.prototype.toString.call(rule[1][0]) === "[object Array]") { rule = rule[1]; j = 0; } for (var pl = rule.length; j < pl; j++) { var prop = rule[j]; - propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; + propStr += prop[0] + ":" + prop[1] + (prop[2] ? " !important" : "") + ";\n"; } // Insert CSS Rule - styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length); + styleSheet.insertRule(selector + "{" + propStr + "}", styleSheet.cssRules.length); } - }; + } addScript(src) { @@ -503,12 +503,12 @@ class Contents { return; } - $script = this.document.createElement('script'); - $script.type = 'text/javascript'; + $script = this.document.createElement("script"); + $script.type = "text/javascript"; $script.async = true; $script.src = src; $script.onload = $script.onreadystatechange = function() { - if ( !ready && (!this.readyState || this.readyState == 'complete') ) { + if ( !ready && (!this.readyState || this.readyState == "complete") ) { ready = true; setTimeout(function(){ resolve(true); @@ -519,7 +519,7 @@ class Contents { this.document.head.appendChild($script); }.bind(this)); - }; + } addClass(className) { var content; @@ -530,7 +530,7 @@ class Contents { content.classList.add(className); - }; + } removeClass(className) { var content; @@ -541,7 +541,7 @@ class Contents { content.classList.remove(className); - }; + } addEventListeners(){ if(!this.document) { @@ -551,7 +551,7 @@ class Contents { this.document.addEventListener(eventName, this.triggerEvent.bind(this), false); }, this); - }; + } removeEventListeners(){ if(!this.document) { @@ -561,26 +561,26 @@ class Contents { this.document.removeEventListener(eventName, this.triggerEvent, false); }, this); - }; + } // Pass browser events triggerEvent(e){ this.emit(e.type, e); - }; + } addSelectionListeners(){ if(!this.document) { return; } this.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); - }; + } removeSelectionListeners(){ if(!this.document) { return; } this.document.removeEventListener("selectionchange", this.onSelectionChange, false); - }; + } onSelectionChange(e){ if (this.selectionEndTimeout) { @@ -590,7 +590,7 @@ class Contents { var selection = this.window.getSelection(); this.triggerSelectedEvent(selection); }.bind(this), 500); - }; + } triggerSelectedEvent(selection){ var range, cfirange; @@ -604,17 +604,17 @@ class Contents { this.emit("selectedRange", range); } } - }; + } range(_cfi, ignoreClass){ var cfi = new EpubCFI(_cfi); return cfi.toRange(this.document, ignoreClass); - }; + } map(layout){ var map = new Mapping(layout); return map.section(); - }; + } size(width, height){ @@ -629,14 +629,13 @@ class Contents { this.css("margin", "0"); this.css("boxSizing", "border-box"); - }; + } columns(width, height, columnWidth, gap){ - var COLUMN_AXIS = prefixed('columnAxis'); - var COLUMN_GAP = prefixed('columnGap'); - var COLUMN_WIDTH = prefixed('columnWidth'); - var COLUMN_FILL = prefixed('columnFill'); - var textWidth; + var COLUMN_AXIS = prefixed("columnAxis"); + var COLUMN_GAP = prefixed("columnGap"); + var COLUMN_WIDTH = prefixed("columnWidth"); + var COLUMN_FILL = prefixed("columnFill"); this.width(width); this.height(height); @@ -655,20 +654,20 @@ class Contents { this.css(COLUMN_GAP, gap+"px"); this.css(COLUMN_WIDTH, columnWidth+"px"); - }; + } scaler(scale, offsetX, offsetY){ - var scale = "scale(" + scale + ")"; - var translate = ''; + var scaleStr = "scale(" + scale + ")"; + var translateStr = ""; // this.css("position", "absolute")); this.css("transformOrigin", "top left"); if (offsetX >= 0 || offsetY >= 0) { - translate = " translate(" + (offsetX || 0 )+ "px, " + (offsetY || 0 )+ "px )"; + translateStr = " translate(" + (offsetX || 0 )+ "px, " + (offsetY || 0 )+ "px )"; } - this.css("transform", scale + translate); - }; + this.css("transform", scaleStr + translateStr); + } fit(width, height){ var viewport = this.viewport(); @@ -689,13 +688,13 @@ class Contents { this.scaler(scale, 0, offsetY); this.css("backgroundColor", "transparent"); - }; + } mapPage(cfiBase, start, end) { var mapping = new Mapping(); return mapping.page(this, cfiBase, start, end); - }; + } destroy() { // Stop observing @@ -705,7 +704,7 @@ class Contents { this.removeListeners(); - }; + } } EventEmitter(Contents.prototype); diff --git a/src/epub.js b/src/epub.js index b6620c9..1d0a530 100644 --- a/src/epub.js +++ b/src/epub.js @@ -1,7 +1,7 @@ -import Book from './book'; -import EpubCFI from './epubcfi'; -import Rendition from './rendition'; -import Contents from './contents'; +import Book from "./book"; +import EpubCFI from "./epubcfi"; +import Rendition from "./rendition"; +import Contents from "./contents"; /** * Creates a new Book @@ -12,9 +12,9 @@ import Contents from './contents'; */ function ePub(url, options) { return new Book(url, options); -}; +} -ePub.VERSION = "0.3.0"; +ePub.VERSION = "0.3.1"; if (typeof(global) !== "undefined") { global.EPUBJS_VERSION = ePub.VERSION; @@ -45,10 +45,10 @@ ePub.register = { }; // Default Views -ePub.register.view("iframe", require('./managers/views/iframe')); +ePub.register.view("iframe", require("./managers/views/iframe")); // Default View Managers -ePub.register.manager("default", require('./managers/default')); -ePub.register.manager("continuous", require('./managers/continuous')); +ePub.register.manager("default", require("./managers/default")); +ePub.register.manager("continuous", require("./managers/continuous")); export default ePub; diff --git a/src/epubcfi.js b/src/epubcfi.js index cfcf449..401a077 100644 --- a/src/epubcfi.js +++ b/src/epubcfi.js @@ -1,4 +1,4 @@ -import {extend, type, findChildren} from './utils/core'; +import {extend, type, findChildren} from "./utils/core"; /** EPUB CFI spec: http://www.idpf.org/epub/linking/cfi/epub-cfi.html @@ -14,16 +14,16 @@ import {extend, type, findChildren} from './utils/core'; - Text Location Assertion ([) */ -var ELEMENT_NODE = 1; -var TEXT_NODE = 3; -var COMMENT_NODE = 8; -var DOCUMENT_NODE = 9; +const ELEMENT_NODE = 1; +const TEXT_NODE = 3; +// const COMMENT_NODE = 8; +const DOCUMENT_NODE = 9; class EpubCFI { constructor(cfiFrom, base, ignoreClass){ var type; - this.str = ''; + this.str = ""; this.base = {}; this.spinePos = 0; // For compatibility @@ -34,62 +34,62 @@ class EpubCFI { this.start = null; this.end = null; - // Allow instantiation without the 'new' keyword + // Allow instantiation without the "new" keyword if (!(this instanceof EpubCFI)) { return new EpubCFI(cfiFrom, base, ignoreClass); } - if(typeof base === 'string') { + if(typeof base === "string") { this.base = this.parseComponent(base); - } else if(typeof base === 'object' && base.steps) { + } else if(typeof base === "object" && base.steps) { this.base = base; } type = this.checkType(cfiFrom); - if(type === 'string') { + if(type === "string") { this.str = cfiFrom; return extend(this, this.parse(cfiFrom)); - } else if (type === 'range') { + } else if (type === "range") { return extend(this, this.fromRange(cfiFrom, this.base, ignoreClass)); - } else if (type === 'node') { + } else if (type === "node") { return extend(this, this.fromNode(cfiFrom, this.base, ignoreClass)); - } else if (type === 'EpubCFI' && cfiFrom.path) { + } else if (type === "EpubCFI" && cfiFrom.path) { return cfiFrom; } else if (!cfiFrom) { return this; } else { - throw new TypeError('not a valid argument for EpubCFI'); + throw new TypeError("not a valid argument for EpubCFI"); } - }; + } checkType(cfi) { if (this.isCfiString(cfi)) { - return 'string'; + return "string"; // Is a range object - } else if (typeof cfi === 'object' && (type(cfi) === "Range" || typeof(cfi.startContainer) != "undefined")){ - return 'range'; - } else if (typeof cfi === 'object' && typeof(cfi.nodeType) != "undefined" ){ // || typeof cfi === 'function' - return 'node'; - } else if (typeof cfi === 'object' && cfi instanceof EpubCFI){ - return 'EpubCFI'; + } else if (typeof cfi === "object" && (type(cfi) === "Range" || typeof(cfi.startContainer) != "undefined")){ + return "range"; + } else if (typeof cfi === "object" && typeof(cfi.nodeType) != "undefined" ){ // || typeof cfi === "function" + return "node"; + } else if (typeof cfi === "object" && cfi instanceof EpubCFI){ + return "EpubCFI"; } else { return false; } - }; + } parse(cfiStr) { var cfi = { - spinePos: -1, - range: false, - base: {}, - path: {}, - start: null, - end: null - }; + spinePos: -1, + range: false, + base: {}, + path: {}, + start: null, + end: null + }; var baseComponent, pathComponent, range; if(typeof cfiStr !== "string") { @@ -128,7 +128,7 @@ class EpubCFI { cfi.spinePos = cfi.base.steps[1].index; return cfi; - }; + } parseComponent(componentStr){ var component = { @@ -138,8 +138,8 @@ class EpubCFI { assertion: null } }; - var parts = componentStr.split(':'); - var steps = parts[0].split('/'); + var parts = componentStr.split(":"); + var steps = parts[0].split("/"); var terminal; if(parts.length > 1) { @@ -147,7 +147,7 @@ class EpubCFI { component.terminal = this.parseTerminal(terminal); } - if (steps[0] === '') { + if (steps[0] === "") { steps.shift(); // Ignore the first slash } @@ -156,7 +156,7 @@ class EpubCFI { }.bind(this)); return component; - }; + } parseStep(stepStr){ var type, num, index, has_brackets, id; @@ -183,46 +183,46 @@ class EpubCFI { return { "type" : type, - 'index' : index, - 'id' : id || null + "index" : index, + "id" : id || null }; - }; + } parseTerminal(termialStr){ var characterOffset, textLocationAssertion; var assertion = termialStr.match(/\[(.*)\]/); if(assertion && assertion[1]){ - characterOffset = parseInt(termialStr.split('[')[0]) || null; + characterOffset = parseInt(termialStr.split("[")[0]) || null; textLocationAssertion = assertion[1]; } else { characterOffset = parseInt(termialStr) || null; } return { - 'offset': characterOffset, - 'assertion': textLocationAssertion + "offset": characterOffset, + "assertion": textLocationAssertion }; - }; + } getChapterComponent(cfiStr) { var indirection = cfiStr.split("!"); return indirection[0]; - }; + } getPathComponent(cfiStr) { var indirection = cfiStr.split("!"); if(indirection[1]) { - let ranges = indirection[1].split(','); + let ranges = indirection[1].split(","); return ranges[0]; } - }; + } getRange(cfiStr) { @@ -236,12 +236,12 @@ class EpubCFI { } return false; - }; + } getCharecterOffsetComponent(cfiStr) { var splitStr = cfiStr.split(":"); - return splitStr[1] || ''; - }; + return splitStr[1] || ""; + } joinSteps(steps) { if(!steps) { @@ -249,13 +249,13 @@ class EpubCFI { } return steps.map(function(part){ - var segment = ''; + var segment = ""; - if(part.type === 'element') { + if(part.type === "element") { segment += (part.index + 1) * 2; } - if(part.type === 'text') { + if(part.type === "text") { segment += 1 + (2 * part.index); // TODO: double check that this is odd } @@ -265,58 +265,58 @@ class EpubCFI { return segment; - }).join('/'); + }).join("/"); - }; + } segmentString(segment) { - var segmentString = '/'; + var segmentString = "/"; segmentString += this.joinSteps(segment.steps); if(segment.terminal && segment.terminal.offset != null){ - segmentString += ':' + segment.terminal.offset; + segmentString += ":" + segment.terminal.offset; } if(segment.terminal && segment.terminal.assertion != null){ - segmentString += '[' + segment.terminal.assertion + ']'; + segmentString += "[" + segment.terminal.assertion + "]"; } return segmentString; - }; + } toString() { - var cfiString = 'epubcfi('; + var cfiString = "epubcfi("; cfiString += this.segmentString(this.base); - cfiString += '!'; + cfiString += "!"; cfiString += this.segmentString(this.path); // Add Range, if present if(this.start) { - cfiString += ','; + cfiString += ","; cfiString += this.segmentString(this.start); } if(this.end) { - cfiString += ','; + cfiString += ","; cfiString += this.segmentString(this.end); } cfiString += ")"; return cfiString; - }; + } compare(cfiOne, cfiTwo) { var stepsA, stepsB; var terminalA, terminalB; - if(typeof cfiOne === 'string') { + if(typeof cfiOne === "string") { cfiOne = new EpubCFI(cfiOne); } - if(typeof cfiTwo === 'string') { + if(typeof cfiTwo === "string") { cfiTwo = new EpubCFI(cfiTwo); } // Compare Spine Positions @@ -375,18 +375,18 @@ class EpubCFI { // CFI's are equal return 0; - }; + } step(node) { - var nodeType = (node.nodeType === TEXT_NODE) ? 'text' : 'element'; + var nodeType = (node.nodeType === TEXT_NODE) ? "text" : "element"; return { - 'id' : node.id, - 'tagName' : node.tagName, - 'type' : nodeType, - 'index' : this.position(node) + "id" : node.id, + "tagName" : node.tagName, + "type" : nodeType, + "index" : this.position(node) }; - }; + } filteredStep(node, ignoreClass) { var filteredNode = this.filter(node, ignoreClass); @@ -398,15 +398,15 @@ class EpubCFI { } // Otherwise add the filter node in - nodeType = (filteredNode.nodeType === TEXT_NODE) ? 'text' : 'element'; + nodeType = (filteredNode.nodeType === TEXT_NODE) ? "text" : "element"; return { - 'id' : filteredNode.id, - 'tagName' : filteredNode.tagName, - 'type' : nodeType, - 'index' : this.filteredPosition(filteredNode, ignoreClass) + "id" : filteredNode.id, + "tagName" : filteredNode.tagName, + "type" : nodeType, + "index" : this.filteredPosition(filteredNode, ignoreClass) }; - }; + } pathTo(node, offset, ignoreClass) { var segment = { @@ -443,8 +443,8 @@ class EpubCFI { // Make sure we are getting to a textNode if there is an offset if(segment.steps[segment.steps.length-1].type != "text") { segment.steps.push({ - 'type' : "text", - 'index' : 0 + "type" : "text", + "index" : 0 }); } @@ -466,16 +466,16 @@ class EpubCFI { } return false; - }; + } fromRange(range, base, ignoreClass) { var cfi = { - range: false, - base: {}, - path: {}, - start: null, - end: null - }; + range: false, + base: {}, + path: {}, + start: null, + end: null + }; var start = range.startContainer; var end = range.endContainer; @@ -487,14 +487,14 @@ class EpubCFI { if (ignoreClass) { // Tell pathTo if / what to ignore - needsIgnoring = (start.ownerDocument.querySelector('.' + ignoreClass) != null); + needsIgnoring = (start.ownerDocument.querySelector("." + ignoreClass) != null); } - if (typeof base === 'string') { + if (typeof base === "string") { cfi.base = this.parseComponent(base); cfi.spinePos = cfi.base.steps[1].index; - } else if (typeof base === 'object') { + } else if (typeof base === "object") { cfi.base = base; } @@ -544,7 +544,7 @@ class EpubCFI { } else { break; } - }; + } cfi.start.steps = cfi.start.steps.slice(cfi.path.steps.length); cfi.end.steps = cfi.end.steps.slice(cfi.path.steps.length); @@ -557,31 +557,24 @@ class EpubCFI { fromNode(anchor, base, ignoreClass) { var cfi = { - range: false, - base: {}, - path: {}, - start: null, - end: null - }; + range: false, + base: {}, + path: {}, + start: null, + end: null + }; - var needsIgnoring = false; - - if (ignoreClass) { - // Tell pathTo if / what to ignore - needsIgnoring = (anchor.ownerDocument.querySelector('.' + ignoreClass) != null); - } - - if (typeof base === 'string') { + if (typeof base === "string") { cfi.base = this.parseComponent(base); cfi.spinePos = cfi.base.steps[1].index; - } else if (typeof base === 'object') { + } else if (typeof base === "object") { cfi.base = base; } cfi.path = this.pathTo(anchor, null, ignoreClass); return cfi; - }; + } filter(anchor, ignoreClass) { var needsIgnoring; @@ -624,15 +617,11 @@ class EpubCFI { return anchor; } - }; + } patchOffset(anchor, offset, ignoreClass) { - var needsIgnoring; - var sibling; - if (anchor.nodeType != TEXT_NODE) { - console.error("Anchor must be a text node"); - return; + throw new Error("Anchor must be a text node"); } var curr = anchor; @@ -661,7 +650,7 @@ class EpubCFI { return totalOffset; - }; + } normalizedMap(children, nodeType, ignoreClass) { var output = {}; @@ -695,11 +684,10 @@ class EpubCFI { } return output; - }; + } position(anchor) { - var children, index, map; - var childNodes, node; + var children, index; if (anchor.nodeType === ELEMENT_NODE) { children = anchor.parentNode.children; if (!children) { @@ -712,7 +700,7 @@ class EpubCFI { } return index; - }; + } filteredPosition(anchor, ignoreClass) { var children, index, map; @@ -734,7 +722,7 @@ class EpubCFI { index = Array.prototype.indexOf.call(children, anchor); return map[index]; - }; + } stepsToXpath(steps) { var xpath = [".", "*"]; @@ -752,7 +740,7 @@ class EpubCFI { }); return xpath.join("/"); - }; + } /* @@ -788,7 +776,7 @@ class EpubCFI { return query.join(">"); - }; + } textNodes(container, ignoreClass) { return Array.prototype.slice.call(container.childNodes). @@ -800,7 +788,7 @@ class EpubCFI { } return false; }); - }; + } walkToNode(steps, _doc, ignoreClass) { var doc = _doc || document; @@ -818,17 +806,17 @@ class EpubCFI { container = this.textNodes(container, ignoreClass)[step.index]; } - }; + } return container; - }; + } findNode(steps, _doc, ignoreClass) { var doc = _doc || document; var container; var xpath; - if(!ignoreClass && typeof doc.evaluate != 'undefined') { + if(!ignoreClass && typeof doc.evaluate != "undefined") { xpath = this.stepsToXpath(steps); container = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; } else if(ignoreClass) { @@ -838,19 +826,17 @@ class EpubCFI { } return container; - }; + } fixMiss(steps, offset, _doc, ignoreClass) { var container = this.findNode(steps.slice(0,-1), _doc, ignoreClass); var children = container.childNodes; var map = this.normalizedMap(children, TEXT_NODE, ignoreClass); - var i; var child; var len; - var childIndex; var lastStepIndex = steps[steps.length-1].index; - for (var childIndex in map) { + for (let childIndex in map) { if (!map.hasOwnProperty(childIndex)) return; if(map[childIndex] === lastStepIndex) { @@ -874,7 +860,7 @@ class EpubCFI { offset: offset }; - }; + } toRange(_doc, ignoreClass) { var doc = _doc || document; @@ -882,7 +868,7 @@ class EpubCFI { var start, end, startContainer, endContainer; var cfi = this; var startSteps, endSteps; - var needsIgnoring = ignoreClass ? (doc.querySelector('.' + ignoreClass) != null) : false; + var needsIgnoring = ignoreClass ? (doc.querySelector("." + ignoreClass) != null) : false; var missed; if (cfi.range) { @@ -934,23 +920,23 @@ class EpubCFI { // doc.defaultView.getSelection().addRange(range); return range; - }; + } // is a cfi string, should be wrapped with "epubcfi()" isCfiString(str) { - if(typeof str === 'string' && - str.indexOf("epubcfi(") === 0 && - str[str.length-1] === ")") { + if(typeof str === "string" && + str.indexOf("epubcfi(") === 0 && + str[str.length-1] === ")") { return true; } return false; - }; + } generateChapterComponent(_spineNodeIndex, _pos, id) { var pos = parseInt(_pos), - spineNodeIndex = _spineNodeIndex + 1, - cfi = '/'+spineNodeIndex+'/'; + spineNodeIndex = _spineNodeIndex + 1, + cfi = "/"+spineNodeIndex+"/"; cfi += (pos + 1) * 2; @@ -959,7 +945,7 @@ class EpubCFI { } return cfi; - }; + } } export default EpubCFI; diff --git a/src/index.js b/src/index.js index 0341291..16ef8b6 100644 --- a/src/index.js +++ b/src/index.js @@ -1,9 +1,9 @@ -import Book from './book'; -import EpubCFI from './epubcfi'; -import Rendition from './rendition'; -import Contents from './contents'; -import Layout from './layout'; -import ePub from './epub'; +import Book from "./book"; +import EpubCFI from "./epubcfi"; +import Rendition from "./rendition"; +import Contents from "./contents"; +import Layout from "./layout"; +import ePub from "./epub"; export default ePub; export { diff --git a/src/layout.js b/src/layout.js index eadbe27..9011129 100644 --- a/src/layout.js +++ b/src/layout.js @@ -1,5 +1,3 @@ -import core from './utils/core'; - /** * Figures out the CSS to apply for a layout * @class @@ -32,7 +30,7 @@ class Layout { this.columnWidth = 0; this.gap = 0; this.divisor = 1; - }; + } /** * Switch the flow between paginated and scrolled @@ -69,7 +67,7 @@ class Layout { var gap = _gap || 0; //-- Check the width and create even width columns - var fullWidth = Math.floor(_width); + // var fullWidth = Math.floor(_width); var width = _width; var section = Math.floor(width / 8); @@ -115,7 +113,7 @@ class Layout { this.columnWidth = colWidth; this.gap = gap; this.divisor = divisor; - }; + } /** * Apply Css to a Document @@ -134,7 +132,7 @@ class Layout { } return formating; // might be a promise in some View Managers - }; + } /** * Count number of pages @@ -150,7 +148,7 @@ class Layout { spreads : spreads, pages : spreads * this.divisor }; - }; + } } export default Layout; diff --git a/src/locations.js b/src/locations.js index 2fe69bf..b5aeb62 100644 --- a/src/locations.js +++ b/src/locations.js @@ -1,7 +1,7 @@ -import {qs, sprint, locationOf} from './utils/core'; -import Queue from './queue'; -import EpubCFI from './epubcfi'; -import EventEmitter from 'event-emitter'; +import {qs, sprint, locationOf} from "./utils/core"; +import Queue from "./utils/queue"; +import EpubCFI from "./epubcfi"; +import EventEmitter from "event-emitter"; /** * Find Locations for a Book @@ -23,7 +23,7 @@ class Locations { this._current = 0; - }; + } /** * Load all of sections in the book to generate locations @@ -55,7 +55,7 @@ class Locations { // console.log(this.percentage(this.book.rendition.location.start), this.percentage(this.book.rendition.location.end)); }.bind(this)); - }; + } createRange () { return { @@ -63,8 +63,8 @@ class Locations { startOffset: undefined, endContainer: undefined, endOffset: undefined - } - }; + }; + } process(section) { @@ -74,13 +74,13 @@ class Locations { this._locations = this._locations.concat(locations); }.bind(this)); - }; + } parse(contents, cfiBase, chars) { var locations = []; var range; var doc = contents.ownerDocument; - var body = qs(doc, 'body'); + var body = qs(doc, "body"); var counter = 0; var prev; var _break = chars || this.break; @@ -151,7 +151,7 @@ class Locations { } return locations; - }; + } locationFromCfi(cfi){ // Check if the location has not been set yet @@ -159,7 +159,7 @@ class Locations { return -1; } return locationOf(cfi.start, this._locations, this.epubcfi.compare); - }; + } percentageFromCfi(cfi) { if(this._locations.length === 0) { @@ -169,20 +169,20 @@ class Locations { var loc = this.locationFromCfi(cfi); // Get percentage in total return this.percentageFromLocation(loc); - }; + } percentageFromLocation(loc) { if (!loc || !this.total) { return 0; } return (loc / this.total); - }; + } cfiFromLocation(loc){ var cfi = -1; // check that pg is an int if(typeof loc != "number"){ - loc = parseInt(pg); + loc = parseInt(loc); } if(loc >= 0 && loc < this._locations.length) { @@ -190,28 +190,28 @@ class Locations { } return cfi; - }; + } cfiFromPercentage(value){ var percentage = (value > 1) ? value / 100 : value; // Normalize value to 0-1 var loc = Math.ceil(this.total * percentage); return this.cfiFromLocation(loc); - }; + } load(locations){ this._locations = JSON.parse(locations); this.total = this._locations.length-1; return this._locations; - }; + } save(json){ return JSON.stringify(this._locations); - }; + } getCurrent(json){ return this._current; - }; + } setCurrent(curr){ var loc; @@ -238,7 +238,7 @@ class Locations { this.emit("changed", { percentage: this.percentageFromLocation(loc) }); - }; + } get currentLocation() { return this._current; @@ -250,7 +250,7 @@ class Locations { length () { return this._locations.length; - }; + } } EventEmitter(Locations.prototype); diff --git a/src/managers/continuous/index.js b/src/managers/continuous/index.js index 53b8992..64c73e2 100644 --- a/src/managers/continuous/index.js +++ b/src/managers/continuous/index.js @@ -1,9 +1,9 @@ -import {extend, defer, requestAnimationFrame} from '../../utils/core'; -import DefaultViewManager from '../default'; +import {extend, defer, requestAnimationFrame} from "../../utils/core"; +import DefaultViewManager from "../default"; class ContinuousViewManager extends DefaultViewManager { constructor(options) { - super(options) + super(options); // DefaultViewManager.apply(this, arguments); // call super constructor. this.name = "continuous"; @@ -36,14 +36,14 @@ class ContinuousViewManager extends DefaultViewManager { this.scrollTop = 0; this.scrollLeft = 0; - }; + } display(section, target){ return DefaultViewManager.prototype.display.call(this, section, target) .then(function () { return this.fill(); }.bind(this)); - }; + } fill(_full){ var full = _full || new defer(); @@ -80,7 +80,7 @@ class ContinuousViewManager extends DefaultViewManager { .then(function(){ this.scrollBy(distX, distY); }.bind(this)); - }; + } /* afterDisplayed(currView){ @@ -103,7 +103,7 @@ class ContinuousViewManager extends DefaultViewManager { // currView.onShown = this.afterDisplayed.bind(this); this.emit("added", currView.section); - }; + } */ resize(width, height){ @@ -134,7 +134,7 @@ class ContinuousViewManager extends DefaultViewManager { height: this.stage.height }); - }; + } onResized(e) { @@ -144,11 +144,11 @@ class ContinuousViewManager extends DefaultViewManager { this.resizeTimeout = setTimeout(function(){ this.resize(); }.bind(this), 150); - }; + } afterResized(view){ this.emit("resize", view.section); - }; + } // Remove Previous Listeners if present removeShownListeners(view){ @@ -157,7 +157,7 @@ class ContinuousViewManager extends DefaultViewManager { // view.off("shown", this.afterDisplayedAbove); view.onDisplayed = function(){}; - }; + } // append(section){ @@ -182,7 +182,7 @@ class ContinuousViewManager extends DefaultViewManager { var view = this.createView(section); this.views.append(view); return view; - }; + } prepend(section){ var view = this.createView(section); @@ -191,7 +191,7 @@ class ContinuousViewManager extends DefaultViewManager { this.views.prepend(view); return view; - }; + } counter(bounds){ @@ -201,7 +201,7 @@ class ContinuousViewManager extends DefaultViewManager { this.scrollBy(bounds.widthDelta, 0, true); } - }; + } update(_offset){ var container = this.bounds(); @@ -245,7 +245,7 @@ class ContinuousViewManager extends DefaultViewManager { return updating.promise; } - }; + } check(_offsetLeft, _offsetTop){ var last, first, next, prev; @@ -290,9 +290,9 @@ class ContinuousViewManager extends DefaultViewManager { // Promise.all(promises) // .then(function() { // Check to see if anything new is on screen after rendering - return this.q.enqueue(function(){ - return this.update(delta); - }.bind(this)); + return this.q.enqueue(function(){ + return this.update(delta); + }.bind(this)); // }.bind(this)); @@ -303,7 +303,7 @@ class ContinuousViewManager extends DefaultViewManager { } - }; + } trim(){ var task = new defer(); @@ -327,7 +327,7 @@ class ContinuousViewManager extends DefaultViewManager { task.resolve(); return task.promise; - }; + } erase(view, above){ //Trim @@ -355,18 +355,18 @@ class ContinuousViewManager extends DefaultViewManager { } } - }; + } addEventListeners(stage){ - window.addEventListener('unload', function(e){ + window.addEventListener("unload", function(e){ this.ignore = true; // this.scrollTo(0,0); this.destroy(); }.bind(this)); this.addScrollListeners(); - }; + } addScrollListeners() { var scroller; @@ -400,7 +400,7 @@ class ContinuousViewManager extends DefaultViewManager { this.scrolled = false; - }; + } onScroll(){ let scrollTop; @@ -408,70 +408,70 @@ class ContinuousViewManager extends DefaultViewManager { // if(!this.ignore) { - if(this.settings.height) { - scrollTop = this.container.scrollTop; - scrollLeft = this.container.scrollLeft; - } else { - scrollTop = window.scrollY; - scrollLeft = window.scrollX; - } + if(this.settings.height) { + scrollTop = this.container.scrollTop; + scrollLeft = this.container.scrollLeft; + } else { + scrollTop = window.scrollY; + scrollLeft = window.scrollX; + } - this.scrollTop = scrollTop; - this.scrollLeft = scrollLeft; + this.scrollTop = scrollTop; + this.scrollLeft = scrollLeft; - if(!this.ignore) { + if(!this.ignore) { - if((this.scrollDeltaVert === 0 && - this.scrollDeltaHorz === 0) || - this.scrollDeltaVert > this.settings.offsetDelta || - this.scrollDeltaHorz > this.settings.offsetDelta) { + if((this.scrollDeltaVert === 0 && + this.scrollDeltaHorz === 0) || + this.scrollDeltaVert > this.settings.offsetDelta || + this.scrollDeltaHorz > this.settings.offsetDelta) { - this.q.enqueue(function() { - this.check(); - }.bind(this)); - // this.check(); + this.q.enqueue(function() { + this.check(); + }.bind(this)); + // this.check(); - this.scrollDeltaVert = 0; - this.scrollDeltaHorz = 0; - - this.emit("scroll", { - top: scrollTop, - left: scrollLeft - }); - - clearTimeout(this.afterScrolled); - this.afterScrolled = setTimeout(function () { - this.emit("scrolled", { - top: this.scrollTop, - left: this.scrollLeft - }); - }.bind(this)); - - } - - } else { - this.ignore = false; - } - - this.scrollDeltaVert += Math.abs(scrollTop-this.prevScrollTop); - this.scrollDeltaHorz += Math.abs(scrollLeft-this.prevScrollLeft); - - this.prevScrollTop = scrollTop; - this.prevScrollLeft = scrollLeft; - - clearTimeout(this.scrollTimeout); - this.scrollTimeout = setTimeout(function(){ this.scrollDeltaVert = 0; this.scrollDeltaHorz = 0; - }.bind(this), 150); + + this.emit("scroll", { + top: scrollTop, + left: scrollLeft + }); + + clearTimeout(this.afterScrolled); + this.afterScrolled = setTimeout(function () { + this.emit("scrolled", { + top: this.scrollTop, + left: this.scrollLeft + }); + }.bind(this)); + + } + + } else { + this.ignore = false; + } + + this.scrollDeltaVert += Math.abs(scrollTop-this.prevScrollTop); + this.scrollDeltaHorz += Math.abs(scrollLeft-this.prevScrollLeft); + + this.prevScrollTop = scrollTop; + this.prevScrollLeft = scrollLeft; + + clearTimeout(this.scrollTimeout); + this.scrollTimeout = setTimeout(function(){ + this.scrollDeltaVert = 0; + this.scrollDeltaHorz = 0; + }.bind(this), 150); - this.scrolled = false; + this.scrolled = false; // } // this.tick.call(window, this.onScroll.bind(this)); - }; + } // resizeView(view) { @@ -493,14 +493,14 @@ class ContinuousViewManager extends DefaultViewManager { } return this.location; - }; + } scrolledLocation(){ var visible = this.visible(); var startPage, endPage; - var container = this.container.getBoundingClientRect(); + // var container = this.container.getBoundingClientRect(); if(visible.length === 1) { return this.mapping.page(visible[0].contents, visible[0].section.cfiBase); @@ -517,7 +517,7 @@ class ContinuousViewManager extends DefaultViewManager { }; } - }; + } paginatedLocation(){ var visible = this.visible(); @@ -550,7 +550,7 @@ class ContinuousViewManager extends DefaultViewManager { end: pageRight.end }; } - }; + } /* current(what){ @@ -595,7 +595,7 @@ class ContinuousViewManager extends DefaultViewManager { } return this._current; - }; + } */ updateLayout() { @@ -626,7 +626,7 @@ class ContinuousViewManager extends DefaultViewManager { this.setLayout(this.layout); - }; + } next(){ @@ -645,7 +645,7 @@ class ContinuousViewManager extends DefaultViewManager { } else { this.scrollBy(0, this.layout.height); } - }; + } prev(){ if(this.settings.axis === "horizontal") { @@ -653,7 +653,7 @@ class ContinuousViewManager extends DefaultViewManager { } else { this.scrollBy(0, -this.layout.height); } - }; + } updateFlow(flow){ var axis = (flow === "paginated") ? "horizontal" : "vertical"; @@ -674,7 +674,7 @@ class ContinuousViewManager extends DefaultViewManager { this.settings.infinite = false; } - }; + } } export default ContinuousViewManager; diff --git a/src/managers/default/index.js b/src/managers/default/index.js index 71da7fb..127fa44 100644 --- a/src/managers/default/index.js +++ b/src/managers/default/index.js @@ -1,10 +1,9 @@ -import EventEmitter from 'event-emitter'; -import {extend, defer} from '../../utils/core'; -import EpubCFI from '../../epubcfi'; -import Mapping from '../../mapping'; -import Queue from '../../queue'; -import Stage from '../helpers/stage'; -import Views from '../helpers/views'; +import EventEmitter from "event-emitter"; +import {extend, defer} from "../../utils/core"; +import Mapping from "../../mapping"; +import Queue from "../../utils/queue"; +import Stage from "../helpers/stage"; +import Views from "../helpers/views"; class DefaultViewManager { constructor(options) { @@ -20,10 +19,10 @@ class DefaultViewManager { hidden: false, width: undefined, height: undefined, - // globalLayoutProperties : { layout: 'reflowable', spread: 'auto', orientation: 'auto'}, + // globalLayoutProperties : { layout: "reflowable", spread: "auto", orientation: "auto"}, // layout: null, axis: "vertical", - ignoreClass: '' + ignoreClass: "" }); extend(this.settings, options.settings || {}); @@ -77,13 +76,13 @@ class DefaultViewManager { if (this.layout) { this.updateLayout(); } - }; + } addEventListeners(){ - window.addEventListener('unload', function(e){ + window.addEventListener("unload", function(e){ this.destroy(); }.bind(this)); - }; + } destroy(){ // this.views.each(function(view){ @@ -99,14 +98,14 @@ class DefaultViewManager { this.element.removeChild(this.container); } */ - }; + } onResized(e) { clearTimeout(this.resizeTimeout); this.resizeTimeout = setTimeout(function(){ this.resize(); }.bind(this), 150); - }; + } resize(width, height){ @@ -132,11 +131,11 @@ class DefaultViewManager { height: this.stage.height }); - }; + } createView(section) { return new this.View(section, this.viewSettings); - }; + } display(section, target){ @@ -185,23 +184,23 @@ class DefaultViewManager { displaying.resolve(); - }.bind(this)) + }.bind(this)); // .then(function(){ // return this.hooks.display.trigger(view); // }.bind(this)) // .then(function(){ // this.views.show(); // }.bind(this)); - return displayed; - }; + return displayed; + } afterDisplayed(view){ this.emit("added", view); - }; + } afterResized(view){ this.emit("resize", view.section); - }; + } // moveTo(offset){ // this.scrollTo(offset.left, offset.top); @@ -209,7 +208,7 @@ class DefaultViewManager { moveTo(offset){ var distX = 0, - distY = 0; + distY = 0; if(this.settings.axis === "vertical") { distY = offset.top; @@ -222,7 +221,7 @@ class DefaultViewManager { } this.scrollTo(distX, distY); - }; + } add(section){ var view = this.createView(section); @@ -235,20 +234,20 @@ class DefaultViewManager { return view.display(this.request); - }; + } append(section){ var view = this.createView(section); this.views.append(view); return view.display(this.request); - }; + } prepend(section){ var view = this.createView(section); this.views.prepend(view); return view.display(this.request); - }; + } // resizeView(view) { // // if(this.settings.globalLayoutProperties.layout === "pre-paginated") { @@ -261,7 +260,6 @@ class DefaultViewManager { next(){ var next; - var view; var left; if(!this.views.length) return; @@ -306,11 +304,10 @@ class DefaultViewManager { } - }; + } prev(){ var prev; - var view; var left; if(!this.views.length) return; @@ -354,7 +351,7 @@ class DefaultViewManager { this.views.show(); }.bind(this)); } - }; + } current(){ var visible = this.visible(); @@ -363,7 +360,7 @@ class DefaultViewManager { return visible[visible.length-1]; } return null; - }; + } currentLocation(){ @@ -373,7 +370,7 @@ class DefaultViewManager { this.location = this.paginatedLocation(); } return this.location; - }; + } scrolledLocation(){ var view; @@ -383,7 +380,7 @@ class DefaultViewManager { return this.mapping.page(view, view.section.cfiBase); } - }; + } paginatedLocation(){ var view; @@ -396,7 +393,7 @@ class DefaultViewManager { return this.mapping.page(view, view.section.cfiBase, start, end); } - }; + } isVisible(view, offsetPrev, offsetNext, _container){ var position = view.position(); @@ -417,7 +414,7 @@ class DefaultViewManager { return false; - }; + } visible(){ // return this.views.displayed(); @@ -438,7 +435,7 @@ class DefaultViewManager { } return visible; - }; + } scrollBy(x, y, silent){ if(silent) { @@ -456,7 +453,7 @@ class DefaultViewManager { // console.log("scrollBy", x, y); this.scrolled = true; this.onScroll(); - }; + } scrollTo(x, y, silent){ if(silent) { @@ -478,11 +475,11 @@ class DefaultViewManager { // }.bind(this), 10); // return; // }; - }; + } onScroll(){ - }; + } bounds() { var bounds; @@ -490,7 +487,7 @@ class DefaultViewManager { bounds = this.stage.bounds(); return bounds; - }; + } applyLayout(layout) { @@ -499,7 +496,7 @@ class DefaultViewManager { this.mapping = new Mapping(this.layout); // this.manager.layout(this.layout.format); - }; + } updateLayout() { if (!this.stage) { @@ -530,7 +527,7 @@ class DefaultViewManager { this.setLayout(this.layout); - }; + } setLayout(layout){ @@ -544,7 +541,7 @@ class DefaultViewManager { } - }; + } updateFlow(flow){ var axis = (flow === "paginated") ? "horizontal" : "vertical"; @@ -558,7 +555,7 @@ class DefaultViewManager { // view.setAxis(axis); // }); - }; + } getContents(){ var contents = []; @@ -566,10 +563,10 @@ class DefaultViewManager { contents.push(view.contents); }); return contents; - }; + } } - //-- Enable binding events to Manager - EventEmitter(DefaultViewManager.prototype); +//-- Enable binding events to Manager +EventEmitter(DefaultViewManager.prototype); export default DefaultViewManager; diff --git a/src/managers/helpers/stage.js b/src/managers/helpers/stage.js index 9f0b5e4..9f9592d 100644 --- a/src/managers/helpers/stage.js +++ b/src/managers/helpers/stage.js @@ -1,4 +1,4 @@ -import {uuid, isNumber, isElement, windowBounds} from '../../utils/core'; +import {uuid, isNumber, isElement, windowBounds} from "../../utils/core"; class Stage { constructor(_options) { @@ -60,7 +60,7 @@ class Stage { } return container; - }; + } wrap(container) { var wrapper = document.createElement("div"); @@ -72,7 +72,7 @@ class Stage { wrapper.appendChild(container); return wrapper; - }; + } getElement(_element){ @@ -85,12 +85,11 @@ class Stage { } if(!element){ - console.error("Not an Element"); - return; + throw new Error("Not an Element"); } return element; - }; + } attachTo(what){ @@ -113,11 +112,11 @@ class Stage { return element; - }; + } getContainer() { return this.container; - }; + } onResize(func){ // Only listen to window for resize event if width and height are not fixed. @@ -127,7 +126,7 @@ class Stage { window.addEventListener("resize", func, false); } - }; + } size(width, height){ var bounds; @@ -185,7 +184,7 @@ class Stage { this.containerPadding.bottom }; - }; + } bounds(){ @@ -222,7 +221,7 @@ class Stage { rules += prop + ":" + set[prop] + ";"; } } - }) + }); this.sheet.insertRule(scope + selector + " {" + rules + "}", 0); } diff --git a/src/managers/helpers/views.js b/src/managers/helpers/views.js index 99804b5..7c8ba1b 100644 --- a/src/managers/helpers/views.js +++ b/src/managers/helpers/views.js @@ -4,31 +4,31 @@ class Views { this._views = []; this.length = 0; this.hidden = false; - }; + } all() { return this._views; - }; + } first() { return this._views[0]; - }; + } last() { return this._views[this._views.length-1]; - }; + } indexOf(view) { return this._views.indexOf(view); - }; + } slice() { return this._views.slice.apply(this._views, arguments); - }; + } get(i) { return this._views[i]; - }; + } append(view){ this._views.push(view); @@ -37,7 +37,7 @@ class Views { } this.length++; return view; - }; + } prepend(view){ this._views.unshift(view); @@ -46,7 +46,7 @@ class Views { } this.length++; return view; - }; + } insert(view, index) { this._views.splice(index, 0, view); @@ -61,7 +61,7 @@ class Views { this.length++; return view; - }; + } remove(view) { var index = this._views.indexOf(view); @@ -74,7 +74,7 @@ class Views { this.destroy(view); this.length--; - }; + } destroy(view) { if(view.displayed){ @@ -85,13 +85,13 @@ class Views { this.container.removeChild(view.element); } view = null; - }; + } // Iterators each() { return this._views.forEach.apply(this._views, arguments); - }; + } clear(){ // Remove all views @@ -107,7 +107,7 @@ class Views { this._views = []; this.length = 0; - }; + } find(section){ @@ -121,7 +121,7 @@ class Views { } } - }; + } displayed(){ var displayed = []; @@ -135,7 +135,7 @@ class Views { } } return displayed; - }; + } show(){ var view; @@ -148,7 +148,7 @@ class Views { } } this.hidden = false; - }; + } hide(){ var view; @@ -161,7 +161,7 @@ class Views { } } this.hidden = true; - }; + } } export default Views; diff --git a/src/managers/views/iframe.js b/src/managers/views/iframe.js index b082d85..57f6e7e 100644 --- a/src/managers/views/iframe.js +++ b/src/managers/views/iframe.js @@ -1,13 +1,13 @@ -import EventEmitter from 'event-emitter'; -import {extend, borders, uuid, isNumber, bounds, defer} from '../../utils/core'; -import EpubCFI from '../../epubcfi'; -import Contents from '../../contents'; +import EventEmitter from "event-emitter"; +import {extend, borders, uuid, isNumber, bounds, defer} from "../../utils/core"; +import EpubCFI from "../../epubcfi"; +import Contents from "../../contents"; class IframeView { constructor(section, options) { this.settings = extend({ - ignoreClass : '', - axis: 'vertical', + ignoreClass : "", + axis: "vertical", width: 0, height: 0, layout: undefined, @@ -36,10 +36,10 @@ class IframeView { this.layout = this.settings.layout; // Dom events to listen for // this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart"]; - }; + } container(axis) { - var element = document.createElement('div'); + var element = document.createElement("div"); element.classList.add("epub-view"); @@ -55,7 +55,7 @@ class IframeView { } return element; - }; + } create() { @@ -67,7 +67,7 @@ class IframeView { this.element = this.createContainer(); } - this.iframe = document.createElement('iframe'); + this.iframe = document.createElement("iframe"); this.iframe.id = this.id; this.iframe.scrolling = "no"; // Might need to be removed: breaks ios width calculations this.iframe.style.overflow = "hidden"; @@ -102,14 +102,14 @@ class IframeView { // Firefox has trouble with baseURI and srcdoc // TODO: Disable for now in firefox - if(!!("srcdoc" in this.iframe)) { + if(!("srcdoc" in this.iframe)) { this.supportsSrcdoc = true; } else { this.supportsSrcdoc = false; } return this.iframe; - }; + } render(request, show) { @@ -163,11 +163,10 @@ class IframeView { }.bind(this)) .catch(function(e){ - console.error(e); this.emit("loaderror", e); }.bind(this)); - }; + } // Determine locks base on settings size(_width, _height) { @@ -182,7 +181,7 @@ class IframeView { this.lock("width", width, height); } - }; + } // Lock an axis to element dimensions, taking borders into account lock(what, width, height) { @@ -217,14 +216,14 @@ class IframeView { if(this.displayed && this.iframe) { - // this.contents.layout(); - this.expand(); + // this.contents.layout(); + this.expand(); } - }; + } // Resize a single axis based on content dimensions expand(force) { @@ -254,8 +253,8 @@ class IframeView { if ( this.settings.layout.divisor > 1 && this.settings.layout.name === "reflowable" && (columns % 2 > 0)) { - // add a blank page - width += this.settings.layout.gap + this.settings.layout.columnWidth; + // add a blank page + width += this.settings.layout.gap + this.settings.layout.columnWidth; } // Save the textWdith @@ -286,7 +285,7 @@ class IframeView { } this._expanding = false; - }; + } contentWidth(min) { var prev; @@ -302,7 +301,7 @@ class IframeView { // Reset iframe size back this.iframe.style.width = prev; return width; - }; + } contentHeight(min) { var prev; @@ -314,7 +313,7 @@ class IframeView { this.iframe.style.height = prev; return height; - }; + } resize(width, height) { @@ -335,7 +334,7 @@ class IframeView { this.reframe(this.iframeBounds.width, this.iframeBounds.height); - }; + } reframe(width, height) { var size; @@ -367,7 +366,7 @@ class IframeView { this.emit("resized", size); - }; + } load(contents) { @@ -403,35 +402,35 @@ class IframeView { } return loaded; - }; + } onLoad(event, promise) { - this.window = this.iframe.contentWindow; - this.document = this.iframe.contentDocument; + this.window = this.iframe.contentWindow; + this.document = this.iframe.contentDocument; - this.contents = new Contents(this.document, this.document.body, this.section.cfiBase); + this.contents = new Contents(this.document, this.document.body, this.section.cfiBase); - this.rendering = false; + this.rendering = false; - var link = this.document.querySelector("link[rel='canonical']"); - if (link) { - link.setAttribute("href", this.section.url); - } else { - link = this.document.createElement("link"); - link.setAttribute("rel", "canonical"); - link.setAttribute("href", this.section.url); - this.document.querySelector("head").appendChild(link); + var link = this.document.querySelector("link[rel='canonical']"); + if (link) { + link.setAttribute("href", this.section.url); + } else { + link = this.document.createElement("link"); + link.setAttribute("rel", "canonical"); + link.setAttribute("href", this.section.url); + this.document.querySelector("head").appendChild(link); + } + + this.contents.on("expand", function () { + if(this.displayed && this.iframe) { + this.expand(); } + }); - this.contents.on("expand", function () { - if(this.displayed && this.iframe) { - this.expand(); - } - }); - - promise.resolve(this.contents); - }; + promise.resolve(this.contents); + } @@ -458,25 +457,25 @@ class IframeView { setLayout(layout) { this.layout = layout; - }; + } setAxis(axis) { this.settings.axis = axis; - }; + } resizeListenters() { // Test size again clearTimeout(this.expanding); this.expanding = setTimeout(this.expand.bind(this), 350); - }; + } addListeners() { //TODO: Add content listeners for expanding - }; + } removeListeners(layoutFunc) { //TODO: remove content listeners for expanding - }; + } display(request) { var displayed = new defer(); @@ -499,7 +498,7 @@ class IframeView { return displayed.promise; - }; + } show() { @@ -510,7 +509,7 @@ class IframeView { } this.emit("shown", this); - }; + } hide() { // this.iframe.style.display = "none"; @@ -519,11 +518,11 @@ class IframeView { this.stopExpanding = true; this.emit("hidden", this); - }; + } position() { return this.element.getBoundingClientRect(); - }; + } locationOf(target) { var parentPos = this.iframe.getBoundingClientRect(); @@ -533,22 +532,22 @@ class IframeView { "left": window.scrollX + parentPos.left + targetPos.left, "top": window.scrollY + parentPos.top + targetPos.top }; - }; + } onDisplayed(view) { // Stub, override with a custom functions - }; + } onResize(view, e) { // Stub, override with a custom functions - }; + } bounds() { if(!this.elementBounds) { this.elementBounds = bounds(this.element); } return this.elementBounds; - }; + } destroy() { @@ -569,7 +568,7 @@ class IframeView { } // this.element.style.height = "0px"; // this.element.style.width = "0px"; - }; + } } EventEmitter(IframeView.prototype); diff --git a/src/managers/views/inline.js b/src/managers/views/inline.js index e207334..c260dbc 100644 --- a/src/managers/views/inline.js +++ b/src/managers/views/inline.js @@ -1,14 +1,13 @@ -import EventEmitter from 'event-emitter'; -import {extend, borders, uuid, isNumber, bounds, defer} from '../../utils/core'; -import EpubCFI from '../../epubcfi'; -import Contents from '../../contents'; -// import URI from 'urijs'; +import EventEmitter from "event-emitter"; +import {extend, borders, uuid, isNumber, bounds, defer, qs, parse} from "../../utils/core"; +import EpubCFI from "../../epubcfi"; +import Contents from "../../contents"; class InlineView { constructor(section, options) { this.settings = extend({ - ignoreClass : '', - axis: 'vertical', + ignoreClass : "", + axis: "vertical", width: 0, height: 0, layout: undefined, @@ -38,10 +37,10 @@ class InlineView { // Dom events to listen for // this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart"]; - }; + } container(axis) { - var element = document.createElement('div'); + var element = document.createElement("div"); element.classList.add("epub-view"); @@ -62,7 +61,7 @@ class InlineView { } return element; - }; + } create() { @@ -74,7 +73,7 @@ class InlineView { this.element = this.createContainer(); } - this.frame = document.createElement('div'); + this.frame = document.createElement("div"); this.frame.id = this.id; this.frame.style.overflow = "hidden"; this.frame.style.wordSpacing = "initial"; @@ -103,7 +102,7 @@ class InlineView { this.elementBounds = bounds(this.element); return this.frame; - }; + } render(request, show) { @@ -144,7 +143,7 @@ class InlineView { if(show !== false) { //this.q.enqueue(function(view){ - this.show(); + this.show(); //}, view); } // this.map = new Map(view, this.layout); @@ -156,7 +155,7 @@ class InlineView { this.emit("loaderror", e); }.bind(this)); - }; + } // Determine locks base on settings size(_width, _height) { @@ -172,7 +171,7 @@ class InlineView { this.lock("width", width, height); } - }; + } // Lock an axis to element dimensions, taking borders into account lock(what, width, height) { @@ -196,8 +195,8 @@ class InlineView { } if(what === "both" && - isNumber(width) && - isNumber(height)){ + isNumber(width) && + isNumber(height)){ this.lockedWidth = width - elBorders.width - iframeBorders.width; this.lockedHeight = height - elBorders.height - iframeBorders.height; @@ -205,7 +204,7 @@ class InlineView { this.resize(this.lockedWidth, this.lockedHeight); } - }; + } // Resize a single axis based on content dimensions expand(force) { @@ -233,16 +232,15 @@ class InlineView { } this._expanding = false; - }; + } contentWidth(min) { return this.frame.scrollWidth; - }; + } contentHeight(min) { - console.log(this.frame.scrollHeight); return this.frame.scrollHeight; - }; + } resize(width, height) { @@ -263,7 +261,7 @@ class InlineView { this.elementBounds = bounds(this.element); - size = { + let size = { width: this.elementBounds.width, height: this.elementBounds.height, widthDelta: this.elementBounds.width - this.prevBounds.width, @@ -274,7 +272,7 @@ class InlineView { this.emit("resized", size); - }; + } load(contents) { @@ -283,10 +281,12 @@ class InlineView { var doc = parse(contents, "text/html"); var body = qs(doc, "body"); + /* var srcs = doc.querySelectorAll("[src]"); + Array.prototype.slice.call(srcs) .forEach(function(item) { - var src = item.getAttribute('src'); + var src = item.getAttribute("src"); var assetUri = URI(src); var origin = assetUri.origin(); var absoluteUri; @@ -296,7 +296,7 @@ class InlineView { item.src = absoluteUri; } }.bind(this)); - + */ this.frame.innerHTML = body.innerHTML; this.document = this.frame.ownerDocument; @@ -310,26 +310,26 @@ class InlineView { return loaded; - }; + } setLayout(layout) { this.layout = layout; - }; + } resizeListenters() { // Test size again // clearTimeout(this.expanding); // this.expanding = setTimeout(this.expand.bind(this), 350); - }; + } addListeners() { //TODO: Add content listeners for expanding - }; + } removeListeners(layoutFunc) { //TODO: remove content listeners for expanding - }; + } display(request) { var displayed = new defer(); @@ -353,7 +353,7 @@ class InlineView { return displayed.promise; - }; + } show() { @@ -364,7 +364,7 @@ class InlineView { } this.emit("shown", this); - }; + } hide() { // this.frame.style.display = "none"; @@ -373,11 +373,11 @@ class InlineView { this.stopExpanding = true; this.emit("hidden", this); - }; + } position() { return this.element.getBoundingClientRect(); - }; + } locationOf(target) { var parentPos = this.frame.getBoundingClientRect(); @@ -387,22 +387,22 @@ class InlineView { "left": window.scrollX + parentPos.left + targetPos.left, "top": window.scrollY + parentPos.top + targetPos.top }; - }; + } onDisplayed(view) { // Stub, override with a custom functions - }; + } onResize(view, e) { // Stub, override with a custom functions - }; + } bounds() { if(!this.elementBounds) { this.elementBounds = bounds(this.element); } return this.elementBounds; - }; + } destroy() { @@ -423,7 +423,7 @@ class InlineView { } // this.element.style.height = "0px"; // this.element.style.width = "0px"; - }; + } } EventEmitter(InlineView.prototype); diff --git a/src/mapping.js b/src/mapping.js index 8e18d01..8976309 100644 --- a/src/mapping.js +++ b/src/mapping.js @@ -1,16 +1,16 @@ -import EpubCFI from './epubcfi'; +import EpubCFI from "./epubcfi"; class Mapping { constructor(layout) { this.layout = layout; - }; + } section(view) { var ranges = this.findRanges(view); var map = this.rangeListToCfiList(view.section.cfiBase, ranges); return map; - }; + } page(contents, cfiBase, start, end) { var root = contents && contents.document ? contents.document.body : false; @@ -23,18 +23,18 @@ class Mapping { start: this.findStart(root, start, end), end: this.findEnd(root, start, end) }); - }; + } walk(root, func) { //var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false); var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: function (node) { - if ( node.data.trim().length > 0 ) { - return NodeFilter.FILTER_ACCEPT; - } else { - return NodeFilter.FILTER_REJECT; - } + acceptNode: function (node) { + if ( node.data.trim().length > 0 ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; } + } }, false); var node; var result; @@ -44,7 +44,7 @@ class Mapping { } return result; - }; + } findRanges(view){ var columns = []; @@ -64,7 +64,7 @@ class Mapping { } return columns; - }; + } findStart(root, start, end){ var stack = [root]; @@ -111,7 +111,7 @@ class Mapping { // Return last element return this.findTextStartRange($prev, start, end); - }; + } findEnd(root, start, end){ var stack = [root]; @@ -161,12 +161,11 @@ class Mapping { // end of chapter return this.findTextEndRange($prev, start, end); - }; + } findTextStartRange(node, start, end){ var ranges = this.splitTextNodeIntoRanges(node); - var prev; var range; var pos; @@ -179,12 +178,12 @@ class Mapping { return range; } - prev = range; + // prev = range; } return ranges[0]; - }; + } findTextEndRange(node, start, end){ var ranges = this.splitTextNodeIntoRanges(node); @@ -210,15 +209,13 @@ class Mapping { // Ends before limit return ranges[ranges.length-1]; - }; + } splitTextNodeIntoRanges(node, _splitter){ var ranges = []; var textContent = node.textContent || ""; var text = textContent.trim(); var range; - var rect; - var list; var doc = node.ownerDocument; var splitter = _splitter || " "; @@ -257,7 +254,7 @@ class Mapping { } return ranges; - }; + } @@ -279,11 +276,11 @@ class Mapping { end: endCfi }; - }; + } rangeListToCfiList(cfiBase, columns){ var map = []; - var rangePair, cifPair; + var cifPair; for (var i = 0; i < columns.length; i++) { cifPair = this.rangePairToCfiPair(cfiBase, columns[i]); @@ -293,7 +290,7 @@ class Mapping { } return map; - }; + } } export default Mapping; diff --git a/src/navigation.js b/src/navigation.js index ccd0d09..e1b12b1 100644 --- a/src/navigation.js +++ b/src/navigation.js @@ -1,4 +1,4 @@ -import {qs, qsa, querySelectorByType} from './utils/core'; +import {qs, qsa, querySelectorByType} from "./utils/core"; /** * Navigation Parser @@ -13,7 +13,7 @@ class Navigation { if (xml) { this.parse(xml); } - }; + } /** * Parse out the navigation items @@ -30,7 +30,7 @@ class Navigation { } this.unpack(this.toc); - }; + } /** * Unpack navigation items @@ -46,7 +46,7 @@ class Navigation { this.tocById[item.id] = i; } - }; + } /** * Get an item from the navigation @@ -67,7 +67,7 @@ class Navigation { } return this.toc[index]; - }; + } /** * Parse from a Epub > 3.0 Nav @@ -98,7 +98,7 @@ class Navigation { } return list; - }; + } /** * Create a navItem @@ -107,16 +107,16 @@ class Navigation { * @return {object} navItem */ navItem(item){ - var id = item.getAttribute('id') || false, + var id = item.getAttribute("id") || false, content = qs(item, "a"), - src = content.getAttribute('href') || '', + src = content.getAttribute("href") || "", text = content.textContent || "", subitems = [], parentNode = item.parentNode, parent; if(parentNode && parentNode.nodeName === "navPoint") { - parent = parentNode.getAttribute('id'); + parent = parentNode.getAttribute("id"); } return { @@ -126,7 +126,7 @@ class Navigation { "subitems" : subitems, "parent" : parent }; - }; + } /** * Parse from a Epub > 3.0 NC @@ -156,7 +156,7 @@ class Navigation { } return list; - }; + } /** * Create a ncxItem @@ -165,9 +165,9 @@ class Navigation { * @return {object} ncxItem */ ncxItem(item){ - var id = item.getAttribute('id') || false, + var id = item.getAttribute("id") || false, content = qs(item, "content"), - src = content.getAttribute('src'), + src = content.getAttribute("src"), navLabel = qs(item, "navLabel"), text = navLabel.textContent ? navLabel.textContent : "", subitems = [], @@ -175,7 +175,7 @@ class Navigation { parent; if(parentNode && parentNode.nodeName === "navPoint") { - parent = parentNode.getAttribute('id'); + parent = parentNode.getAttribute("id"); } @@ -186,7 +186,7 @@ class Navigation { "subitems" : subitems, "parent" : parent }; - }; + } /** * forEach pass through @@ -195,7 +195,7 @@ class Navigation { */ forEach(fn) { return this.toc.forEach(fn); - }; + } } export default Navigation; diff --git a/src/packaging.js b/src/packaging.js index bc5c9bb..012003d 100644 --- a/src/packaging.js +++ b/src/packaging.js @@ -1,5 +1,4 @@ -import {qs, qsa, qsp} from './utils/core'; -import EpubCFI from './epubcfi'; +import {qs, qsa, qsp} from "./utils/core"; /** * Open Packaging Format Parser @@ -11,7 +10,7 @@ class Packaging { if (packageDocument) { this.parse(packageDocument); } - }; + } /** * Parse OPF XML @@ -22,26 +21,22 @@ class Packaging { var metadataNode, manifestNode, spineNode; if(!packageDocument) { - console.error("Package File Not Found"); - return; + throw new Error("Package File Not Found"); } metadataNode = qs(packageDocument, "metadata"); if(!metadataNode) { - console.error("No Metadata Found"); - return; + throw new Error("No Metadata Found"); } manifestNode = qs(packageDocument, "manifest"); if(!manifestNode) { - console.error("No Manifest Found"); - return; + throw new Error("No Manifest Found"); } spineNode = qs(packageDocument, "spine"); if(!spineNode) { - console.error("No Spine Found"); - return; + throw new Error("No Spine Found"); } this.manifest = this.parseManifest(manifestNode); @@ -59,15 +54,15 @@ class Packaging { return { - 'metadata' : this.metadata, - 'spine' : this.spine, - 'manifest' : this.manifest, - 'navPath' : this.navPath, - 'ncxPath' : this.ncxPath, - 'coverPath': this.coverPath, - 'spineNodeIndex' : this.spineNodeIndex + "metadata" : this.metadata, + "spine" : this.spine, + "manifest" : this.manifest, + "navPath" : this.navPath, + "ncxPath" : this.ncxPath, + "coverPath": this.coverPath, + "spineNodeIndex" : this.spineNodeIndex }; - }; + } /** * Parse Metadata @@ -78,28 +73,28 @@ class Packaging { parseMetadata(xml){ var metadata = {}; - metadata.title = this.getElementText(xml, 'title'); - metadata.creator = this.getElementText(xml, 'creator'); - metadata.description = this.getElementText(xml, 'description'); + metadata.title = this.getElementText(xml, "title"); + metadata.creator = this.getElementText(xml, "creator"); + metadata.description = this.getElementText(xml, "description"); - metadata.pubdate = this.getElementText(xml, 'date'); + metadata.pubdate = this.getElementText(xml, "date"); - metadata.publisher = this.getElementText(xml, 'publisher'); + metadata.publisher = this.getElementText(xml, "publisher"); metadata.identifier = this.getElementText(xml, "identifier"); metadata.language = this.getElementText(xml, "language"); metadata.rights = this.getElementText(xml, "rights"); - metadata.modified_date = this.getPropertyText(xml, 'dcterms:modified'); + metadata.modified_date = this.getPropertyText(xml, "dcterms:modified"); metadata.layout = this.getPropertyText(xml, "rendition:layout"); - metadata.orientation = this.getPropertyText(xml, 'rendition:orientation'); - metadata.flow = this.getPropertyText(xml, 'rendition:flow'); - metadata.viewport = this.getPropertyText(xml, 'rendition:viewport'); + metadata.orientation = this.getPropertyText(xml, "rendition:orientation"); + metadata.flow = this.getPropertyText(xml, "rendition:flow"); + metadata.viewport = this.getPropertyText(xml, "rendition:viewport"); // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); return metadata; - }; + } /** * Parse Manifest @@ -117,23 +112,23 @@ class Packaging { //-- Create an object with the id as key items.forEach(function(item){ - var id = item.getAttribute('id'), - href = item.getAttribute('href') || '', - type = item.getAttribute('media-type') || '', - properties = item.getAttribute('properties') || ''; + var id = item.getAttribute("id"), + href = item.getAttribute("href") || "", + type = item.getAttribute("media-type") || "", + properties = item.getAttribute("properties") || ""; manifest[id] = { - 'href' : href, - // 'url' : href, - 'type' : type, - 'properties' : properties.length ? properties.split(' ') : [] + "href" : href, + // "url" : href, + "type" : type, + "properties" : properties.length ? properties.split(" ") : [] }; }); return manifest; - }; + } /** * Parse Spine @@ -144,46 +139,46 @@ class Packaging { parseSpine(spineXml, manifest){ var spine = []; - var selected = spineXml.getElementsByTagName("itemref"), - items = Array.prototype.slice.call(selected); + var selected = spineXml.getElementsByTagName("itemref"); + var items = Array.prototype.slice.call(selected); - var epubcfi = new EpubCFI(); + // var epubcfi = new EpubCFI(); //-- Add to array to mantain ordering and cross reference with manifest items.forEach(function(item, index){ - var idref = item.getAttribute('idref'); + var idref = item.getAttribute("idref"); // var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); - var props = item.getAttribute('properties') || ''; - var propArray = props.length ? props.split(' ') : []; + var props = item.getAttribute("properties") || ""; + var propArray = props.length ? props.split(" ") : []; // var manifestProps = manifest[Id].properties; - // var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : []; + // var manifestPropArray = manifestProps.length ? manifestProps.split(" ") : []; var itemref = { - 'idref' : idref, - 'linear' : item.getAttribute('linear') || '', - 'properties' : propArray, - // 'href' : manifest[Id].href, - // 'url' : manifest[Id].url, - 'index' : index - // 'cfiBase' : cfiBase + "idref" : idref, + "linear" : item.getAttribute("linear") || "", + "properties" : propArray, + // "href" : manifest[Id].href, + // "url" : manifest[Id].url, + "index" : index + // "cfiBase" : cfiBase }; spine.push(itemref); }); return spine; - }; + } /** * Find TOC NAV * @private */ findNavPath(manifestNode){ - // Find item with property 'nav' + // Find item with property "nav" // Should catch nav irregardless of order // var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); var node = qsp(manifestNode, "item", {"properties":"nav"}); - return node ? node.getAttribute('href') : false; - }; + return node ? node.getAttribute("href") : false; + } /** * Find TOC NCX @@ -206,8 +201,8 @@ class Packaging { } } - return node ? node.getAttribute('href') : false; - }; + return node ? node.getAttribute("href") : false; + } /** * Find the Cover Path @@ -218,15 +213,15 @@ class Packaging { */ findCoverPath(packageXml){ var pkg = qs(packageXml, "package"); - var epubVersion = pkg.getAttribute('version'); + var epubVersion = pkg.getAttribute("version"); - if (epubVersion === '2.0') { - var metaCover = qsp(packageXml, 'meta', {'name':'cover'}); + if (epubVersion === "2.0") { + var metaCover = qsp(packageXml, "meta", {"name":"cover"}); if (metaCover) { - var coverId = metaCover.getAttribute('content'); + var coverId = metaCover.getAttribute("content"); // var cover = packageXml.querySelector("item[id='" + coverId + "']"); var cover = packageXml.getElementById(coverId); - return cover ? cover.getAttribute('href') : ''; + return cover ? cover.getAttribute("href") : ""; } else { return false; @@ -234,10 +229,10 @@ class Packaging { } else { // var node = packageXml.querySelector("item[properties='cover-image']"); - var node = qsp(packageXml, 'item', {'properties':'cover-image'}); - return node ? node.getAttribute('href') : ''; + var node = qsp(packageXml, "item", {"properties":"cover-image"}); + return node ? node.getAttribute("href") : ""; } - }; + } /** * Get text of a namespaced element @@ -247,10 +242,10 @@ class Packaging { * @return {string} text */ getElementText(xml, tag){ - var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), - el; + var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag); + var el; - if(!found || found.length === 0) return ''; + if(!found || found.length === 0) return ""; el = found[0]; @@ -258,9 +253,9 @@ class Packaging { return el.childNodes[0].nodeValue; } - return ''; + return ""; - }; + } /** * Get text by property @@ -276,8 +271,8 @@ class Packaging { return el.childNodes[0].nodeValue; } - return ''; - }; + return ""; + } } export default Packaging; diff --git a/src/pagelist.js b/src/pagelist.js index 4ad4626..fa95318 100644 --- a/src/pagelist.js +++ b/src/pagelist.js @@ -1,11 +1,11 @@ -import EpubCFI from './epubcfi'; +import EpubCFI from "./epubcfi"; import { qs, qsa, querySelectorByType, indexOfSorted, locationOf -} from './utils/core'; +} from "./utils/core"; /** * Page List Parser @@ -24,7 +24,7 @@ class PageList { if(this.pageList && this.pageList.length) { this.process(this.pageList); } - }; + } /** * Parse PageList Xml @@ -32,7 +32,7 @@ class PageList { */ parse(xml) { var html = qs(xml, "html"); - // var ncx = qs(xml, "ncx"); + var ncx = qs(xml, "ncx"); if(html) { this.toc = this.parseNav(xml); @@ -41,7 +41,7 @@ class PageList { return; } - }; + } /** * Parse a Nav PageList @@ -54,7 +54,6 @@ class PageList { var navItems = navElement ? qsa(navElement, "li") : []; var length = navItems.length; var i; - var toc = {}; var list = []; var item; @@ -66,7 +65,7 @@ class PageList { } return list; - }; + } /** * Page List Item @@ -75,15 +74,14 @@ class PageList { * @return {object} pageListItem */ item(item){ - var id = item.getAttribute('id') || false, - content = qs(item, "a"), - href = content.getAttribute('href') || '', - text = content.textContent || "", - page = parseInt(text), - isCfi = href.indexOf("epubcfi"), - split, - packageUrl, - cfi; + var content = qs(item, "a"), + href = content.getAttribute("href") || "", + text = content.textContent || "", + page = parseInt(text), + isCfi = href.indexOf("epubcfi"), + split, + packageUrl, + cfi; if(isCfi != -1) { split = href.split("#"); @@ -101,7 +99,7 @@ class PageList { "page" : page }; } - }; + } /** * Process pageList items @@ -118,7 +116,7 @@ class PageList { this.firstPage = parseInt(this.pages[0]); this.lastPage = parseInt(this.pages[this.pages.length-1]); this.totalPages = this.lastPage - this.firstPage; - }; + } /** @@ -159,7 +157,7 @@ class PageList { } return deferred.promise; - }; + } */ /** @@ -198,7 +196,7 @@ class PageList { } return pg; - }; + } /** * Get an EpubCFI from a Page List Item @@ -220,7 +218,7 @@ class PageList { } // TODO: handle pages not in the list return cfi; - }; + } /** * Get a Page from Book percentage @@ -230,7 +228,7 @@ class PageList { pageFromPercentage(percent){ var pg = Math.round(this.totalPages * percent); return pg; - }; + } /** * Returns a value between 0 - 1 corresponding to the location of a page @@ -240,7 +238,7 @@ class PageList { percentageFromPage(pg){ var percentage = (pg - this.firstPage) / this.totalPages; return Math.round(percentage * 1000) / 1000; - }; + } /** * Returns a value between 0 - 1 corresponding to the location of a cfi @@ -251,7 +249,7 @@ class PageList { var pg = this.pageFromCfi(cfi); var percentage = this.percentageFromPage(pg); return percentage; - }; + } } export default PageList; diff --git a/src/rendition.js b/src/rendition.js index 75ff7cd..d906315 100644 --- a/src/rendition.js +++ b/src/rendition.js @@ -1,13 +1,12 @@ -import EventEmitter from 'event-emitter'; -import { extend, defer, isFloat } from './utils/core'; -import {replaceLinks} from './replacements'; -import Hook from './hook'; -import EpubCFI from './epubcfi'; -import Queue from './queue'; -import Layout from './layout'; -import Mapping from './mapping'; -import Themes from './themes'; -import Path from './utils/path'; +import EventEmitter from "event-emitter"; +import { extend, defer, isFloat } from "./utils/core"; +import {replaceLinks} from "./utils/replacements"; +import Hook from "./utils/hook"; +import EpubCFI from "./epubcfi"; +import Queue from "./utils/queue"; +import Layout from "./layout"; +import Mapping from "./mapping"; +import Themes from "./themes"; /** * [Rendition description] @@ -29,7 +28,7 @@ class Rendition { this.settings = extend(this.settings || {}, { width: null, height: null, - ignoreClass: '', + ignoreClass: "", manager: "default", view: "iframe", flow: null, @@ -84,7 +83,7 @@ class Rendition { this.starting = new defer(); this.started = this.starting.promise; this.q.enqueue(this.start); - }; + } /** * Set the manager function @@ -92,7 +91,7 @@ class Rendition { */ setManager(manager) { this.manager = manager; - }; + } /** * Require the manager from passed string, or as a function @@ -106,14 +105,14 @@ class Rendition { // or require included managers directly if (typeof manager === "string") { // Use global or require - viewManager = typeof ePub != "undefined" ? ePub.ViewManagers[manager] : undefined; //require('./managers/'+manager); + viewManager = typeof ePub != "undefined" ? ePub.ViewManagers[manager] : undefined; //require("./managers/"+manager); } else { // otherwise, assume we were passed a function - viewManager = manager + viewManager = manager; } return viewManager; - }; + } /** * Require the view from passed string, or as a function @@ -124,14 +123,14 @@ class Rendition { var View; if (typeof view == "string") { - View = typeof ePub != "undefined" ? ePub.Views[view] : undefined; //require('./views/'+view); + View = typeof ePub != "undefined" ? ePub.Views[view] : undefined; //require("./views/"+view); } else { // otherwise, assume we were passed a function - View = view + View = view; } return View; - }; + } /** * Start the rendering @@ -168,14 +167,14 @@ class Rendition { this.manager.on("scroll", this.reportLocation.bind(this)); - this.on('displayed', this.reportLocation.bind(this)); + this.on("displayed", this.reportLocation.bind(this)); // Trigger that rendering has started this.emit("started"); // Start processing queue this.starting.resolve(); - }; + } /** * Call to attach the container to an element in the dom @@ -198,7 +197,7 @@ class Rendition { }.bind(this)); - }; + } /** * Display a point in the book @@ -212,7 +211,7 @@ class Rendition { return this.q.enqueue(this._display, target); - }; + } /** * Tells the manager what to display immediately @@ -229,9 +228,7 @@ class Rendition { // Check if this is a book percentage if (this.book.locations.length && isFloat(target)) { - console.log("percentage", target); - target = book.locations.cfiFromPercentage(target); - console.log("cfi", target); + target = this.book.locations.cfiFromPercentage(target); } section = this.book.spine.get(target); @@ -245,7 +242,7 @@ class Rendition { // removing the chapter if(!isCfiString && typeof target === "string" && target.indexOf("#") > -1) { - moveTo = target.substring(target.indexOf("#")+1); + moveTo = target.substring(target.indexOf("#")+1); } if (isCfiString) { @@ -257,7 +254,7 @@ class Rendition { // this.emit("displayed", section); }.bind(this)); - }; + } /* render(view, show) { @@ -301,7 +298,7 @@ class Rendition { this.trigger("loaderror", e); }.bind(this)); - }; + } */ /** @@ -313,7 +310,7 @@ class Rendition { this.hooks.content.trigger(view, this); this.emit("rendered", view.section); this.reportLocation(); - }; + } /** * Report resize events and display the last seen location @@ -330,7 +327,7 @@ class Rendition { height: size.height }); - }; + } /** * Move the Rendition to a specific offset @@ -339,7 +336,7 @@ class Rendition { */ moveTo(offset){ this.manager.moveTo(offset); - }; + } /** * Go to the next "page" in the rendition @@ -348,7 +345,7 @@ class Rendition { next(){ return this.q.enqueue(this.manager.next.bind(this.manager)) .then(this.reportLocation.bind(this)); - }; + } /** * Go to the previous "page" in the rendition @@ -357,7 +354,7 @@ class Rendition { prev(){ return this.q.enqueue(this.manager.prev.bind(this.manager)) .then(this.reportLocation.bind(this)); - }; + } //-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering /** @@ -389,7 +386,7 @@ class Rendition { }; return properties; - }; + } // applyLayoutProperties(){ // var settings = this.determineLayoutProperties(this.book.package.metadata); @@ -421,7 +418,7 @@ class Rendition { if (this.manager) { this.manager.updateFlow(_flow); } - }; + } /** * Adjust the layout of the rendition to reflowable or pre-paginated @@ -440,7 +437,7 @@ class Rendition { } return this._layout; - }; + } /** * Adjust if the rendition uses spreads @@ -454,7 +451,7 @@ class Rendition { if (this.manager.isRendered()) { this.manager.updateLayout(); } - }; + } /** * Report the current location @@ -463,7 +460,7 @@ class Rendition { reportLocation(){ return this.q.enqueue(function(){ var location = this.manager.currentLocation(); - if (location && location.then && typeof location.then === 'function') { + if (location && location.then && typeof location.then === "function") { location.then(function(result) { this.location = result; @@ -485,7 +482,7 @@ class Rendition { } }.bind(this)); - }; + } /** * Get the Current Location CFI @@ -493,7 +490,7 @@ class Rendition { */ currentLocation(){ var location = this.manager.currentLocation(); - if (location && location.then && typeof location.then === 'function') { + if (location && location.then && typeof location.then === "function") { location.then(function(result) { var percentage = this.book.locations.percentageFromCfi(result); if (percentage != null) { @@ -508,7 +505,7 @@ class Rendition { } return location; } - }; + } /** * Remove and Clean Up the Rendition @@ -518,7 +515,7 @@ class Rendition { this.q.clear(); this.manager.destroy(); - }; + } /** * Pass the events from a view @@ -531,7 +528,7 @@ class Rendition { }.bind(this)); view.on("selected", this.triggerSelectedEvent.bind(this)); - }; + } /** * Emit events passed by a view @@ -540,7 +537,7 @@ class Rendition { */ triggerViewEvent(e){ this.emit(e.type, e); - }; + } /** * Emit a selection event's CFI Range passed from a a view @@ -549,7 +546,7 @@ class Rendition { */ triggerSelectedEvent(cfirange){ this.emit("selected", cfirange); - }; + } /** * Get a Range from a Visible CFI @@ -567,7 +564,7 @@ class Rendition { if (found.length) { return found[0].range(_cfi, ignoreClass); } - }; + } /** * Hook to adjust images to fit in columns @@ -576,10 +573,10 @@ class Rendition { adjustImages(view) { view.addStylesheetRules([ - ["img", - ["max-width", (view.layout.spreadWidth) + "px"], - ["max-height", (view.layout.height) + "px"] - ] + ["img", + ["max-width", (view.layout.spreadWidth) + "px"], + ["max-height", (view.layout.height) + "px"] + ] ]); return new Promise(function(resolve, reject){ // Wait to apply @@ -587,11 +584,11 @@ class Rendition { resolve(); }, 1); }); - }; + } getContents () { return this.manager ? this.manager.getContents() : []; - }; + } } //-- Enable binding events to Renderer diff --git a/src/resources.js b/src/resources.js index a09b9c6..53edb1a 100644 --- a/src/resources.js +++ b/src/resources.js @@ -1,21 +1,21 @@ -import {substitute} from './replacements'; -import {createBase64Url, createBlobUrl} from './utils/core'; -import Path from './utils/path'; -import path from 'path-webpack'; +import {substitute} from "./utils/replacements"; +import {createBase64Url, createBlobUrl} from "./utils/core"; +import Path from "./utils/path"; +import path from "path-webpack"; /** * Handle Package Resources * @class * @param {Manifest} manifest * @param {[object]} options - * @param {[string='base64']} options.replacements + * @param {[string="base64"]} options.replacements * @param {[Archive]} options.archive * @param {[method]} options.resolver */ class Resources { constructor(manifest, options) { this.settings = { - replacements: (options && options.replacements) || 'base64', + replacements: (options && options.replacements) || "base64", archive: (options && options.archive), resolver: (options && options.resolver) }; @@ -62,7 +62,7 @@ class Resources { return true; } }); - }; + } /** * Convert split resources into Urls @@ -81,7 +81,7 @@ class Resources { return item.href; }); - }; + } /** * Create blob urls for all the assets @@ -94,24 +94,24 @@ class Resources { resolver = resolver || this.settings.resolver; if (this.settings.replacements === "none") { - return new Promise(function(resolve, reject) { + return new Promise(function(resolve) { resolve(this.urls); }.bind(this)); } var replacements = this.urls. - map(function(url) { + map( (url) => { var absolute = resolver(url); return archive.createUrl(absolute, {"base64": (this.settings.replacements === "base64")}); - }.bind(this)) + }); return Promise.all(replacements) - .then(function(replacementUrls) { + .then( (replacementUrls) => { this.replacementUrls = replacementUrls; return replacementUrls; - }.bind(this)); - }; + }); + } /** * Replace URLs in CSS resources @@ -137,7 +137,7 @@ class Resources { replaced.push(replacement); }.bind(this)); return Promise.all(replaced); - }; + } /** * Create a new CSS file with the replaced URLs @@ -148,44 +148,43 @@ class Resources { * @return {Promise} returns a BlobUrl to the new CSS file or a data url */ createCssFile(href, archive, resolver){ - var newUrl; - var indexInUrls; - archive = archive || this.settings.archive; - resolver = resolver || this.settings.resolver; + var newUrl; + archive = archive || this.settings.archive; + resolver = resolver || this.settings.resolver; - if (path.isAbsolute(href)) { - return new Promise(function(resolve, reject){ - resolve(urls, replacementUrls); - }); + if (path.isAbsolute(href)) { + return new Promise(function(resolve){ + resolve(); + }); + } + + var absolute = resolver(href); + + // Get the text of the css file from the archive + var textResponse = archive.getText(absolute); + // Get asset links relative to css file + var relUrls = this.urls.map( (assetHref) => { + var resolved = resolver(assetHref); + var relative = new Path(absolute).relative(resolved); + + return relative; + }); + + return textResponse.then( (text) => { + // Replacements in the css text + text = substitute(text, relUrls, this.replacementUrls); + + // Get the new url + if (this.settings.replacements === "base64") { + newUrl = createBase64Url(text, "text/css"); + } else { + newUrl = createBlobUrl(text, "text/css"); } - var absolute = resolver(href); + return newUrl; + }); - // Get the text of the css file from the archive - var textResponse = archive.getText(absolute); - // Get asset links relative to css file - var relUrls = this.urls.map(function(assetHref) { - var resolved = resolver(assetHref); - var relative = new Path(absolute).relative(resolved); - - return relative; - }.bind(this)); - - return textResponse.then(function (text) { - // Replacements in the css text - text = substitute(text, relUrls, this.replacementUrls); - - // Get the new url - if (this.settings.replacements === "base64") { - newUrl = createBase64Url(text, 'text/css'); - } else { - newUrl = createBlobUrl(text, 'text/css'); - } - - return newUrl; - }.bind(this)); - - }; + } /** * Resolve all resources URLs relative to an absolute URL @@ -203,7 +202,7 @@ class Resources { var relative = new Path(absolute).relative(resolved); return relative; }.bind(this)); - }; + } /** * Get a URL for a resource @@ -220,8 +219,8 @@ class Resources { resolve(this.replacementUrls[indexInUrls]); }.bind(this)); } else { - return archive.createUrl(absolute, - {"base64": (this.settings.replacements === "base64")}) + return this.archive.createUrl(path, + {"base64": (this.settings.replacements === "base64")}); } } @@ -240,7 +239,7 @@ class Resources { relUrls = this.urls; } return substitute(content, relUrls, this.replacementUrls); - }; + } } export default Resources; diff --git a/src/section.js b/src/section.js index 611de63..e1c11d1 100644 --- a/src/section.js +++ b/src/section.js @@ -1,7 +1,7 @@ -import { defer } from './utils/core'; -import EpubCFI from './epubcfi'; -import Hook from './hook'; -import Url from './utils/url'; +import { defer } from "./utils/core"; +import EpubCFI from "./epubcfi"; +import Hook from "./utils/hook"; +import { replaceBase } from "./utils/replacements"; /** * Represents a Section of the Book @@ -11,26 +11,25 @@ import Url from './utils/url'; */ class Section { constructor(item, hooks){ - this.idref = item.idref; - this.linear = item.linear; - this.properties = item.properties; - this.index = item.index; - this.href = item.href; - this.url = item.url; - this.next = item.next; - this.prev = item.prev; + this.idref = item.idref; + this.linear = item.linear; + this.properties = item.properties; + this.index = item.index; + this.href = item.href; + this.url = item.url; + this.next = item.next; + this.prev = item.prev; - this.cfiBase = item.cfiBase; + this.cfiBase = item.cfiBase; - if (hooks) { - this.hooks = hooks; - } else { - this.hooks = {}; - this.hooks.serialize = new Hook(this); - this.hooks.content = new Hook(this); - } - - }; + if (hooks) { + this.hooks = hooks; + } else { + this.hooks = {}; + this.hooks.serialize = new Hook(this); + this.hooks.content = new Hook(this); + } + } /** * Load the section from its url @@ -38,7 +37,7 @@ class Section { * @return {document} a promise with the xml document */ load(_request){ - var request = _request || this.request || require('./request'); + var request = _request || this.request || require("./utils/request"); var loading = new defer(); var loaded = loading.promise; @@ -47,8 +46,7 @@ class Section { } else { request(this.url) .then(function(xml){ - var base; - var directory = new Url(this.url).directory; + // var directory = new Url(this.url).directory; this.document = xml; this.contents = xml.documentElement; @@ -64,33 +62,15 @@ class Section { } return loaded; - }; + } /** * Adds a base tag for resolving urls in the section * @private - * @param {document} _document */ - base(_document){ - var task = new defer(); - var base = _document.createElement("base"); // TODO: check if exists - var head; - - base.setAttribute("href", window.location.origin + "/" +this.url); - - if(_document) { - head = _document.querySelector("head"); - } - if(head) { - head.insertBefore(base, head.firstChild); - task.resolve(); - } else { - task.reject(new Error("No head to insert into")); - } - - - return task.promise; - }; + base(){ + return replaceBase(this.document, this); + } /** * Render the contents of a section @@ -108,7 +88,7 @@ class Section { var Serializer; if (typeof XMLSerializer === "undefined") { - Serializer = require('xmldom').XMLSerializer; + Serializer = require("xmldom").XMLSerializer; } else { Serializer = XMLSerializer; } @@ -127,7 +107,7 @@ class Section { }); return rendered; - }; + } /** * Find a string in a section @@ -135,9 +115,9 @@ class Section { * @param {string} query [description] * @return {[type]} [description] */ - find(query){ + find(){ - }; + } /** * Reconciles the current chapters layout properies with @@ -155,7 +135,7 @@ class Section { //-- Get the chapter's display type this.properties.forEach(function(prop){ - var rendition = prop.replace("rendition:", ''); + var rendition = prop.replace("rendition:", ""); var split = rendition.indexOf("-"); var property, value; @@ -166,8 +146,8 @@ class Section { settings[property] = value; } }); - return settings; - }; + return settings; + } /** * Get a CFI from a Range in the Section @@ -176,7 +156,7 @@ class Section { */ cfiFromRange(_range) { return new EpubCFI(_range, this.cfiBase).toString(); - }; + } /** * Get a CFI from an Element in the Section @@ -185,7 +165,7 @@ class Section { */ cfiFromElement(el) { return new EpubCFI(el, this.cfiBase).toString(); - }; + } } export default Section; diff --git a/src/spine.js b/src/spine.js index cce1a4a..2aa444e 100644 --- a/src/spine.js +++ b/src/spine.js @@ -1,8 +1,7 @@ -import core from './utils/core'; -import EpubCFI from './epubcfi'; -import Hook from './hook'; -import Section from './section'; -import {replaceBase, replaceCanonical} from './replacements'; +import EpubCFI from "./epubcfi"; +import Hook from "./utils/hook"; +import Section from "./section"; +import {replaceBase, replaceCanonical} from "./utils/replacements"; /** * A collection of Spine Items @@ -24,7 +23,7 @@ class Spine { this.epubcfi = new EpubCFI(); this.loaded = false; - }; + } /** * Unpack items from a opf into spine items @@ -36,11 +35,10 @@ class Spine { this.items = _package.spine; this.manifest = _package.manifest; this.spineNodeIndex = _package.spineNodeIndex; - this.baseUrl = _package.baseUrl || _package.basePath || ''; + this.baseUrl = _package.baseUrl || _package.basePath || ""; this.length = this.items.length; - this.items.forEach(function(item, index){ - var href, url; + this.items.forEach( (item, index) => { var manifestItem = this.manifest[item.idref]; var spineItem; @@ -63,10 +61,10 @@ class Spine { this.append(spineItem); - }.bind(this)); + }); this.loaded = true; - }; + } /** * Get an item from the spine @@ -94,7 +92,7 @@ class Spine { } return this.spineItems[index] || null; - }; + } /** * Append a Section to the Spine @@ -111,7 +109,7 @@ class Spine { this.spineById[section.idref] = index; return index; - }; + } /** * Prepend a Section to the Spine @@ -119,7 +117,7 @@ class Spine { * @param {Section} section */ prepend(section) { - var index = this.spineItems.unshift(section); + // var index = this.spineItems.unshift(section); this.spineByHref[section.href] = 0; this.spineById[section.idref] = 0; @@ -129,7 +127,7 @@ class Spine { }); return 0; - }; + } // insert(section, index) { // @@ -149,7 +147,7 @@ class Spine { return this.spineItems.splice(index, 1); } - }; + } /** * Loop over the Sections in the Spine @@ -157,7 +155,7 @@ class Spine { */ each() { return this.spineItems.forEach.apply(this.spineItems, arguments); - }; + } } export default Spine; diff --git a/src/themes.js b/src/themes.js index c08ff36..a056a4e 100644 --- a/src/themes.js +++ b/src/themes.js @@ -1,4 +1,4 @@ -import Url from './utils/url'; +import Url from "./utils/url"; class Themes { constructor(rendition) { @@ -7,7 +7,7 @@ class Themes { "default" : { "rules" : [], "url" : "", - "serialized" : '' + "serialized" : "" } }; this._overrides = {}; @@ -34,7 +34,7 @@ class Themes { if (arguments.length === 2 && typeof(arguments[1]) === "object") { return this.registerRules(arguments[0], arguments[1]); } - }; + } default (theme) { if (!theme) { @@ -46,7 +46,7 @@ class Themes { if (typeof(theme) === "object") { return this.registerRules("default", theme); } - }; + } registerThemes (themes) { for (var theme in themes) { @@ -58,17 +58,17 @@ class Themes { } } } - }; + } registerUrl (name, input) { var url = new Url(input); this._themes[name] = { "url": url.toString() }; - }; + } registerRules (name, rules) { this._themes[name] = { "rules": rules }; // TODO: serialize css rules - }; + } apply (name) { var prev = this._current; @@ -78,18 +78,18 @@ class Themes { this.update(name); contents = this.rendition.getContents(); - contents.forEach(function (content) { + contents.forEach( (content) => { content.removeClass(prev); content.addClass(name); - }.bind(this)); - }; + }); + } update (name) { var contents = this.rendition.getContents(); - contents.forEach(function (content) { + contents.forEach( (content) => { this.add(name, content); - }.bind(this)); - }; + }); + } inject (view) { var links = []; @@ -108,7 +108,7 @@ class Themes { if(this._current) { view.contents.addClass(this._current); } - }; + } add (name, contents) { var theme = this._themes[name]; @@ -125,33 +125,32 @@ class Themes { contents.addStylesheetRules(theme.rules); theme.injected = true; } - }; + } override (name, value) { var contents = this.rendition.getContents(); this._overrides[name] = value; - contents.forEach(function (content) { + contents.forEach( (content) => { content.css(name, this._overrides[name]); - }.bind(this)); - }; + }); + } overrides (view) { var contents = view.contents; var overrides = this._overrides; - var rules = []; for (var rule in overrides) { if (overrides.hasOwnProperty(rule)) { contents.css(rule, overrides[rule]); } } - }; + } fontSize (size) { this.override("font-size", size); - }; + } } diff --git a/src/utils/core.js b/src/utils/core.js index 72be08f..d5e076f 100644 --- a/src/utils/core.js +++ b/src/utils/core.js @@ -1,32 +1,19 @@ -export const requestAnimationFrame = (typeof window != 'undefined') ? (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame) : false; +export const requestAnimationFrame = (typeof window != "undefined") ? (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame) : false; export function isElement(obj) { - return !!(obj && obj.nodeType == 1); -}; + return !!(obj && obj.nodeType == 1); +} // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript export function uuid() { var d = new Date().getTime(); - var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = (d + Math.random()*16)%16 | 0; - d = Math.floor(d/16); - return (c=='x' ? r : (r&0x7|0x8)).toString(16); + var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { + var r = (d + Math.random()*16)%16 | 0; + d = Math.floor(d/16); + return (c=="x" ? r : (r&0x7|0x8)).toString(16); }); return uuid; -}; - -// From Lodash -export function values(object) { - var index = -1, - props = Object.keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; -}; +} export function documentHeight() { return Math.max( @@ -36,34 +23,34 @@ export function documentHeight() { document.body.offsetHeight, document.documentElement.offsetHeight ); -}; +} export function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); -}; +} export function isFloat(n) { return isNumber(n) && (Math.floor(n) !== n); } export function prefixed(unprefixed) { - var vendors = ["Webkit", "Moz", "O", "ms" ], - prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], - upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), - length = vendors.length; + var vendors = ["Webkit", "Moz", "O", "ms" ]; + // var prefixes = ["-Webkit-", "-moz-", "-o-", "-ms-"]; + var upper = unprefixed[0].toUpperCase() + unprefixed.slice(1); + var length = vendors.length; - if (typeof(document) === 'undefined' || typeof(document.body.style[unprefixed]) != 'undefined') { + if (typeof(document) === "undefined" || typeof(document.body.style[unprefixed]) != "undefined") { return unprefixed; } for ( var i=0; i < length; i++ ) { - if (typeof(document.body.style[vendors[i] + upper]) != 'undefined') { + if (typeof(document.body.style[vendors[i] + upper]) != "undefined") { return vendors[i] + upper; } } return unprefixed; -}; +} export function defaults(obj) { for (var i = 1, length = arguments.length; i < length; i++) { @@ -73,18 +60,18 @@ export function defaults(obj) { } } return obj; -}; +} export function extend(target) { - var sources = [].slice.call(arguments, 1); - sources.forEach(function (source) { - if(!source) return; - Object.getOwnPropertyNames(source).forEach(function(propName) { - Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); - }); + var sources = [].slice.call(arguments, 1); + sources.forEach(function (source) { + if(!source) return; + Object.getOwnPropertyNames(source).forEach(function(propName) { + Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); }); - return target; -}; + }); + return target; +} // Fast quicksort insert for sorted array -- based on: // http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers @@ -93,7 +80,8 @@ export function insert(item, array, compareFunction) { array.splice(location, 0, item); return location; -}; +} + // Returns where something would fit in export function locationOf(item, array, compareFunction, _start, _end) { var start = _start || 0; @@ -104,7 +92,7 @@ export function locationOf(item, array, compareFunction, _start, _end) { compareFunction = function(a, b) { if(a > b) return 1; if(a < b) return -1; - if(a = b) return 0; + if(a == b) return 0; }; } if(end-start <= 0) { @@ -124,7 +112,8 @@ export function locationOf(item, array, compareFunction, _start, _end) { } else{ return locationOf(item, array, compareFunction, start, pivot); } -}; +} + // Returns -1 of mpt found export function indexOfSorted(item, array, compareFunction, _start, _end) { var start = _start || 0; @@ -135,7 +124,7 @@ export function indexOfSorted(item, array, compareFunction, _start, _end) { compareFunction = function(a, b) { if(a > b) return 1; if(a < b) return -1; - if(a = b) return 0; + if(a == b) return 0; }; } if(end-start <= 0) { @@ -154,7 +143,7 @@ export function indexOfSorted(item, array, compareFunction, _start, _end) { } else{ return indexOfSorted(item, array, compareFunction, start, pivot); } -}; +} export function bounds(el) { @@ -178,7 +167,7 @@ export function bounds(el) { width: width }; -}; +} export function borders(el) { @@ -202,7 +191,7 @@ export function borders(el) { width: width }; -}; +} export function windowBounds() { @@ -218,23 +207,23 @@ export function windowBounds() { height: height }; -}; +} -//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 +//-- https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 export function cleanStringForXpath(str) { - var parts = str.match(/[^'"]+|['"]/g); - parts = parts.map(function(part){ - if (part === "'") { - return '\"\'\"'; // output "'" - } + var parts = str.match(/[^'"]+|['"]/g); + parts = parts.map(function(part){ + if (part === "'") { + return "\"\'\""; // output "'" + } - if (part === '"') { - return "\'\"\'"; // output '"' - } - return "\'" + part + "\'"; - }); - return "concat(\'\'," + parts.join(",") + ")"; -}; + if (part === "\"") { + return "\'\"\'"; // output '"' + } + return `\'${part}\'`; + }); + return `concat(\'\',${ parts.join(",") })`; +} export function indexOfTextNode(textNode){ var parent = textNode.parentNode; @@ -250,17 +239,15 @@ export function indexOfTextNode(textNode){ } return index; -}; +} export function isXml(ext) { - return ['xml', 'opf', 'ncx'].indexOf(ext) > -1; + return ["xml", "opf", "ncx"].indexOf(ext) > -1; } export function createBlob(content, mime){ - var blob = new Blob([content], {type : mime }); - - return blob; -}; + return new Blob([content], {type : mime }); +} export function createBlobUrl(content, mime){ var _URL = window.URL || window.webkitURL || window.mozURL; @@ -270,10 +257,9 @@ export function createBlobUrl(content, mime){ tempUrl = _URL.createObjectURL(blob); return tempUrl; -}; +} export function createBase64Url(content, mime){ - var string; var data; var datauri; @@ -287,7 +273,7 @@ export function createBase64Url(content, mime){ datauri = "data:" + mime + ";base64," + data; return datauri; -}; +} export function type(obj){ return Object.prototype.toString.call(obj).slice(8, -1); @@ -298,7 +284,7 @@ export function parse(markup, mime, forceXMLDom) { var Parser; if (typeof DOMParser === "undefined" || forceXMLDom) { - Parser = require('xmldom').DOMParser; + Parser = require("xmldom").DOMParser; } else { Parser = DOMParser; } @@ -312,7 +298,7 @@ export function parse(markup, mime, forceXMLDom) { export function qs(el, sel) { var elements; if (!el) { - throw new Error('No Element Provided'); + throw new Error("No Element Provided"); } if (typeof el.querySelector != "undefined") { @@ -337,11 +323,11 @@ export function qsa(el, sel) { export function qsp(el, sel, props) { var q, filtered; if (typeof el.querySelector != "undefined") { - sel += '['; + sel += "["; for (var prop in props) { sel += prop + "='" + props[prop] + "'"; } - sel += ']'; + sel += "]"; return el.querySelector(sel); } else { q = el.getElementsByTagName(sel); @@ -409,10 +395,15 @@ export function walk(node,callback){ if(callback(node)){ return true; } - if(node = node.firstChild){ + node = node.firstChild; + if(node){ do{ - if(walk(node,callback)){return true} - }while(node=node.nextSibling) + let walked = walk(node,callback); + if(walked){ + return true; + } + node = node.nextSibling; + } while(node); } } @@ -421,7 +412,7 @@ export function blob2base64(blob, cb) { reader.readAsDataURL(blob); reader.onloadend = function() { cb(reader.result); - } + }; } // From: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#backwards_forwards_compatible @@ -456,10 +447,10 @@ export function defer() { Object.freeze(this); } - export function querySelectorByType(html, element, type){ +export function querySelectorByType(html, element, type){ var query; if (typeof html.querySelector != "undefined") { - query = html.querySelector(element+'[*|type="'+type+'"]'); + query = html.querySelector(`${element}[*|type="${type}"]`); } // Handle IE not supporting namespaced epub:type in querySelector if(!query || query.length === 0) { @@ -482,6 +473,6 @@ export function findChildren(el) { if (node.nodeType === 1) { result.push(node); } - }; + } return result; } diff --git a/src/hook.js b/src/utils/hook.js similarity index 95% rename from src/hook.js rename to src/utils/hook.js index 45c21c8..e7e8e3d 100644 --- a/src/hook.js +++ b/src/utils/hook.js @@ -9,7 +9,7 @@ class Hook { constructor(context){ this.context = context || this; this.hooks = []; - }; + } /** * Adds a function to be run before a hook completes @@ -26,7 +26,7 @@ class Hook { } } } - }; + } /** * Triggers a hook to run all functions @@ -37,7 +37,7 @@ class Hook { var context = this.context; var promises = []; - this.hooks.forEach(function(task, i) { + this.hooks.forEach(function(task) { var executing = task.apply(context, args); if(executing && typeof executing["then"] === "function") { @@ -49,15 +49,15 @@ class Hook { return Promise.all(promises); - }; + } // Adds a function to be run before a hook completes list(){ return this.hooks; - }; + } clear(){ return this.hooks = []; - }; + } } export default Hook; diff --git a/src/queue.js b/src/utils/queue.js similarity index 89% rename from src/queue.js rename to src/utils/queue.js index c3e3272..47f061b 100644 --- a/src/queue.js +++ b/src/utils/queue.js @@ -1,4 +1,4 @@ -import {defer, requestAnimationFrame} from './utils/core'; +import {defer, requestAnimationFrame} from "./core"; /** * Queue for handling tasks one at a time @@ -12,7 +12,7 @@ class Queue { this.tick = requestAnimationFrame; this.running = false; this.paused = false; - }; + } /** * Add an item to the queue @@ -29,7 +29,7 @@ class Queue { // args = [args]; // } if(!task) { - return console.error("No Task Provided"); + throw new Error("No Task Provided"); } if(typeof task === "function"){ @@ -63,7 +63,7 @@ class Queue { } return queued.promise; - }; + } /** * Run one item @@ -84,7 +84,7 @@ class Queue { // Task is a function that returns a promise return result.then(function(){ inwait.deferred.resolve.apply(this.context, arguments); - }.bind(this), function(reason) { + }.bind(this), function() { inwait.deferred.reject.apply(this.context, arguments); }.bind(this)); } else { @@ -106,14 +106,14 @@ class Queue { return inwait.promise; } - }; + } // Run All Immediately dump(){ while(this._q.length) { this.dequeue(); } - }; + } /** * Run all tasks sequentially, at convince @@ -126,7 +126,7 @@ class Queue { this.defered = new defer(); } - this.tick.call(window, function() { + this.tick.call(window, () => { if(this._q.length) { @@ -140,7 +140,7 @@ class Queue { this.running = undefined; } - }.bind(this)); + }); // Unpause if(this.paused == true) { @@ -148,7 +148,7 @@ class Queue { } return this.defered.promise; - }; + } /** * Flush all, as quickly as possible @@ -170,7 +170,7 @@ class Queue { return this.running; } - }; + } /** * Clear all items in wait @@ -178,7 +178,7 @@ class Queue { clear(){ this._q = []; this.running = false; - }; + } /** * Get the number of tasks in the queue @@ -186,14 +186,14 @@ class Queue { */ length(){ return this._q.length; - }; + } /** * Pause a running queue */ pause(){ this.paused = true; - }; + } } @@ -212,22 +212,27 @@ class Task { return function(){ var toApply = arguments || []; - return new Promise(function(resolve, reject) { - var callback = function(value){ - resolve(value); + return new Promise( (resolve, reject) => { + var callback = function(value, err){ + if (!value && err) { + reject(err); + } else { + resolve(value); + } }; // Add the callback to the arguments list toApply.push(callback); // Apply all arguments to the functions - task.apply(this, toApply); + task.apply(context || this, toApply); - }.bind(this)); + }); }; - }; + } } export default Queue; +export { Task }; diff --git a/src/replacements.js b/src/utils/replacements.js similarity index 92% rename from src/replacements.js rename to src/utils/replacements.js index dc98348..b10a69f 100644 --- a/src/replacements.js +++ b/src/utils/replacements.js @@ -1,6 +1,5 @@ -// import URI from 'urijs'; -import { qs } from './utils/core'; -import Url from './utils/url'; +import { qs } from "./core"; +import Url from "./url"; export function replaceBase(doc, section){ var base; @@ -96,12 +95,12 @@ export function replaceLinks(view, renderer) { } -}; +} export function substitute(content, urls, replacements) { urls.forEach(function(url, i){ if (url && replacements[i]) { - content = content.replace(new RegExp(url, 'g'), replacements[i]); + content = content.replace(new RegExp(url, "g"), replacements[i]); } }); return content; diff --git a/src/request.js b/src/utils/request.js similarity index 78% rename from src/request.js rename to src/utils/request.js index 75c1fce..c369b56 100644 --- a/src/request.js +++ b/src/utils/request.js @@ -1,10 +1,9 @@ -import {defer, isXml, parse} from './utils/core'; -import Path from './utils/path'; +import {defer, isXml, parse} from "./core"; +import Path from "./path"; function request(url, type, withCredentials, headers) { var supportsURL = (typeof window != "undefined") ? window.URL : false; // TODO: fallback for url if window isn't defined var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; - var uri; var deferred = new defer(); @@ -16,12 +15,13 @@ function request(url, type, withCredentials, headers) { var header; - if (!('overrideMimeType' in xhrPrototype)) { + if (!("overrideMimeType" in xhrPrototype)) { // IE10 might have response, but not overrideMimeType - Object.defineProperty(xhrPrototype, 'overrideMimeType', { - value: function xmlHttpRequestOverrideMimeType(mimeType) {} + Object.defineProperty(xhrPrototype, "overrideMimeType", { + value: function xmlHttpRequestOverrideMimeType() {} }); } + if(withCredentials) { xhr.withCredentials = true; } @@ -39,28 +39,28 @@ function request(url, type, withCredentials, headers) { xhr.setRequestHeader("Accept", "application/json"); } - // If type isn't set, determine it from the file extension + // If type isn"t set, determine it from the file extension if(!type) { type = new Path(url).extension; } - if(type == 'blob'){ + if(type == "blob"){ xhr.responseType = BLOB_RESPONSE; } if(isXml(type)) { // xhr.responseType = "document"; - xhr.overrideMimeType('text/xml'); // for OPF parsing + xhr.overrideMimeType("text/xml"); // for OPF parsing } - if(type == 'xhtml') { + if(type == "xhtml") { // xhr.responseType = "document"; } - if(type == 'html' || type == 'htm') { + if(type == "html" || type == "htm") { // xhr.responseType = "document"; - } + } if(type == "binary") { xhr.responseType = "arraybuffer"; @@ -69,7 +69,6 @@ function request(url, type, withCredentials, headers) { xhr.send(); function err(e) { - console.error(e); deferred.reject(e); } @@ -77,7 +76,7 @@ function request(url, type, withCredentials, headers) { if (this.readyState === XMLHttpRequest.DONE) { var responseXML = false; - if(this.responseType === '' || this.responseType === "document") { + if(this.responseType === "" || this.responseType === "document") { responseXML = this.responseXML; } @@ -107,20 +106,20 @@ function request(url, type, withCredentials, headers) { r = this.responseXML; } else if(isXml(type)){ - // xhr.overrideMimeType('text/xml'); // for OPF parsing + // xhr.overrideMimeType("text/xml"); // for OPF parsing // If this.responseXML wasn't set, try to parse using a DOMParser from text r = parse(this.response, "text/xml"); }else - if(type == 'xhtml'){ + if(type == "xhtml"){ r = parse(this.response, "application/xhtml+xml"); }else - if(type == 'html' || type == 'htm'){ + if(type == "html" || type == "htm"){ r = parse(this.response, "text/html"); }else - if(type == 'json'){ + if(type == "json"){ r = JSON.parse(this.response); }else - if(type == 'blob'){ + if(type == "blob"){ if(supportsURL) { r = this.response; @@ -147,6 +146,6 @@ function request(url, type, withCredentials, headers) { } return deferred.promise; -}; +} export default request; diff --git a/src/utils/url.js b/src/utils/url.js index f472d31..35e0be4 100644 --- a/src/utils/url.js +++ b/src/utils/url.js @@ -1,4 +1,4 @@ -import Path from "./path" +import Path from "./path"; import path from "path-webpack"; /**