doc.js 36.8 KB
Newer Older
C
Catouse 已提交
1 2
(function(window, $)
{
C
Catouse 已提交
3
    'use strict';
C
Catouse 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16
    // Polyfill
    if (!String.prototype.endsWith) {
        String.prototype.endsWith = function(searchString, position) {
            var subjectString = this.toString();
            if (position === undefined || position > subjectString.length) {
                position = subjectString.length;
            }
            position -= searchString.length;
            var lastIndex = subjectString.indexOf(searchString, position);
            return lastIndex !== -1 && lastIndex === position;
        };
    }

C
Catouse 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        };
    }

    if (!String.prototype.includes) {
        String.prototype.includes = function() {
            return String.prototype.indexOf.apply(this, arguments) !== -1;
        };
    }

C
Catouse 已提交
30
    var saveTraffic = false;
C
Catouse 已提交
31 32
    var debug = 1;
    if(debug) console.error("DEBUG ENABLED.");
C
Catouse 已提交
33 34

    var chapters = {
C
Catouse 已提交
35
        learn: {col: 1}, 
C
Catouse 已提交
36 37 38 39 40 41
        start: {col: 1}, 
        basic: {col: 1}, 
        control: {col: 2}, 
        component: {col: 2}, 
        javascript: {col: 3}, 
        view: {col: 3}
C
Catouse 已提交
42 43
    };
    var LAST_RELOAD_ANIMATE_ID = 'lastReloadAnimate';
C
Catouse 已提交
44
    var LAST_QUERY_ID = 'LAST_QUERY_ID';
C
Catouse 已提交
45
    var INDEX_JSON = 'index.json';
C
Catouse 已提交
46
    var UNDEFINED = undefined;
C
Catouse 已提交
47
    var PAGE_SHOW_FULL = 'page-show-full';
C
Catouse 已提交
48 49
    var dataVersion;
    var storageEnable;
C
Catouse 已提交
50
    var dataset = {
C
Catouse 已提交
51
        // 'index.json': null
C
Catouse 已提交
52 53 54
    };
    if(debug) window.dataset = dataset;

C
Catouse 已提交
55
    var sectionsShowed;
C
Catouse 已提交
56
    var scrollBarWidth = -1;
C
Catouse 已提交
57
    var bestPageWidth = 1120;
C
Catouse 已提交
58 59
    var $body, $window, $grid, $sectionTemplate,
        $queryInput, $chapters, $chaptersCols,
C
Catouse 已提交
60
        $choosedSection, $page, $pageHeader, $pageContent, 
C
Catouse 已提交
61
        $pageContainer, $pageBody, $navbar,
C
Catouse 已提交
62
        $header, $sections, $chapterHeadings; // elements
C
Catouse 已提交
63

C
Catouse 已提交
64 65 66 67 68 69 70
    var limitString = function(str, len) {
        if(str && str.length > len) {
            return str.substr(0, len) + '...[' + str.length + ']';
        }
        return str;
    };

C
Catouse 已提交
71 72 73 74 75 76 77
    var getQueryString = function(name)
    {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    };

C
Catouse 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    var checkScrollbar = function()
    {
        if (document.body.clientWidth >= window.innerWidth) return;

        if(scrollBarWidth < 0) {
            var scrollDiv = document.createElement('div');
            scrollDiv.className = 'modal-scrollbar-measure';
            $body.append(scrollDiv);
            scrollBarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
            $body[0].removeChild(scrollDiv);
        }

        if (scrollBarWidth) {
            var bodyPad = parseInt(($body.css('padding-right') || 0), 10);
            $body.css('padding-right', bodyPad + scrollBarWidth);
C
Catouse 已提交
93
            $navbar.css('padding-right', scrollBarWidth);
C
Catouse 已提交
94 95 96 97 98 99
        }
    };

    var resetScrollbar = function()
    {
        $body.css('padding-right', '');
C
Catouse 已提交
100
        $navbar.css('padding-right', '');
C
Catouse 已提交
101 102
    };

C
Catouse 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115
    var loadData = function(url, callback) {
        var cacheData = dataset[url];
        var isHasCache = cacheData && cacheData.version;
        var isIndexJson = url === INDEX_JSON;
        if(!isHasCache && storageEnable) {
            var storedData = $.store.get('//' + url, null);
            if(storedData !== null) {
                var storedVersion = $.store.get('//' + url + '::V');
                if(storedVersion) {
                    cacheData = {data: storedData, version: storedVersion};
                    dataset[url] = cacheData;
                    isHasCache = true;
                    if(debug) console.log('Load', url, 'from storage:', cacheData);
C
Catouse 已提交
116
                }
C
Catouse 已提交
117
            }
C
Catouse 已提交
118 119
        }

C
Catouse 已提交
120 121 122 123
        if(isHasCache && (isIndexJson || cacheData.version === dataVersion)) {
            if(debug) console.log('Load', url, 'from cache:', cacheData);
            callback(cacheData.data);
            if(!isIndexJson) return;
C
Catouse 已提交
124
        }
C
Catouse 已提交
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

        var dataType = url.endsWith('.json') ? 'json' : 'html';
        $.get(url, function(data){
            if(data !== null) {
                if(isIndexJson) {
                    dataVersion = data.version;
                }
                cacheData = {data: data, version: dataVersion};
                dataset[url] = cacheData;
                $.store.set('//' + url, data);
                $.store.set('//' + url + '::V', dataVersion);

                if(debug) console.log('Load', url, 'from remote:', cacheData);
                callback(data);
            } else if(isHasCache && !isIndexJson) {
                if(debug) console.log('Failed load', url, 'from remote, instead load cache:', cacheData);
                callback(cacheData.data);
            }
        }, dataType).error(function(){
            if(debug) console.error("Ajax error:", url);
            if(isHasCache && !isIndexJson) {
                if(debug) console.log('Failed load', url, 'from remote with error, instead load cache:', cacheData);
                callback(cacheData.data);
            }
        });
C
Catouse 已提交
150 151 152
    };

    var eachSection = function(callback, eachChapterCallback) {
C
Catouse 已提交
153
        var docIndex = dataset[INDEX_JSON].data;
C
Catouse 已提交
154 155 156 157
        if (!docIndex) {
            console.error("Document index is empty.");
            return false;
        };
C
Catouse 已提交
158

C
Catouse 已提交
159 160
        $.each(chapters, function(chapterName, chapter){
            if(!docIndex.chapters[chapterName]) return;
C
Catouse 已提交
161 162 163 164 165 166 167 168 169 170 171 172
            $.extend(chapter, docIndex.chapters[chapterName]);
            var sections = chapter.sections;
            var data = null;
            if(eachChapterCallback) {
                data = eachChapterCallback(chapter, sections);
                if(data === false) return false;
            }
            $.each(sections, function(i, section){
                if(callback(chapter, section, data) === false) return false;
            });
        });
        return true;
C
Catouse 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185
    };

    var displaySectionIcon = function($icon, section) {
        $icon.attr('class', 'icon').text('');
        if (section.icon === undefined || section.icon === null || section.icon === "") {
            section.icon = section.name.substr(0, 1).toUpperCase();
        }
        if (section.icon.indexOf('icon-') === 0) {
            $icon.addClass(section.icon);
        } else {
            $icon.addClass('text-icon').text(section.icon);
        }
    };
C
Catouse 已提交
186

C
Catouse 已提交
187
    var displaySection = function() {
C
Catouse 已提交
188
        var order = 0;
C
Catouse 已提交
189 190
        if(eachSection(function(chapter, section, $sectionList){
            var chapterName = chapter.id;
C
Catouse 已提交
191
            section.chapter = chapterName;
C
Catouse 已提交
192 193
            var id = chapterName + '-' + section.id;
            var $tpl = $sectionTemplate.clone().attr('id', 'section-' + id).data('section', section);
C
Catouse 已提交
194
            $tpl.attr('data-id', section.id).attr('data-chapter', chapterName).attr('data-order', order++);
C
Catouse 已提交
195
            var $head = $tpl.children('.card-heading');
C
Catouse 已提交
196
            $head.find('.name').text(section.name).attr('href', '#' + id);
C
Catouse 已提交
197
            $head.children('.desc').text(section.desc);
C
Catouse 已提交
198
            displaySectionIcon($head.children('.icon'), section);
C
Catouse 已提交
199 200 201 202 203 204 205 206 207 208 209
            var $topics = $tpl.find('.topics');
            if (section.topics && section.topics.length) {
                for (var tName in section.topics) {
                    var topic = section.topics[tName];
                    topic.id = tName;
                    $topics.append('<li data-id="' + tName + '">' + topic.name + '</li>');
                }
            } else {
                $topics.remove('.card-content');
                $tpl.addClass('without-topics');
            }
C
Catouse 已提交
210
            $sectionList.append($tpl.addClass('show' + (sectionsShowed ? ' in' : '')));
C
Catouse 已提交
211
        }, function(chapter, sections){
C
Catouse 已提交
212 213
            var $sectionList = chapter.$sections;
            $sectionList.children().remove();
C
Catouse 已提交
214 215
            return $sectionList;
        })) {
C
Catouse 已提交
216
            $body.children('.loader').removeClass('loading');
C
Catouse 已提交
217 218 219 220 221 222 223 224
            if(!sectionsShowed) {
                clearTimeout($grid.data(LAST_RELOAD_ANIMATE_ID));
                $grid.data(LAST_RELOAD_ANIMATE_ID, setTimeout(function(){
                    $sections = $grid.find('.section').addClass('in');
                    $chapterHeadings.addClass('in');
                }, 100));
                sectionsShowed = true;
            }
C
Catouse 已提交
225 226 227 228 229
        } else if(debug) {
            console.error("Display sections failed.");
        }
    };

C
Catouse 已提交
230 231 232 233 234 235 236 237 238 239
    var scrollToThis = function($container, toTop, callback) {
        if($container === UNDEFINED) $container = $body;
        if(toTop === UNDEFINED || toTop === 'down') {
            toTop = $container.scrollTop() + ($window.height() - $container.offset().top) * 0.8;
        } else if(toTop === 'up') {
            toTop = $container.scrollTop() - ($window.height() - $container.offset().top) * 0.8;
        }
        $container.animate({scrollTop: toTop}, 200, 'swing', callback);
    };

C
Catouse 已提交
240 241 242 243 244 245 246 247 248
    var scrollToSection = function($section) {
        if($section) {
            var top = $section.offset().top;
            var height = $section.outerHeight();
            var winHeight = $window.height();
            var scrollTop = $body.scrollTop();
            if(winHeight < (top + height)) {

            }
C
Catouse 已提交
249 250
        }
    };
C
Catouse 已提交
251

C
Catouse 已提交
252 253 254
    var isChoosedSection = function($section) {
        if($section === UNDEFINED) {
            $section = $choosedSection;
C
Catouse 已提交
255
        }
C
Catouse 已提交
256
        return $section && $section.hasClass('choosed') && $section.hasClass('show');
C
Catouse 已提交
257 258
    };

C
Catouse 已提交
259
    var chooseSection = function($section, keepOtherOpen, notOpenSelf) {
C
Catouse 已提交
260
        if($sections) {
C
Catouse 已提交
261
            if(isChoosedSection($section || null) && !notOpenSelf) {
C
Catouse 已提交
262 263
                $choosedSection = $section.addClass('open');
                scrollToSection($section);
C
Catouse 已提交
264 265 266
                return;
            }
            var isOpened = $section && $section.hasClass('open');
C
Catouse 已提交
267
            $sections.removeClass(keepOtherOpen ? 'choosed' : 'choosed open');
C
Catouse 已提交
268
            if($section && $section.hasClass('section')) {
C
Catouse 已提交
269
                $choosedSection = $section.addClass((notOpenSelf && !isOpened) ? 'choosed' : 'choosed open');
C
Catouse 已提交
270
                scrollToSection($section);
C
Catouse 已提交
271
            }
C
Catouse 已提交
272
        }
C
Catouse 已提交
273
    };
C
Catouse 已提交
274

C
Catouse 已提交
275 276
    var choosePrevSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
277
        if(isChoosedSection()) {
C
Catouse 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
            var order = parseInt($choosedSection.data('order'));
            var $section = $choosedSection;
            while((--order) > -1) {
                var $prev = $all.filter('[data-order="' + order + '"]');
                if($prev.length) {
                    $section = $prev;
                    break;
                }
            }
            chooseSection($section);
        } else {
            chooseSection($all.first());
        }
    };

    var chooseNextSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
295
        if(isChoosedSection()) {
C
Catouse 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            var order = parseInt($choosedSection.data('order'));
            var $section = $choosedSection;
            var allCount = $sections.length;
            while((order++) < allCount) {
                var $next = $all.filter('[data-order="' + order + '"]');
                if($next.length) {
                    $section = $next;
                    break;
                }
            }
            chooseSection($section);
        } else {
            chooseSection($all.first());
        }
    };

    var distanceBetweenPoint = function(x1, y1, x2, y2) {
        return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2), 2);
    };

    var chooseLeftSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
318
        if(isChoosedSection()) {
C
Catouse 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
            var offset = $choosedSection.offset();
            var left = offset.left - $grid.children('.container').offset().left - 10;
            if(left < 50) {
                choosePrevSection();
                return;
            }
            var top = offset.top;
            left = offset.left;
            var $section = $choosedSection;
            var delta = 99999;
            $all.each(function(){
                var $this = $(this);
                var offset = $this.offset();
                if((offset.left + 50) < left) {
                    var thisDelta = distanceBetweenPoint(offset.left, offset.top, left, top);
                    if(thisDelta < delta) {
                        $section = $this;
                        delta = thisDelta;
                    }
                }
            });
            chooseSection($section);
        } else {
            chooseSection($all.first());
        }
    };

    var chooseRightSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
348
        if(isChoosedSection()) {
C
Catouse 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
            var offset = $choosedSection.offset();
            var $container = $grid.children('.container');
            var left = offset.left - $container.offset().left - 10;
            if((left + 20 + $choosedSection.outerWidth() + 50) >= $container.outerWidth()) {
                chooseNextSection();
                return;
            }
            var top = offset.top;
            left = offset.left;
            var $section = $choosedSection;
            var delta = 99999;
            $all.each(function(){
                var $this = $(this);
                var offset = $this.offset();
                if(offset.left > left) {
                    var thisDelta = distanceBetweenPoint(offset.left, offset.top, left, top);
                    if(thisDelta < delta) {
                        $section = $this;
                        delta = thisDelta;
                    }
                }
            });
            chooseSection($section);
        } else {
            chooseSection($all.first());
        }
    };

C
Catouse 已提交
377 378 379 380 381 382 383 384 385 386 387 388
    var resetQuery = function() {
        $chaptersCols.removeClass('hide');
        $chapters.removeClass('hide');
        $sections.addClass('show');
        $chapterHeadings.addClass('show');
        $grid.data(LAST_RELOAD_ANIMATE_ID, setTimeout(function(){
            $sections.addClass('in');
            $chapterHeadings.addClass('in');
        }, 20));
        $body.removeClass('query-enabled');
    };

C
Catouse 已提交
389
    var query = function(keyString) {
C
Catouse 已提交
390 391 392 393
        if(!$sections) {
            if(debug) console.log('Query failed, $sections is empty. key:', keyString);
            return;
        }
C
Catouse 已提交
394 395 396 397 398 399 400

        if($queryInput.data('queryString') !== keyString) {
            $queryInput.data('queryString', keyString).val(keyString);
            $grid.css('min-height', $grid.height());
        }

        if(keyString === UNDEFINED || keyString === null || !keyString.length) {
C
Catouse 已提交
401
            resetQuery();
C
Catouse 已提交
402 403 404
            return;
        }

C
Catouse 已提交
405 406
        $body.addClass('query-enabled');

C
Catouse 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
        var keys = [];
        $.each(keyString.split(' '), function(i, key){
            key = $.trim(key).toLowerCase();
            var keyOption = {origin: key};
            if(key.startsWith('#')) {
                keyOption.type = 'id';
                keyOption.val = key.substr(1);
            } else if(key.startsWith('icon-') || key.startsWith('icon:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(5);
            } else if(key.startsWith('i:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(1);
            } else if(key.startsWith('ver:')) {
                keyOption.type = 'version';
                keyOption.val = key.substr(4);
            } else if(key.startsWith('v:')) {
                keyOption.type = 'version';
                keyOption.val = key.substr(2);
            } else if(key.startsWith('version:')) {
                keyOption.type = 'version';
                keyOption.val = key.substr(8);
            } else if(key.startsWith('grunt:') || key.startsWith('build:')) {
                keyOption.type = 'build';
                keyOption.val = key.substr(6);
            } else if(key.startsWith('g:') || key.startsWith('b:')) {
                keyOption.type = 'build';
                keyOption.val = key.substr(2);
            } else {
                $.each(chapters, function(name){
                    if(key.startsWith(name + ':')) {
                        keyOption.type = 'id';
                        keyOption.chapter = name;
                        keyOption.val = key.substr(name.length);
                        return false;
                    }
                });
                if(!keyOption.type) {
                    keyOption.type = 'any';
                    keyOption.val = key;
                }
            }
C
Catouse 已提交
449 450 451
            if(keyOption.val.length) {
                keys.push(keyOption);
            }
C
Catouse 已提交
452 453
        });

C
Catouse 已提交
454 455 456 457 458
        if(!keys.length) {
            resetQuery();
            return;
        }

C
Catouse 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        var resultMap = {}, chapterMap = {}, weight, id, chooseThis, chooseThisKey, keyVal, matches, matchType;
        if(eachSection(function(chapter, section){
            chooseThis = true;
            matches = [];
            weight = 0;
            $.each(keys, function(keyIndex, key){
                keyVal = key.val;
                matchType = null;
                chooseThisKey = false;
                switch(key.type) {
                    case 'id':
                        chooseThisKey = (key.chapter ? chapter : section).id.includes(keyVal);
                        if(chooseThisKey) matchType = [key.chapter ? 'chapter' : 'section', 'id'];
                        weight = 100;
                        break;
                    case 'icon':
                        chooseThisKey = section.id === 'icons';
                        if(chooseThisKey) matchType = ['section', 'id'];
                        weight = 100;
                        break;
                    default:
                        if(section.name.toLowerCase().includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['section', 'name'];
                            weight = 80;
                            break;
                        }
                        if(chapter.name.toLowerCase().includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['chapter', 'name'];
                            weight = 70;
                            break;
                        }
                        if(keyVal.length > 1) {
                            if(section.id.includes(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['section', 'id'];
                                weight = 65;
                                break;
                            }
                            if(chapter.id.includes(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['chapter', 'id'];
                                weight = 60;
                                break;
                            }
                            if($.isArray(section.topics)) {
                                var isBreak = false;
                                $.each(section.topics, function(topicIndex, topic){
                                    if(topic.name && topic.name.toLowerCase().includes(keyVal)) {
                                        chooseThisKey = true;
                                        matchType = ['section', 'topic', topicIndex];
                                        isBreak = true;
                                        weight = 20;
                                        return false;
                                    }
                                });
                                if(isBreak) break;
                            }
                            if(section.desc.toLowerCase().includes(keyVal)) {
                                chooseThisKey = true;
                                matchType = 'section.desc';
                                weight = 30;
                                break;
                            }
                        } else {
                            if(chapter.id.startsWith(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['chapter', 'id'];
                                weight = 60;
                                break;
                            }
                            if(section.id.startsWith(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['section', 'id'];
                                weight = 50;
                                break;
                            }
                        }
C
Catouse 已提交
538
                }
C
Catouse 已提交
539 540 541
                if(!chooseThisKey) {
                    chooseThis = false;
                    return false;
C
Catouse 已提交
542
                } else {
C
Catouse 已提交
543
                    matches.push({key: key, type: matchType});
C
Catouse 已提交
544
                }
C
Catouse 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
            });

            id = chapter.id + '-' + section.id;
            if(chooseThis) {
                chapterMap[chapter.id]++;
                resultMap[id] = {hidden: false, matches: matches, weight: weight};
            } else {
                resultMap[id] = {hidden: true};
            }
        }, function(chapter){
            chapterMap[chapter.id] = 0;
        })) {
            var $hide = $(), $show = $(), $section, choosedWeight = -1, $choosed;
            $.each(resultMap, function(id, result){
                $section = $('#section-' + id);
                if(result.hidden) {
                    $hide = $hide.add($section);
C
Catouse 已提交
562
                } else {
C
Catouse 已提交
563 564 565 566 567
                    $show = $show.add($section);
                    if(choosedWeight < result.weight) {
                        $choosed = $section;
                        choosedWeight = result.weight;
                    }
C
Catouse 已提交
568
                }
C
Catouse 已提交
569
                chooseSection($choosed);
C
Catouse 已提交
570
            });
C
Catouse 已提交
571 572 573 574 575 576 577 578

            var $chapter, hide, chapter;
            $.each(chapterMap, function(chapterId, resultCount){
                chapter = chapters[chapterId];
                hide = !resultCount;
                chapter.$.toggleClass('hide', hide);
            });
            var $col;
C
Catouse 已提交
579
            var showColCount = 0;
C
Catouse 已提交
580 581
            $chaptersCols.each(function(){
                $col = $(this);
C
Catouse 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
                var showCol = $col.children('.chapter:not(.hide)').length;
                $col.toggleClass('hide', !showCol);
                if(showCol) {
                    showColCount++;
                    if(!$body.hasClass('compact-mode')) {
                        var showCount = $col.find('.section:not(.hide)').length;
                        if(showCount > 2 && $window.height() < ($header.height() + showCount * 70)) {
                            $body.addClass('compact-mode');
                            setTimeout(function(){
                                $window.scrollTop(1);
                                $body.addClass('compact-mode-in');
                            }, 10);
                        }
                    }
                }
C
Catouse 已提交
597
            });
C
Catouse 已提交
598
            $grid.attr('data-show-col', showColCount);
C
Catouse 已提交
599 600 601

            if($hide.length) {
                $hide.removeClass('in');
C
Catouse 已提交
602
                setTimeout(function(){$hide.removeClass('show');}, 100);
C
Catouse 已提交
603 604 605 606 607
            }
            if($show.length) {
                $show.addClass('show');
                setTimeout(function(){$show.addClass('in');}, 20);
            }
C
Catouse 已提交
608 609

            $window.scrollTop(1);
C
Catouse 已提交
610
            closePage();
C
Catouse 已提交
611 612 613
        } else if(debug) {
            console.error("Query failed with key: ", keys);
        }
C
Catouse 已提交
614 615 616
    };

    var toggleCompactMode = function(toggle, callback) {
C
Catouse 已提交
617 618 619 620
        if(toggle === UNDEFINED) {
            toggle = !$body.hasClass('compact-mode');
        }

C
Catouse 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
        var animateName = 'isScrollAnimating';
        if(toggle) {
            if(!$body.hasClass('compact-mode')) {
                $body.data(animateName, true).addClass('compact-mode')
                setTimeout(function(){
                    $body.addClass('compact-mode-in');
                    $window.scrollTop(1);
                    setTimeout(function(){
                        $body.data(animateName, false);
                        if(callback) callback();
                    }, 500);
                }, 10);
            } else if(callback) {
                callback();
            }
        } else {
            if($body.hasClass('compact-mode')) {
                $body.data(animateName, true).removeClass('compact-mode-in');
                setTimeout(function(){
                    $body.removeClass('compact-mode');
                    $body.data(animateName, false);
                    if(callback) callback();
                }, 500);
            } else if(callback) {
                callback();
            }
        }
    };

    var closePage = function() {
C
Catouse 已提交
651
        if($body.hasClass('page-open')) {
C
Catouse 已提交
652 653 654
            var style = $page.data('trans-style');
            style['max-height'] = '';
            $page.css(style);
C
Catouse 已提交
655
            $body.addClass('page-show-out').removeClass('page-open page-show-in');
C
Catouse 已提交
656
            setTimeout(function(){
C
Catouse 已提交
657
                $body.removeClass('page-show page-show-out');
C
Catouse 已提交
658
                resetScrollbar();
C
Catouse 已提交
659
            }, 300);
C
Catouse 已提交
660
            return true;
C
Catouse 已提交
661
        }
C
Catouse 已提交
662
        return false;
C
Catouse 已提交
663 664
    };

C
Catouse 已提交
665
    var openPage = function($section, section, topic) {
C
Catouse 已提交
666 667 668 669 670
        var pageId = section.chapter + '-' + section.id;
        if($body.hasClass('page-open') && pageId === $body.attr('data-page')) {
            if(debug) console.error('The page already showed.');
            return;
        }
C
Catouse 已提交
671
        chooseSection($section, false, true);
C
Catouse 已提交
672

C
Catouse 已提交
673 674 675 676
        window.location.hash = '#' + pageId;
        $body.attr('data-page-chapter', section.chapter).attr('data-page', pageId);
        displaySectionIcon($pageHeader.find('.icon'), section);
        $pageHeader.find('.name').text(section.name).attr('href', '#' + section.chapter + '-' + section.id);
C
Catouse 已提交
677
        $pageHeader.children('.desc').text(section.desc);
C
Catouse 已提交
678
        $pageContent.html('');
C
Catouse 已提交
679
        var $loader = $page.addClass('loading').find('.loader').addClass('loading');
C
Catouse 已提交
680 681 682

        loadData(section.url, function(data){
            $page.removeClass('loading');
C
Catouse 已提交
683
            $loader.removeClass('loading');
C
Catouse 已提交
684
            $pageContent.html(data);
C
Catouse 已提交
685
            $queryInput.blur();
C
Catouse 已提交
686 687
            $pageBody.scrollTop(0);
        });
C
Catouse 已提交
688

C
Catouse 已提交
689 690 691 692 693 694 695
        if($body.hasClass('page-open')) {
            if(debug) console.log('open section in open page', section);
            return;
        }

        $body.addClass('page-open');

C
Catouse 已提交
696 697
        toggleCompactMode(true, function(){
            var offset = $section.offset();
C
Catouse 已提交
698 699 700
            var sectionHeight = $section.outerHeight();
            var style = {
                left: offset.left - $grid.children('.container').offset().left - 6,
C
Catouse 已提交
701
                top: offset.top - $window.scrollTop() - 81,
C
Catouse 已提交
702
                width: $section.outerWidth(),
C
Catouse 已提交
703 704 705
                height: sectionHeight,
                'max-height': sectionHeight
            };
C
Catouse 已提交
706 707
            checkScrollbar();
            $body.addClass('page-show');
C
Catouse 已提交
708 709 710
            $page.css(style).data('trans-style', style);
            $pageBody.css('width', bestPageWidth);
            
C
Catouse 已提交
711 712
            setTimeout(function(){
                $body.addClass('page-show-in');
C
Catouse 已提交
713 714 715 716 717
                if($page.hasClass('loading')) $page.addClass('openning').css('height', 380);
                $pageBody.scrollTop(0);
                setTimeout(function(){
                    $page.removeClass('openning');
                    bestPageWidth = $pageBody.css('width', '').width() + 40;
C
Catouse 已提交
718
                    resizePage();
C
Catouse 已提交
719
                }, 310);
C
Catouse 已提交
720 721 722
            }, 10);
        });
    };
C
Catouse 已提交
723

C
Catouse 已提交
724
    var openSection = function(section, topic) {
C
Catouse 已提交
725 726
        section = section || $choosedSection;

C
Catouse 已提交
727
        var $section;
C
Catouse 已提交
728
        if($.isArray(section)) {
C
Catouse 已提交
729
            var docIndex = dataset[INDEX_JSON].data;
C
Catouse 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
            if(docIndex && section.length > 1) {
                var sectionId = section[1];
                var sections = docIndex.chapters[section[0]].sections;
                var ok = false;
                for(var i in sections) {
                    var s = sections[i];
                    if(s.id === sectionId) {
                        if(section.length > 2) {
                            topic = section[2];
                        }
                        section = s;
                        ok = true;
                        break;
                    }
                }
                if(!ok) {
                    console.error("Open section failed: can't find the section with id " + section.join('-'));
                    return;
                }
            } else {
                if(debug) {
                    console.error("Open section stop by null docIndex or wrong section value.");
                }
                return;
            }
        }
C
Catouse 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
        if($.isPlainObject(section)) {
            $section = $('#section-' + section.chapter + '-' + section.id);
        } else {
            var $temp = section;
            section = $temp.data('section');
            $section = $temp;
        }

        var url = section.url;

        if(url === null) {
            if(debug) console.error("Open section stop by null url.");
            return;
        }

        if(!url) {
            url = 'part/' + section.chapter + '-' + section.id + '.html';
            section.url = url;
        }

        url = url.toLowerCase();
        if(url.startsWith('http://') || url.startsWith('https://') ) {
            window.open(url, '_blank');
        } else {
            openPage($section, section, topic);
        }
    };

C
Catouse 已提交
784 785
    window.openS = openSection;

C
Catouse 已提交
786
    var resizePage = function() {
C
Catouse 已提交
787
        if($body.hasClass('page-show-out') || $page.hasClass('loading')) return;
C
Catouse 已提交
788 789 790 791 792 793 794
        var height;
        if($body.hasClass(PAGE_SHOW_FULL)) {
            height = $window.height();
            $pageBody.toggleClass('with-scrollbar', $pageContent.outerHeight() > (height - 40 - $pageHeader.outerHeight()));
        } else {
            height = Math.min($pageContainer.outerHeight(), $pageHeader.outerHeight() + $pageContent.outerHeight() + 50);
        }
C
Catouse 已提交
795
        $page.css('height', height);
C
Catouse 已提交
796 797
    };

C
Catouse 已提交
798
    $(function() {
C
Catouse 已提交
799 800 801 802
        var stopPropagation = function(e) {
            e.stopPropagation();
        }

C
Catouse 已提交
803 804
        $window = $(window);
        $body = $('body');
C
Catouse 已提交
805
        $navbar = $('#navbar');
C
Catouse 已提交
806 807
        $grid = $('#grid');
        $header = $('#header');
C
Catouse 已提交
808
        $chaptersCols = $grid.find('.col');
C
Catouse 已提交
809 810
        $page = $('#page');
        $pageHeader = $('#pageHeader');
C
Catouse 已提交
811 812
        $pageContainer = $('#pageContainer');
        $pageContent = $('#pageContent');
C
Catouse 已提交
813 814 815
        $chapters = $grid.find('.chapter');
        $queryInput = $('#searchInput');
        $chapterHeadings = $grid.find('.chapter-heading');
C
Catouse 已提交
816
        $sectionTemplate = $('#sectionTemplate').attr('id', null);
C
Catouse 已提交
817
        $pageBody = $('#pageBody');
C
Catouse 已提交
818 819 820 821 822 823
        $.each(chapters, function(chapterId, chapter){
            chapterId = chapterId.toLowerCase();
            chapter.$ = $('#chapter-' + chapterId);
            chapter.id = chapterId;
            chapter.$sections = $('#sections-' + chapterId);
        });
C
Catouse 已提交
824

C
Catouse 已提交
825
        bestPageWidth = $grid.children('.container').outerWidth();
C
Catouse 已提交
826

C
Catouse 已提交
827
        $body.toggleClass(PAGE_SHOW_FULL, $.store.get(PAGE_SHOW_FULL, false));
C
Catouse 已提交
828 829 830 831 832 833 834 835 836 837 838

        // check storage
        storageEnable = $.store && $.store.enable;

        // Get document version
        // dataVersion = $body.data('version');

        // Setup ajax
        $.ajaxSetup({cache: false});
        
        // Load index.json
C
Catouse 已提交
839
        loadData(INDEX_JSON, function(data){
C
Catouse 已提交
840
            var firstLoad = !sectionsShowed;
C
Catouse 已提交
841
            displaySection(data);
C
Catouse 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

            if(!firstLoad) {
                var q = getQueryString('q');
                if(q) {
                    setTimeout(function(){
                        query(q);
                    }, 300);
                }

                var hash = window.location.hash
                if(hash) {
                    hash = hash.substr(1);
                    setTimeout(function(){
                        openSection(hash.split('-'));
                    }, 600);
                } else {
                    $queryInput.focus();
                }
C
Catouse 已提交
860 861
            }
        });
C
Catouse 已提交
862 863

        // Bind events
C
Catouse 已提交
864 865 866 867 868
        $(document).on('click', function(e){
            if($body.hasClass('page-show')) {
                closePage();
                return;
            }
C
Catouse 已提交
869 870 871
            chooseSection();
            $sections.removeClass('open');
        });
C
Catouse 已提交
872
        $page.on('click', stopPropagation);
C
Catouse 已提交
873
        $grid.on('click', '.card-heading', function(e) {
C
Catouse 已提交
874
            var $card = $(this).closest('.card');
C
Catouse 已提交
875 876
            if(!$card.hasClass('choosed')) {
                chooseSection($card, true);
C
Catouse 已提交
877 878 879
            } else {
                $card.toggleClass('open');
            }
C
Catouse 已提交
880
            stopPropagation(e);
C
Catouse 已提交
881
        }).on('click', '.card', function(e){
C
Catouse 已提交
882
            chooseSection($(this), true);
C
Catouse 已提交
883 884
            stopPropagation(e);
        }).on('click', '.card-heading > h5 > .name, .card-heading > .icon', function(e){
C
Catouse 已提交
885
            openSection($(this).closest('.section'));
C
Catouse 已提交
886 887 888
            stopPropagation(e);
        }).on('click', '.topics > li', function(e){
            var $li = $(this);
C
Catouse 已提交
889
            openSection($li.closest('.section'), $li.data('id'));
C
Catouse 已提交
890
            stopPropagation(e);
C
Catouse 已提交
891 892 893 894 895 896
        }).on('mouseenter', '.card-heading > h5 > .name, .card-heading > .icon', function(){
            $(this).closest('.card-heading').addClass('hover');
        }).on('mouseleave', '.card-heading > h5 > .name, .card-heading > .icon', function(){
            $(this).closest('.card-heading').removeClass('hover');
        });

C
Catouse 已提交
897 898 899
        $pageContent.on('resize', resizePage);
        $window.resize(resizePage);

C
Catouse 已提交
900 901
        $pageHeader.on('click', '.path-close-btn', function(){
            closePage();
C
Catouse 已提交
902 903
        }).on('click', '.path-max-btn', function(){
            $body.toggleClass(PAGE_SHOW_FULL);
C
Catouse 已提交
904
            setTimeout(resizePage, 300);
C
Catouse 已提交
905
            $.store.set(PAGE_SHOW_FULL, $body.hasClass(PAGE_SHOW_FULL));
C
Catouse 已提交
906 907
        });

C
Catouse 已提交
908 909 910
        var scrollHeight = $('#navbar').outerHeight();
        var lastScrollTop;
        $window.on('scroll', function(e){
C
Catouse 已提交
911
            var isScrollAnimating = $body.data('isScrollAnimating');
C
Catouse 已提交
912
            if(isScrollAnimating) {
C
Catouse 已提交
913
                $window.scrollTop(1);
C
Catouse 已提交
914
                return;
C
Catouse 已提交
915 916 917
            }
            lastScrollTop = $window.scrollTop();
            if(lastScrollTop > scrollHeight && !$body.hasClass('compact-mode')) {
C
Catouse 已提交
918
                toggleCompactMode(true);
C
Catouse 已提交
919 920
            } else if($body.hasClass('compact-mode')) {
                if(lastScrollTop < 1) {
C
Catouse 已提交
921
                    toggleCompactMode(false);
C
Catouse 已提交
922 923 924 925
                } else {
                    $header.toggleClass('with-shadow', lastScrollTop > 20);
                }
            }
C
Catouse 已提交
926 927
        }).on('keydown', function(e){
            var code = e.which;
C
Catouse 已提交
928
            // console.log('keydown', code);
C
Catouse 已提交
929
            var isPageNotShow = !$body.hasClass('page-show');
C
Catouse 已提交
930
            if(code === 13) { // Enter
C
Catouse 已提交
931 932
                if(isPageNotShow && isChoosedSection()) {
                    openSection();
C
Catouse 已提交
933 934 935 936 937 938 939
                }
            } else if(code === 27) { // Esc
                if(!closePage()) {
                    if($body.hasClass('input-query-focus')) {
                        query();
                    }
                }
C
Catouse 已提交
940 941 942 943 944 945 946 947
            } else if(code === 32) { // Space
                if(closePage()) {
                } else if(!$body.hasClass('compact-mode')) {
                    toggleCompactMode(true);
                } else if(isChoosedSection()) {
                    openSection();
                }
                e.preventDefault();
C
Catouse 已提交
948 949 950 951 952 953 954
            } else if(code === 37) { // Left
                chooseLeftSection();
                e.preventDefault();
            } else if(code === 39) { // Right
                chooseRightSection();
                e.preventDefault();
            } else if(code === 38) { // Top
C
Catouse 已提交
955 956
                if(isPageNotShow) {
                    choosePrevSection();
C
Catouse 已提交
957
                    e.preventDefault();
C
Catouse 已提交
958 959 960
                } else {
                    scrollToThis($pageBody, 'up');
                }
C
Catouse 已提交
961
            } else if(code === 40) { // Down
C
Catouse 已提交
962 963
                if(isPageNotShow) {
                    chooseNextSection();
C
Catouse 已提交
964
                    e.preventDefault();
C
Catouse 已提交
965 966 967
                } else {
                    scrollToThis($pageBody);
                }
C
Catouse 已提交
968 969 970 971 972 973
                e.preventDefault();
            }
        });

        $pageBody.on('scroll', function(e){
            $page.toggleClass('with-shadow', $pageBody.scrollTop() > 20);
C
Catouse 已提交
974
        });
C
Catouse 已提交
975 976 977 978 979 980 981

        $queryInput.on('change keyup paste input propertychange', function(){
            var val = $queryInput.val();
            if(val === $queryInput.data('queryString')) return;
            clearTimeout($queryInput.data(LAST_QUERY_ID));
            $queryInput.data(LAST_QUERY_ID, setTimeout(function(){
                query(val);
C
Catouse 已提交
982
            }, 150));
C
Catouse 已提交
983 984 985 986 987 988 989 990
        }).on('focus', function(){
            $body.addClass('input-query-focus');
            if($queryInput.val() && !$sections.filter('.open').length) {
                chooseSection($sections.filter('.show:first'));
            }
        }).on('blur', function(){
            $body.removeClass('input-query-focus');
        }).on('click', stopPropagation);
C
Catouse 已提交
991 992

        $('[data-toggle="tooltip"]').tooltip({container: 'body'});
C
Catouse 已提交
993
    });
C
Catouse 已提交
994
}(window, jQuery));