navigation.js 4.4 KB
Newer Older
1 2 3
var $ = require('jquery');
var url = require('url');

J
Johan Preynat 已提交
4 5
var events  = require('../core').events;
var state   = require('../core').state;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
var loading = require('./loading');


var usePushState = (typeof history.pushState !== 'undefined');

function handleNavigation(relativeUrl, push) {
    var uri = url.resolve(window.location.pathname, relativeUrl);

    if (!usePushState) {
        // Refresh the page to the new URL if pushState not supported
        location.href = relativeUrl;
        return;
    }

    return loading.show($.get(uri)
    .done(function (html) {
        // Push url to history
        if (push) history.pushState({ path: uri }, null, uri);

        // Replace html content
        html = html.replace( /<(\/?)(html|head|body)([^>]*)>/ig, function(a,b,c,d){
            return '<' + b + 'div' + ( b ? '' : ' data-element="' + c + '"' ) + d + '>';
        });

        var $page = $(html);
        var $pageHead = $page.find('[data-element=head]');
        var $pageBody = $page.find('.book');

        // Merge heads
        // !! Warning !!: we only update necessary portions to avoid strange behavior (page flickering etc ...)

        // Update title
        document.title = $pageHead.find('title').text();

        // Reference to $('head');
        var $head = $('head');

        // Update next & prev <link> tags
        // Remove old
        $head.find('link[rel=prev]').remove();
        $head.find('link[rel=next]').remove();

        // Add new next * prev <link> tags
        $head.append($pageHead.find('link[rel=prev]'));
        $head.append($pageHead.find('link[rel=next]'));

        // Merge body
        var bodyClass = $('.book').attr('class');
        var scrollPosition = $('.book-summary .summary').scrollTop();
        $pageBody.toggleClass('with-summary', $('.book').hasClass('with-summary'));

        $('.book').replaceWith($pageBody);
        $('.book').attr('class', bodyClass);
        $('.book-summary .summary').scrollTop(scrollPosition);

        // Update state
        state.update($('html'));
        preparePage();
    })
    .fail(function (e) {
        location.href = relativeUrl;
    }));
}

function updateNavigationPosition() {
    var bodyInnerWidth, pageWrapperWidth;

    bodyInnerWidth = parseInt($('.body-inner').css('width'), 10);
    pageWrapperWidth = parseInt($('.page-wrapper').css('width'), 10);
    $('.navigation-next').css('margin-right', (bodyInnerWidth - pageWrapperWidth) + 'px');
}

function notifyPageChange() {
    events.trigger('page.change');
}

function preparePage(notify) {
    var $bookBody = $('.book-body');
    var $bookInner = $bookBody.find('.body-inner');
    var $pageWrapper = $bookInner.find('.page-wrapper');

    // Update navigation position
    updateNavigationPosition();

    // Focus on content
    $pageWrapper.focus();

    // Reset scroll
    $bookInner.scrollTop(0);
    $bookBody.scrollTop(0);

    // Notify
    if (notify !== false) notifyPageChange();
}

function isLeftClickEvent(e) {
    return e.button === 0;
}

function isModifiedEvent(e) {
    return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
}

function handlePagination(e) {
    if (isModifiedEvent(e) || !isLeftClickEvent(e)) {
        return;
    }

    e.stopPropagation();
    e.preventDefault();

    var url = $(this).attr('href');
    if (url) handleNavigation(url, true);
}

function goNext() {
    var url = $('.navigation-next').attr('href');
    if (url) handleNavigation(url, true);
}

function goPrev() {
    var url = $('.navigation-prev').attr('href');
    if (url) handleNavigation(url, true);
}


function init() {
    // Prevent cache so that using the back button works
    // See: http://stackoverflow.com/a/15805399/983070
    $.ajaxSetup({
        cache: false
    });

    // Recreate first page when the page loads.
    history.replaceState({ path: window.location.href }, '');

    // Back Button Hijacking :(
    window.onpopstate = function (event) {
        if (event.state === null) {
            return;
        }
        return handleNavigation(event.state.path, false);
    };

    $(document).on('click', '.navigation-prev', handlePagination);
    $(document).on('click', '.navigation-next', handlePagination);
    $(document).on('click', '.summary [data-path] a', handlePagination);

    $(window).resize(updateNavigationPosition);

    // Prepare current page
    preparePage(false);
}

module.exports = {
    init: init,
    goNext: goNext,
    goPrev: goPrev,
    notify: notifyPageChange
};