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

var loading = require('./loading');
S
Samy Pesse 已提交
5 6
var platform = require('./platform');

J
Johan Preynat 已提交
7
var gitbook = window.gitbook;
8 9 10

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

S
Samy Pesse 已提交
11 12 13 14 15 16 17 18 19 20 21
/*
    Get current scroller element
*/
function getScroller() {
    if (platform.isMobile()) {
        return $('.book-body');
    } else {
        return $('.body-inner');
    }
}

22 23 24 25
/*
    Scroll to a specific hash tag in the content
*/
function scrollToHash(hash) {
S
Samy Pesse 已提交
26
    var $scroller = getScroller();
27 28 29
    var dest = 0;

    if (hash) {
S
Samy Pesse 已提交
30
        dest = $scroller.find(hash).position().top;
31 32
    }

S
Samy Pesse 已提交
33
    $scroller.animate({
34 35 36 37 38 39 40
        scrollTop: dest
    }, 800, 'swing');
}

/*
    Handle a change of url withotu refresh the whole page
*/
S
Samy Pesse 已提交
41
var prevUri = location.href;
42
function handleNavigation(relativeUrl, push) {
43 44
    var prevUriParsed = url.parse(prevUri);

45
    var uri = url.resolve(window.location.pathname, relativeUrl);
46 47 48 49 50 51 52 53
    var uriParsed = url.parse(uri);
    var hash = uriParsed.hash;

    // Is it the same url (just hash changed?)
    var pathHasChanged = (uriParsed.pathname !== prevUriParsed.pathname);

    // Is it an absolute url
    var isAbsolute = Boolean(uriParsed.hostname);
54

55
    if (!usePushState || isAbsolute) {
56 57 58 59 60
        // Refresh the page to the new URL if pushState not supported
        location.href = relativeUrl;
        return;
    }

61 62 63 64 65 66
    // Don't fetch same page
    if (!pathHasChanged) {
        if (push) history.pushState({ path: uri }, null, uri);
        return scrollToHash(hash);
    }

S
Samy Pesse 已提交
67
    prevUri = uri;
S
Samy Pesse 已提交
68 69 70 71 72 73 74

    var promise = $.Deferred(function(deferred) {
        $.ajax({
            type: 'GET',
            url: uri,
            cache: true,
            headers:{
75
                'Access-Control-Expose-Headers': 'X-Current-Location'
S
Samy Pesse 已提交
76 77
            },
            success: function(html, status, xhr) {
78 79
                // For GitBook.com, we handle redirection signaled by the server
                var responseURL = xhr.getResponseHeader('X-Current-Location') || uri;
S
Samy Pesse 已提交
80 81 82 83 84 85

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

86 87 88
                var $page = $(html),
                    $pageBody = $page.find('.book'),
                    $pageHead;
S
Samy Pesse 已提交
89 90 91 92 93 94 95 96 97 98

                // We only use history.pushState for pages generated with GitBook
                if ($pageBody.length === 0) {
                    var err = new Error('Invalid gitbook page, redirecting...');
                    return deferred.reject(err);
                }

                // Push url to history
                if (push) {
                    history.pushState({
99 100
                        path: responseURL
                    }, null, responseURL);
S
Samy Pesse 已提交
101 102
                }

103 104 105 106 107
                // Force reparsing HTML to prevent wrong URLs in Safari
                $page = $(html);
                $pageHead = $page.find('[data-element=head]');
                $pageBody = $page.find('.book');

S
Samy Pesse 已提交
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
                // 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').scrollTop();

                $pageBody.toggleClass('with-summary', $('.book').hasClass('with-summary'));

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

                // Scroll to hashtag position
                if (hash) {
                    scrollToHash(hash);
                }

                // Update state
                gitbook.state.$book = $('.book');
                preparePage(!hash);

                deferred.resolve();
            }
147
        });
S
Samy Pesse 已提交
148
    }).promise();
149

S
Samy Pesse 已提交
150 151 152 153 154


    return loading.show(
        promise
        .fail(function (e) {
155 156
            console.log(e); // eslint-disable-line no-console
            // location.href = relativeUrl;
S
Samy Pesse 已提交
157 158
        })
    );
159 160 161 162 163 164 165 166 167 168
}

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');
}

169
function preparePage(resetScroll) {
170 171 172 173 174 175 176 177 178 179 180
    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
181
    if (resetScroll !== false) $bookInner.scrollTop(0);
182 183 184 185 186 187 188 189 190 191 192
    $bookBody.scrollTop(0);
}

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

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

193 194 195 196 197 198 199 200
/*
    Handle click on a link
*/
function handleLinkClick(e) {
    var $this = $(this);
    var target = $this.attr('target');

    if (isModifiedEvent(e) || !isLeftClickEvent(e) || target) {
201 202 203 204 205 206
        return;
    }

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

207
    var url = $this.attr('href');
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    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;
        }
S
Samy Pesse 已提交
237

238 239 240
        return handleNavigation(event.state.path, false);
    };

241 242 243 244
    $(document).on('click', '.navigation-prev', handleLinkClick);
    $(document).on('click', '.navigation-next', handleLinkClick);
    $(document).on('click', '.summary [data-path] a', handleLinkClick);
    $(document).on('click', '.page-inner a', handleLinkClick);
245 246 247 248

    $(window).resize(updateNavigationPosition);

    // Prepare current page
249
    preparePage();
250 251 252 253 254
}

module.exports = {
    init: init,
    goNext: goNext,
S
Samy Pessé 已提交
255
    goPrev: goPrev
256
};