Skip to content

Tips and Tricks (v0.3)

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

Here are some useful snippets for v0.3.

Searching the entire book

By @geek1011.

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

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