1
0
Fork 0
mirror of https://github.com/futurepress/epub.js.git synced 2025-10-04 15:09:16 +02:00

setup browserify and requires

This commit is contained in:
fchasen 2015-12-03 23:41:49 -05:00
parent 76aab85dc4
commit 91d1df14b1
25 changed files with 4789 additions and 4441 deletions

7882
dist/epub.js vendored

File diff suppressed because it is too large Load diff

1
dist/epub.js.map vendored Normal file

File diff suppressed because one or more lines are too long

7
dist/epub.min.js vendored

File diff suppressed because one or more lines are too long

1
dist/epub.min.js.map vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -10,28 +10,14 @@ var onError = function (err) {
}; };
var server = require("./tools/serve.js"); var server = require("./tools/serve.js");
var files = [ var browserify = require('browserify');
'node_modules/rsvp/dist/rsvp.js', var watchify = require('watchify');
'src/epub.js', var source = require('vinyl-source-stream');
'src/core.js', var buffer = require('vinyl-buffer');
'src/queue.js', var sourcemaps = require('gulp-sourcemaps');
'src/hooks.js',
'src/parser.js', // https://github.com/mishoo/UglifyJS2/pull/265
'src/epubcfi.js', // uglify.AST_Node.warn_function = function() {};
'src/navigation.js',
'src/section.js',
'src/spine.js',
'src/replacements.js',
'src/book.js',
'src/view.js',
'src/views.js',
'src/layout.js',
'src/rendition.js',
'src/continuous.js',
'src/paginate.js',
'src/map.js',
'src/locations.js'
];
// Lint JS // Lint JS
gulp.task('lint', function() { gulp.task('lint', function() {
@ -40,20 +26,30 @@ gulp.task('lint', function() {
.pipe(jshint.reporter('default')); .pipe(jshint.reporter('default'));
}); });
// Concat & Minify JS // set up the browserify instance on a task basis
gulp.task('minify', function(){ gulp.task('bundle', function () {
return gulp.src(files) return bundle('epub.js');
});
// Minify JS
gulp.task('minify', ['bundle'], function(){
var uglifyOptions = {
mangle: true,
preserveComments : "license"
};
return gulp.src('dist/epub.js')
.pipe(plumber({ errorHandler: onError })) .pipe(plumber({ errorHandler: onError }))
.pipe(concat('epub.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('epub.min.js')) .pipe(rename('epub.min.js'))
.pipe(uglify()) .pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify(uglifyOptions))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist')); .pipe(gulp.dest('dist'));
}); });
// Watch Our Files // Watch Our Files
gulp.task('watch', function() { gulp.task('watch', function() {
gulp.watch('src/*.js', ['minify']); // gulp.watch('src/*.js', ['watchify']);
return bundle('epub.js', true);
}); });
gulp.task('serve', ["watch"], function() { gulp.task('serve', ["watch"], function() {
@ -61,8 +57,38 @@ gulp.task('serve', ["watch"], function() {
}); });
// Default // Default
gulp.task('default', ['lint', 'minify']); gulp.task('default', ['lint', 'build']);
// gulp.task('default', function() { // gulp.task('default', function() {
// // place code for your default task here // // place code for your default task here
// }); // });
function bundle(file, watch) {
var opt = {
entries: ['src/'+file],
debug : true
};
// watchify() if watch requested, otherwise run browserify() once
var bundler = watch ? watchify(browserify(opt)) : browserify(opt);
function rebundle() {
var stream = bundler.bundle();
return stream
.on('error', gutil.log)
.pipe(source(file))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/'));
}
// listen for an update and run rebundle
bundler.on('update', function() {
rebundle();
gutil.log('Rebundle...');
});
// run it once the first time buildScript is called
return rebundle();
}

View file

@ -16,19 +16,24 @@
"colors": "^0.6.2", "colors": "^0.6.2",
"connect": "^3.0.1", "connect": "^3.0.1",
"express": "^4.5.1", "express": "^4.5.1",
"gulp": "^3.8.7", "gulp": "^3.9.0",
"gulp-concat": "^2.3.4", "gulp-concat": "^2.3.4",
"gulp-connect": "~2.0.6", "gulp-connect": "~2.0.6",
"gulp-jshint": "^1.8.4", "gulp-jshint": "^1.8.4",
"gulp-plumber": "^0.6.4", "gulp-plumber": "^0.6.4",
"gulp-rename": "^1.2.0", "gulp-rename": "^1.2.0",
"gulp-sourcemaps": "^1.6.0",
"gulp-uglify": "^0.3.1", "gulp-uglify": "^0.3.1",
"gulp-util": "^3.0.0", "gulp-util": "^3.0.0",
"morgan": "^1.1.1", "morgan": "^1.1.1",
"optimist": "^0.6.1", "optimist": "^0.6.1",
"portfinder": "^0.2.1", "portfinder": "^0.2.1",
"qunitjs": "^1.14.0", "qunitjs": "^1.14.0",
"serve-static": "^1.3.1" "serve-static": "^1.3.1",
"uglify": "^0.1.5",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0",
"watchify": "^3.6.1"
}, },
"dependencies": { "dependencies": {
"rsvp": "^3.0.18" "rsvp": "^3.0.18"

View file

@ -1,4 +1,14 @@
EPUBJS.Book = function(_url, options){ var RSVP = require('rsvp');
var core = require('./core');
var Spine = require('./spine');
var Locations = require('./locations');
var Parser = require('./parser');
var Navigation = require('./navigation');
var Rendition = require('./rendition');
var Continuous = require('./continuous');
var Paginate = require('./paginate');
function Book(_url, options){
// Promises // Promises
this.opening = new RSVP.defer(); this.opening = new RSVP.defer();
this.opened = this.opening.promise; this.opened = this.opening.promise;
@ -28,21 +38,21 @@ EPUBJS.Book = function(_url, options){
// Queue for methods used before opening // Queue for methods used before opening
this.isRendered = false; this.isRendered = false;
this._q = EPUBJS.core.queue(this); // this._q = core.queue(this);
this.request = this.requestMethod.bind(this); this.request = this.requestMethod.bind(this);
this.spine = new EPUBJS.Spine(this.request); this.spine = new Spine(this.request);
this.locations = new EPUBJS.Locations(this.spine, this.request); this.locations = new Locations(this.spine, this.request);
if(_url) { if(_url) {
this.open(_url); this.open(_url);
} }
}; };
EPUBJS.Book.prototype.open = function(_url){ Book.prototype.open = function(_url){
var uri; var uri;
var parse = new EPUBJS.Parser(); var parse = new Parser();
var epubPackage; var epubPackage;
var book = this; var book = this;
var containerPath = "META-INF/container.xml"; var containerPath = "META-INF/container.xml";
@ -57,7 +67,7 @@ EPUBJS.Book.prototype.open = function(_url){
if(typeof(_url) === "object") { if(typeof(_url) === "object") {
uri = _url; uri = _url;
} else { } else {
uri = EPUBJS.core.uri(_url); uri = core.uri(_url);
} }
// Find path to the Container // Find path to the Container
@ -69,8 +79,8 @@ EPUBJS.Book.prototype.open = function(_url){
if(uri.origin) { if(uri.origin) {
this.url = uri.base; this.url = uri.base;
} else if(window){ } else if(window){
location = EPUBJS.core.uri(window.location.href); location = core.uri(window.location.href);
this.url = EPUBJS.core.resolveUrl(location.base, uri.directory); this.url = core.resolveUrl(location.base, uri.directory);
} else { } else {
this.url = uri.directory; this.url = uri.directory;
} }
@ -93,7 +103,7 @@ EPUBJS.Book.prototype.open = function(_url){
return parse.container(containerXml); // Container has path to content return parse.container(containerXml); // Container has path to content
}). }).
then(function(paths){ then(function(paths){
var packageUri = EPUBJS.core.uri(paths.packagePath); var packageUri = core.uri(paths.packagePath);
book.packageUrl = _url + paths.packagePath; book.packageUrl = _url + paths.packagePath;
book.encoding = paths.encoding; book.encoding = paths.encoding;
@ -101,8 +111,8 @@ EPUBJS.Book.prototype.open = function(_url){
if(packageUri.origin) { if(packageUri.origin) {
book.url = packageUri.base; book.url = packageUri.base;
} else if(window){ } else if(window){
location = EPUBJS.core.uri(window.location.href); location = core.uri(window.location.href);
book.url = EPUBJS.core.resolveUrl(location.base, _url + packageUri.directory); book.url = core.resolveUrl(location.base, _url + packageUri.directory);
} else { } else {
book.url = packageUri.directory; book.url = packageUri.directory;
} }
@ -143,16 +153,16 @@ EPUBJS.Book.prototype.open = function(_url){
return this.opened; return this.opened;
}; };
EPUBJS.Book.prototype.unpack = function(packageXml){ Book.prototype.unpack = function(packageXml){
var book = this, var book = this,
parse = new EPUBJS.Parser(); parse = new Parser();
book.package = parse.packageContents(packageXml); // Extract info from contents book.package = parse.packageContents(packageXml); // Extract info from contents
book.package.baseUrl = book.url; // Provides a url base for resolving paths book.package.baseUrl = book.url; // Provides a url base for resolving paths
this.spine.load(book.package); this.spine.load(book.package);
book.navigation = new EPUBJS.Navigation(book.package, this.request); book.navigation = new Navigation(book.package, this.request);
book.navigation.load().then(function(toc){ book.navigation.load().then(function(toc){
book.toc = toc; book.toc = toc;
book.loading.navigation.resolve(book.toc); book.loading.navigation.resolve(book.toc);
@ -166,45 +176,48 @@ EPUBJS.Book.prototype.unpack = function(packageXml){
}; };
// Alias for book.spine.get // Alias for book.spine.get
EPUBJS.Book.prototype.section = function(target) { Book.prototype.section = function(target) {
return this.spine.get(target); return this.spine.get(target);
}; };
// Sugar to render a book // Sugar to render a book
EPUBJS.Book.prototype.renderTo = function(element, options) { Book.prototype.renderTo = function(element, options) {
var renderer = (options && options.method) ? var renderMethod = (options && options.method) ?
options.method.charAt(0).toUpperCase() + options.method.substr(1) : options.method :
"Rendition"; "rendition";
var Renderer = require('./'+renderMethod);
this.rendition = new EPUBJS[renderer](this, options); this.rendition = new Renderer(this, options);
this.rendition.attachTo(element); this.rendition.attachTo(element);
return this.rendition; return this.rendition;
}; };
EPUBJS.Book.prototype.requestMethod = function(_url) { Book.prototype.requestMethod = function(_url) {
// Switch request methods // Switch request methods
if(this.archived) { if(this.archived) {
// TODO: handle archived // TODO: handle archived
} else { } else {
return EPUBJS.core.request(_url, 'xml', this.requestCredentials, this.requestHeaders); return core.request(_url, 'xml', this.requestCredentials, this.requestHeaders);
} }
}; };
EPUBJS.Book.prototype.setRequestCredentials = function(_credentials) { Book.prototype.setRequestCredentials = function(_credentials) {
this.requestCredentials = _credentials; this.requestCredentials = _credentials;
}; };
EPUBJS.Book.prototype.setRequestHeaders = function(_headers) { Book.prototype.setRequestHeaders = function(_headers) {
this.requestHeaders = _headers; this.requestHeaders = _headers;
}; };
module.exports = Book;
//-- Enable binding events to book //-- Enable binding events to book
RSVP.EventTarget.mixin(EPUBJS.Book.prototype); RSVP.EventTarget.mixin(Book.prototype);
//-- Handle RSVP Errors //-- Handle RSVP Errors
RSVP.on('error', function(event) { RSVP.on('error', function(event) {
//console.error(event, event.detail); console.error(event);
}); });
RSVP.configure('instrument', true); //-- true | will logging out all RSVP rejections RSVP.configure('instrument', true); //-- true | will logging out all RSVP rejections

View file

@ -1,8 +1,13 @@
EPUBJS.Continuous = function(book, options) { var RSVP = require('rsvp');
var core = require('./core');
var Rendition = require('./rendition');
var View = require('./view');
EPUBJS.Rendition.apply(this, arguments); // call super constructor. function Continuous(book, options) {
this.settings = EPUBJS.core.extend(this.settings || {}, { Rendition.apply(this, arguments); // call super constructor.
this.settings = core.extend(this.settings || {}, {
infinite: true, infinite: true,
overflow: "auto", overflow: "auto",
axis: "vertical", axis: "vertical",
@ -10,7 +15,7 @@ EPUBJS.Continuous = function(book, options) {
offsetDelta: 250 offsetDelta: 250
}); });
EPUBJS.core.extend(this.settings, options); core.extend(this.settings, options);
if(this.settings.hidden) { if(this.settings.hidden) {
this.wrapper = this.wrap(this.container); this.wrapper = this.wrap(this.container);
@ -20,14 +25,14 @@ EPUBJS.Continuous = function(book, options) {
}; };
// subclass extends superclass // subclass extends superclass
EPUBJS.Continuous.prototype = Object.create(EPUBJS.Rendition.prototype); Continuous.prototype = Object.create(Rendition.prototype);
EPUBJS.Continuous.prototype.constructor = EPUBJS.Continuous; Continuous.prototype.constructor = Continuous;
EPUBJS.Continuous.prototype.attachListeners = function(){ Continuous.prototype.attachListeners = function(){
// Listen to window for resize event if width or height is set to a percent // Listen to window for resize event if width or height is set to a percent
if(!EPUBJS.core.isNumber(this.settings.width) || if(!core.isNumber(this.settings.width) ||
!EPUBJS.core.isNumber(this.settings.height) ) { !core.isNumber(this.settings.height) ) {
window.addEventListener("resize", this.onResized.bind(this), false); window.addEventListener("resize", this.onResized.bind(this), false);
} }
@ -39,7 +44,7 @@ EPUBJS.Continuous.prototype.attachListeners = function(){
}; };
EPUBJS.Continuous.prototype.parseTarget = function(target){ Continuous.prototype.parseTarget = function(target){
if(this.epubcfi.isCfiString(target)) { if(this.epubcfi.isCfiString(target)) {
cfi = this.epubcfi.parse(target); cfi = this.epubcfi.parse(target);
spinePos = cfi.spinePos; spinePos = cfi.spinePos;
@ -49,7 +54,7 @@ EPUBJS.Continuous.prototype.parseTarget = function(target){
} }
}; };
EPUBJS.Continuous.prototype.moveTo = function(offset){ Continuous.prototype.moveTo = function(offset){
// var bounds = this.bounds(); // var bounds = this.bounds();
// var dist = Math.floor(offset.top / bounds.height) * bounds.height; // var dist = Math.floor(offset.top / bounds.height) * bounds.height;
return this.check( return this.check(
@ -66,19 +71,19 @@ EPUBJS.Continuous.prototype.moveTo = function(offset){
}.bind(this)); }.bind(this));
}; };
EPUBJS.Continuous.prototype.afterDisplayed = function(currView){ Continuous.prototype.afterDisplayed = function(currView){
var next = currView.section.next(); var next = currView.section.next();
var prev = currView.section.prev(); var prev = currView.section.prev();
var index = this.views.indexOf(currView); var index = this.views.indexOf(currView);
var prevView, nextView; var prevView, nextView;
if(index + 1 === this.views.length && next) { if(index + 1 === this.views.length && next) {
nextView = new EPUBJS.View(next, this.viewSettings); nextView = new View(next, this.viewSettings);
this.q.enqueue(this.append, nextView); this.q.enqueue(this.append, nextView);
} }
if(index === 0 && prev) { if(index === 0 && prev) {
prevView = new EPUBJS.View(prev, this.viewSettings); prevView = new View(prev, this.viewSettings);
this.q.enqueue(this.prepend, prevView); this.q.enqueue(this.prepend, prevView);
} }
@ -90,7 +95,7 @@ EPUBJS.Continuous.prototype.afterDisplayed = function(currView){
// Remove Previous Listeners if present // Remove Previous Listeners if present
EPUBJS.Continuous.prototype.removeShownListeners = function(view){ Continuous.prototype.removeShownListeners = function(view){
// view.off("shown", this.afterDisplayed); // view.off("shown", this.afterDisplayed);
// view.off("shown", this.afterDisplayedAbove); // view.off("shown", this.afterDisplayedAbove);
@ -98,7 +103,7 @@ EPUBJS.Continuous.prototype.removeShownListeners = function(view){
}; };
EPUBJS.Continuous.prototype.append = function(view){ Continuous.prototype.append = function(view){
// view.on("shown", this.afterDisplayed.bind(this)); // view.on("shown", this.afterDisplayed.bind(this));
view.onDisplayed = this.afterDisplayed.bind(this); view.onDisplayed = this.afterDisplayed.bind(this);
@ -109,7 +114,7 @@ EPUBJS.Continuous.prototype.append = function(view){
return this.check(); return this.check();
}; };
EPUBJS.Continuous.prototype.prepend = function(view){ Continuous.prototype.prepend = function(view){
// view.on("shown", this.afterDisplayedAbove.bind(this)); // view.on("shown", this.afterDisplayedAbove.bind(this));
view.onDisplayed = this.afterDisplayed.bind(this); view.onDisplayed = this.afterDisplayed.bind(this);
@ -121,7 +126,7 @@ EPUBJS.Continuous.prototype.prepend = function(view){
return this.check(); return this.check();
}; };
EPUBJS.Continuous.prototype.counter = function(bounds){ Continuous.prototype.counter = function(bounds){
if(this.settings.axis === "vertical") { if(this.settings.axis === "vertical") {
this.scrollBy(0, bounds.heightDelta, true); this.scrollBy(0, bounds.heightDelta, true);
@ -131,7 +136,7 @@ EPUBJS.Continuous.prototype.counter = function(bounds){
}; };
EPUBJS.Continuous.prototype.check = function(_offset){ Continuous.prototype.check = function(_offset){
var checking = new RSVP.defer(); var checking = new RSVP.defer();
var container = this.bounds(); var container = this.bounds();
var promises = []; var promises = [];
@ -182,7 +187,7 @@ EPUBJS.Continuous.prototype.check = function(_offset){
}; };
EPUBJS.Continuous.prototype.trim = function(){ Continuous.prototype.trim = function(){
var task = new RSVP.defer(); var task = new RSVP.defer();
var displayed = this.views.displayed(); var displayed = this.views.displayed();
var first = displayed[0]; var first = displayed[0];
@ -206,7 +211,7 @@ EPUBJS.Continuous.prototype.trim = function(){
return task.promise; return task.promise;
}; };
EPUBJS.Continuous.prototype.erase = function(view, above){ //Trim Continuous.prototype.erase = function(view, above){ //Trim
var prevTop; var prevTop;
var prevLeft; var prevLeft;
@ -234,10 +239,10 @@ EPUBJS.Continuous.prototype.erase = function(view, above){ //Trim
}; };
EPUBJS.Continuous.prototype.start = function() { Continuous.prototype.start = function() {
var scroller; var scroller;
this.tick = EPUBJS.core.requestAnimationFrame; this.tick = core.requestAnimationFrame;
if(this.settings.height) { if(this.settings.height) {
this.prevScrollTop = this.container.scrollTop; this.prevScrollTop = this.container.scrollTop;
@ -275,7 +280,7 @@ EPUBJS.Continuous.prototype.start = function() {
}; };
EPUBJS.Continuous.prototype.onScroll = function(){ Continuous.prototype.onScroll = function(){
if(this.scrolled) { if(this.scrolled) {
@ -331,7 +336,7 @@ EPUBJS.Continuous.prototype.onScroll = function(){
}; };
EPUBJS.Continuous.prototype.resizeView = function(view) { Continuous.prototype.resizeView = function(view) {
if(this.settings.axis === "horizontal") { if(this.settings.axis === "horizontal") {
view.lock("height", this.stage.width, this.stage.height); view.lock("height", this.stage.width, this.stage.height);
@ -341,7 +346,7 @@ EPUBJS.Continuous.prototype.onScroll = function(){
}; };
EPUBJS.Continuous.prototype.currentLocation = function(){ Continuous.prototype.currentLocation = function(){
var visible = this.visible(); var visible = this.visible();
var startPage, endPage; var startPage, endPage;
@ -365,7 +370,7 @@ EPUBJS.Continuous.prototype.currentLocation = function(){
}; };
/* /*
EPUBJS.Continuous.prototype.current = function(what){ Continuous.prototype.current = function(what){
var view, top; var view, top;
var container = this.container.getBoundingClientRect(); var container = this.container.getBoundingClientRect();
var length = this.views.length - 1; var length = this.views.length - 1;
@ -409,3 +414,5 @@ EPUBJS.Continuous.prototype.current = function(what){
return this._current; return this._current;
}; };
*/ */
module.exports = Continuous;

View file

@ -1,6 +1,6 @@
EPUBJS.core = {}; var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
EPUBJS.core.request = function(url, type, withCredentials, headers) { function request(url, type, withCredentials, headers) {
var supportsURL = window.URL; var supportsURL = window.URL;
var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer";
@ -92,7 +92,7 @@ EPUBJS.core.request = function(url, type, withCredentials, headers) {
}; };
//-- Parse the different parts of a url, returning a object //-- Parse the different parts of a url, returning a object
EPUBJS.core.uri = function(url){ function uri(url){
var uri = { var uri = {
protocol : '', protocol : '',
host : '', host : '',
@ -139,13 +139,13 @@ EPUBJS.core.uri = function(url){
uri.origin = uri.protocol + "://" + uri.host; uri.origin = uri.protocol + "://" + uri.host;
uri.directory = EPUBJS.core.folder(uri.path); uri.directory = folder(uri.path);
uri.base = uri.origin + uri.directory; uri.base = uri.origin + uri.directory;
// return origin; // return origin;
} else { } else {
uri.path = url; uri.path = url;
uri.directory = EPUBJS.core.folder(url); uri.directory = folder(url);
uri.base = uri.directory; uri.base = uri.directory;
} }
@ -159,7 +159,7 @@ EPUBJS.core.uri = function(url){
}; };
//-- Parse out the folder, will return everything before the last slash //-- Parse out the folder, will return everything before the last slash
EPUBJS.core.folder = function(url){ function folder(url){
var lastSlash = url.lastIndexOf('/'); var lastSlash = url.lastIndexOf('/');
@ -171,61 +171,12 @@ EPUBJS.core.folder = function(url){
}; };
function isElement(obj) {
EPUBJS.core.queue = function(_scope){
var _q = [];
var scope = _scope;
// Add an item to the queue
var enqueue = function(funcName, args, context) {
_q.push({
"funcName" : funcName,
"args" : args,
"context" : context
});
return _q;
};
// Run one item
var dequeue = function(){
var inwait;
if(_q.length) {
inwait = _q.shift();
// Defer to any current tasks
// setTimeout(function(){
scope[inwait.funcName].apply(inwait.context || scope, inwait.args);
// }, 0);
}
};
// Run All
var flush = function(){
while(_q.length) {
dequeue();
}
};
// Clear all items in wait
var clear = function(){
_q = [];
};
var length = function(){
return _q.length;
};
return {
"enqueue" : enqueue,
"dequeue" : dequeue,
"flush" : flush,
"clear" : clear,
"length" : length
};
};
EPUBJS.core.isElement = function(obj) {
return !!(obj && obj.nodeType == 1); return !!(obj && obj.nodeType == 1);
}; };
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
EPUBJS.core.uuid = function() { function uuid() {
var d = new Date().getTime(); var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0; var r = (d + Math.random()*16)%16 | 0;
@ -236,7 +187,7 @@ EPUBJS.core.uuid = function() {
}; };
// From Lodash // From Lodash
EPUBJS.core.values = function(object) { function values(object) {
var index = -1, var index = -1,
props = Object.keys(object), props = Object.keys(object),
length = props.length, length = props.length,
@ -248,11 +199,11 @@ EPUBJS.core.values = function(object) {
return result; return result;
}; };
EPUBJS.core.resolveUrl = function(base, path) { function resolveUrl(base, path) {
var url = [], var url = [],
segments = [], segments = [],
baseUri = EPUBJS.core.uri(base), baseUri = uri(base),
pathUri = EPUBJS.core.uri(path), pathUri = uri(path),
baseDirectory = baseUri.directory, baseDirectory = baseUri.directory,
pathDirectory = pathUri.directory, pathDirectory = pathUri.directory,
directories = [], directories = [],
@ -311,7 +262,7 @@ EPUBJS.core.resolveUrl = function(base, path) {
return url.join("/"); return url.join("/");
}; };
EPUBJS.core.documentHeight = function() { function documentHeight() {
return Math.max( return Math.max(
document.documentElement.clientHeight, document.documentElement.clientHeight,
document.body.scrollHeight, document.body.scrollHeight,
@ -321,11 +272,11 @@ EPUBJS.core.documentHeight = function() {
); );
}; };
EPUBJS.core.isNumber = function(n) { function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n); return !isNaN(parseFloat(n)) && isFinite(n);
}; };
EPUBJS.core.prefixed = function(unprefixed) { function prefixed(unprefixed) {
var vendors = ["Webkit", "Moz", "O", "ms" ], var vendors = ["Webkit", "Moz", "O", "ms" ],
prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'],
upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), upper = unprefixed[0].toUpperCase() + unprefixed.slice(1),
@ -344,7 +295,7 @@ EPUBJS.core.prefixed = function(unprefixed) {
return unprefixed; return unprefixed;
}; };
EPUBJS.core.defaults = function(obj) { function defaults(obj) {
for (var i = 1, length = arguments.length; i < length; i++) { for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i]; var source = arguments[i];
for (var prop in source) { for (var prop in source) {
@ -354,7 +305,7 @@ EPUBJS.core.defaults = function(obj) {
return obj; return obj;
}; };
EPUBJS.core.extend = function(target) { function extend(target) {
var sources = [].slice.call(arguments, 1); var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) { sources.forEach(function (source) {
if(!source) return; if(!source) return;
@ -367,14 +318,14 @@ EPUBJS.core.extend = function(target) {
// Fast quicksort insert for sorted array -- based on: // 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 // http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers
EPUBJS.core.insert = function(item, array, compareFunction) { function insert(item, array, compareFunction) {
var location = EPUBJS.core.locationOf(item, array, compareFunction); var location = locationOf(item, array, compareFunction);
array.splice(location, 0, item); array.splice(location, 0, item);
return location; return location;
}; };
// Returns where something would fit in // Returns where something would fit in
EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { function locationOf(item, array, compareFunction, _start, _end) {
var start = _start || 0; var start = _start || 0;
var end = _end || array.length; var end = _end || array.length;
var pivot = parseInt(start + (end - start) / 2); var pivot = parseInt(start + (end - start) / 2);
@ -399,13 +350,13 @@ EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) {
return pivot; return pivot;
} }
if(compared === -1) { if(compared === -1) {
return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); return locationOf(item, array, compareFunction, pivot, end);
} else{ } else{
return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); return locationOf(item, array, compareFunction, start, pivot);
} }
}; };
// Returns -1 of mpt found // Returns -1 of mpt found
EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { function indexOfSorted(item, array, compareFunction, _start, _end) {
var start = _start || 0; var start = _start || 0;
var end = _end || array.length; var end = _end || array.length;
var pivot = parseInt(start + (end - start) / 2); var pivot = parseInt(start + (end - start) / 2);
@ -429,15 +380,13 @@ EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end)
return pivot; // Found return pivot; // Found
} }
if(compared === -1) { if(compared === -1) {
return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); return indexOfSorted(item, array, compareFunction, pivot, end);
} else{ } else{
return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); return indexOfSorted(item, array, compareFunction, start, pivot);
} }
}; };
EPUBJS.core.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; function bounds(el) {
EPUBJS.core.bounds = function(el) {
var style = window.getComputedStyle(el); var style = window.getComputedStyle(el);
var widthProps = ["width", "paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"]; var widthProps = ["width", "paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"];
@ -461,7 +410,7 @@ EPUBJS.core.bounds = function(el) {
}; };
EPUBJS.core.borders = function(el) { function borders(el) {
var style = window.getComputedStyle(el); var style = window.getComputedStyle(el);
var widthProps = ["paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"]; var widthProps = ["paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"];
@ -485,7 +434,7 @@ EPUBJS.core.borders = function(el) {
}; };
EPUBJS.core.windowBounds = function() { function windowBounds() {
var width = window.innerWidth; var width = window.innerWidth;
var height = window.innerHeight; var height = window.innerHeight;
@ -502,7 +451,7 @@ EPUBJS.core.windowBounds = function() {
}; };
//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
EPUBJS.core.cleanStringForXpath = function(str) { function cleanStringForXpath(str) {
var parts = str.match(/[^'"]+|['"]/g); var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){ parts = parts.map(function(part){
if (part === "'") { if (part === "'") {
@ -517,7 +466,7 @@ EPUBJS.core.cleanStringForXpath = function(str) {
return "concat(\'\'," + parts.join(",") + ")"; return "concat(\'\'," + parts.join(",") + ")";
}; };
EPUBJS.core.indexOfTextNode = function(textNode){ function indexOfTextNode(textNode){
var parent = textNode.parentNode; var parent = textNode.parentNode;
var children = parent.childNodes; var children = parent.childNodes;
var sib; var sib;
@ -532,3 +481,28 @@ EPUBJS.core.indexOfTextNode = function(textNode){
return index; return index;
}; };
module.exports = {
'request': request,
'uri': uri,
'folder': folder,
'isElement': isElement,
'uuid': uuid,
'values': values,
'resolveUrl': resolveUrl,
'indexOfSorted': indexOfSorted,
'documentHeight': documentHeight,
'isNumber': isNumber,
'prefixed': prefixed,
'defaults': defaults,
'extend': extend,
'insert': insert,
'locationOf': locationOf,
'indexOfSorted': indexOfSorted,
'requestAnimationFrame': requestAnimationFrame,
'bounds': bounds,
'borders': borders,
'windowBounds': windowBounds,
'cleanStringForXpath': cleanStringForXpath,
'indexOfTextNode': indexOfTextNode,
};

View file

@ -4,15 +4,28 @@ if (typeof EPUBJS === 'undefined') {
EPUBJS.VERSION = "0.3.0"; EPUBJS.VERSION = "0.3.0";
var Book = require('./book');
var RSVP = require("rsvp");
function ePub(_url) {
return new Book(_url);
};
if (typeof window !== 'undefined') {
window.ePub = ePub;
window.RSVP = window.RSVP || RSVP;
}
module.exports = ePub;
/*
(function(root) { (function(root) {
"use strict"; "use strict";
var ePub = function(_url) {
return new EPUBJS.Book(_url); module.exports = ePub;
};
// CommonJS // CommonJS
if (typeof exports === "object") { if (typeof exports === "object") {
root.RSVP = require("rsvp"); // root.RSVP = require("rsvp");
module.exports = ePub; module.exports = ePub;
// RequireJS // RequireJS
} else if (typeof define === "function" && define.amd) { } else if (typeof define === "function" && define.amd) {
@ -23,4 +36,4 @@ EPUBJS.VERSION = "0.3.0";
} }
})(this); })(this);
*/

View file

@ -1,8 +1,10 @@
EPUBJS.EpubCFI = function(cfiStr){ var core = require('./core');
function EpubCFI(cfiStr){
if(cfiStr) return this.parse(cfiStr); if(cfiStr) return this.parse(cfiStr);
}; };
EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) { EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) {
var pos = parseInt(_pos), var pos = parseInt(_pos),
spineNodeIndex = _spineNodeIndex + 1, spineNodeIndex = _spineNodeIndex + 1,
cfi = '/'+spineNodeIndex+'/'; cfi = '/'+spineNodeIndex+'/';
@ -16,7 +18,7 @@ EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _p
return cfi; return cfi;
}; };
EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) { EpubCFI.prototype.generatePathComponent = function(steps) {
var parts = []; var parts = [];
steps.forEach(function(part){ steps.forEach(function(part){
@ -33,7 +35,7 @@ EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) {
return parts.join('/'); return parts.join('/');
}; };
EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) { EpubCFI.prototype.generateCfiFromElement = function(element, chapter) {
var steps = this.pathTo(element); var steps = this.pathTo(element);
var path = this.generatePathComponent(steps); var path = this.generatePathComponent(steps);
if(!path.length) { if(!path.length) {
@ -45,7 +47,7 @@ EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) {
} }
}; };
EPUBJS.EpubCFI.prototype.pathTo = function(node) { EpubCFI.prototype.pathTo = function(node) {
var stack = [], var stack = [],
children; children;
@ -65,14 +67,14 @@ EPUBJS.EpubCFI.prototype.pathTo = function(node) {
return stack; return stack;
}; };
EPUBJS.EpubCFI.prototype.getChapterComponent = function(cfiStr) { EpubCFI.prototype.getChapterComponent = function(cfiStr) {
var splitStr = cfiStr.split("!"); var splitStr = cfiStr.split("!");
return splitStr[0]; return splitStr[0];
}; };
EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) { EpubCFI.prototype.getPathComponent = function(cfiStr) {
var splitStr = cfiStr.split("!"); var splitStr = cfiStr.split("!");
var pathComponent = splitStr[1] ? splitStr[1].split(":") : ''; var pathComponent = splitStr[1] ? splitStr[1].split(":") : '';
@ -80,13 +82,13 @@ EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) {
return pathComponent[0]; return pathComponent[0];
}; };
EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) { EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) {
var splitStr = cfiStr.split(":"); var splitStr = cfiStr.split(":");
return splitStr[1] || ''; return splitStr[1] || '';
}; };
EPUBJS.EpubCFI.prototype.parse = function(cfiStr) { EpubCFI.prototype.parse = function(cfiStr) {
var cfi = {}, var cfi = {},
chapSegment, chapSegment,
chapterComponent, chapterComponent,
@ -190,7 +192,7 @@ EPUBJS.EpubCFI.prototype.parse = function(cfiStr) {
return cfi; return cfi;
}; };
EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) { EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) {
var doc = _doc || document; var doc = _doc || document;
var marker = _marker || this.createMarker(doc); var marker = _marker || this.createMarker(doc);
var parent; var parent;
@ -235,16 +237,16 @@ EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) {
return marker; return marker;
}; };
EPUBJS.EpubCFI.prototype.createMarker = function(_doc) { EpubCFI.prototype.createMarker = function(_doc) {
var doc = _doc || document; var doc = _doc || document;
var element = doc.createElement('span'); var element = doc.createElement('span');
element.id = "EPUBJS-CFI-MARKER:"+ EPUBJS.core.uuid(); element.id = "EPUBJS-CFI-MARKER:"+ core.uuid();
element.classList.add("EPUBJS-CFI-MARKER"); element.classList.add("EPUBJS-CFI-MARKER");
return element; return element;
}; };
EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) { EpubCFI.prototype.removeMarker = function(marker, _doc) {
var doc = _doc || document; var doc = _doc || document;
// var id = marker.id; // var id = marker.id;
@ -268,7 +270,7 @@ EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) {
}; };
EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) { EpubCFI.prototype.findParent = function(cfi, _doc) {
var doc = _doc || document, var doc = _doc || document,
element = doc.getElementsByTagName('html')[0], element = doc.getElementsByTagName('html')[0],
children = Array.prototype.slice.call(element.children), children = Array.prototype.slice.call(element.children),
@ -309,12 +311,12 @@ EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) {
return element; return element;
}; };
EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) { EpubCFI.prototype.compare = function(cfiOne, cfiTwo) {
if(typeof cfiOne === 'string') { if(typeof cfiOne === 'string') {
cfiOne = new EPUBJS.EpubCFI(cfiOne); cfiOne = new EpubCFI(cfiOne);
} }
if(typeof cfiTwo === 'string') { if(typeof cfiTwo === 'string') {
cfiTwo = new EPUBJS.EpubCFI(cfiTwo); cfiTwo = new EpubCFI(cfiTwo);
} }
// Compare Spine Positions // Compare Spine Positions
if(cfiOne.spinePos > cfiTwo.spinePos) { if(cfiOne.spinePos > cfiTwo.spinePos) {
@ -356,14 +358,14 @@ EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) {
return 0; return 0;
}; };
EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) { EpubCFI.prototype.generateCfiFromHref = function(href, book) {
var uri = EPUBJS.core.uri(href); var uri = core.uri(href);
var path = uri.path; var path = uri.path;
var fragment = uri.fragment; var fragment = uri.fragment;
var spinePos = book.spineIndexByURL[path]; var spinePos = book.spineIndexByURL[path];
var loaded; var loaded;
var deferred = new RSVP.defer(); var deferred = new RSVP.defer();
var epubcfi = new EPUBJS.EpubCFI(); var epubcfi = new EpubCFI();
var spineItem; var spineItem;
if(typeof spinePos !== "undefined"){ if(typeof spinePos !== "undefined"){
@ -380,7 +382,7 @@ EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) {
return deferred.promise; return deferred.promise;
}; };
EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) { EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) {
var parent = anchor.parentNode; var parent = anchor.parentNode;
var steps = this.pathTo(parent); var steps = this.pathTo(parent);
var path = this.generatePathComponent(steps); var path = this.generatePathComponent(steps);
@ -388,13 +390,13 @@ EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base
return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")"; return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")";
}; };
EPUBJS.EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) { EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) {
var anchor = range.anchorNode; var anchor = range.anchorNode;
var offset = range.anchorOffset; var offset = range.anchorOffset;
return this.generateCfiFromTextNode(anchor, offset, base); return this.generateCfiFromTextNode(anchor, offset, base);
}; };
EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) { EpubCFI.prototype.generateCfiFromRange = function(range, base) {
var start, startElement, startSteps, startPath, startOffset, startIndex; var start, startElement, startSteps, startPath, startOffset, startIndex;
var end, endElement, endSteps, endPath, endOffset, endIndex; var end, endElement, endSteps, endPath, endOffset, endIndex;
@ -403,7 +405,7 @@ EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) {
if(start.nodeType === 3) { // text node if(start.nodeType === 3) { // text node
startElement = start.parentNode; startElement = start.parentNode;
//startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start)); //startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start));
startIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(start)); startIndex = 1 + (2 * core.indexOfTextNode(start));
startSteps = this.pathTo(startElement); startSteps = this.pathTo(startElement);
} else if(range.collapsed) { } else if(range.collapsed) {
return this.generateCfiFromElement(start, base); // single element return this.generateCfiFromElement(start, base); // single element
@ -420,7 +422,7 @@ EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) {
if(end.nodeType === 3) { // text node if(end.nodeType === 3) { // text node
endElement = end.parentNode; endElement = end.parentNode;
// endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end)); // endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end));
endIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(end)); endIndex = 1 + (2 * core.indexOfTextNode(end));
endSteps = this.pathTo(endElement); endSteps = this.pathTo(endElement);
} else { } else {
@ -444,7 +446,7 @@ EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) {
} }
}; };
EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) { EpubCFI.prototype.generateXpathFromSteps = function(steps) {
var xpath = [".", "*"]; var xpath = [".", "*"];
steps.forEach(function(step){ steps.forEach(function(step){
@ -463,7 +465,7 @@ EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) {
}; };
EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) { EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) {
var doc = _doc || document; var doc = _doc || document;
var range = doc.createRange(); var range = doc.createRange();
var lastStep; var lastStep;
@ -509,7 +511,7 @@ EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) {
return range; return range;
}; };
EPUBJS.EpubCFI.prototype.isCfiString = function(target) { EpubCFI.prototype.isCfiString = function(target) {
if(typeof target === "string" && if(typeof target === "string" &&
target.indexOf("epubcfi(") === 0) { target.indexOf("epubcfi(") === 0) {
return true; return true;
@ -517,3 +519,5 @@ EPUBJS.EpubCFI.prototype.isCfiString = function(target) {
return false; return false;
}; };
module.exports = EpubCFI;

View file

@ -1,7 +1,4 @@
EPUBJS.Hook = function(context){ var RSVP = require('rsvp');
this.context = context || this;
this.hooks = [];
};
//-- Hooks allow for injecting functions that must all complete in order before finishing //-- Hooks allow for injecting functions that must all complete in order before finishing
// They will execute in parallel but all must finish before continuing // They will execute in parallel but all must finish before continuing
@ -11,13 +8,18 @@ EPUBJS.Hook = function(context){
// this.content.register(function(){}); // this.content.register(function(){});
// this.content.trigger(args).then(function(){}); // this.content.trigger(args).then(function(){});
function Hook(context){
this.context = context || this;
this.hooks = [];
};
// Adds a function to be run before a hook completes // Adds a function to be run before a hook completes
EPUBJS.Hook.prototype.register = function(func){ Hook.prototype.register = function(func){
this.hooks.push(func); this.hooks.push(func);
}; };
// Triggers a hook to run all functions // Triggers a hook to run all functions
EPUBJS.Hook.prototype.trigger = function(){ Hook.prototype.trigger = function(){
var args = arguments; var args = arguments;
var context = this.context; var context = this.context;
var promises = []; var promises = [];
@ -35,3 +37,5 @@ EPUBJS.Hook.prototype.trigger = function(){
return RSVP.all(promises); return RSVP.all(promises);
}; };
module.exports = Hook;

View file

@ -1,10 +1,10 @@
EPUBJS.Layout = EPUBJS.Layout || {}; var core = require('./core');
EPUBJS.Layout.Reflowable = function(){ function Reflowable(){
}; };
EPUBJS.Layout.Reflowable.prototype.calculate = function(_width, _height, _gap, _devisor){ Reflowable.prototype.calculate = function(_width, _height, _gap, _devisor){
var divisor = _devisor || 1; var divisor = _devisor || 1;
@ -32,10 +32,10 @@ EPUBJS.Layout.Reflowable.prototype.calculate = function(_width, _height, _gap, _
this.columnAxis = EPUBJS.core.prefixed('columnAxis'); this.columnAxis = core.prefixed('columnAxis');
this.columnGap = EPUBJS.core.prefixed('columnGap'); this.columnGap = core.prefixed('columnGap');
this.columnWidth = EPUBJS.core.prefixed('columnWidth'); this.columnWidth = core.prefixed('columnWidth');
this.columnFill = EPUBJS.core.prefixed('columnFill'); this.columnFill = core.prefixed('columnFill');
this.width = width; this.width = width;
this.height = _height; this.height = _height;
@ -48,7 +48,7 @@ EPUBJS.Layout.Reflowable.prototype.calculate = function(_width, _height, _gap, _
}; };
EPUBJS.Layout.Reflowable.prototype.format = function(view){ Reflowable.prototype.format = function(view){
var $doc = view.document.documentElement; var $doc = view.document.documentElement;
var $body = view.document.body;//view.document.querySelector("body"); var $body = view.document.body;//view.document.querySelector("body");
@ -72,7 +72,7 @@ EPUBJS.Layout.Reflowable.prototype.format = function(view){
view.iframe.style.marginRight = this.gap+"px"; view.iframe.style.marginRight = this.gap+"px";
}; };
EPUBJS.Layout.Reflowable.prototype.count = function(view) { Reflowable.prototype.count = function(view) {
var totalWidth = view.root().scrollWidth; var totalWidth = view.root().scrollWidth;
var spreads = Math.ceil(totalWidth / this.spread); var spreads = Math.ceil(totalWidth / this.spread);
@ -82,15 +82,15 @@ EPUBJS.Layout.Reflowable.prototype.count = function(view) {
}; };
}; };
EPUBJS.Layout.Fixed = function(_width, _height){ function Fixed(_width, _height){
}; };
EPUBJS.Layout.Fixed.prototype.calculate = function(_width, _height){ Fixed.prototype.calculate = function(_width, _height){
}; };
EPUBJS.Layout.Fixed.prototype.format = function(view){ Fixed.prototype.format = function(view){
var width, height; var width, height;
var $doc = view.document.documentElement; var $doc = view.document.documentElement;
@ -121,24 +121,24 @@ EPUBJS.Layout.Fixed.prototype.format = function(view){
}; };
EPUBJS.Layout.Fixed.prototype.count = function(){ Fixed.prototype.count = function(){
return { return {
spreads : 1, spreads : 1,
pages : 1 pages : 1
}; };
}; };
EPUBJS.Layout.Scroll = function(){ function Scroll(){
}; };
EPUBJS.Layout.Scroll.prototype.calculate = function(_width, _height){ Scroll.prototype.calculate = function(_width, _height){
this.spread = _width; this.spread = _width;
this.column = _width; this.column = _width;
this.gap = 0; this.gap = 0;
}; };
EPUBJS.Layout.Scroll.prototype.format = function(view){ Scroll.prototype.format = function(view){
var $doc = view.document.documentElement; var $doc = view.document.documentElement;
@ -147,9 +147,15 @@ EPUBJS.Layout.Scroll.prototype.format = function(view){
}; };
EPUBJS.Layout.Scroll.prototype.count = function(){ Scroll.prototype.count = function(){
return { return {
spreads : 1, spreads : 1,
pages : 1 pages : 1
}; };
}; };
module.exports = {
'Reflowable': Reflowable,
'Fixed': Fixed,
'Scroll': Scroll
};

View file

@ -1,9 +1,14 @@
EPUBJS.Locations = function(spine, request) { var core = require('./core');
var Queue = require('./queue');
var EpubCFI = require('./epubcfi');
var RSVP = require('rsvp');
function Locations(spine, request) {
this.spine = spine; this.spine = spine;
this.request = request; this.request = request;
this.q = new EPUBJS.Queue(this); this.q = new Queue(this);
this.epubcfi = new EPUBJS.EpubCFI(); this.epubcfi = new EpubCFI();
this._locations = []; this._locations = [];
this.total = 0; this.total = 0;
@ -15,7 +20,7 @@ EPUBJS.Locations = function(spine, request) {
}; };
// Load all of sections in the book // Load all of sections in the book
EPUBJS.Locations.prototype.generate = function(chars) { Locations.prototype.generate = function(chars) {
if (chars) { if (chars) {
this.break = chars; this.break = chars;
@ -42,7 +47,7 @@ EPUBJS.Locations.prototype.generate = function(chars) {
}; };
EPUBJS.Locations.prototype.process = function(section) { Locations.prototype.process = function(section) {
return section.load(this.request) return section.load(this.request)
.then(function(contents) { .then(function(contents) {
@ -110,7 +115,7 @@ EPUBJS.Locations.prototype.process = function(section) {
}; };
EPUBJS.Locations.prototype.sprint = function(root, func) { Locations.prototype.sprint = function(root, func) {
var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false); var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);
while ((node = treeWalker.nextNode())) { while ((node = treeWalker.nextNode())) {
@ -119,27 +124,27 @@ EPUBJS.Locations.prototype.sprint = function(root, func) {
}; };
EPUBJS.Locations.prototype.locationFromCfi = function(cfi){ Locations.prototype.locationFromCfi = function(cfi){
// Check if the location has not been set yet // Check if the location has not been set yet
if(this._locations.length === 0) { if(this._locations.length === 0) {
return -1; return -1;
} }
return EPUBJS.core.locationOf(cfi, this._locations, this.epubcfi.compare); return core.locationOf(cfi, this._locations, this.epubcfi.compare);
}; };
EPUBJS.Locations.prototype.precentageFromCfi = function(cfi) { Locations.prototype.precentageFromCfi = function(cfi) {
// Find closest cfi // Find closest cfi
var loc = this.locationFromCfi(cfi); var loc = this.locationFromCfi(cfi);
// Get percentage in total // Get percentage in total
return this.precentageFromLocation(loc); return this.precentageFromLocation(loc);
}; };
EPUBJS.Locations.prototype.precentageFromLocation = function(loc) { Locations.prototype.precentageFromLocation = function(loc) {
return Math.ceil((loc / this.total ) * 1000) / 1000; return Math.ceil((loc / this.total ) * 1000) / 1000;
}; };
EPUBJS.Locations.prototype.cfiFromLocation = function(loc){ Locations.prototype.cfiFromLocation = function(loc){
var cfi = -1; var cfi = -1;
// check that pg is an int // check that pg is an int
if(typeof loc != "number"){ if(typeof loc != "number"){
@ -153,26 +158,26 @@ EPUBJS.Locations.prototype.cfiFromLocation = function(loc){
return cfi; return cfi;
}; };
EPUBJS.Locations.prototype.cfiFromPercentage = function(percent){ Locations.prototype.cfiFromPercentage = function(percent){
var loc = Math.round(this.total * percent); var loc = Math.round(this.total * percent);
return this.cfiFromLocation(loc); return this.cfiFromLocation(loc);
}; };
EPUBJS.Locations.prototype.load = function(locations){ Locations.prototype.load = function(locations){
this._locations = JSON.parse(locations); this._locations = JSON.parse(locations);
this.total = this._locations.length-1; this.total = this._locations.length-1;
return this._locations; return this._locations;
}; };
EPUBJS.Locations.prototype.save = function(json){ Locations.prototype.save = function(json){
return JSON.stringify(this._locations); return JSON.stringify(this._locations);
}; };
EPUBJS.Locations.prototype.getCurrent = function(json){ Locations.prototype.getCurrent = function(json){
return this._current; return this._current;
}; };
EPUBJS.Locations.prototype.setCurrent = function(curr){ Locations.prototype.setCurrent = function(curr){
var loc; var loc;
if(typeof curr == "string"){ if(typeof curr == "string"){
@ -199,7 +204,7 @@ EPUBJS.Locations.prototype.setCurrent = function(curr){
}); });
}; };
Object.defineProperty(EPUBJS.Locations.prototype, 'currentLocation', { Object.defineProperty(Locations.prototype, 'currentLocation', {
get: function () { get: function () {
return this._current; return this._current;
}, },
@ -208,4 +213,6 @@ Object.defineProperty(EPUBJS.Locations.prototype, 'currentLocation', {
} }
}); });
RSVP.EventTarget.mixin(EPUBJS.Locations.prototype); RSVP.EventTarget.mixin(Locations.prototype);
module.exports = Locations;

View file

@ -1,15 +1,15 @@
EPUBJS.Map = function(layout){ function Map(layout){
this.layout = layout; this.layout = layout;
}; };
EPUBJS.Map.prototype.section = function(view) { Map.prototype.section = function(view) {
var ranges = this.findRanges(view); var ranges = this.findRanges(view);
var map = this.rangeListToCfiList(view, ranges); var map = this.rangeListToCfiList(view, ranges);
return map; return map;
}; };
EPUBJS.Map.prototype.page = function(view, start, end) { Map.prototype.page = function(view, start, end) {
var root = view.document.body; var root = view.document.body;
return this.rangePairToCfiPair(view.section, { return this.rangePairToCfiPair(view.section, {
start: this.findStart(root, start, end), start: this.findStart(root, start, end),
@ -17,7 +17,7 @@ EPUBJS.Map.prototype.page = function(view, start, end) {
}); });
}; };
EPUBJS.Map.prototype.walk = function(root, func) { Map.prototype.walk = function(root, func) {
//var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false); //var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false);
var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode: function (node) { acceptNode: function (node) {
@ -38,7 +38,7 @@ EPUBJS.Map.prototype.walk = function(root, func) {
return result; return result;
}; };
EPUBJS.Map.prototype.findRanges = function(view){ Map.prototype.findRanges = function(view){
var columns = []; var columns = [];
var count = this.layout.count(view); var count = this.layout.count(view);
var column = this.layout.column; var column = this.layout.column;
@ -57,7 +57,7 @@ EPUBJS.Map.prototype.findRanges = function(view){
return columns; return columns;
}; };
EPUBJS.Map.prototype.findStart = function(root, start, end){ Map.prototype.findStart = function(root, start, end){
var stack = [root]; var stack = [root];
var $el; var $el;
var found; var found;
@ -104,7 +104,7 @@ EPUBJS.Map.prototype.findStart = function(root, start, end){
return this.findTextStartRange($prev, start, end); return this.findTextStartRange($prev, start, end);
}; };
EPUBJS.Map.prototype.findEnd = function(root, start, end){ Map.prototype.findEnd = function(root, start, end){
var stack = [root]; var stack = [root];
var $el; var $el;
var $prev = root; var $prev = root;
@ -155,7 +155,7 @@ EPUBJS.Map.prototype.findEnd = function(root, start, end){
}; };
EPUBJS.Map.prototype.findTextStartRange = function(node, start, end){ Map.prototype.findTextStartRange = function(node, start, end){
var ranges = this.splitTextNodeIntoRanges(node); var ranges = this.splitTextNodeIntoRanges(node);
var prev; var prev;
var range; var range;
@ -177,7 +177,7 @@ EPUBJS.Map.prototype.findTextStartRange = function(node, start, end){
return ranges[0]; return ranges[0];
}; };
EPUBJS.Map.prototype.findTextEndRange = function(node, start, end){ Map.prototype.findTextEndRange = function(node, start, end){
var ranges = this.splitTextNodeIntoRanges(node); var ranges = this.splitTextNodeIntoRanges(node);
var prev; var prev;
var range; var range;
@ -203,7 +203,7 @@ EPUBJS.Map.prototype.findTextEndRange = function(node, start, end){
}; };
EPUBJS.Map.prototype.splitTextNodeIntoRanges = function(node, _splitter){ Map.prototype.splitTextNodeIntoRanges = function(node, _splitter){
var ranges = []; var ranges = [];
var textContent = node.textContent || ""; var textContent = node.textContent || "";
var text = textContent.trim(); var text = textContent.trim();
@ -252,7 +252,7 @@ EPUBJS.Map.prototype.splitTextNodeIntoRanges = function(node, _splitter){
EPUBJS.Map.prototype.rangePairToCfiPair = function(section, rangePair){ Map.prototype.rangePairToCfiPair = function(section, rangePair){
var startRange = rangePair.start; var startRange = rangePair.start;
var endRange = rangePair.end; var endRange = rangePair.end;
@ -270,7 +270,7 @@ EPUBJS.Map.prototype.rangePairToCfiPair = function(section, rangePair){
}; };
EPUBJS.Map.prototype.rangeListToCfiList = function(view, columns){ Map.prototype.rangeListToCfiList = function(view, columns){
var map = []; var map = [];
var rangePair, cifPair; var rangePair, cifPair;
@ -283,3 +283,5 @@ EPUBJS.Map.prototype.rangeListToCfiList = function(view, columns){
return map; return map;
}; };
module.exports = Map;

View file

@ -1,7 +1,11 @@
EPUBJS.Navigation = function(_package, _request){ var core = require('./core');
var Parser = require('./parser');
var RSVP = require('rsvp');
function Navigation(_package, _request){
var navigation = this; var navigation = this;
var parse = new EPUBJS.Parser(); var parse = new Parser();
var request = _request || EPUBJS.core.request; var request = _request || core.request;
this.package = _package; this.package = _package;
this.toc = []; this.toc = [];
@ -48,8 +52,8 @@ EPUBJS.Navigation = function(_package, _request){
}; };
// Load the navigation // Load the navigation
EPUBJS.Navigation.prototype.load = function(_request) { Navigation.prototype.load = function(_request) {
var request = _request || EPUBJS.core.request; var request = _request || core.request;
var loading, loaded; var loading, loaded;
if(this.nav) { if(this.nav) {
@ -66,7 +70,7 @@ EPUBJS.Navigation.prototype.load = function(_request) {
}; };
EPUBJS.Navigation.prototype.loaded = function(toc) { Navigation.prototype.loaded = function(toc) {
var item; var item;
for (var i = 0; i < toc.length; i++) { for (var i = 0; i < toc.length; i++) {
@ -78,7 +82,7 @@ EPUBJS.Navigation.prototype.loaded = function(toc) {
}; };
// Get an item from the navigation // Get an item from the navigation
EPUBJS.Navigation.prototype.get = function(target) { Navigation.prototype.get = function(target) {
var index; var index;
if(!target) { if(!target) {
@ -93,3 +97,5 @@ EPUBJS.Navigation.prototype.get = function(target) {
return this.toc[index]; return this.toc[index];
}; };
module.exports = Navigation;

View file

@ -1,8 +1,14 @@
EPUBJS.Paginate = function(book, options) { var RSVP = require('rsvp');
var core = require('./core');
var Continuous = require('./continuous');
var Map = require('./map');
var Layout = require('./layout');
EPUBJS.Continuous.apply(this, arguments); function Paginate(book, options) {
this.settings = EPUBJS.core.extend(this.settings || {}, { Continuous.apply(this, arguments);
this.settings = core.extend(this.settings || {}, {
width: 600, width: 600,
height: 400, height: 400,
axis: "horizontal", axis: "horizontal",
@ -13,7 +19,7 @@ EPUBJS.Paginate = function(book, options) {
infinite: false infinite: false
}); });
EPUBJS.core.extend(this.settings, options); core.extend(this.settings, options);
this.isForcedSingle = this.settings.forceSingle; this.isForcedSingle = this.settings.forceSingle;
@ -24,11 +30,11 @@ EPUBJS.Paginate = function(book, options) {
this.start(); this.start();
}; };
EPUBJS.Paginate.prototype = Object.create(EPUBJS.Continuous.prototype); Paginate.prototype = Object.create(Continuous.prototype);
EPUBJS.Paginate.prototype.constructor = EPUBJS.Paginate; Paginate.prototype.constructor = Paginate;
EPUBJS.Paginate.prototype.determineSpreads = function(cutoff){ Paginate.prototype.determineSpreads = function(cutoff){
if(this.isForcedSingle || !cutoff || this.bounds().width < cutoff) { if(this.isForcedSingle || !cutoff || this.bounds().width < cutoff) {
return 1; //-- Single Page return 1; //-- Single Page
}else{ }else{
@ -36,7 +42,7 @@ EPUBJS.Paginate.prototype.determineSpreads = function(cutoff){
} }
}; };
EPUBJS.Paginate.prototype.forceSingle = function(bool){ Paginate.prototype.forceSingle = function(bool){
if(bool === false) { if(bool === false) {
this.isForcedSingle = false; this.isForcedSingle = false;
// this.spreads = false; // this.spreads = false;
@ -53,7 +59,7 @@ EPUBJS.Paginate.prototype.forceSingle = function(bool){
* Takes: Layout settings object * Takes: Layout settings object
* Returns: String of appropriate for EPUBJS.Layout function * Returns: String of appropriate for EPUBJS.Layout function
*/ */
// EPUBJS.Paginate.prototype.determineLayout = function(settings){ // Paginate.prototype.determineLayout = function(settings){
// // Default is layout: reflowable & spread: auto // // Default is layout: reflowable & spread: auto
// var spreads = this.determineSpreads(this.settings.minSpreadWidth); // var spreads = this.determineSpreads(this.settings.minSpreadWidth);
// console.log("spreads", spreads, this.settings.minSpreadWidth) // console.log("spreads", spreads, this.settings.minSpreadWidth)
@ -83,7 +89,7 @@ EPUBJS.Paginate.prototype.forceSingle = function(bool){
// return layoutMethod; // return layoutMethod;
// }; // };
EPUBJS.Paginate.prototype.start = function(){ Paginate.prototype.start = function(){
// On display // On display
// this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties); // this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties);
// this.layoutMethod = this.determineLayout(this.layoutSettings); // this.layoutMethod = this.determineLayout(this.layoutSettings);
@ -110,18 +116,18 @@ EPUBJS.Paginate.prototype.start = function(){
// return view; // return view;
// }; // };
EPUBJS.Paginate.prototype.applyLayoutMethod = function() { Paginate.prototype.applyLayoutMethod = function() {
//var task = new RSVP.defer(); //var task = new RSVP.defer();
// this.spreads = this.determineSpreads(this.settings.minSpreadWidth); // this.spreads = this.determineSpreads(this.settings.minSpreadWidth);
this.layout = new EPUBJS.Layout.Reflowable(); this.layout = new Layout.Reflowable();
this.updateLayout(); this.updateLayout();
// Set the look ahead offset for what is visible // Set the look ahead offset for what is visible
this.map = new EPUBJS.Map(this.layout); this.map = new Map(this.layout);
// this.hooks.layout.register(this.layout.format.bind(this)); // this.hooks.layout.register(this.layout.format.bind(this));
@ -130,7 +136,7 @@ EPUBJS.Paginate.prototype.applyLayoutMethod = function() {
// return layout; // return layout;
}; };
EPUBJS.Paginate.prototype.updateLayout = function() { Paginate.prototype.updateLayout = function() {
this.spreads = this.determineSpreads(this.settings.minSpreadWidth); this.spreads = this.determineSpreads(this.settings.minSpreadWidth);
@ -145,14 +151,14 @@ EPUBJS.Paginate.prototype.updateLayout = function() {
}; };
EPUBJS.Paginate.prototype.moveTo = function(offset){ Paginate.prototype.moveTo = function(offset){
var dist = Math.floor(offset.left / this.layout.delta) * this.layout.delta; var dist = Math.floor(offset.left / this.layout.delta) * this.layout.delta;
return this.check(0, dist+this.settings.offset).then(function(){ return this.check(0, dist+this.settings.offset).then(function(){
this.scrollBy(dist, 0); this.scrollBy(dist, 0);
}.bind(this)); }.bind(this));
}; };
EPUBJS.Paginate.prototype.page = function(pg){ Paginate.prototype.page = function(pg){
// this.currentPage = pg; // this.currentPage = pg;
// this.renderer.infinite.scrollTo(this.currentPage * this.formated.pageWidth, 0); // this.renderer.infinite.scrollTo(this.currentPage * this.formated.pageWidth, 0);
@ -160,7 +166,7 @@ EPUBJS.Paginate.prototype.page = function(pg){
// return false; // return false;
}; };
EPUBJS.Paginate.prototype.next = function(){ Paginate.prototype.next = function(){
return this.q.enqueue(function(){ return this.q.enqueue(function(){
// console.log(this.container.scrollWidth, this.container.scrollLeft + this.container.offsetWidth + this.layout.delta) // console.log(this.container.scrollWidth, this.container.scrollLeft + this.container.offsetWidth + this.layout.delta)
@ -178,7 +184,7 @@ EPUBJS.Paginate.prototype.next = function(){
// return this.page(this.currentPage + 1); // return this.page(this.currentPage + 1);
}; };
EPUBJS.Paginate.prototype.prev = function(){ Paginate.prototype.prev = function(){
return this.q.enqueue(function(){ return this.q.enqueue(function(){
this.scrollBy(-this.layout.delta, 0); this.scrollBy(-this.layout.delta, 0);
@ -188,14 +194,14 @@ EPUBJS.Paginate.prototype.prev = function(){
// return this.page(this.currentPage - 1); // return this.page(this.currentPage - 1);
}; };
// EPUBJS.Paginate.prototype.reportLocation = function(){ // Paginate.prototype.reportLocation = function(){
// return this.q.enqueue(function(){ // return this.q.enqueue(function(){
// this.location = this.currentLocation(); // this.location = this.currentLocation();
// this.trigger("locationChanged", this.location); // this.trigger("locationChanged", this.location);
// }.bind(this)); // }.bind(this));
// }; // };
EPUBJS.Paginate.prototype.currentLocation = function(){ Paginate.prototype.currentLocation = function(){
var visible = this.visible(); var visible = this.visible();
var startA, startB, endA, endB; var startA, startB, endA, endB;
var pageLeft, pageRight; var pageLeft, pageRight;
@ -228,7 +234,7 @@ EPUBJS.Paginate.prototype.currentLocation = function(){
} }
}; };
EPUBJS.Paginate.prototype.resize = function(width, height){ Paginate.prototype.resize = function(width, height){
// Clear the queue // Clear the queue
this.q.clear(); this.q.clear();
@ -247,7 +253,7 @@ EPUBJS.Paginate.prototype.resize = function(width, height){
}; };
EPUBJS.Paginate.prototype.onResized = function(e) { Paginate.prototype.onResized = function(e) {
this.views.clear(); this.views.clear();
@ -257,7 +263,7 @@ EPUBJS.Paginate.prototype.onResized = function(e) {
}.bind(this), 150); }.bind(this), 150);
}; };
EPUBJS.Paginate.prototype.adjustImages = function(view) { Paginate.prototype.adjustImages = function(view) {
view.addStylesheetRules([ view.addStylesheetRules([
["img", ["img",
@ -273,6 +279,8 @@ EPUBJS.Paginate.prototype.adjustImages = function(view) {
}); });
}; };
// EPUBJS.Paginate.prototype.display = function(what){ // Paginate.prototype.display = function(what){
// return this.display(what); // return this.display(what);
// }; // };
module.exports = Paginate;

View file

@ -1,6 +1,9 @@
EPUBJS.Parser = function(){}; var core = require('./core');
var EpubCFI = require('./epubcfi');
EPUBJS.Parser.prototype.container = function(containerXml){ function Parser(){};
Parser.prototype.container = function(containerXml){
//-- <rootfile full-path="OPS/package.opf" media-type="application/oebps-package+xml"/> //-- <rootfile full-path="OPS/package.opf" media-type="application/oebps-package+xml"/>
var rootfile, fullpath, folder, encoding; var rootfile, fullpath, folder, encoding;
@ -17,7 +20,7 @@ EPUBJS.Parser.prototype.container = function(containerXml){
} }
fullpath = rootfile.getAttribute('full-path'); fullpath = rootfile.getAttribute('full-path');
folder = EPUBJS.core.uri(fullpath).directory; folder = core.uri(fullpath).directory;
encoding = containerXml.xmlEncoding; encoding = containerXml.xmlEncoding;
//-- Now that we have the path we can parse the contents //-- Now that we have the path we can parse the contents
@ -28,7 +31,7 @@ EPUBJS.Parser.prototype.container = function(containerXml){
}; };
}; };
EPUBJS.Parser.prototype.identifier = function(packageXml){ Parser.prototype.identifier = function(packageXml){
var metadataNode; var metadataNode;
if(!packageXml) { if(!packageXml) {
@ -46,7 +49,7 @@ EPUBJS.Parser.prototype.identifier = function(packageXml){
return this.getElementText(metadataNode, "identifier"); return this.getElementText(metadataNode, "identifier");
}; };
EPUBJS.Parser.prototype.packageContents = function(packageXml){ Parser.prototype.packageContents = function(packageXml){
var parse = this; var parse = this;
var metadataNode, manifestNode, spineNode; var metadataNode, manifestNode, spineNode;
var manifest, navPath, ncxPath, coverPath; var manifest, navPath, ncxPath, coverPath;
@ -98,25 +101,25 @@ EPUBJS.Parser.prototype.packageContents = function(packageXml){
}; };
//-- Find TOC NAV: media-type="application/xhtml+xml" href="toc.ncx" //-- Find TOC NAV: media-type="application/xhtml+xml" href="toc.ncx"
EPUBJS.Parser.prototype.findNavPath = function(manifestNode){ Parser.prototype.findNavPath = function(manifestNode){
var node = manifestNode.querySelector("item[properties^='nav']"); var node = manifestNode.querySelector("item[properties^='nav']");
return node ? node.getAttribute('href') : false; return node ? node.getAttribute('href') : false;
}; };
//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" //-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx"
EPUBJS.Parser.prototype.findNcxPath = function(manifestNode){ Parser.prototype.findNcxPath = function(manifestNode){
var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']");
return node ? node.getAttribute('href') : false; return node ? node.getAttribute('href') : false;
}; };
//-- Find Cover: <item properties="cover-image" id="ci" href="cover.svg" media-type="image/svg+xml" /> //-- Find Cover: <item properties="cover-image" id="ci" href="cover.svg" media-type="image/svg+xml" />
EPUBJS.Parser.prototype.findCoverPath = function(manifestNode){ Parser.prototype.findCoverPath = function(manifestNode){
var node = manifestNode.querySelector("item[properties='cover-image']"); var node = manifestNode.querySelector("item[properties='cover-image']");
return node ? node.getAttribute('href') : false; return node ? node.getAttribute('href') : false;
}; };
//-- Expanded to match Readium web components //-- Expanded to match Readium web components
EPUBJS.Parser.prototype.metadata = function(xml){ Parser.prototype.metadata = function(xml){
var metadata = {}, var metadata = {},
p = this; p = this;
@ -141,7 +144,7 @@ EPUBJS.Parser.prototype.metadata = function(xml){
return metadata; return metadata;
}; };
EPUBJS.Parser.prototype.getElementText = function(xml, tag){ Parser.prototype.getElementText = function(xml, tag){
var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag),
el; el;
@ -157,7 +160,7 @@ EPUBJS.Parser.prototype.getElementText = function(xml, tag){
}; };
EPUBJS.Parser.prototype.querySelectorText = function(xml, q){ Parser.prototype.querySelectorText = function(xml, q){
var el = xml.querySelector(q); var el = xml.querySelector(q);
if(el && el.childNodes.length){ if(el && el.childNodes.length){
@ -167,7 +170,7 @@ EPUBJS.Parser.prototype.querySelectorText = function(xml, q){
return ''; return '';
}; };
EPUBJS.Parser.prototype.manifest = function(manifestXml){ Parser.prototype.manifest = function(manifestXml){
var manifest = {}; var manifest = {};
//-- Turn items into an array //-- Turn items into an array
@ -194,13 +197,13 @@ EPUBJS.Parser.prototype.manifest = function(manifestXml){
}; };
EPUBJS.Parser.prototype.spine = function(spineXml, manifest){ Parser.prototype.spine = function(spineXml, manifest){
var spine = []; var spine = [];
var selected = spineXml.getElementsByTagName("itemref"), var selected = spineXml.getElementsByTagName("itemref"),
items = Array.prototype.slice.call(selected); items = Array.prototype.slice.call(selected);
var epubcfi = new EPUBJS.EpubCFI(); var epubcfi = new EpubCFI();
//-- Add to array to mantain ordering and cross reference with manifest //-- Add to array to mantain ordering and cross reference with manifest
items.forEach(function(item, index){ items.forEach(function(item, index){
@ -226,7 +229,7 @@ EPUBJS.Parser.prototype.spine = function(spineXml, manifest){
return spine; return spine;
}; };
EPUBJS.Parser.prototype.nav = function(navHtml){ Parser.prototype.nav = function(navHtml){
var navEl = navHtml.querySelector('nav[*|type="toc"]'), //-- [*|type="toc"] * Doesn't seem to work var navEl = navHtml.querySelector('nav[*|type="toc"]'), //-- [*|type="toc"] * Doesn't seem to work
idCounter = 0; idCounter = 0;
@ -312,7 +315,7 @@ EPUBJS.Parser.prototype.nav = function(navHtml){
return getTOC(navEl); return getTOC(navEl);
}; };
EPUBJS.Parser.prototype.ncx = function(tocXml){ Parser.prototype.ncx = function(tocXml){
var navMap = tocXml.querySelector("navMap"); var navMap = tocXml.querySelector("navMap");
if(!navMap) return []; if(!navMap) return [];
@ -365,3 +368,5 @@ EPUBJS.Parser.prototype.ncx = function(tocXml){
return getTOC(navMap); return getTOC(navMap);
}; };
module.exports = Parser;

View file

@ -1,13 +1,16 @@
EPUBJS.Queue = function(_context){ var RSVP = require('rsvp');
var core = require('./core');
function Queue(_context){
this._q = []; this._q = [];
this.context = _context; this.context = _context;
this.tick = EPUBJS.core.requestAnimationFrame; this.tick = core.requestAnimationFrame;
this.running = false; this.running = false;
this.paused = false; this.paused = false;
}; };
// Add an item to the queue // Add an item to the queue
EPUBJS.Queue.prototype.enqueue = function() { Queue.prototype.enqueue = function() {
var deferred, promise; var deferred, promise;
var queued; var queued;
var task = [].shift.call(arguments); var task = [].shift.call(arguments);
@ -55,7 +58,7 @@ EPUBJS.Queue.prototype.enqueue = function() {
}; };
// Run one item // Run one item
EPUBJS.Queue.prototype.dequeue = function(){ Queue.prototype.dequeue = function(){
var inwait, task, result; var inwait, task, result;
if(this._q.length) { if(this._q.length) {
@ -93,7 +96,7 @@ EPUBJS.Queue.prototype.dequeue = function(){
}; };
// Run All Immediately // Run All Immediately
EPUBJS.Queue.prototype.dump = function(){ Queue.prototype.dump = function(){
while(this._q.length) { while(this._q.length) {
this.dequeue(); this.dequeue();
} }
@ -101,7 +104,7 @@ EPUBJS.Queue.prototype.dump = function(){
// Run all sequentially, at convince // Run all sequentially, at convince
EPUBJS.Queue.prototype.run = function(){ Queue.prototype.run = function(){
if(!this.running){ if(!this.running){
this.running = true; this.running = true;
@ -133,7 +136,7 @@ EPUBJS.Queue.prototype.run = function(){
}; };
// Flush all, as quickly as possible // Flush all, as quickly as possible
EPUBJS.Queue.prototype.flush = function(){ Queue.prototype.flush = function(){
if(this.running){ if(this.running){
return this.running; return this.running;
@ -152,21 +155,21 @@ EPUBJS.Queue.prototype.flush = function(){
}; };
// Clear all items in wait // Clear all items in wait
EPUBJS.Queue.prototype.clear = function(){ Queue.prototype.clear = function(){
this._q = []; this._q = [];
this.running = false; this.running = false;
}; };
EPUBJS.Queue.prototype.length = function(){ Queue.prototype.length = function(){
return this._q.length; return this._q.length;
}; };
EPUBJS.Queue.prototype.pause = function(){ Queue.prototype.pause = function(){
this.paused = true; this.paused = true;
}; };
// Create a new task from a callback // Create a new task from a callback
EPUBJS.Task = function(task, args, context){ function Task(task, args, context){
return function(){ return function(){
var toApply = arguments || []; var toApply = arguments || [];
@ -186,3 +189,5 @@ EPUBJS.Task = function(task, args, context){
}; };
}; };
module.exports = Queue;

View file

@ -1,6 +1,17 @@
EPUBJS.Rendition = function(book, options) { var RSVP = require('rsvp');
var core = require('./core');
var replace = require('./replacements');
var Hook = require('./hook');
var EpubCFI = require('./epubcfi');
var Queue = require('./queue');
var View = require('./view');
var Views = require('./views');
var Layout = require('./layout');
var Map = require('./map');
this.settings = EPUBJS.core.extend(this.settings || {}, { function Rendition(book, options) {
this.settings = core.extend(this.settings || {}, {
infinite: true, infinite: true,
hidden: false, hidden: false,
width: false, width: false,
@ -9,7 +20,7 @@ EPUBJS.Rendition = function(book, options) {
axis: "vertical" axis: "vertical"
}); });
EPUBJS.core.extend(this.settings, options); core.extend(this.settings, options);
this.viewSettings = {}; this.viewSettings = {};
@ -19,20 +30,20 @@ EPUBJS.Rendition = function(book, options) {
//-- Adds Hook methods to the Rendition prototype //-- Adds Hook methods to the Rendition prototype
this.hooks = {}; this.hooks = {};
this.hooks.display = new EPUBJS.Hook(this); this.hooks.display = new Hook(this);
this.hooks.content = new EPUBJS.Hook(this); this.hooks.content = new Hook(this);
this.hooks.layout = new EPUBJS.Hook(this); this.hooks.layout = new Hook(this);
this.hooks.render = new EPUBJS.Hook(this); this.hooks.render = new Hook(this);
this.hooks.show = new EPUBJS.Hook(this); this.hooks.show = new Hook(this);
this.hooks.content.register(EPUBJS.replace.links.bind(this)); this.hooks.content.register(replace.links.bind(this));
this.hooks.content.register(this.passViewEvents.bind(this)); this.hooks.content.register(this.passViewEvents.bind(this));
// this.hooks.display.register(this.afterDisplay.bind(this)); // this.hooks.display.register(this.afterDisplay.bind(this));
this.epubcfi = new EPUBJS.EpubCFI(); this.epubcfi = new EpubCFI();
this.q = new EPUBJS.Queue(this); this.q = new Queue(this);
this.q.enqueue(this.book.opened); this.q.enqueue(this.book.opened);
@ -44,7 +55,7 @@ EPUBJS.Rendition = function(book, options) {
* Creates an element to render to. * Creates an element to render to.
* Resizes to passed width and height or to the elements size * Resizes to passed width and height or to the elements size
*/ */
EPUBJS.Rendition.prototype.initialize = function(_options){ Rendition.prototype.initialize = function(_options){
var options = _options || {}; var options = _options || {};
var height = options.height;// !== false ? options.height : "100%"; var height = options.height;// !== false ? options.height : "100%";
var width = options.width;// !== false ? options.width : "100%"; var width = options.width;// !== false ? options.width : "100%";
@ -52,18 +63,18 @@ EPUBJS.Rendition.prototype.initialize = function(_options){
var container; var container;
var wrapper; var wrapper;
if(options.height && EPUBJS.core.isNumber(options.height)) { if(options.height && core.isNumber(options.height)) {
height = options.height + "px"; height = options.height + "px";
} }
if(options.width && EPUBJS.core.isNumber(options.width)) { if(options.width && core.isNumber(options.width)) {
width = options.width + "px"; width = options.width + "px";
} }
// Create new container element // Create new container element
container = document.createElement("div"); container = document.createElement("div");
container.id = "epubjs-container:" + EPUBJS.core.uuid(); container.id = "epubjs-container:" + core.uuid();
container.classList.add("epub-container"); container.classList.add("epub-container");
// Style Element // Style Element
@ -89,7 +100,7 @@ EPUBJS.Rendition.prototype.initialize = function(_options){
return container; return container;
}; };
EPUBJS.Rendition.wrap = function(container) { Rendition.wrap = function(container) {
var wrapper = document.createElement("div"); var wrapper = document.createElement("div");
wrapper.style.visibility = "hidden"; wrapper.style.visibility = "hidden";
@ -103,7 +114,7 @@ EPUBJS.Rendition.wrap = function(container) {
// Call to attach the container to an element in the dom // Call to attach the container to an element in the dom
// Container must be attached before rendering can begin // Container must be attached before rendering can begin
EPUBJS.Rendition.prototype.attachTo = function(_element){ Rendition.prototype.attachTo = function(_element){
var bounds; var bounds;
this.container = this.initialize({ this.container = this.initialize({
@ -111,7 +122,7 @@ EPUBJS.Rendition.prototype.attachTo = function(_element){
"height" : this.settings.height "height" : this.settings.height
}); });
if(EPUBJS.core.isElement(_element)) { if(core.isElement(_element)) {
this.element = _element; this.element = _element;
} else if (typeof _element === "string") { } else if (typeof _element === "string") {
this.element = document.getElementById(_element); this.element = document.getElementById(_element);
@ -129,7 +140,7 @@ EPUBJS.Rendition.prototype.attachTo = function(_element){
this.element.appendChild(this.container); this.element.appendChild(this.container);
} }
this.views = new EPUBJS.Views(this.container); this.views = new Views(this.container);
// Attach Listeners // Attach Listeners
this.attachListeners(); this.attachListeners();
@ -148,27 +159,27 @@ EPUBJS.Rendition.prototype.attachTo = function(_element){
}; };
EPUBJS.Rendition.prototype.attachListeners = function(){ Rendition.prototype.attachListeners = function(){
// Listen to window for resize event if width or height is set to 100% // Listen to window for resize event if width or height is set to 100%
if(!EPUBJS.core.isNumber(this.settings.width) || if(!core.isNumber(this.settings.width) ||
!EPUBJS.core.isNumber(this.settings.height) ) { !core.isNumber(this.settings.height) ) {
window.addEventListener("resize", this.onResized.bind(this), false); window.addEventListener("resize", this.onResized.bind(this), false);
} }
}; };
EPUBJS.Rendition.prototype.bounds = function() { Rendition.prototype.bounds = function() {
return this.container.getBoundingClientRect(); return this.container.getBoundingClientRect();
}; };
EPUBJS.Rendition.prototype.display = function(target){ Rendition.prototype.display = function(target){
return this.q.enqueue(this._display, target); return this.q.enqueue(this._display, target);
}; };
EPUBJS.Rendition.prototype._display = function(target){ Rendition.prototype._display = function(target){
var displaying = new RSVP.defer(); var displaying = new RSVP.defer();
var displayed = displaying.promise; var displayed = displaying.promise;
@ -203,7 +214,7 @@ EPUBJS.Rendition.prototype._display = function(target){
this.views.hide(); this.views.hide();
// Create a new view // Create a new view
view = new EPUBJS.View(section, this.viewSettings); view = new View(section, this.viewSettings);
// This will clear all previous views // This will clear all previous views
displayed = this.fill(view) displayed = this.fill(view)
@ -244,11 +255,11 @@ EPUBJS.Rendition.prototype._display = function(target){
}; };
// Takes a cfi, fragment or page? // Takes a cfi, fragment or page?
EPUBJS.Rendition.prototype.moveTo = function(offset){ Rendition.prototype.moveTo = function(offset){
this.scrollBy(offset.left, offset.top); this.scrollBy(offset.left, offset.top);
}; };
EPUBJS.Rendition.prototype.render = function(view, show) { Rendition.prototype.render = function(view, show) {
view.create(); view.create();
@ -279,7 +290,7 @@ EPUBJS.Rendition.prototype.render = function(view, show) {
} }
// this.map = new EPUBJS.Map(view, this.layout); // this.map = new Map(view, this.layout);
this.hooks.show.trigger(view, this); this.hooks.show.trigger(view, this);
this.trigger("rendered", view.section); this.trigger("rendered", view.section);
@ -291,11 +302,11 @@ EPUBJS.Rendition.prototype.render = function(view, show) {
}; };
EPUBJS.Rendition.prototype.afterDisplayed = function(view){ Rendition.prototype.afterDisplayed = function(view){
this.trigger("added", view.section); this.trigger("added", view.section);
}; };
EPUBJS.Rendition.prototype.fill = function(view){ Rendition.prototype.fill = function(view){
this.views.clear(); this.views.clear();
@ -307,7 +318,7 @@ EPUBJS.Rendition.prototype.fill = function(view){
return this.render(view); return this.render(view);
}; };
EPUBJS.Rendition.prototype.resizeView = function(view) { Rendition.prototype.resizeView = function(view) {
if(this.globalLayoutProperties.layout === "pre-paginated") { if(this.globalLayoutProperties.layout === "pre-paginated") {
view.lock("both", this.stage.width, this.stage.height); view.lock("both", this.stage.width, this.stage.height);
@ -317,7 +328,7 @@ EPUBJS.Rendition.prototype.resizeView = function(view) {
}; };
EPUBJS.Rendition.prototype.stageSize = function(_width, _height){ Rendition.prototype.stageSize = function(_width, _height){
var bounds; var bounds;
var width = _width || this.settings.width; var width = _width || this.settings.width;
var height = _height || this.settings.height; var height = _height || this.settings.height;
@ -342,13 +353,13 @@ EPUBJS.Rendition.prototype.stageSize = function(_width, _height){
} }
if(width && !EPUBJS.core.isNumber(width)) { if(width && !core.isNumber(width)) {
bounds = this.container.getBoundingClientRect(); bounds = this.container.getBoundingClientRect();
width = bounds.width; width = bounds.width;
//height = bounds.height; //height = bounds.height;
} }
if(height && !EPUBJS.core.isNumber(height)) { if(height && !core.isNumber(height)) {
bounds = bounds || this.container.getBoundingClientRect(); bounds = bounds || this.container.getBoundingClientRect();
//width = bounds.width; //width = bounds.width;
height = bounds.height; height = bounds.height;
@ -376,21 +387,21 @@ EPUBJS.Rendition.prototype.stageSize = function(_width, _height){
}; };
EPUBJS.Rendition.prototype.applyLayoutMethod = function() { Rendition.prototype.applyLayoutMethod = function() {
this.layout = new EPUBJS.Layout.Scroll(); this.layout = new Layout.Scroll();
this.updateLayout(); this.updateLayout();
this.map = new EPUBJS.Map(this.layout); this.map = new Map(this.layout);
}; };
EPUBJS.Rendition.prototype.updateLayout = function() { Rendition.prototype.updateLayout = function() {
this.layout.calculate(this.stage.width, this.stage.height); this.layout.calculate(this.stage.width, this.stage.height);
}; };
EPUBJS.Rendition.prototype.resize = function(width, height){ Rendition.prototype.resize = function(width, height){
this.stageSize(width, height); this.stageSize(width, height);
@ -405,15 +416,15 @@ EPUBJS.Rendition.prototype.resize = function(width, height){
}; };
EPUBJS.Rendition.prototype.onResized = function(e) { Rendition.prototype.onResized = function(e) {
this.resize(); this.resize();
}; };
EPUBJS.Rendition.prototype.createView = function(section) { Rendition.prototype.createView = function(section) {
return new EPUBJS.View(section, this.viewSettings); return new View(section, this.viewSettings);
}; };
EPUBJS.Rendition.prototype.next = function(){ Rendition.prototype.next = function(){
return this.q.enqueue(function(){ return this.q.enqueue(function(){
@ -433,7 +444,7 @@ EPUBJS.Rendition.prototype.next = function(){
}; };
EPUBJS.Rendition.prototype.prev = function(){ Rendition.prototype.prev = function(){
return this.q.enqueue(function(){ return this.q.enqueue(function(){
@ -453,7 +464,7 @@ EPUBJS.Rendition.prototype.prev = function(){
}; };
//-- http://www.idpf.org/epub/fxl/ //-- http://www.idpf.org/epub/fxl/
EPUBJS.Rendition.prototype.parseLayoutProperties = function(_metadata){ Rendition.prototype.parseLayoutProperties = function(_metadata){
var metadata = _metadata || this.book.package.metadata; var metadata = _metadata || this.book.package.metadata;
var layout = (this.layoutOveride && this.layoutOveride.layout) || metadata.layout || "reflowable"; var layout = (this.layoutOveride && this.layoutOveride.layout) || metadata.layout || "reflowable";
var spread = (this.layoutOveride && this.layoutOveride.spread) || metadata.spread || "auto"; var spread = (this.layoutOveride && this.layoutOveride.spread) || metadata.spread || "auto";
@ -467,7 +478,7 @@ EPUBJS.Rendition.prototype.parseLayoutProperties = function(_metadata){
}; };
EPUBJS.Rendition.prototype.current = function(){ Rendition.prototype.current = function(){
var visible = this.visible(); var visible = this.visible();
if(visible.length){ if(visible.length){
// Current is the last visible view // Current is the last visible view
@ -476,7 +487,7 @@ EPUBJS.Rendition.prototype.current = function(){
return null; return null;
}; };
EPUBJS.Rendition.prototype.isVisible = function(view, offsetPrev, offsetNext, _container){ Rendition.prototype.isVisible = function(view, offsetPrev, offsetNext, _container){
var position = view.position(); var position = view.position();
var container = _container || this.container.getBoundingClientRect(); var container = _container || this.container.getBoundingClientRect();
@ -497,7 +508,7 @@ EPUBJS.Rendition.prototype.isVisible = function(view, offsetPrev, offsetNext, _c
}; };
EPUBJS.Rendition.prototype.visible = function(){ Rendition.prototype.visible = function(){
var container = this.bounds(); var container = this.bounds();
var displayedViews = this.views.displayed(); var displayedViews = this.views.displayed();
var visible = []; var visible = [];
@ -517,11 +528,11 @@ EPUBJS.Rendition.prototype.visible = function(){
}; };
EPUBJS.Rendition.prototype.bounds = function(func) { Rendition.prototype.bounds = function(func) {
var bounds; var bounds;
if(!this.settings.height) { if(!this.settings.height) {
bounds = EPUBJS.core.windowBounds(); bounds = core.windowBounds();
} else { } else {
bounds = this.container.getBoundingClientRect(); bounds = this.container.getBoundingClientRect();
} }
@ -529,7 +540,7 @@ EPUBJS.Rendition.prototype.bounds = function(func) {
return bounds; return bounds;
}; };
EPUBJS.Rendition.prototype.destroy = function(){ Rendition.prototype.destroy = function(){
// Clear the queue // Clear the queue
this.q.clear(); this.q.clear();
@ -544,14 +555,14 @@ EPUBJS.Rendition.prototype.destroy = function(){
}; };
EPUBJS.Rendition.prototype.reportLocation = function(){ Rendition.prototype.reportLocation = function(){
return this.q.enqueue(function(){ return this.q.enqueue(function(){
this.location = this.currentLocation(); this.location = this.currentLocation();
this.trigger("locationChanged", this.location); this.trigger("locationChanged", this.location);
}.bind(this)); }.bind(this));
}; };
EPUBJS.Rendition.prototype.currentLocation = function(){ Rendition.prototype.currentLocation = function(){
var view; var view;
var start, end; var start, end;
@ -565,7 +576,7 @@ EPUBJS.Rendition.prototype.currentLocation = function(){
}; };
EPUBJS.Rendition.prototype.scrollBy = function(x, y, silent){ Rendition.prototype.scrollBy = function(x, y, silent){
if(silent) { if(silent) {
this.ignore = true; this.ignore = true;
} }
@ -582,7 +593,7 @@ EPUBJS.Rendition.prototype.scrollBy = function(x, y, silent){
this.scrolled = true; this.scrolled = true;
}; };
EPUBJS.Rendition.prototype.scrollTo = function(x, y, silent){ Rendition.prototype.scrollTo = function(x, y, silent){
if(silent) { if(silent) {
this.ignore = true; this.ignore = true;
} }
@ -603,15 +614,17 @@ EPUBJS.Rendition.prototype.scrollTo = function(x, y, silent){
// }; // };
}; };
EPUBJS.Rendition.prototype.passViewEvents = function(view){ Rendition.prototype.passViewEvents = function(view){
view.listenedEvents.forEach(function(e){ view.listenedEvents.forEach(function(e){
view.on(e, this.triggerViewEvent.bind(this)); view.on(e, this.triggerViewEvent.bind(this));
}.bind(this)); }.bind(this));
}; };
EPUBJS.Rendition.prototype.triggerViewEvent = function(e){ Rendition.prototype.triggerViewEvent = function(e){
this.trigger(e.type, e); this.trigger(e.type, e);
}; };
//-- Enable binding events to Renderer //-- Enable binding events to Renderer
RSVP.EventTarget.mixin(EPUBJS.Rendition.prototype); RSVP.EventTarget.mixin(Rendition.prototype);
module.exports = Rendition;

View file

@ -1,10 +1,11 @@
EPUBJS.replace = {}; var core = require('./core');
EPUBJS.replace.links = function(view, renderer) {
function links(view, renderer) {
var links = view.document.querySelectorAll("a[href]"); var links = view.document.querySelectorAll("a[href]");
var replaceLinks = function(link){ var replaceLinks = function(link){
var href = link.getAttribute("href"); var href = link.getAttribute("href");
var uri = new EPUBJS.core.uri(href); var uri = new core.uri(href);
if(uri.protocol){ if(uri.protocol){
@ -13,7 +14,7 @@ EPUBJS.replace.links = function(view, renderer) {
}else{ }else{
// relative = EPUBJS.core.resolveUrl(directory, href); // relative = core.resolveUrl(directory, href);
// if(uri.fragment && !base) { // if(uri.fragment && !base) {
// link.onclick = function(){ // link.onclick = function(){
// renderer.fragment(href); // renderer.fragment(href);
@ -41,3 +42,7 @@ EPUBJS.replace.links = function(view, renderer) {
}; };
module.exports = {
'links': links
};

View file

@ -1,4 +1,9 @@
EPUBJS.Section = function(item){ var RSVP = require('rsvp');
var core = require('./core');
var EpubCFI = require('./epubcfi');
var Hook = require('./hook');
function Section(item){
this.idref = item.idref; this.idref = item.idref;
this.linear = item.linear; this.linear = item.linear;
this.properties = item.properties; this.properties = item.properties;
@ -8,19 +13,19 @@ EPUBJS.Section = function(item){
this.next = item.next; this.next = item.next;
this.prev = item.prev; this.prev = item.prev;
this.epubcfi = new EPUBJS.EpubCFI(); this.epubcfi = new EpubCFI();
this.cfiBase = item.cfiBase; this.cfiBase = item.cfiBase;
this.hooks = {}; this.hooks = {};
this.hooks.replacements = new EPUBJS.Hook(this); this.hooks.replacements = new Hook(this);
// Register replacements // Register replacements
this.hooks.replacements.register(this.replacements); this.hooks.replacements.register(this.replacements);
}; };
EPUBJS.Section.prototype.load = function(_request){ Section.prototype.load = function(_request){
var request = _request || this.request || EPUBJS.core.request; var request = _request || this.request || core.request;
var loading = new RSVP.defer(); var loading = new RSVP.defer();
var loaded = loading.promise; var loaded = loading.promise;
@ -30,7 +35,7 @@ EPUBJS.Section.prototype.load = function(_request){
request(this.url, 'xml') request(this.url, 'xml')
.then(function(xml){ .then(function(xml){
var base; var base;
var directory = EPUBJS.core.folder(this.url); var directory = core.folder(this.url);
this.document = xml; this.document = xml;
this.contents = xml.documentElement; this.contents = xml.documentElement;
@ -48,7 +53,7 @@ EPUBJS.Section.prototype.load = function(_request){
return loaded; return loaded;
}; };
EPUBJS.Section.prototype.replacements = function(_document){ Section.prototype.replacements = function(_document){
var task = new RSVP.defer(); var task = new RSVP.defer();
var base = _document.createElement("base"); // TODO: check if exists var base = _document.createElement("base"); // TODO: check if exists
var head; var head;
@ -69,11 +74,11 @@ EPUBJS.Section.prototype.replacements = function(_document){
return task.promise; return task.promise;
}; };
EPUBJS.Section.prototype.beforeSectionLoad = function(){ Section.prototype.beforeSectionLoad = function(){
// Stub for a hook - replace me for now // Stub for a hook - replace me for now
}; };
EPUBJS.Section.prototype.render = function(_request){ Section.prototype.render = function(_request){
var rendering = new RSVP.defer(); var rendering = new RSVP.defer();
var rendered = rendering.promise; var rendered = rendering.promise;
@ -89,7 +94,7 @@ EPUBJS.Section.prototype.render = function(_request){
return rendered; return rendered;
}; };
EPUBJS.Section.prototype.find = function(_query){ Section.prototype.find = function(_query){
}; };
@ -99,7 +104,7 @@ EPUBJS.Section.prototype.find = function(_query){
* Takes: global layout settings object, chapter properties string * Takes: global layout settings object, chapter properties string
* Returns: Object with layout properties * Returns: Object with layout properties
*/ */
EPUBJS.Section.prototype.reconcileLayoutSettings = function(global){ Section.prototype.reconcileLayoutSettings = function(global){
//-- Get the global defaults //-- Get the global defaults
var settings = { var settings = {
layout : global.layout, layout : global.layout,
@ -123,10 +128,12 @@ EPUBJS.Section.prototype.reconcileLayoutSettings = function(global){
return settings; return settings;
}; };
EPUBJS.Section.prototype.cfiFromRange = function(_range) { Section.prototype.cfiFromRange = function(_range) {
return this.epubcfi.generateCfiFromRange(_range, this.cfiBase); return this.epubcfi.generateCfiFromRange(_range, this.cfiBase);
}; };
EPUBJS.Section.prototype.cfiFromElement = function(el) { Section.prototype.cfiFromElement = function(el) {
return this.epubcfi.generateCfiFromElement(el, this.cfiBase); return this.epubcfi.generateCfiFromElement(el, this.cfiBase);
}; };
module.exports = Section;

View file

@ -1,4 +1,9 @@
EPUBJS.Spine = function(_request){ var RSVP = require('rsvp');
var core = require('./core');
var EpubCFI = require('./epubcfi');
var Section = require('./section');
function Spine(_request){
this.request = _request; this.request = _request;
this.spineItems = []; this.spineItems = [];
this.spineByHref = {}; this.spineByHref = {};
@ -6,14 +11,14 @@ EPUBJS.Spine = function(_request){
}; };
EPUBJS.Spine.prototype.load = function(_package) { Spine.prototype.load = function(_package) {
this.items = _package.spine; this.items = _package.spine;
this.manifest = _package.manifest; this.manifest = _package.manifest;
this.spineNodeIndex = _package.spineNodeIndex; this.spineNodeIndex = _package.spineNodeIndex;
this.baseUrl = _package.baseUrl || ''; this.baseUrl = _package.baseUrl || '';
this.length = this.items.length; this.length = this.items.length;
this.epubcfi = new EPUBJS.EpubCFI(); this.epubcfi = new EpubCFI();
this.items.forEach(function(item, index){ this.items.forEach(function(item, index){
var href, url; var href, url;
@ -39,7 +44,7 @@ EPUBJS.Spine.prototype.load = function(_package) {
item.next = function(){ return this.get(index+1); }.bind(this); item.next = function(){ return this.get(index+1); }.bind(this);
// } // }
spineItem = new EPUBJS.Section(item); spineItem = new Section(item);
this.append(spineItem); this.append(spineItem);
@ -51,7 +56,7 @@ EPUBJS.Spine.prototype.load = function(_package) {
// book.spine.get(1); // book.spine.get(1);
// book.spine.get("chap1.html"); // book.spine.get("chap1.html");
// book.spine.get("#id1234"); // book.spine.get("#id1234");
EPUBJS.Spine.prototype.get = function(target) { Spine.prototype.get = function(target) {
var index = 0; var index = 0;
if(this.epubcfi.isCfiString(target)) { if(this.epubcfi.isCfiString(target)) {
@ -70,7 +75,7 @@ EPUBJS.Spine.prototype.get = function(target) {
return this.spineItems[index] || null; return this.spineItems[index] || null;
}; };
EPUBJS.Spine.prototype.append = function(section) { Spine.prototype.append = function(section) {
var index = this.spineItems.length; var index = this.spineItems.length;
section.index = index; section.index = index;
@ -82,7 +87,7 @@ EPUBJS.Spine.prototype.append = function(section) {
return index; return index;
}; };
EPUBJS.Spine.prototype.prepend = function(section) { Spine.prototype.prepend = function(section) {
var index = this.spineItems.unshift(section); var index = this.spineItems.unshift(section);
this.spineByHref[section.href] = 0; this.spineByHref[section.href] = 0;
this.spineById[section.idref] = 0; this.spineById[section.idref] = 0;
@ -95,11 +100,11 @@ EPUBJS.Spine.prototype.prepend = function(section) {
return 0; return 0;
}; };
EPUBJS.Spine.prototype.insert = function(section, index) { Spine.prototype.insert = function(section, index) {
}; };
EPUBJS.Spine.prototype.remove = function(section) { Spine.prototype.remove = function(section) {
var index = this.spineItems.indexOf(section); var index = this.spineItems.indexOf(section);
if(index > -1) { if(index > -1) {
@ -110,6 +115,8 @@ EPUBJS.Spine.prototype.remove = function(section) {
} }
}; };
EPUBJS.Spine.prototype.each = function() { Spine.prototype.each = function() {
return this.spineItems.forEach.apply(this.spineItems, arguments); return this.spineItems.forEach.apply(this.spineItems, arguments);
}; };
module.exports = Spine;

View file

@ -1,7 +1,11 @@
EPUBJS.View = function(section, options) { var RSVP = require('rsvp');
var core = require('./core');
var EpubCFI = require('./epubcfi');
function View(section, options) {
this.settings = options || {}; this.settings = options || {};
this.id = "epubjs-view:" + EPUBJS.core.uuid(); this.id = "epubjs-view:" + core.uuid();
this.section = section; this.section = section;
this.index = section.index; this.index = section.index;
@ -22,7 +26,7 @@ EPUBJS.View = function(section, options) {
//this.height = 0; //this.height = 0;
// Blank Cfi for Parsing // Blank Cfi for Parsing
this.epubcfi = new EPUBJS.EpubCFI(); this.epubcfi = new EpubCFI();
if(this.settings.axis && this.settings.axis == "horizontal"){ if(this.settings.axis && this.settings.axis == "horizontal"){
this.element.style.display = "inline-block"; this.element.style.display = "inline-block";
@ -35,7 +39,7 @@ EPUBJS.View = function(section, options) {
}; };
EPUBJS.View.prototype.create = function() { View.prototype.create = function() {
if(this.iframe) { if(this.iframe) {
return this.iframe; return this.iframe;
@ -63,14 +67,14 @@ EPUBJS.View.prototype.create = function() {
this.element.appendChild(this.iframe); this.element.appendChild(this.iframe);
this.added = true; this.added = true;
this.elementBounds = EPUBJS.core.bounds(this.element); this.elementBounds = core.bounds(this.element);
// if(width || height){ // if(width || height){
// this.resize(width, height); // this.resize(width, height);
// } else if(this.width && this.height){ // } else if(this.width && this.height){
// this.resize(this.width, this.height); // this.resize(this.width, this.height);
// } else { // } else {
// this.iframeBounds = EPUBJS.core.bounds(this.iframe); // this.iframeBounds = core.bounds(this.iframe);
// } // }
// Firefox has trouble with baseURI and srcdoc // Firefox has trouble with baseURI and srcdoc
@ -88,30 +92,30 @@ EPUBJS.View.prototype.create = function() {
}; };
EPUBJS.View.prototype.lock = function(what, width, height) { View.prototype.lock = function(what, width, height) {
var elBorders = EPUBJS.core.borders(this.element); var elBorders = core.borders(this.element);
var iframeBorders; var iframeBorders;
if(this.iframe) { if(this.iframe) {
iframeBorders = EPUBJS.core.borders(this.iframe); iframeBorders = core.borders(this.iframe);
} else { } else {
iframeBorders = {width: 0, height: 0}; iframeBorders = {width: 0, height: 0};
} }
if(what == "width" && EPUBJS.core.isNumber(width)){ if(what == "width" && core.isNumber(width)){
this.lockedWidth = width - elBorders.width - iframeBorders.width; this.lockedWidth = width - elBorders.width - iframeBorders.width;
this.resize(this.lockedWidth, width); // width keeps ratio correct this.resize(this.lockedWidth, width); // width keeps ratio correct
} }
if(what == "height" && EPUBJS.core.isNumber(height)){ if(what == "height" && core.isNumber(height)){
this.lockedHeight = height - elBorders.height - iframeBorders.height; this.lockedHeight = height - elBorders.height - iframeBorders.height;
this.resize(width, this.lockedHeight); this.resize(width, this.lockedHeight);
} }
if(what === "both" && if(what === "both" &&
EPUBJS.core.isNumber(width) && core.isNumber(width) &&
EPUBJS.core.isNumber(height)){ core.isNumber(height)){
this.lockedWidth = width - elBorders.width - iframeBorders.width; this.lockedWidth = width - elBorders.width - iframeBorders.width;
this.lockedHeight = height - elBorders.height - iframeBorders.height; this.lockedHeight = height - elBorders.height - iframeBorders.height;
@ -130,7 +134,7 @@ EPUBJS.View.prototype.lock = function(what, width, height) {
}; };
EPUBJS.View.prototype.expand = function(force) { View.prototype.expand = function(force) {
var width = this.lockedWidth; var width = this.lockedWidth;
var height = this.lockedHeight; var height = this.lockedHeight;
@ -180,7 +184,7 @@ EPUBJS.View.prototype.expand = function(force) {
this._expanding = false; this._expanding = false;
}; };
EPUBJS.View.prototype.contentWidth = function(min) { View.prototype.contentWidth = function(min) {
var prev; var prev;
var width; var width;
@ -196,7 +200,7 @@ EPUBJS.View.prototype.contentWidth = function(min) {
return width; return width;
}; };
EPUBJS.View.prototype.contentHeight = function(min) { View.prototype.contentHeight = function(min) {
var prev; var prev;
var height; var height;
@ -207,7 +211,7 @@ EPUBJS.View.prototype.contentHeight = function(min) {
return height; return height;
}; };
EPUBJS.View.prototype.textWidth = function() { View.prototype.textWidth = function() {
var width; var width;
var range = this.document.createRange(); var range = this.document.createRange();
@ -220,7 +224,7 @@ EPUBJS.View.prototype.textWidth = function() {
}; };
EPUBJS.View.prototype.textHeight = function() { View.prototype.textHeight = function() {
var height; var height;
var range = this.document.createRange(); var range = this.document.createRange();
@ -230,27 +234,27 @@ EPUBJS.View.prototype.textHeight = function() {
return height; return height;
}; };
EPUBJS.View.prototype.resize = function(width, height) { View.prototype.resize = function(width, height) {
if(!this.iframe) return; if(!this.iframe) return;
if(EPUBJS.core.isNumber(width)){ if(core.isNumber(width)){
this.iframe.style.width = width + "px"; this.iframe.style.width = width + "px";
this._width = width; this._width = width;
} }
if(EPUBJS.core.isNumber(height)){ if(core.isNumber(height)){
this.iframe.style.height = height + "px"; this.iframe.style.height = height + "px";
this._height = height; this._height = height;
} }
this.iframeBounds = EPUBJS.core.bounds(this.iframe); this.iframeBounds = core.bounds(this.iframe);
this.reframe(this.iframeBounds.width, this.iframeBounds.height); this.reframe(this.iframeBounds.width, this.iframeBounds.height);
}; };
EPUBJS.View.prototype.reframe = function(width, height) { View.prototype.reframe = function(width, height) {
//var prevBounds; //var prevBounds;
if(!this.displayed) { if(!this.displayed) {
@ -258,17 +262,17 @@ EPUBJS.View.prototype.reframe = function(width, height) {
return; return;
} }
if(EPUBJS.core.isNumber(width)){ if(core.isNumber(width)){
this.element.style.width = width + "px"; this.element.style.width = width + "px";
} }
if(EPUBJS.core.isNumber(height)){ if(core.isNumber(height)){
this.element.style.height = height + "px"; this.element.style.height = height + "px";
} }
this.prevBounds = this.elementBounds; this.prevBounds = this.elementBounds;
this.elementBounds = EPUBJS.core.bounds(this.element); this.elementBounds = core.bounds(this.element);
this.trigger("resized", { this.trigger("resized", {
width: this.elementBounds.width, width: this.elementBounds.width,
@ -279,7 +283,7 @@ EPUBJS.View.prototype.reframe = function(width, height) {
}; };
EPUBJS.View.prototype.resized = function(e) { View.prototype.resized = function(e) {
/* /*
if (!this.resizing) { if (!this.resizing) {
if(this.iframe) { if(this.iframe) {
@ -291,7 +295,7 @@ EPUBJS.View.prototype.resized = function(e) {
}; };
EPUBJS.View.prototype.render = function(_request) { View.prototype.render = function(_request) {
// if(this.rendering){ // if(this.rendering){
// return this.displayed; // return this.displayed;
@ -307,7 +311,7 @@ EPUBJS.View.prototype.render = function(_request) {
}.bind(this)); }.bind(this));
}; };
EPUBJS.View.prototype.load = function(contents) { View.prototype.load = function(contents) {
var loading = new RSVP.defer(); var loading = new RSVP.defer();
var loaded = loading.promise; var loaded = loading.promise;
@ -346,7 +350,7 @@ EPUBJS.View.prototype.load = function(contents) {
}; };
EPUBJS.View.prototype.layout = function(layoutFunc) { View.prototype.layout = function(layoutFunc) {
this.iframe.style.display = "inline-block"; this.iframe.style.display = "inline-block";
@ -363,11 +367,11 @@ EPUBJS.View.prototype.layout = function(layoutFunc) {
}; };
EPUBJS.View.prototype.onLayout = function(view) { View.prototype.onLayout = function(view) {
// stub // stub
}; };
EPUBJS.View.prototype.listeners = function() { View.prototype.listeners = function() {
/* /*
setTimeout(function(){ setTimeout(function(){
this.window.addEventListener("resize", this.resized.bind(this), false); this.window.addEventListener("resize", this.resized.bind(this), false);
@ -401,21 +405,21 @@ EPUBJS.View.prototype.listeners = function() {
this.addSelectionListeners(); this.addSelectionListeners();
}; };
EPUBJS.View.prototype.removeListeners = function() { View.prototype.removeListeners = function() {
this.removeEventListeners(); this.removeEventListeners();
this.removeSelectionListeners(); this.removeSelectionListeners();
}; };
EPUBJS.View.prototype.resizeListenters = function() { View.prototype.resizeListenters = function() {
// Test size again // Test size again
clearTimeout(this.expanding); clearTimeout(this.expanding);
this.expanding = setTimeout(this.expand.bind(this), 350); this.expanding = setTimeout(this.expand.bind(this), 350);
}; };
//https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js //https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js
EPUBJS.View.prototype.mediaQueryListeners = function() { View.prototype.mediaQueryListeners = function() {
var sheets = this.document.styleSheets; var sheets = this.document.styleSheets;
var mediaChangeHandler = function(m){ var mediaChangeHandler = function(m){
if(m.matches && !this._expanding) { if(m.matches && !this._expanding) {
@ -438,7 +442,7 @@ EPUBJS.View.prototype.mediaQueryListeners = function() {
} }
}; };
EPUBJS.View.prototype.observe = function(target) { View.prototype.observe = function(target) {
var renderer = this; var renderer = this;
// create an observer instance // create an observer instance
@ -460,17 +464,17 @@ EPUBJS.View.prototype.observe = function(target) {
return observer; return observer;
}; };
// EPUBJS.View.prototype.appendTo = function(element) { // View.prototype.appendTo = function(element) {
// this.element = element; // this.element = element;
// this.element.appendChild(this.iframe); // this.element.appendChild(this.iframe);
// }; // };
// //
// EPUBJS.View.prototype.prependTo = function(element) { // View.prototype.prependTo = function(element) {
// this.element = element; // this.element = element;
// element.insertBefore(this.iframe, element.firstChild); // element.insertBefore(this.iframe, element.firstChild);
// }; // };
EPUBJS.View.prototype.imageLoadListeners = function(target) { View.prototype.imageLoadListeners = function(target) {
var images = this.document.body.querySelectorAll("img"); var images = this.document.body.querySelectorAll("img");
var img; var img;
for (var i = 0; i < images.length; i++) { for (var i = 0; i < images.length; i++) {
@ -483,7 +487,7 @@ EPUBJS.View.prototype.imageLoadListeners = function(target) {
} }
}; };
EPUBJS.View.prototype.display = function() { View.prototype.display = function() {
var displayed = new RSVP.defer(); var displayed = new RSVP.defer();
this.displayed = true; this.displayed = true;
@ -502,7 +506,7 @@ EPUBJS.View.prototype.display = function() {
return displayed.promise; return displayed.promise;
}; };
EPUBJS.View.prototype.show = function() { View.prototype.show = function() {
this.element.style.visibility = "visible"; this.element.style.visibility = "visible";
@ -513,7 +517,7 @@ EPUBJS.View.prototype.show = function() {
this.trigger("shown", this); this.trigger("shown", this);
}; };
EPUBJS.View.prototype.hide = function() { View.prototype.hide = function() {
// this.iframe.style.display = "none"; // this.iframe.style.display = "none";
this.element.style.visibility = "hidden"; this.element.style.visibility = "hidden";
this.iframe.style.visibility = "hidden"; this.iframe.style.visibility = "hidden";
@ -522,22 +526,22 @@ EPUBJS.View.prototype.hide = function() {
this.trigger("hidden", this); this.trigger("hidden", this);
}; };
EPUBJS.View.prototype.position = function() { View.prototype.position = function() {
return this.element.getBoundingClientRect(); return this.element.getBoundingClientRect();
}; };
EPUBJS.View.prototype.onDisplayed = function(view) { View.prototype.onDisplayed = function(view) {
// Stub, override with a custom functions // Stub, override with a custom functions
}; };
EPUBJS.View.prototype.bounds = function() { View.prototype.bounds = function() {
if(!this.elementBounds) { if(!this.elementBounds) {
this.elementBounds = EPUBJS.core.bounds(this.element); this.elementBounds = core.bounds(this.element);
} }
return this.elementBounds; return this.elementBounds;
}; };
EPUBJS.View.prototype.destroy = function() { View.prototype.destroy = function() {
// Stop observing // Stop observing
if(this.observer) { if(this.observer) {
this.observer.disconnect(); this.observer.disconnect();
@ -560,12 +564,12 @@ EPUBJS.View.prototype.destroy = function() {
// this.element.style.width = "0px"; // this.element.style.width = "0px";
}; };
EPUBJS.View.prototype.root = function() { View.prototype.root = function() {
if(!this.document) return null; if(!this.document) return null;
return this.document.documentElement; return this.document.documentElement;
}; };
EPUBJS.View.prototype.locationOf = function(target) { View.prototype.locationOf = function(target) {
var parentPos = this.iframe.getBoundingClientRect(); var parentPos = this.iframe.getBoundingClientRect();
var targetPos = {"left": 0, "top": 0}; var targetPos = {"left": 0, "top": 0};
@ -605,7 +609,7 @@ EPUBJS.View.prototype.locationOf = function(target) {
}; };
}; };
EPUBJS.View.prototype.addCss = function(src) { View.prototype.addCss = function(src) {
return new RSVP.Promise(function(resolve, reject){ return new RSVP.Promise(function(resolve, reject){
var $stylesheet; var $stylesheet;
var ready = false; var ready = false;
@ -635,7 +639,7 @@ EPUBJS.View.prototype.addCss = function(src) {
}; };
// https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule
EPUBJS.View.prototype.addStylesheetRules = function(rules) { View.prototype.addStylesheetRules = function(rules) {
var styleEl; var styleEl;
var styleSheet; var styleSheet;
@ -667,7 +671,7 @@ EPUBJS.View.prototype.addStylesheetRules = function(rules) {
} }
}; };
EPUBJS.View.prototype.addScript = function(src) { View.prototype.addScript = function(src) {
return new RSVP.Promise(function(resolve, reject){ return new RSVP.Promise(function(resolve, reject){
var $script; var $script;
@ -696,7 +700,7 @@ EPUBJS.View.prototype.addScript = function(src) {
}.bind(this)); }.bind(this));
}; };
EPUBJS.View.prototype.addEventListeners = function(){ View.prototype.addEventListeners = function(){
if(!this.document) { if(!this.document) {
return; return;
} }
@ -706,7 +710,7 @@ EPUBJS.View.prototype.addEventListeners = function(){
}; };
EPUBJS.View.prototype.removeEventListeners = function(){ View.prototype.removeEventListeners = function(){
if(!this.document) { if(!this.document) {
return; return;
} }
@ -717,25 +721,25 @@ EPUBJS.View.prototype.removeEventListeners = function(){
}; };
// Pass browser events // Pass browser events
EPUBJS.View.prototype.triggerEvent = function(e){ View.prototype.triggerEvent = function(e){
this.trigger(e.type, e); this.trigger(e.type, e);
}; };
EPUBJS.View.prototype.addSelectionListeners = function(){ View.prototype.addSelectionListeners = function(){
if(!this.document) { if(!this.document) {
return; return;
} }
this.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); this.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false);
}; };
EPUBJS.View.prototype.removeSelectionListeners = function(){ View.prototype.removeSelectionListeners = function(){
if(!this.document) { if(!this.document) {
return; return;
} }
this.document.removeEventListener("selectionchange", this.onSelectionChange, false); this.document.removeEventListener("selectionchange", this.onSelectionChange, false);
}; };
EPUBJS.View.prototype.onSelectionChange = function(e){ View.prototype.onSelectionChange = function(e){
if (this.selectionEndTimeout) { if (this.selectionEndTimeout) {
clearTimeout(this.selectionEndTimeout); clearTimeout(this.selectionEndTimeout);
} }
@ -745,4 +749,6 @@ EPUBJS.View.prototype.onSelectionChange = function(e){
}.bind(this), 500); }.bind(this), 500);
}; };
RSVP.EventTarget.mixin(EPUBJS.View.prototype); RSVP.EventTarget.mixin(View.prototype);
module.exports = View;

View file

@ -1,49 +1,49 @@
EPUBJS.Views = function(container) { function Views(container) {
this.container = container; this.container = container;
this._views = []; this._views = [];
this.length = 0; this.length = 0;
this.hidden = false; this.hidden = false;
}; };
EPUBJS.Views.prototype.first = function() { Views.prototype.first = function() {
return this._views[0]; return this._views[0];
}; };
EPUBJS.Views.prototype.last = function() { Views.prototype.last = function() {
return this._views[this._views.length-1]; return this._views[this._views.length-1];
}; };
EPUBJS.Views.prototype.each = function() { Views.prototype.each = function() {
return this._views.forEach.apply(this._views, arguments); return this._views.forEach.apply(this._views, arguments);
}; };
EPUBJS.Views.prototype.indexOf = function(view) { Views.prototype.indexOf = function(view) {
return this._views.indexOf(view); return this._views.indexOf(view);
}; };
EPUBJS.Views.prototype.slice = function() { Views.prototype.slice = function() {
return this._views.slice.apply(this._views, arguments); return this._views.slice.apply(this._views, arguments);
}; };
EPUBJS.Views.prototype.get = function(i) { Views.prototype.get = function(i) {
return this._views[i]; return this._views[i];
}; };
EPUBJS.Views.prototype.append = function(view){ Views.prototype.append = function(view){
this._views.push(view); this._views.push(view);
this.container.appendChild(view.element); this.container.appendChild(view.element);
this.length++; this.length++;
return view; return view;
}; };
EPUBJS.Views.prototype.prepend = function(view){ Views.prototype.prepend = function(view){
this._views.unshift(view); this._views.unshift(view);
this.container.insertBefore(view.element, this.container.firstChild); this.container.insertBefore(view.element, this.container.firstChild);
this.length++; this.length++;
return view; return view;
}; };
EPUBJS.Views.prototype.insert = function(view, index) { Views.prototype.insert = function(view, index) {
this._views.splice(index, 0, view); this._views.splice(index, 0, view);
if(index < this.container.children.length){ if(index < this.container.children.length){
@ -55,7 +55,7 @@ EPUBJS.Views.prototype.insert = function(view, index) {
return view; return view;
}; };
EPUBJS.Views.prototype.remove = function(view) { Views.prototype.remove = function(view) {
var index = this._views.indexOf(view); var index = this._views.indexOf(view);
if(index > -1) { if(index > -1) {
@ -68,7 +68,7 @@ EPUBJS.Views.prototype.remove = function(view) {
this.length--; this.length--;
}; };
EPUBJS.Views.prototype.destroy = function(view) { Views.prototype.destroy = function(view) {
view.off("resized"); view.off("resized");
if(view.displayed){ if(view.displayed){
@ -81,7 +81,7 @@ EPUBJS.Views.prototype.destroy = function(view) {
// Iterators // Iterators
EPUBJS.Views.prototype.clear = function(){ Views.prototype.clear = function(){
// Remove all views // Remove all views
var view; var view;
var len = this.length; var len = this.length;
@ -97,7 +97,7 @@ EPUBJS.Views.prototype.clear = function(){
this.length = 0; this.length = 0;
}; };
EPUBJS.Views.prototype.find = function(section){ Views.prototype.find = function(section){
var view; var view;
var len = this.length; var len = this.length;
@ -111,7 +111,7 @@ EPUBJS.Views.prototype.find = function(section){
}; };
EPUBJS.Views.prototype.displayed = function(){ Views.prototype.displayed = function(){
var displayed = []; var displayed = [];
var view; var view;
var len = this.length; var len = this.length;
@ -125,7 +125,7 @@ EPUBJS.Views.prototype.displayed = function(){
return displayed; return displayed;
}; };
EPUBJS.Views.prototype.show = function(){ Views.prototype.show = function(){
var view; var view;
var len = this.length; var len = this.length;
@ -138,7 +138,7 @@ EPUBJS.Views.prototype.show = function(){
this.hidden = false; this.hidden = false;
}; };
EPUBJS.Views.prototype.hide = function(){ Views.prototype.hide = function(){
var view; var view;
var len = this.length; var len = this.length;
@ -150,3 +150,5 @@ EPUBJS.Views.prototype.hide = function(){
} }
this.hidden = true; this.hidden = true;
}; };
module.exports = Views;