navigation.js 6.8 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 86 87 88 89 90 91 92 93 94 95 96 97 98

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

                // 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 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
                }

                // 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();
            }
142
        });
S
Samy Pesse 已提交
143
    }).promise();
144

S
Samy Pesse 已提交
145 146 147 148 149 150 151 152 153


    return loading.show(
        promise
        .fail(function (e) {
            console.log(e);
            //location.href = relativeUrl;
        })
    );
154 155 156 157 158 159 160 161 162 163
}

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

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

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

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

188 189 190 191 192 193 194 195
/*
    Handle click on a link
*/
function handleLinkClick(e) {
    var $this = $(this);
    var target = $this.attr('target');

    if (isModifiedEvent(e) || !isLeftClickEvent(e) || target) {
196 197 198 199 200 201
        return;
    }

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

202
    var url = $this.attr('href');
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    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 已提交
232

233 234 235
        return handleNavigation(event.state.path, false);
    };

236 237 238 239
    $(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);
240 241 242 243

    $(window).resize(updateNavigationPosition);

    // Prepare current page
244
    preparePage();
245 246 247 248 249
}

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