76 KiB
ePub
Creates a new Book
Parameters
url
(string | ArrayBuffer) URL, Path or ArrayBufferoptions
object to pass to the book
Examples
ePub("/path/to/book.epub", {})
Returns Book a new Book object
Book
An Epub representation with methods for the loading, parsing and manipulation of its contents.
Parameters
url
string?options
object?options.requestMethod
method? a request function to use instead of the defaultoptions.requestCredentials
boolean send the xhr request withCredentials (optional, defaultundefined
)options.requestHeaders
object send the xhr request headers (optional, defaultundefined
)options.encoding
string optional to pass 'binary' or base64' for archived Epubs (optional, defaultbinary
)options.replacements
string use base64, blobUrl, or none for replacing assets in archived Epubs (optional, defaultnone
)options.canonical
method? optional function to determine canonical urls for a pathoptions.openAs
string? optional string to determine the input type
Examples
new Book("/path/to/book.epub", {})
new Book({ replacements: "blobUrl" })
Returns Book
open
Open a epub or url
Parameters
input
(string | ArrayBuffer) Url, Path or ArrayBufferwhat
string force opening as a certain type (optional, default"binary","base64","epub","opf","json","directory"
)
Examples
book.open("/path/to/book.epub")
Returns Promise of when the book has been loaded
load
Load a resource from the Book
Parameters
path
string path to the resource to load
Returns Promise returns a promise with the requested resource
resolve
Resolve a path to it's absolute position in the Book
Parameters
Returns string the resolved path string
canonical
Get a canonical link to a path
Parameters
path
string
Returns string the canonical path string
section
Gets a Section of the Book from the Spine
Alias for book.spine.get
Parameters
target
string
Returns Section
renderTo
Sugar to render a book to an element
Parameters
Returns Rendition
setRequestCredentials
Set if request should use withCredentials
Parameters
credentials
boolean
setRequestHeaders
Set headers request should use
Parameters
headers
object
coverUrl
Get the cover url
Returns string coverUrl
getRange
Find a DOM Range for a given CFI Range
Parameters
cfiRange
EpubCFI a epub cfi range
Returns Range
key
Generates the Book Key using the identifer in the manifest or other string provided
Parameters
identifier
string? to use instead of metadata identifier
Returns string key
destroy
Destroy the Book and all associated objects
opened
spine
Type: Spine
locations
Type: Locations
navigation
Type: Navigation
pagelist
Type: PageList
Url
creates a Url object for parsing and manipulation of a url string
Parameters
urlString
string a url string (relative or absolute)baseString
string? optional base for the url, default to window.location.href
path
Returns Path
resolve
Resolves a relative path to a absolute url
Parameters
what
string
Returns string url
relative
Resolve a path relative to the url
Parameters
what
string
Returns string path
toString
Returns string
Path
Creates a Path object for parsing and manipulation of a path strings
Uses a polyfill for Nodejs path: https://nodejs.org/api/path.html
Parameters
pathString
string a url string (relative or absolute)
parse
Parse the path: https://nodejs.org/api/path.html#path_path_parse_path
Parameters
what
string
Returns object
isAbsolute
Parameters
what
string
Returns boolean
isDirectory
Check if path ends with a directory
Parameters
what
string
Returns boolean
resolve
Resolve a path against the directory of the Path
https://nodejs.org/api/path.html#path_path_resolve_paths
Parameters
what
string
Returns string resolved
relative
Resolve a path relative to the directory of the Path
https://nodejs.org/api/path.html#path_path_relative_from_to
Parameters
what
string
Returns string relative
toString
Return the path string
Returns string path
Spine
A collection of Spine Items
unpack
Unpack items from a opf into spine items
Parameters
_package
Packagingresolver
method URL resolvercanonical
method Resolve canonical url
get
Get an item from the spine
Parameters
Examples
spine.get();
spine.get(1);
spine.get("chap1.html");
spine.get("#id1234");
Returns Section section
each
Loop over the Sections in the Spine
Returns method forEach
first
Find the first Section in the Spine
Returns Section first section
last
Find the last Section in the Spine
Returns Section last section
Section
Represents a Section of the Book
In most books this is equivelent to a Chapter
Parameters
load
Load the section from its url
Parameters
_request
method? a request method to use for loading
Returns document a promise with the xml document
render
Render the contents of a section
Parameters
_request
method? a request method to use for loading
Returns string output a serialized XML Document
find
Find a string in a section
Parameters
_query
string The query string to find
Returns Array<object> A list of matches, with form {cfi, excerpt}
reconcileLayoutSettings
Reconciles the current chapters layout properies with the global layout properities.
Parameters
globalLayout
object The global layout settings object, chapter properties string
Returns object layoutProperties Object with layout properties
cfiFromRange
Get a CFI from a Range in the Section
Parameters
_range
range
Returns string cfi an EpubCFI string
cfiFromElement
Get a CFI from an Element in the Section
Parameters
el
element
Returns string cfi an EpubCFI string
unload
Unload the section document
Locations
Find Locations for a Book
Parameters
generate
Load all of sections in the book to generate locations
Parameters
chars
int how many chars to split on
Returns object locations
locationFromCfi
Get a location from an EpubCFI
Parameters
cfi
EpubCFI
Returns number
percentageFromCfi
Get a percentage position in locations from an EpubCFI
Parameters
cfi
EpubCFI
Returns number
percentageFromLocation
Get a percentage position from a location index
Parameters
loc
location
number
Returns number
cfiFromLocation
Get an EpubCFI from location index
Parameters
loc
number
Returns EpubCFI cfi
cfiFromPercentage
Get an EpubCFI from location percentage
Parameters
percentage
number
Returns EpubCFI cfi
load
Load locations from JSON
Parameters
locations
json
save
Save locations to JSON
Returns json
currentLocation
Get the current location
currentLocation
Set the current location
Parameters
curr
length
Locations length
Container
Handles Parsing and Accessing an Epub Container
Parameters
containerDocument
document? xml document
parse
Parse the Container XML
Parameters
containerDocument
document
Packaging
Open Packaging Format Parser
Parameters
packageDocument
document OPF XML
parse
Parse OPF XML
Parameters
packageDocument
document OPF XML
Returns object parsed package parts
load
Load JSON Manifest
Parameters
json
packageDocument
document OPF XML
Returns object parsed package parts
Navigation
Navigation Parser
Parameters
xml
document navigation html / xhtml / ncx
parse
Parse out the navigation items
Parameters
xml
document navigation html / xhtml / ncx
get
Get an item from the navigation
Parameters
target
string
Returns object navItem
landmark
Get a landmark by type List of types: https://idpf.github.io/epub-vocabs/structure/
Parameters
type
string
Returns object landmarkItem
load
Load Spine Items
Parameters
json
object the items to be loaded
Returns Array navItems
forEach
forEach pass through
Parameters
fn
Function function to run on each item
Returns method forEach loop
Resources
Handle Package Resources
Parameters
manifest
Manifestoptions
object?
createUrl
Create a url to a resource
Parameters
url
string
Returns Promise<string> Promise resolves with url string
replacements
Create blob urls for all the assets
Returns Promise returns replacement urls
relativeTo
Resolve all resources URLs relative to an absolute URL
Parameters
absolute
string to be resolved toresolver
resolver?
Returns Array<string> array with relative Urls
get
Get a URL for a resource
Parameters
path
string
Returns string url
substitute
Substitute urls in content, with replacements, relative to a url if provided
Parameters
Returns string content with urls substituted
PageList
Page List Parser
Parameters
xml
document?
parse
Parse PageList Xml
Parameters
xml
document
pageFromCfi
Get a PageList result from a EpubCFI
Parameters
cfi
string EpubCFI String
Returns number page
cfiFromPage
Get an EpubCFI from a Page List Item
Parameters
Returns string cfi
pageFromPercentage
Get a Page from Book percentage
Parameters
percent
number
Returns number page
percentageFromPage
Returns a value between 0 - 1 corresponding to the location of a page
Parameters
pg
number the page
Returns number percentage
percentageFromCfi
Returns a value between 0 - 1 corresponding to the location of a cfi
Parameters
cfi
string EpubCFI String
Returns number percentage
destroy
Destroy
Archive
Handles Unzipping a requesting files from an Epub Archive
open
Open an archive
Parameters
input
binaryisBase64
boolean? tells JSZip if the input data is base64 encoded
Returns Promise zipfile
openUrl
Load and Open an archive
Parameters
Returns Promise zipfile
request
Request a url from the archive
Parameters
Returns Promise<(Blob | string | JSON | Document | XMLDocument)>
getBlob
Get a Blob from Archive by Url
Parameters
Returns Blob
getText
Get Text from Archive by Url
Parameters
Returns string
getBase64
Get a base64 encoded result from Archive by Url
Parameters
Returns string base64 encoded
createUrl
Create a Url from an unarchived item
Parameters
url
stringoptions
Returns Promise url promise with Url string
revokeUrl
Revoke Temp Url for a achive item
Parameters
url
string url of the item in the archive
Rendition
Displays an Epub as a series of Views for each Section. Requires Manager and View class to handle specifics of rendering the section content.
Parameters
book
Bookoptions
object?options.width
number?options.height
number?options.ignoreClass
string? class for the cfi parser to ignoreoptions.manager
(string | function | object) (optional, default'default'
)options.view
(string | function) (optional, default'iframe'
)options.layout
string? layout to forceoptions.spread
string? force spread valueoptions.minSpreadWidth
number? overridden by spread: none (never) / both (always)options.stylesheet
string? url of stylesheet to be injectedoptions.resizeOnOrientationChange
boolean? false to disable orientation eventsoptions.script
string? url of script to be injected
setManager
Set the manager function
Parameters
manager
function
requireManager
Require the manager from passed string, or as a class function
Parameters
Returns method
requireView
Require the view from passed string, or as a class function
Parameters
Returns view
start
Start the rendering
Returns Promise rendering has started
attachTo
Call to attach the container to an element in the dom Container must be attached before rendering can begin
Parameters
element
element to attach to
Returns Promise
display
Display a point in the book The request will be added to the rendering Queue, so it will wait until book is opened, rendering started and all other rendering tasks have finished to be called.
Parameters
target
string Url or EpubCFI
Returns Promise
moveTo
Move the Rendition to a specific offset Usually you would be better off calling display()
Parameters
offset
object
resize
Trigger a resize of the views
Parameters
clear
Clear all rendered views
next
Go to the next "page" in the rendition
Returns Promise
prev
Go to the previous "page" in the rendition
Returns Promise
flow
Adjust the flow of the rendition to paginated or scrolled (scrolled-continuous vs scrolled-doc are handled by different view managers)
Parameters
flow
string
layout
Adjust the layout of the rendition to reflowable or pre-paginated
Parameters
settings
object
spread
Adjust if the rendition uses spreads
Parameters
spread
string none | auto (TODO: implement landscape, portrait, both)min
int min width to use spreads at
direction
Adjust the direction of the rendition
Parameters
dir
string
reportLocation
Report the current location
currentLocation
Get the Current Location object
Returns (displayedLocation | promise) location (may be a promise)
destroy
Remove and Clean Up the Rendition
getRange
Get a Range from a Visible CFI
Parameters
Returns range
getContents
Get the Contents object of each rendered view
views
Get the views member from the manager
Returns Views
hooks
Adds Hook methods to the Rendition prototype
Type: object
themes
Type: Themes
annotations
Type: Annotations
location
A Rendered Location Range
Properties
started
Hook
Hooks allow for injecting functions that must all complete in order before finishing They will execute in parallel but all must finish before continuing Functions may return a promise if they are asycn.
Parameters
context
any scope of this
Examples
this.content = new EPUBJS.Hook(this);
register
Adds a function to be run before a hook completes
Examples
this.content.register(function(){...});
trigger
Triggers a hook to run all functions
Examples
this.content.trigger(args).then(function(){...});
Queue
Queue for handling tasks one at a time
Parameters
context
scope what this will resolve to in the tasks
enqueue
Add an item to the queue
Returns Promise
dequeue
Run one item
Returns Promise
run
Run all tasks sequentially, at convince
Returns Promise
flush
Flush all, as quickly as possible
Returns Promise
clear
Clear all items in wait
length
Get the number of tasks in the queue
Returns number tasks
pause
Pause a running queue
stop
End the queue
Layout
Figures out the CSS values to apply for a layout
Parameters
settings
object
flow
Switch the flow between paginated and scrolled
Parameters
flow
string paginated | scrolled
Returns string simplified flow
spread
Switch between using spreads or not, and set the width at which they switch to single.
Parameters
Returns boolean spread true | false
calculate
Calculate the dimensions of the pagination
Parameters
_width
number width of the rendering_height
number height of the rendering_gap
number width of the gap between columns
format
Apply Css to a Document
Parameters
contents
Contents
Returns Promise
count
Count number of pages
Parameters
Returns {spreads: Number, pages: Number}
Themes
Themes to apply to displayed content
Parameters
rendition
Rendition
register
Add themes to be used by a rendition
Examples
themes.register("light", "http://example.com/light.css")
themes.register("light", { "body": { "color": "purple"}})
themes.register({ "light" : {...}, "dark" : {...}})
default
Add a default theme to be used by a rendition
Parameters
Examples
themes.register("http://example.com/default.css")
themes.register({ "body": { "color": "purple"}})
registerThemes
Register themes object
Parameters
themes
object
registerUrl
Register a url
Parameters
registerRules
Register rule
Parameters
select
Select a theme
Parameters
name
string
update
Update a theme
Parameters
name
string
inject
Inject all themes into contents
Parameters
contents
Contents
add
Add Theme to contents
Parameters
override
Add override
Parameters
overrides
Add all overrides
Parameters
contents
content
Content
fontSize
Adjust the font size of a rendition
Parameters
size
number
font
Adjust the font-family of a rendition
Parameters
f
string
Annotations
Handles managing adding & removing Annotations
Parameters
rendition
Rendition
add
Add an annotation to store
Parameters
type
string Type of annotation to add: "highlight", "underline", "mark"cfiRange
EpubCFI EpubCFI range to attach annotation todata
object Data to assign to annotationcb
function? Callback after annotation is addedclassName
string CSS class to assign to annotationstyles
object CSS styles to assign to annotation
Returns Annotation annotation
remove
Remove an annotation from store
Parameters
cfiRange
EpubCFI EpubCFI range the annotation is attached totype
string Type of annotation to add: "highlight", "underline", "mark"
highlight
Add a highlight to the store
Parameters
cfiRange
EpubCFI EpubCFI range to attach annotation todata
object Data to assign to annotationcb
function Callback after annotation is addedclassName
string CSS class to assign to annotationstyles
object CSS styles to assign to annotation
underline
Add a underline to the store
Parameters
cfiRange
EpubCFI EpubCFI range to attach annotation todata
object Data to assign to annotationcb
function Callback after annotation is addedclassName
string CSS class to assign to annotationstyles
object CSS styles to assign to annotation
mark
Add a mark to the store
Parameters
cfiRange
EpubCFI EpubCFI range to attach annotation todata
object Data to assign to annotationcb
function Callback after annotation is added
each
iterate over annotations in the store
show
[Not Implemented] Show annotations
hide
[Not Implemented] Hide annotations
Annotation
Annotation object
Parameters
$0
Object$0.type
$0.cfiRange
$0.data
$0.sectionIndex
$0.cb
$0.className
$0.styles
options
objectoptions.type
string Type of annotation to add: "highlight", "underline", "mark"options.cfiRange
EpubCFI EpubCFI range to attach annotation tooptions.data
object Data to assign to annotationoptions.sectionIndex
int Index in the Spine of the Section annotation belongs tooptions.cb
function? Callback after annotation is added
className
string CSS class to assign to annotationstyles
object CSS styles to assign to annotation
Returns Annotation annotation
update
Update stored data
Parameters
data
object
attach
Add to a view
Parameters
view
View
detach
Remove from a view
Parameters
view
View
text
[Not Implemented] Get text of an annotation
EpubCFI
Parsing and creation of EpubCFIs: http://www.idpf.org/epub/linking/cfi/epub-cfi.html
Implements:
- Character Offset: epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3)
- Simple Ranges : epubcfi(/6/4[chap01ref]!/4[body01]/10[para05],/2/1:1,/3:4)
Does Not Implement:
- Temporal Offset (~)
- Spatial Offset (@)
- Temporal-Spatial Offset (~ + @)
- Text Location Assertion ([)
Parameters
cfiFrom
(string | Range | Node)?base
(string | object)?ignoreClass
string? class to ignore when parsing DOM
parse
Parse a cfi string to a CFI object representation
Parameters
cfiStr
string
Returns object cfi
toString
Convert CFI to a epubcfi(...) string
Returns string epubcfi
compare
Compare which of two CFIs is earlier in the text
Parameters
cfiOne
cfiTwo
Returns number First is earlier = -1, Second is earlier = 1, They are equal = 0
fromRange
Create a CFI object from a Range
Parameters
Returns object cfi
fromNode
Create a CFI object from a Node
Parameters
Returns object cfi
toRange
Creates a DOM range representing a CFI
Parameters
Returns Range
isCfiString
Check if a string is wrapped with "epubcfi()"
Parameters
str
string
Returns boolean
collapse
Collapse a CFI Range to a single CFI Position
Parameters
toStart
boolean (optional, defaultfalse
)
Contents
Handles DOM manipulation, queries and events for View contents
Parameters
doc
document Documentcontent
element Parent Element (typically Body)cfiBase
string Section component of CFIssectionIndex
number Index in Spine of Conntent's Section
width
Get or Set width
Parameters
w
number?
Returns number width
height
Get or Set height
Parameters
h
number?
Returns number height
contentWidth
Get or Set width of the contents
Parameters
w
number?
Returns number width
contentHeight
Get or Set height of the contents
Parameters
h
number?
Returns number height
textWidth
Get the width of the text using Range
Returns number width
textHeight
Get the height of the text using Range
Returns number height
scrollWidth
Get documentElement scrollWidth
Returns number width
scrollHeight
Get documentElement scrollHeight
Returns number height
overflow
Set overflow css style of the contents
Parameters
overflow
string?
overflowX
Set overflowX css style of the documentElement
Parameters
overflow
string?
overflowY
Set overflowY css style of the documentElement
Parameters
overflow
string?
css
Set Css styles on the contents element (typically Body)
Parameters
viewport
Get or Set the viewport element
Parameters
options
object?
root
Get the documentElement
Returns element documentElement
locationOf
Get the location offset of a EpubCFI or an #id
Parameters
addStylesheet
Append a stylesheet link to the document head
Parameters
src
string url
addStylesheetRules
Append stylesheet rules to a generate stylesheet Array: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule Object: https://github.com/desirable-objects/json-to-css
Parameters
addScript
Append a script tag to the document head
Parameters
src
string url
Returns Promise loaded
addClass
Add a class to the contents container
Parameters
className
string
removeClass
Remove a class from the contents container
Parameters
className
removeClass
string
range
Get a Dom Range from EpubCFI
Parameters
Returns Range range
cfiFromRange
Get an EpubCFI from a Dom Range
Parameters
Returns EpubCFI cfi
cfiFromNode
Get an EpubCFI from a Dom node
Parameters
Returns EpubCFI cfi
size
Size the contents to a given width and height
Parameters
columns
Apply columns to the contents for pagination
Parameters
scaler
Scale contents from center
Parameters
fit
Fit contents into a fixed width and height
Parameters
direction
Set the direction of the text
Parameters
dir
string "rtl" | "ltr" (optional, default"ltr"
)
writingMode
Set the writingMode of the text
Parameters
mode
string "horizontal-tb" | "vertical-rl" | "vertical-lr" (optional, default"horizontal-tb"
)
listenedEvents
Get DOM events that are listened for and passed along
Mapping
Map text locations to CFI ranges
Parameters
layout
Layout Layout to applydirection
string Text direction (optional, default"ltr"
)axis
string vertical or horizontal axis (optional, default"horizontal"
)dev
boolean? toggle developer highlighting
section
Find CFI pairs for entire section at once
Parameters
view
page
Find CFI pairs for a page
Parameters
contents
Contents Contents from viewcfiBase
string string of the base for a cfistart
number position to start atend
number position to end at
axis
Set the axis for mapping
Parameters
axis
string horizontal | vertical
Returns boolean is it horizontal?
Core
Core Utilities and Helpers
requestAnimationFrame
Vendor prefixed requestAnimationFrame
Returns function requestAnimationFrame
uuid
Generates a UUID based on: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
Returns string uuid
documentHeight
Gets the height of a document
Returns number height
isElement
Checks if a node is an element
Parameters
obj
object
Returns boolean
isNumber
Parameters
n
any
Returns boolean
isFloat
Parameters
n
any
Returns boolean
prefixed
Get a prefixed css property
Parameters
unprefixed
string
Returns string
defaults
Apply defaults to an object
Parameters
obj
object
Returns object
extend
Extend properties of an object
Parameters
target
object
Returns object
insert
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
Parameters
Returns number location (in array)
locationOf
Finds where something would fit into a sorted array
Parameters
Returns number location (in array)
indexOfSorted
Finds index of something in a sorted array Returns -1 if not found
Parameters
Returns number index (in array) or -1
bounds
Find the bounds of an element taking padding and margin into account
Parameters
el
element
Returns {width: Number, height: Number}
borders
Find the bounds of an element taking padding, margin and borders into account
Parameters
el
element
Returns {width: Number, height: Number}
nodeBounds
Find the bounds of any node allows for getting bounds of text nodes by wrapping them in a range
Parameters
node
node
Returns BoundingClientRect
windowBounds
Find the equivelent of getBoundingClientRect of a browser window
Returns {width: Number, height: Number, top: Number, left: Number, right: Number, bottom: Number}
indexOfNode
Gets the index of a node in its parent
Parameters
Returns number index
indexOfTextNode
Gets the index of a text node in its parent
Parameters
textNode
node
Returns number index
indexOfElementNode
Gets the index of an element node in its parent
Parameters
elementNode
element
Returns number index
isXml
Check if extension is xml
Parameters
ext
string
Returns boolean
createBlob
Create a new blob
Parameters
content
anymime
string
Returns Blob
createBlobUrl
Create a new blob url
Parameters
content
anymime
string
Returns string url
revokeBlobUrl
Remove a blob url
Parameters
url
string
createBase64Url
Create a new base64 encoded url
Parameters
content
anymime
string
Returns string url
type
Get type of an object
Parameters
obj
object
Returns string type
parse
Parse xml (or html) markup
Parameters
Returns document document
qs
querySelector polyfill
Parameters
Returns element element
qsa
querySelectorAll polyfill
Parameters
Returns Array<element> elements
qsp
querySelector by property
Parameters
Returns Array<element> elements
sprint
Sprint through all text nodes in a document
Parameters
treeWalker
Create a treeWalker
Parameters
root
element element to start withfunc
function function to run on each elementfilter
(function | object) funtion or object to filter with
walk
Parameters
node
nodecallback
return
callback false for continue,true for break inside callback
blob2base64
Convert a blob to a base64 encoded string
Parameters
blob
Blog
Returns string
defer
Creates a new pending promise and provides methods to resolve or reject it. From: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#backwards_forwards_compatible
querySelectorByType
querySelector with filter by epub type
Parameters
Returns Array<element> elements
findChildren
Find direct decendents of an element
Parameters
el
element
Returns Array<element> children
parents
Find all parents (ancestors) of an element
Parameters
node
element
Returns Array<element> parents
filterChildren
Find all direct decendents of a specific type
Parameters
Returns Array<element> children
getParentByTagName
Filter all parents (ancestors) with tag name
Parameters
Returns Array<element> parents
RangeObject
Lightweight Polyfill for DOM Range