API.md
December 16, 2021 ยท View on GitHub
ePub
Creates a new Book
Parameters
url(string | ArrayBuffer) URL, Path or ArrayBufferoptionsobject 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
urlstring?optionsobject?options.requestMethodmethod? a request function to use instead of the defaultoptions.requestCredentialsboolean send the xhr request withCredentials (optional, defaultundefined)options.requestHeadersobject send the xhr request headers (optional, defaultundefined)options.encodingstring optional to pass 'binary' or base64' for archived Epubs (optional, defaultbinary)options.replacementsstring use base64, blobUrl, or none for replacing assets in archived Epubs (optional, defaultnone)options.canonicalmethod? optional function to determine canonical urls for a pathoptions.openAsstring? 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 ArrayBufferwhatstring 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
pathstring 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
pathstring
Returns string the canonical path string
section
Gets a Section of the Book from the Spine
Alias for book.spine.get
Parameters
targetstring
Returns Section
renderTo
Sugar to render a book to an element
Parameters
Returns Rendition
setRequestCredentials
Set if request should use withCredentials
Parameters
credentialsboolean
setRequestHeaders
Set headers request should use
Parameters
headersobject
coverUrl
Get the cover url if there is a cover
Returns Promise<?string> Promise resolves with maybe a url string
getRange
Find a DOM Range for a given CFI Range
Parameters
cfiRangeEpubCFI a epub cfi range
Returns Range
key
Generates the Book Key using the identifier in the manifest or other string provided
Parameters
identifierstring? 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
urlStringstring a url string (relative or absolute)baseStringstring? optional base for the url, default to window.location.href
path
Returns Path
resolve
Resolves a relative path to a absolute url
Parameters
whatstring
Returns string url
relative
Resolve a path relative to the url
Parameters
whatstring
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
pathStringstring a url string (relative or absolute)
parse
Parse the path: https://nodejs.org/api/path.html#path_path_parse_path
Parameters
whatstring
Returns object
isAbsolute
Parameters
whatstring
Returns boolean
isDirectory
Check if path ends with a directory
Parameters
whatstring
Returns boolean
resolve
Resolve a path against the directory of the Path
https://nodejs.org/api/path.html#path_path_resolve_paths
Parameters
whatstring
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
whatstring
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
_packagePackagingresolvermethod URL resolvercanonicalmethod 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 equivalent to a Chapter
Parameters
load
Load the section from its url
Parameters
_requestmethod? a request method to use for loading
Returns document a promise with the xml document
render
Render the contents of a section
Parameters
_requestmethod? a request method to use for loading
Returns string output a serialized XML Document
find
Find a string in a section
Parameters
_querystring The query string to find
Returns Array<object> A list of matches, with form {cfi, excerpt}
reconcileLayoutSettings
Reconciles the current chapters layout properties with the global layout properties.
Parameters
globalLayoutobject 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
_rangerange
Returns string cfi an EpubCFI string
cfiFromElement
Get a CFI from an Element in the Section
Parameters
elelement
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
charsint how many chars to split on
Returns object locations
locationFromCfi
Get a location from an EpubCFI
Parameters
cfiEpubCFI
Returns number
percentageFromCfi
Get a percentage position in locations from an EpubCFI
Parameters
cfiEpubCFI
Returns number
percentageFromLocation
Get a percentage position from a location index
Parameters
loclocationnumber
Returns number
cfiFromLocation
Get an EpubCFI from location index
Parameters
locnumber
Returns EpubCFI cfi
cfiFromPercentage
Get an EpubCFI from location percentage
Parameters
percentagenumber
Returns EpubCFI cfi
load
Load locations from JSON
Parameters
locationsjson
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
containerDocumentdocument? xml document
parse
Parse the Container XML
Parameters
containerDocumentdocument
Packaging
Open Packaging Format Parser
Parameters
packageDocumentdocument OPF XML
parse
Parse OPF XML
Parameters
packageDocumentdocument OPF XML
Returns object parsed package parts
load
Load JSON Manifest
Parameters
jsonpackageDocumentdocument OPF XML
Returns object parsed package parts
Navigation
Navigation Parser
Parameters
xmldocument navigation html / xhtml / ncx
parse
Parse out the navigation items
Parameters
xmldocument navigation html / xhtml / ncx
get
Get an item from the navigation
Parameters
targetstring
Returns object navItem
landmark
Get a landmark by type List of types: https://idpf.github.io/epub-vocabs/structure/
Parameters
typestring
Returns object landmarkItem
load
Load Spine Items
Parameters
jsonobject the items to be loaded
Returns Array navItems
forEach
forEach pass through
Parameters
fnFunction function to run on each item
Returns method forEach loop
Resources
Handle Package Resources
Parameters
manifestManifestoptionsobject?
createUrl
Create a url to a resource
Parameters
urlstring
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
absolutestring to be resolved toresolverresolver?
Returns Array<string> array with relative Urls
get
Get a URL for a resource
Parameters
pathstring
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
xmldocument?
parse
Parse PageList Xml
Parameters
xmldocument
pageFromCfi
Get a PageList result from a EpubCFI
Parameters
cfistring 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
percentnumber
Returns number page
percentageFromPage
Returns a value between 0 - 1 corresponding to the location of a page
Parameters
pgnumber the page
Returns number percentage
percentageFromCfi
Returns a value between 0 - 1 corresponding to the location of a cfi
Parameters
cfistring EpubCFI String
Returns number percentage
destroy
Destroy
Archive
Handles Unzipping a requesting files from an Epub Archive
open
Open an archive
Parameters
inputbinaryisBase64boolean? 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
urlstringoptions
Returns Promise url promise with Url string
revokeUrl
Revoke Temp Url for a archive item
Parameters
urlstring 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
bookBookoptionsobject?options.widthnumber?options.heightnumber?options.ignoreClassstring? class for the cfi parser to ignoreoptions.manager(string | function | object) (optional, default'default')options.view(string | function) (optional, default'iframe')options.layoutstring? layout to forceoptions.spreadstring? force spread valueoptions.minSpreadWidthnumber? overridden by spread: none (never) / both (always)options.stylesheetstring? url of stylesheet to be injectedoptions.resizeOnOrientationChangeboolean? false to disable orientation eventsoptions.scriptstring? url of script to be injected
setManager
Set the manager function
Parameters
managerfunction
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
elementelement 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
targetstring Url or EpubCFI
Returns Promise
moveTo
Move the Rendition to a specific offset Usually you would be better off calling display()
Parameters
offsetobject
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
flowstring
layout
Adjust the layout of the rendition to reflowable or pre-paginated
Parameters
settingsobject
spread
Adjust if the rendition uses spreads
Parameters
spreadstring none | auto (TODO: implement landscape, portrait, both)minint min width to use spreads at
direction
Adjust the direction of the rendition
Parameters
dirstring
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 async.
Parameters
contextany 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
contextscope 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
settingsobject
flow
Switch the flow between paginated and scrolled
Parameters
flowstring 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
_widthnumber width of the rendering_heightnumber height of the rendering_gapnumber width of the gap between columns
format
Apply Css to a Document
Parameters
contentsContents
Returns Promise
count
Count number of pages
Parameters
Returns {spreads: Number, pages: Number}
Themes
Themes to apply to displayed content
Parameters
renditionRendition
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
themesobject
registerUrl
Register a url
Parameters
registerRules
Register rule
Parameters
select
Select a theme
Parameters
namestring
update
Update a theme
Parameters
namestring
inject
Inject all themes into contents
Parameters
contentsContents
add
Add Theme to contents
Parameters
override
Add override
Parameters
overrides
Add all overrides
Parameters
contentscontentContent
fontSize
Adjust the font size of a rendition
Parameters
sizenumber
font
Adjust the font-family of a rendition
Parameters
fstring
Annotations
Handles managing adding & removing Annotations
Parameters
renditionRendition
add
Add an annotation to store
Parameters
typestring Type of annotation to add: "highlight", "underline", "mark"cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction? Callback after annotation is addedclassNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
Returns Annotation annotation
remove
Remove an annotation from store
Parameters
cfiRangeEpubCFI EpubCFI range the annotation is attached totypestring Type of annotation to add: "highlight", "underline", "mark"
highlight
Add a highlight to the store
Parameters
cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction Callback after annotation is addedclassNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
underline
Add a underline to the store
Parameters
cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction Callback after annotation is addedclassNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
mark
Add a mark to the store
Parameters
cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction 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
$0Object$0.type$0.cfiRange$0.data$0.sectionIndex$0.cb$0.className$0.styles
optionsobjectoptions.typestring Type of annotation to add: "highlight", "underline", "mark"options.cfiRangeEpubCFI EpubCFI range to attach annotation tooptions.dataobject Data to assign to annotationoptions.sectionIndexint Index in the Spine of the Section annotation belongs tooptions.cbfunction? Callback after annotation is added
classNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
Returns Annotation annotation
update
Update stored data
Parameters
dataobject
attach
Add to a view
Parameters
viewView
detach
Remove from a view
Parameters
viewView
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)?ignoreClassstring? class to ignore when parsing DOM
parse
Parse a cfi string to a CFI object representation
Parameters
cfiStrstring
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
cfiOnecfiTwo
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
strstring
Returns boolean
collapse
Collapse a CFI Range to a single CFI Position
Parameters
toStartboolean (optional, defaultfalse)
Contents
Handles DOM manipulation, queries and events for View contents
Parameters
docdocument Documentcontentelement Parent Element (typically Body)cfiBasestring Section component of CFIssectionIndexnumber Index in Spine of Conntent's Section
width
Get or Set width
Parameters
wnumber?
Returns number width
height
Get or Set height
Parameters
hnumber?
Returns number height
contentWidth
Get or Set width of the contents
Parameters
wnumber?
Returns number width
contentHeight
Get or Set height of the contents
Parameters
hnumber?
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
overflowstring?
overflowX
Set overflowX css style of the documentElement
Parameters
overflowstring?
overflowY
Set overflowY css style of the documentElement
Parameters
overflowstring?
css
Set Css styles on the contents element (typically Body)
Parameters
viewport
Get or Set the viewport element
Parameters
optionsobject?
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
srcstring 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
srcstring url
Returns Promise loaded
addClass
Add a class to the contents container
Parameters
classNamestring
removeClass
Remove a class from the contents container
Parameters
classNameremoveClassstring
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
dirstring "rtl" | "ltr" (optional, default"ltr")
writingMode
Set the writingMode of the text
Parameters
modestring "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
layoutLayout Layout to applydirectionstring Text direction (optional, default"ltr")axisstring vertical or horizontal axis (optional, default"horizontal")devboolean? toggle developer highlighting
section
Find CFI pairs for entire section at once
Parameters
view
page
Find CFI pairs for a page
Parameters
contentsContents Contents from viewcfiBasestring string of the base for a cfistartnumber position to start atendnumber position to end at
axis
Set the axis for mapping
Parameters
axisstring 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
objobject
Returns boolean
isNumber
Parameters
nany
Returns boolean
isFloat
Parameters
nany
Returns boolean
prefixed
Get a prefixed css property
Parameters
unprefixedstring
Returns string
defaults
Apply defaults to an object
Parameters
objobject
Returns object
extend
Extend properties of an object
Parameters
targetobject
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
elelement
Returns {width: Number, height: Number}
borders
Find the bounds of an element taking padding, margin and borders into account
Parameters
elelement
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
nodenode
Returns BoundingClientRect
windowBounds
Find the equivalent 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
textNodenode
Returns number index
indexOfElementNode
Gets the index of an element node in its parent
Parameters
elementNodeelement
Returns number index
isXml
Check if extension is xml
Parameters
extstring
Returns boolean
createBlob
Create a new blob
Parameters
contentanymimestring
Returns Blob
createBlobUrl
Create a new blob url
Parameters
contentanymimestring
Returns string url
revokeBlobUrl
Remove a blob url
Parameters
urlstring
createBase64Url
Create a new base64 encoded url
Parameters
contentanymimestring
Returns string url
type
Get type of an object
Parameters
objobject
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
rootelement element to start withfuncfunction function to run on each elementfilter(function | object) function or object to filter with
walk
Parameters
nodenodecallbackreturncallback false for continue,true for break inside callback
blob2base64
Convert a blob to a base64 encoded string
Parameters
blobBlog
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 descendents of an element
Parameters
elelement
Returns Array<element> children
parents
Find all parents (ancestors) of an element
Parameters
nodeelement
Returns Array<element> parents
filterChildren
Find all direct descendents 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