Skip to content

Tips and Tricks (v0.3)

Patrick G edited this page May 21, 2018 · 6 revisions

Here are some useful snippets for v0.3.

Searching the entire book

By @geek1011.

function doSearch(q) {
    return Promise.all(
        book.spine.spineItems.map(item => item.load(book.load.bind(book)).then(item.find.bind(item, q)).finally(item.unload.bind(item)))
    ).then(results => Promise.resolve([].concat.apply([], results)));
};

Searching the current chapter

By @geek1011.

function doChapterSearch(q) {
    let item = book.spine.get(rendition.location.start.cfi);
    return item.load(book.load.bind(book)).then(item.find.bind(item, q)).finally(item.unload.bind(item));
};

Swipe to turn pages

By @geek1011. Note that this does not work on Chrome (it would need to use the new Pointer events for that).

rendition.on("displayed", event => {
    let start = null
    let end = null;
    const el = event.document.documentElement;

    el.addEventListener('touchstart', event => {
        start = event.changedTouches[0];
    });
    el.addEventListener('touchend', event => {
        end = event.changedTouches[0];

        let hr = (end.screenX - start.screenX) / el.getBoundingClientRect().width;
        let vr = (end.screenY - start.screenY) / el.getBoundingClientRect().height;

        if (hr > vr && hr > 0.25) return rendition.prev();
        if (hr < vr && hr < -0.25) return rendition.next();
        if (vr > hr && vr > 0.25) return;
        if (vr < hr && vr < -0.25) return;
    });
});

Generating and saving locations

By @geek1011. You can change chars to change the break point.

book.ready.then(() => {
    let chars = 1650
    let key = `${book.key()}:locations-${chars}`;
    let stored = localStorage.getItem(key);

    if (stored) return book.locations.load(stored);
    return book.locations.generate(chars).then(() => {
        localStorage.setItem(key, book.locations.save());
    }).catch(err => console.error("error generating locations", err));
});

Turning pages with arrow keys

By @geek1011.

rendition.on("keyup", event => {
    let kc = event.keyCode || event.which;
    if (kc == 37) rendition.prev();
    if (kc == 39) rendition.next();
});
Clone this wiki locally