Skip to content

Latest commit

 

History

History
2310 lines (1276 loc) · 76.1 KB

API.md

File metadata and controls

2310 lines (1276 loc) · 76.1 KB

ePub

Creates a new Book

Parameters

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 default
    • options.requestCredentials boolean send the xhr request withCredentials (optional, default undefined)
    • options.requestHeaders object send the xhr request headers (optional, default undefined)
    • options.encoding string optional to pass 'binary' or base64' for archived Epubs (optional, default binary)
    • options.replacements string use base64, blobUrl, or none for replacing assets in archived Epubs (optional, default none)
    • options.canonical method? optional function to determine canonical urls for a path
    • options.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 ArrayBuffer
  • what 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

Returns string the canonical path string

section

Gets a Section of the Book from the Spine Alias for book.spine.get

Parameters

Returns Section

renderTo

Sugar to render a book to an element

Parameters

Returns Rendition

setRequestCredentials

Set if request should use withCredentials

Parameters

setRequestHeaders

Set headers request should use

Parameters

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

  • cfiRange EpubCFI a epub cfi range

Returns Range

key

Generates the Book Key using the identifier 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

Returns string url

relative

Resolve a path relative to the url

Parameters

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

Returns object

isAbsolute

Parameters

Returns boolean

isDirectory

Check if path ends with a directory

Parameters

Returns boolean

resolve

Resolve a path against the directory of the Path

https://nodejs.org/api/path.html#path_path_resolve_paths

Parameters

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

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 Packaging
  • resolver method URL resolver
  • canonical 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 equivalent to a Chapter

Parameters

  • item object The spine item representing the section
  • hooks object hooks for serialize and content

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 properties with the global layout properties.

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

Returns string cfi an EpubCFI string

cfiFromElement

Get a CFI from an Element in the Section

Parameters

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

Returns number

percentageFromCfi

Get a percentage position in locations from an EpubCFI

Parameters

Returns number

percentageFromLocation

Get a percentage position from a location index

Parameters

Returns number

cfiFromLocation

Get an EpubCFI from location index

Parameters

Returns EpubCFI cfi

cfiFromPercentage

Get an EpubCFI from location percentage

Parameters

Returns EpubCFI cfi

load

Load locations from JSON

Parameters

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

Packaging

Open Packaging Format Parser

Parameters

parse

Parse OPF XML

Parameters

Returns object parsed package parts

load

Load JSON Manifest

Parameters

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

Returns object navItem

landmark

Get a landmark by type List of types: https://idpf.github.io/epub-vocabs/structure/

Parameters

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 Manifest
  • options object?
    • options.replacements string (optional, default "base64")
    • options.archive Archive?
    • options.resolver method?

createUrl

Create a url to a resource

Parameters

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 to
  • resolver resolver?

Returns Array<string> array with relative Urls

get

Get a URL for a resource

Parameters

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

parse

Parse PageList Xml

Parameters

pageFromCfi

Get a PageList result from a EpubCFI

Parameters

Returns number page

cfiFromPage

Get an EpubCFI from a Page List Item

Parameters

Returns string cfi

pageFromPercentage

Get a Page from Book percentage

Parameters

Returns number page

percentageFromPage

Returns a value between 0 - 1 corresponding to the location of a page

Parameters

Returns number percentage

percentageFromCfi

Returns a value between 0 - 1 corresponding to the location of a cfi

Parameters

Returns number percentage

destroy

Destroy

Archive

Handles Unzipping a requesting files from an Epub Archive

open

Open an archive

Parameters

  • input binary
  • isBase64 boolean? tells JSZip if the input data is base64 encoded

Returns Promise zipfile

openUrl

Load and Open an archive

Parameters

  • zipUrl string
  • isBase64 boolean? tells JSZip if the input data is base64 encoded

Returns Promise zipfile

request

Request a url from the archive

Parameters

  • url string a url to request from the archive
  • type string? specify the type of the returned result

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

Returns Promise url promise with Url string

revokeUrl

Revoke Temp Url for a archive 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 Book
  • options object?
    • options.width number?
    • options.height number?
    • options.ignoreClass string? class for the cfi parser to ignore
    • options.manager (string | function | object) (optional, default 'default')
    • options.view (string | function) (optional, default 'iframe')
    • options.layout string? layout to force
    • options.spread string? force spread value
    • options.minSpreadWidth number? overridden by spread: none (never) / both (always)
    • options.stylesheet string? url of stylesheet to be injected
    • options.resizeOnOrientationChange boolean? false to disable orientation events
    • options.script string? url of script to be injected

setManager

Set the manager function

Parameters

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

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

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

layout

Adjust the layout of the rendition to reflowable or pre-paginated

Parameters

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

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

Returns Array<Contents>

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

  • 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
    • settings.layout string (optional, default 'reflowable')
    • settings.spread string?
    • settings.minSpreadWidth number (optional, default 800)
    • settings.evenSpreads boolean (optional, default false)

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

  • spread string "none" | "always" | "auto"
  • min number integer in pixels

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

Returns Promise

count

Count number of pages

Parameters

Returns {spreads: Number, pages: Number}

Themes

Themes to apply to displayed content

Parameters

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

registerUrl

Register a url

Parameters

registerRules

Register rule

Parameters

select

Select a theme

Parameters

update

Update a theme

Parameters

inject

Inject all themes into contents

Parameters

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

font

Adjust the font-family of a rendition

Parameters

Annotations

Handles managing adding & removing Annotations

Parameters

add

Add an annotation to store

Parameters

  • type string Type of annotation to add: "highlight", "underline", "mark"
  • cfiRange EpubCFI EpubCFI range to attach annotation to
  • data object Data to assign to annotation
  • cb function? Callback after annotation is added
  • className string CSS class to assign to annotation
  • styles 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 to
  • type string Type of annotation to add: "highlight", "underline", "mark"

highlight

Add a highlight to the store

Parameters

  • cfiRange EpubCFI EpubCFI range to attach annotation to
  • data object Data to assign to annotation
  • cb function Callback after annotation is added
  • className string CSS class to assign to annotation
  • styles object CSS styles to assign to annotation

underline

Add a underline to the store

Parameters

  • cfiRange EpubCFI EpubCFI range to attach annotation to
  • data object Data to assign to annotation
  • cb function Callback after annotation is added
  • className string CSS class to assign to annotation
  • styles object CSS styles to assign to annotation

mark

Add a mark to the store

Parameters

  • cfiRange EpubCFI EpubCFI range to attach annotation to
  • data object Data to assign to annotation
  • cb 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 object
    • options.type string Type of annotation to add: "highlight", "underline", "mark"
    • options.cfiRange EpubCFI EpubCFI range to attach annotation to
    • options.data object Data to assign to annotation
    • options.sectionIndex int Index in the Spine of the Section annotation belongs to
    • options.cb function? Callback after annotation is added
  • className string CSS class to assign to annotation
  • styles object CSS styles to assign to annotation

Returns Annotation annotation

update

Update stored data

Parameters

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

parse

Parse a cfi string to a CFI object representation

Parameters

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

Returns boolean

collapse

Collapse a CFI Range to a single CFI Position

Parameters

  • toStart boolean (optional, default false)

Contents

Handles DOM manipulation, queries and events for View contents

Parameters

  • doc document Document
  • content element Parent Element (typically Body)
  • cfiBase string Section component of CFIs
  • sectionIndex number Index in Spine of Conntent's Section

width

Get or Set width

Parameters

Returns number width

height

Get or Set height

Parameters

Returns number height

contentWidth

Get or Set width of the contents

Parameters

Returns number width

contentHeight

Get or Set height of the contents

Parameters

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

overflowX

Set overflowX css style of the documentElement

Parameters

overflowY

Set overflowY css style of the documentElement

Parameters

css

Set Css styles on the contents element (typically Body)

Parameters

viewport

Get or Set the viewport element

Parameters

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

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

Returns Promise loaded

addClass

Add a class to the contents container

Parameters

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 apply
  • direction 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 view
  • cfiBase string string of the base for a cfi
  • start number position to start at
  • end 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

Returns boolean

isNumber

Parameters

  • n any

Returns boolean

isFloat

Parameters

  • n any

Returns boolean

prefixed

Get a prefixed css property

Parameters

Returns string

defaults

Apply defaults to an object

Parameters

Returns object

extend

Extend properties of an object

Parameters

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

Returns {width: Number, height: Number}

borders

Find the bounds of an element taking padding, margin and borders into account

Parameters

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

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

Returns number index

indexOfElementNode

Gets the index of an element node in its parent

Parameters

Returns number index

isXml

Check if extension is xml

Parameters

Returns boolean

createBlob

Create a new blob

Parameters

Returns Blob

createBlobUrl

Create a new blob url

Parameters

Returns string url

revokeBlobUrl

Remove a blob url

Parameters

createBase64Url

Create a new base64 encoded url

Parameters

Returns string url

type

Get type of an object

Parameters

Returns string type

parse

Parse xml (or html) markup

Parameters

  • markup string
  • mime string
  • forceXMLDom boolean force using xmlDom to parse instead of native parser

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

  • root element element to start with
  • func function function to run on each element

treeWalker

Create a treeWalker

Parameters

walk

Parameters

  • node node
  • callback
  • 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 descendents of an element

Parameters

Returns Array<element> children

parents

Find all parents (ancestors) of an element

Parameters

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