doc.js 57.4 KB
Newer Older
C
Catouse 已提交
1 2
(function(window, $)
{
C
Catouse 已提交
3
    'use strict';
C
Catouse 已提交
4

C
Catouse 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17
    // 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 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30
    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 已提交
31
    var saveTraffic = false;
C
Catouse 已提交
32
    var debug = 1;
C
Catouse 已提交
33
    if(debug) console.error("DEBUG ENABLED.");
C
Catouse 已提交
34 35

    var chapters = {
36 37 38 39 40 41
        learn: {col: 1},
        start: {col: 1},
        basic: {col: 1},
        control: {col: 2},
        component: {col: 2},
        javascript: {col: 3},
42
        view: {col: 3},
C
Catouse 已提交
43
        promotion: {col: 1, row: 2},
C
Catouse 已提交
44 45
        resource: {col: 1, row: 2},
        contribution: {col: 1, row: 2}
C
Catouse 已提交
46 47
    };
    var LAST_RELOAD_ANIMATE_ID = 'lastReloadAnimate';
C
Catouse 已提交
48
    var LAST_QUERY_ID = 'LAST_QUERY_ID';
C
Catouse 已提交
49
    var INDEX_JSON = 'index.json';
50
    var ICONS_JSON = 'icons.json';
51
    var PKG_JSON = '/package.json';
C
Catouse 已提交
52
    var UNDEFINED = undefined;
C
Catouse 已提交
53
    var PAGE_SHOW_FULL = 'page-show-full';
C
Catouse 已提交
54 55
    var dataVersion;
    var storageEnable;
C
Catouse 已提交
56
    var dataset = {
C
Catouse 已提交
57
        // 'index.json': null
C
Catouse 已提交
58 59
    };
    if(debug) window.dataset = dataset;
60
    var pkgLibs = {standard: null, lite: null, separate: null};
C
Catouse 已提交
61

62
    var documentTitle = 'ZUI';
C
Catouse 已提交
63
    var sectionsShowed;
C
Catouse 已提交
64
    var queryGaCallback;
C
Catouse 已提交
65
    var scrollBarWidth = -1;
C
Catouse 已提交
66
    var bestPageWidth = 1120;
C
Catouse 已提交
67 68
    var $body, $window, $grid, $sectionTemplate,
        $queryInput, $chapters, $chaptersCols,
C
Catouse 已提交
69
        $choosedSection, $page, $pageHeader, $pageContent, $pageLoader,
70
        $pageContainer, $pageBody, $navbar, $search, lastQueryString,
C
Catouse 已提交
71
        $header, $sections, $chapterHeadings; // elements
C
Catouse 已提交
72

C
Catouse 已提交
73 74 75 76 77 78 79 80
    var isExternalUrl = function(url) {
        if(typeof url === 'string') {
            url = url.toLowerCase();
            return url.startsWith('http://') || url.startsWith('https://');
        }
        return false;
    };

C
Catouse 已提交
81 82 83 84 85 86 87
    var limitString = function(str, len) {
        if(str && str.length > len) {
            return str.substr(0, len) + '...[' + str.length + ']';
        }
        return str;
    };

C
Catouse 已提交
88 89 90 91 92 93 94
    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 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    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 已提交
110
            $navbar.css('padding-right', scrollBarWidth);
C
Catouse 已提交
111 112 113 114 115 116
        }
    };

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

C
Catouse 已提交
120 121 122 123 124
    var loadData = function(url, callback) {
        var cacheData = dataset[url];
        var isHasCache = cacheData && cacheData.version;
        var isIndexJson = url === INDEX_JSON;
        if(!isHasCache && storageEnable) {
C
Catouse 已提交
125
            var storedData = $.zui.store.get('//' + url, null);
C
Catouse 已提交
126
            if(storedData !== null) {
C
Catouse 已提交
127
                var storedVersion = $.zui.store.get('//' + url + '::V');
C
Catouse 已提交
128 129 130 131 132
                if(storedVersion) {
                    cacheData = {data: storedData, version: storedVersion};
                    dataset[url] = cacheData;
                    isHasCache = true;
                    if(debug) console.log('Load', url, 'from storage:', cacheData);
C
Catouse 已提交
133
                }
C
Catouse 已提交
134
            }
C
Catouse 已提交
135 136
        }

C
Catouse 已提交
137 138 139
        if(isHasCache && (isIndexJson || cacheData.version === dataVersion)) {
            if(debug) console.log('Load', url, 'from cache:', cacheData);
            callback(cacheData.data);
C
Catouse 已提交
140
            if(!isIndexJson && !debug) return;
C
Catouse 已提交
141
        }
C
Catouse 已提交
142 143 144 145 146 147 148 149 150

        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;
C
Catouse 已提交
151 152
                $.zui.store.set('//' + url, data);
                $.zui.store.set('//' + url + '::V', dataVersion);
C
Catouse 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165

                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 已提交
166 167 168 169

            if($body.hasClass('page-open')) {
                $pageBody.children('.loader').addClass('with-error');
            }
C
Catouse 已提交
170
        });
C
Catouse 已提交
171 172 173
    };

    var eachSection = function(callback, eachChapterCallback) {
C
Catouse 已提交
174
        var docIndex = dataset[INDEX_JSON].data;
C
Catouse 已提交
175 176 177 178
        if (!docIndex) {
            console.error("Document index is empty.");
            return false;
        };
C
Catouse 已提交
179

C
Catouse 已提交
180 181
        $.each(chapters, function(chapterName, chapter){
            if(!docIndex.chapters[chapterName]) return;
C
Catouse 已提交
182 183 184 185 186 187 188 189 190 191 192 193
            $.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 已提交
194 195 196
    };

    var displaySectionIcon = function($icon, section) {
197 198 199 200
        var icon = section.icon;
        $icon.attr('class', 'icon').text('').css('background-image', '');
        if (icon === undefined || icon === null || icon === "") {
            icon = section.name.substr(0, 1).toUpperCase();
C
Catouse 已提交
201
        }
202 203 204 205
        if (icon.startsWith('icon-')) {
            $icon.addClass(icon);
        } else if(icon.endsWith('.png')) {
            $icon.css('background-image', 'url(' + icon + ')').addClass('with-img');
C
Catouse 已提交
206
        } else {
207
            $icon.addClass('text-icon').text(icon);
C
Catouse 已提交
208 209
        }
    };
C
Catouse 已提交
210

C
Catouse 已提交
211
    var displaySection = function() {
C
Catouse 已提交
212
        var order = 0;
C
Catouse 已提交
213 214
        if(eachSection(function(chapter, section, $sectionList){
            var chapterName = chapter.id;
C
Catouse 已提交
215
            section.chapter = chapterName;
216
            section.chapterName = chapter.name;
217 218 219 220 221

            var url = section.url;
            if(typeof url === 'undefined') {
                section.url = 'part/' + section.chapter + '-' + section.id + '.html';
                section.target = 'page';
C
Catouse 已提交
222
            } else if(isExternalUrl(url)) {
223 224 225 226 227
                section.target = 'external';
            } else {
                section.target = '';
            }

C
Catouse 已提交
228
            var id = chapterName + '-' + section.id;
229
            var $tpl = $sectionTemplate.clone().data('section', section);
230
            $tpl.attr({
231
                'id': 'section-' + id,
232 233 234
                'data-id': section.id,
                'data-chapter': chapterName,
                'data-order': order++,
235 236
                'data-accent': chapter.accent,
                'data-target': section.target
237
            });
C
Catouse 已提交
238
            var $head = $tpl.children('.card-heading');
239 240
            var sectionUrl = '#' + chapterName + '/' + section.id;
            $head.find('.name').text(section.name).attr('href', sectionUrl);
C
Catouse 已提交
241
            $head.children('.desc').text(section.desc);
C
Catouse 已提交
242
            displaySectionIcon($head.children('.icon'), section);
C
Catouse 已提交
243 244 245 246
            var $topics = $tpl.find('.topics');
            if (section.topics && section.topics.length) {
                for (var tName in section.topics) {
                    var topic = section.topics[tName];
C
Catouse 已提交
247

248
                    if(typeof topic.id === 'undefined') topic.id = tName;
C
Catouse 已提交
249 250 251
                    var topicUrl = typeof topic.url === 'undefined' ? (sectionUrl + '/' + topic.id) : topic.url;

                    $topics.append('<li data-id="' + tName + '"><a href="' + topicUrl + '"' + (isExternalUrl(topicUrl) ? ' target="_blank"' : '') + '>' + topic.name + '</a></li>');
C
Catouse 已提交
252 253 254 255 256
                }
            } else {
                $topics.remove('.card-content');
                $tpl.addClass('without-topics');
            }
C
Catouse 已提交
257
            $sectionList.append($tpl.addClass('show' + (sectionsShowed ? ' in' : '')));
C
Catouse 已提交
258
        }, function(chapter, sections){
259
            chapter.$.attr('data-accent', chapter.accent);
C
Catouse 已提交
260 261
            var $sectionList = chapter.$sections;
            $sectionList.children().remove();
C
Catouse 已提交
262 263
            return $sectionList;
        })) {
C
Catouse 已提交
264
            $body.children('.loader').removeClass('loading');
C
Catouse 已提交
265
            $sections = $grid.find('.section');
C
Catouse 已提交
266 267 268
            if(!sectionsShowed) {
                clearTimeout($grid.data(LAST_RELOAD_ANIMATE_ID));
                $grid.data(LAST_RELOAD_ANIMATE_ID, setTimeout(function(){
C
Catouse 已提交
269
                    $sections.addClass('in');
C
Catouse 已提交
270 271 272 273
                    $chapterHeadings.addClass('in');
                }, 100));
                sectionsShowed = true;
            }
C
Catouse 已提交
274 275 276 277 278
        } else if(debug) {
            console.error("Display sections failed.");
        }
    };

C
Catouse 已提交
279 280 281 282 283 284 285 286 287 288
    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 已提交
289 290 291 292 293 294 295 296 297
    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 已提交
298 299
        }
    };
C
Catouse 已提交
300

C
Catouse 已提交
301 302 303
    var isChoosedSection = function($section) {
        if($section === UNDEFINED) {
            $section = $choosedSection;
C
Catouse 已提交
304
        }
C
Catouse 已提交
305
        return $section && $section.hasClass('choosed') && $section.hasClass('show');
C
Catouse 已提交
306 307
    };

C
Catouse 已提交
308
    var chooseSection = function($section, keepOtherOpen, notOpenSelf) {
C
Catouse 已提交
309
        if($sections) {
C
Catouse 已提交
310
            if(isChoosedSection($section || null) && !notOpenSelf) {
C
Catouse 已提交
311 312
                $choosedSection = $section.addClass('open');
                scrollToSection($section);
C
Catouse 已提交
313 314 315
                return;
            }
            var isOpened = $section && $section.hasClass('open');
C
Catouse 已提交
316
            $sections.removeClass(keepOtherOpen ? 'choosed' : 'choosed open');
C
Catouse 已提交
317
            if($section && $section.hasClass('section')) {
C
Catouse 已提交
318
                $choosedSection = $section.addClass((notOpenSelf && !isOpened) ? 'choosed' : 'choosed open');
C
Catouse 已提交
319
                scrollToSection($section);
C
Catouse 已提交
320
            }
C
Catouse 已提交
321
        }
C
Catouse 已提交
322
    };
C
Catouse 已提交
323

C
Catouse 已提交
324 325
    var choosePrevSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
326
        if(isChoosedSection()) {
C
Catouse 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
            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 已提交
344
        if(isChoosedSection()) {
C
Catouse 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
            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 已提交
367
        if(isChoosedSection()) {
C
Catouse 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            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 已提交
397
        if(isChoosedSection()) {
C
Catouse 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
            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 已提交
426 427 428 429 430 431 432 433 434
    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));
C
Catouse 已提交
435
        $body.removeClass('query-enabled').attr('data-query', '');
C
Catouse 已提交
436 437
    };

438 439 440 441 442 443 444 445 446 447
    var chooseIcon = function($icon){
        var $search = $('#section-control-icons');
        if(!$icon || !$icon.length) {
            $search.removeClass('section-preview-show').data('preview', null);
            return;
        }
        $search.addClass('open section-preview-show');
        var $preview = $search.children('.section-preview');
        var oldIcon = $search.data('preview');
        if(!$preview.length) {
C
Catouse 已提交
448
            $preview = $('#iconPreviewTemplate').clone().attr('id', '');
449 450 451 452 453 454 455 456 457 458 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
            $search.children('.card-heading').after($preview);
        }
        $search.children('.section-search').find('li.active').removeClass('active');
        $icon.addClass('active');
        if(oldIcon) $preview.find('.icon').removeClass('icon-' + oldIcon);
        var icon = $icon.data('icon');
        $search.data('preview', icon.id);
        var id = 'icon-' + icon.id;
        $preview.find('.icon').addClass(id);
        $preview.find('.name').text(id);
        $preview.find('.unicode').text(icon.code);
        if(icon.alias && icon.alias.length) {
            $preview.find('.alias').removeClass('hide').find('.alias-values').text(icon.alias.join(','));
        } else {
            $preview.find('.alias').addClass('hide');
        }
    };

    var queryIcon = function(keys) {
        if(!$.isArray(keys) && (keys || keys.length) ) {
            keys = [keys];
        }

        var $section = $('#section-control-icons');
        $body.attr('data-query', 'icons');
        var $search = $section.children('.section-search');
        if(!$search.length) {
            $search = $('<div class="section-search card-content"><div class="loader loading"><i class="icon icon-spin icon-spinner"></i> 正在拼命加载中...</div></div>');
            $section.children('.card-heading').after($search);
            $search = $section.children('.section-search');
        }

        loadData(ICONS_JSON, function(data){
            var $list = $search.children('ul');
            if(!$list.length) {
                $list = $('<ul data-view="icons">');
                $.each(data, function(iconName, icon){
                    var $li = $('<li id="control-icons-' + iconName + '" data-id="' + iconName + '"><a href="#control/icons/' + iconName + '"><i class="icon icon-' + iconName + '"></i> icon-' + iconName + '</a></li>');
                    icon.id = iconName;
                    $li.data('icon', icon);
                    $list.append($li);
                });
                $search.children('.loader').replaceWith($list);
            }

            if(!keys.length) {
                $list.children('.hide').removeClass('hide');
                chooseIcon($list.children().first());
                return;
            }

            for(var keyIndex in keys) {
                keys[keyIndex] = keys[keyIndex].toLowerCase();
            }

            var $bestMatch, bestMatchWeight = 0;
            $.each(data, function(iconId, icon){
                var choosed = false;
                var weight = 0;
                iconId = iconId.toLowerCase();
                $.each(keys, function(keyIndex, key){
                    var choosedThis = false;
                    if(iconId.includes(key)) {
                        choosedThis = true;
                        weight += iconId.startsWith(key) ? 120: 110;
                    } else if(icon.name && icon.name.toLowerCase().includes(key)) {
                        choosedThis = true;
                        weight += icon.name.toLowerCase().startsWith(key) ? 100: 95;
517
                    } else if(key.startsWith('\\') && icon.code && icon.code.toLowerCase().includes(key.substr(1))) {
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
                        choosedThis = true;
                        weight += 120;
                    } else {
                        var filters = [];
                        if($.isArray(icon.filter) && icon.filter.length) filters = filters.concat(icon.filter);
                        if($.isArray(icon.categories) && icon.categories.length) filters = filters.concat(icon.categories);
                        if($.isArray(icon.alias) && icon.alias.length) filters = filters.concat(icon.alias);
                        if(!filters.length) return;
                        $.each(filters, function(filterIndex, filter){
                            filter = filter.toLowerCase();
                            if(filter.includes(key)) {
                                choosedThis = true;
                                weight += 50;
                                return false;
                            }
                        });
                    }

                    if(!choosedThis) {
                        choosed = false;
                        return choosed;
                    } else {
                        choosed = true;
                    }
                });

                var $li = $('#control-icons-' + iconId).toggleClass('hide', !choosed);
                if(choosed && bestMatchWeight < weight) {
                    bestMatchWeight = weight;
                    $bestMatch = $li;
                }
            });
            chooseIcon($bestMatch);
        });
    };

C
Catouse 已提交
554
    var query = function(keyString) {
C
Catouse 已提交
555 556 557 558
        if(!$sections) {
            if(debug) console.log('Query failed, $sections is empty. key:', keyString);
            return;
        }
C
Catouse 已提交
559

560 561
        if(typeof keyString === 'undefined') keyString = null;

C
Catouse 已提交
562 563 564 565 566
        if($queryInput.data('queryString') !== keyString) {
            $queryInput.data('queryString', keyString).val(keyString);
            $grid.css('min-height', $grid.height());
        }

567
        if(keyString === null || !keyString.length) {
C
Catouse 已提交
568
            resetQuery();
569
            $search.removeClass('with-query-text');
C
Catouse 已提交
570 571
            return;
        }
572
        $search.addClass('with-query-text');
C
Catouse 已提交
573

574
        $body.addClass('query-enabled').attr('data-query', '');
C
Catouse 已提交
575

C
Catouse 已提交
576 577 578 579 580 581 582 583
        // Send ga data
        if($.isFunction(ga)) {
            if(queryGaCallback) clearTimeout(queryGaCallback);
            queryGaCallback = setTimeout(function(){
                ga('send', 'pageview', window.location.pathname + '#search/' + keyString);
            }, 2000);
        }

C
Catouse 已提交
584 585 586 587
        var keys = [];
        $.each(keyString.split(' '), function(i, key){
            key = $.trim(key).toLowerCase();
            var keyOption = {origin: key};
588
            if(key.startsWith('@')) {
C
Catouse 已提交
589
                keyOption.type = 'id';
590 591 592 593 594
                keyOption.chapter = key.substr(1);
                keyOption.val = keyOption.chapter;
            } else if(key.startsWith('#')) {
                keyOption.type = 'id';
                keyOption.val = key.substr(2);
C
Catouse 已提交
595 596 597 598 599
            } else if(key.startsWith('icon-') || key.startsWith('icon:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(5);
            } else if(key.startsWith('i:')) {
                keyOption.type = 'icon';
600
                keyOption.val = key.substr(2);
C
Catouse 已提交
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
            } 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;
                }
            }
630
            if(keyOption.val.length || (keyOption.type && keyOption.type !== 'any')) {
C
Catouse 已提交
631 632
                keys.push(keyOption);
            }
C
Catouse 已提交
633 634
        });

C
Catouse 已提交
635 636 637 638 639
        if(!keys.length) {
            resetQuery();
            return;
        }

C
Catouse 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
        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':
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
                        chooseThis = section.id === 'icons';
                        if(chooseThis) {
                            weight = 120;
                            matches.push({key: key, type: ['section', 'id']});
                            var iconKeys = [];
                            if(key.val || key.val.length) {
                                iconKeys.push(key.val);
                            }
                            for(var iconKeyIndex in keys) {
                                var iconKey = keys[iconKeyIndex];
                                if(iconKey.val !== key.val && (iconKey.val || iconKey.val.length)) {
                                    iconKeys.push(iconKey.val);
                                }
                            }
                            queryIcon(iconKeys);
                            return false;
                        }
C
Catouse 已提交
673 674
                        break;
                    default:
C
Catouse 已提交
675 676
                        var sectionName = section.name.toLowerCase();
                        if(sectionName.includes(keyVal)) {
C
Catouse 已提交
677 678
                            chooseThisKey = true;
                            matchType = ['section', 'name'];
679 680 681 682 683 684 685
                            weight = sectionName.startsWith(keyVal) ? 85 : 82;
                            break;
                        }
                        if(section.filter && section.filter.includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['section', 'filter'];
                            weight = 80;
C
Catouse 已提交
686 687
                            break;
                        }
C
Catouse 已提交
688 689
                        var chapterName = chapter.name.toLowerCase();
                        if(chapterName.includes(keyVal)) {
C
Catouse 已提交
690 691
                            chooseThisKey = true;
                            matchType = ['chapter', 'name'];
692 693 694 695 696 697 698
                            weight = chapterName.startsWith(keyVal) ? 75 : 73;
                            break;
                        }
                        if(chapter.filter && chapter.filter.includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['chapter', 'filter'];
                            weight = 70;
C
Catouse 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
                            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 已提交
747
                }
C
Catouse 已提交
748 749 750
                if(!chooseThisKey) {
                    chooseThis = false;
                    return false;
C
Catouse 已提交
751
                } else {
C
Catouse 已提交
752
                    matches.push({key: key, type: matchType});
C
Catouse 已提交
753
                }
C
Catouse 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
            });

            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 已提交
771
                } else {
C
Catouse 已提交
772 773 774 775 776
                    $show = $show.add($section);
                    if(choosedWeight < result.weight) {
                        $choosed = $section;
                        choosedWeight = result.weight;
                    }
C
Catouse 已提交
777
                }
C
Catouse 已提交
778
                chooseSection($choosed);
C
Catouse 已提交
779
            });
C
Catouse 已提交
780 781 782 783 784 785 786 787

            var $chapter, hide, chapter;
            $.each(chapterMap, function(chapterId, resultCount){
                chapter = chapters[chapterId];
                hide = !resultCount;
                chapter.$.toggleClass('hide', hide);
            });
            var $col;
C
Catouse 已提交
788
            var showColCount = 0;
C
Catouse 已提交
789 790
            $chaptersCols.each(function(){
                $col = $(this);
C
Catouse 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
                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 已提交
806
            });
C
Catouse 已提交
807
            $grid.attr('data-show-col', showColCount);
C
Catouse 已提交
808 809 810

            if($hide.length) {
                $hide.removeClass('in');
C
Catouse 已提交
811
                setTimeout(function(){$hide.removeClass('show');}, 100);
C
Catouse 已提交
812 813 814 815 816
            }
            if($show.length) {
                $show.addClass('show');
                setTimeout(function(){$show.addClass('in');}, 20);
            }
C
Catouse 已提交
817 818

            $window.scrollTop(1);
C
Catouse 已提交
819
            closePage();
C
Catouse 已提交
820 821 822
        } else if(debug) {
            console.error("Query failed with key: ", keys);
        }
C
Catouse 已提交
823 824 825
    };

    var toggleCompactMode = function(toggle, callback) {
C
Catouse 已提交
826 827 828 829
        if(toggle === UNDEFINED) {
            toggle = !$body.hasClass('compact-mode');
        }

C
Catouse 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
        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() {
860
        window['afterPageLoad'] = null;
C
Catouse 已提交
861 862 863 864 865
        window['onPageLoad'] = null;
        if($.isFunction(window['onPageClose'])) {
            window['onPageClose']();
            window['onPageClose'] = null;
        }
C
Catouse 已提交
866
        if($body.hasClass('page-open')) {
C
Catouse 已提交
867
            var style = $page.data('trans-style');
C
Catouse 已提交
868 869 870 871
            if(style){
                style['max-height'] = '';
                $page.css(style);
            }
C
Catouse 已提交
872
            $body.addClass('page-show-out').removeClass('page-open page-show-in');
873

874 875 876 877
            if($queryInput.val() !== '') {
                $queryInput.focus();
            }

878
            window.document.title = documentTitle;
879
            window.location.hash = '#/';
C
Catouse 已提交
880
            setTimeout(function(){
C
Catouse 已提交
881
                $body.removeClass('page-show page-show-out');
C
Catouse 已提交
882
                resetScrollbar();
C
Catouse 已提交
883
            }, 300);
C
Catouse 已提交
884
            return true;
C
Catouse 已提交
885
        }
C
Catouse 已提交
886
        return false;
C
Catouse 已提交
887 888
    };

889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    var showPageTopic = function(topic) {
        $page.removeClass('page-collapsed');
        var valType = typeof topic;
        if(valType === 'undefined') return;
        if(valType === 'string') {
            var num = parseInt(topic);
            if(num !== NaN) {
                valType = 'number';
                topic = num;
            }
        }

        var expandTopic = function($section) {
            if($section && $section.length) {
                togglePageSection(false);
                togglePageSection($section.addClass('hover'), true);
            }
        };

        if(valType === 'number') {
            expandTopic($pageContent.children('section').eq(topic));
        } else if(valType === 'string' && valType.length) {
            // highlight element with the id string.
        }
    };

C
Catouse 已提交
915 916 917 918 919
    var mutePageLoading = function() {
        $page.removeClass('loading');
        $pageLoader.removeClass('loading');
    };

C
Catouse 已提交
920
    var handlePageLoad = function() {
C
Catouse 已提交
921 922 923
        var delayMutedPageLoading = false;
        if($.isFunction(window['onPageLoad'])) {
            delayMutedPageLoading = window['onPageLoad']() === false;
C
Catouse 已提交
924 925
        }

C
Catouse 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
        setTimeout(function(){
            if($.isFunction(window['afterPageLoad'])) {
                if(window['afterPageLoad'](mutePageLoading) === true) {
                    handlePageLoad();
                }
            }

            // pretty code
            var $codes = $pageBody.find('pre');
            if($codes.length && window['prettyPrint']) {
                $codes.addClass('prettyprint');
                window['prettyPrint']();
            }
        }, 1000);

        if(!delayMutedPageLoading) mutePageLoading();
C
Catouse 已提交
942 943
    };

C
Catouse 已提交
944
    var openPage = function($section, section, topic) {
C
Catouse 已提交
945 946 947 948 949
        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 已提交
950
        chooseSection($section, false, true);
C
Catouse 已提交
951

C
Catouse 已提交
952 953 954
        // Send ga data
        var pageUrl = '#' + section.chapter + '/' + section.id;
        if(topic) pageUrl += '/' + topic;
955
        window.document.title = section.chapterName + ' > ' + section.name + ' - ' + documentTitle;
C
Catouse 已提交
956 957 958
        window.location.hash = pageUrl;
        if($.isFunction(ga)) ga('send','pageview', window.location.pathname + pageUrl);

959
        $body.attr('data-page-accent', $section.data('accent')).attr('data-page', pageId);
C
Catouse 已提交
960
        displaySectionIcon($pageHeader.find('.icon'), section);
C
Catouse 已提交
961
        $pageHeader.find('.name').text(section.name).attr('href', pageUrl);
C
Catouse 已提交
962
        $pageHeader.find('.desc').text(section.desc);
C
Catouse 已提交
963
        $pageContent.html('');
C
Catouse 已提交
964 965
        $page.addClass('loading');
        $pageLoader.removeClass('with-error').addClass('loading');
C
Catouse 已提交
966 967
        var lastShowDataCall;
        var pageSh
C
Catouse 已提交
968 969

        loadData(section.url, function(data){
C
Catouse 已提交
970 971 972 973 974 975 976 977 978 979 980 981
            var showData = function(){
                $pageContent.html(data);
                $pageBody.scrollTop(0);
                showPageTopic(topic);
                handlePageLoad();
            }
            if($page.hasClass('openning')) {
                if(lastShowDataCall) clearTimeout(lastShowDataCall);
                lastShowDataCall = setTimeout(showData, 320);
            } else {
                showData();
            }
C
Catouse 已提交
982
        });
C
Catouse 已提交
983

C
Catouse 已提交
984 985 986 987 988 989 990
        if($body.hasClass('page-open')) {
            if(debug) console.log('open section in open page', section);
            return;
        }

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

C
Catouse 已提交
991 992
        toggleCompactMode(true, function(){
            var offset = $section.offset();
C
Catouse 已提交
993 994
            var sectionHeight = $section.outerHeight();
            var style = {
C
Catouse 已提交
995 996
                left: Math.floor(offset.left - $grid.children('.container').offset().left - 5),
                top: Math.floor(offset.top - $window.scrollTop() - 60),
C
Catouse 已提交
997
                width: $section.outerWidth(),
C
Catouse 已提交
998 999 1000
                height: sectionHeight,
                'max-height': sectionHeight
            };
C
Catouse 已提交
1001 1002
            checkScrollbar();
            $body.addClass('page-show');
C
Catouse 已提交
1003 1004
            $page.css(style).data('trans-style', style);
            $pageBody.css('width', bestPageWidth);
1005

C
Catouse 已提交
1006 1007
            setTimeout(function(){
                $body.addClass('page-show-in');
C
Catouse 已提交
1008 1009 1010 1011 1012
                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 已提交
1013
                    resizePage();
C
Catouse 已提交
1014
                }, 300);
C
Catouse 已提交
1015 1016 1017
            }, 10);
        });
    };
C
Catouse 已提交
1018

C
Catouse 已提交
1019
    var openSection = function(section, topic) {
C
Catouse 已提交
1020
        // if(debug) console.log('openSection', section, topic);
C
Catouse 已提交
1021 1022
        section = section || $choosedSection;

C
Catouse 已提交
1023
        var $section;
C
Catouse 已提交
1024
        if($.isArray(section)) {
1025
            if(typeof topic !== 'undefined') section = section.push(topic);
C
Catouse 已提交
1026 1027 1028 1029
            if(!section[0]) {
                if(debug) console.error("Open section failed: can't find the section with id " + section.join('-'));
                return;
            }
1030 1031 1032 1033
            if(section.length > 0 && section[0] === 'search') {
                query(section[1]);
                return;
            }
C
Catouse 已提交
1034
            var docIndex = dataset[INDEX_JSON].data;
C
Catouse 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
            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) {
C
Catouse 已提交
1051
                    if(debug) console.error("Open section failed: can't find the section with id " + section.join('-'));
C
Catouse 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060
                    return;
                }
            } else {
                if(debug) {
                    console.error("Open section stop by null docIndex or wrong section value.");
                }
                return;
            }
        }
C
Catouse 已提交
1061 1062 1063 1064 1065 1066 1067 1068
        if($.isPlainObject(section)) {
            $section = $('#section-' + section.chapter + '-' + section.id);
        } else {
            var $temp = section;
            section = $temp.data('section');
            $section = $temp;
        }

C
Catouse 已提交
1069 1070 1071 1072 1073
        if(section.url === '') {
            $.zui.messager.show('该链接所指示的文档尚未完成。你可以Fork项目来完善文档。');
            return;
        }

1074 1075 1076 1077 1078 1079 1080 1081 1082
        switch(section.target) {
            case 'external':
                window.open(section.url, '_blank');
                break;
            case 'page':
                openPage($section, section, topic);
                break;
            default:
                if(debug) console.error("Open section failed: unknown target.");
C
Catouse 已提交
1083 1084 1085 1086
        }
    };

    var resizePage = function() {
C
Catouse 已提交
1087
        if($body.hasClass('page-show-out') || $page.hasClass('loading')) return;
C
Catouse 已提交
1088 1089 1090 1091 1092 1093 1094
        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 已提交
1095
        $page.css('height', height);
C
Catouse 已提交
1096 1097
    };

C
Catouse 已提交
1098
    var togglePageSection = function($section, toggle) {
1099 1100 1101 1102 1103 1104
        var valType = typeof $section;
        if(valType === 'object') {
            if(typeof toggle === 'undefined') {
                toggle = $section.hasClass('collapsed');
            }
            $section.toggleClass('collapsed', !toggle);
C
Catouse 已提交
1105 1106 1107
            var $setions = $pageContent.children('section');
            var sectionsCount = $setions.length, collapsedSectionCount = $setions.filter('.collapsed').length;
            if(collapsedSectionCount === 0) {
C
Catouse 已提交
1108
                $page.removeClass('page-collapsed');
C
Catouse 已提交
1109
            } else if(collapsedSectionCount === sectionsCount) {
C
Catouse 已提交
1110
                $page.addClass('page-collapsed');
C
Catouse 已提交
1111 1112
            }
        } else {
1113
            toggle = valType === 'boolean' ? $section : $page.hasClass('page-collapsed');
C
Catouse 已提交
1114
            $page.toggleClass('page-collapsed', !toggle);
1115
            if(!toggle) {
C
Catouse 已提交
1116 1117 1118 1119 1120 1121 1122
                $pageContent.children('section').addClass('collapsed');
            } else {
                $pageContent.children('section').removeClass('collapsed');
            }
        }
    };

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    var openPageUrl = function(url) {
        if(url.startsWith('#')) {
            url = url.substr(1);
            setTimeout(function(){
                var params = url.split('/');
                var controllerName = params[0].toLowerCase();
                if(controllerName === 'search' || controllerName === 'query') {
                    query(params[1]);
                } else {
                    openSection(params);
                }
            }, 600);
C
Catouse 已提交
1135
        } else if(isExternalUrl(url)) {
1136
            window.open(url, '_blank');
C
Catouse 已提交
1137 1138
        } else {
            if(debug) console.error('Open page url failed: unknown url', url);
1139 1140 1141
        }
    };

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    var getBuildList = function(pkg, build, lib, list)
    {
        if(!list)
        {
            list = [];
        }
        if(!$.isArray(list))
        {
            list = [list];
        }

        if(build.bundles)
        {
            $.each(build.bundles, function(idx, val)
            {
                if(pkg.builds[val])
                {
                    getBuildList(pkg, pkg.builds[val], lib, list);
                }
                else
                {
                    list = getItemList(lib, [val], list);
                }
            });
        }

        if(build.basicDpds) list = getItemList(lib, build.basicDpds, list);
        list = getItemList(lib, build.includes, list, build.ignoreDpds);

        return list;
    };

    var getItemList  = function(lib, list, items, ignoreDpds, ignoreCombine)
    {
        items = items || [];

        if($.isArray(list))
        {
            $.each(list, function(idx, name)
            {
                getItemList(lib, name, items, ignoreDpds);
            });
        }
        else
        {
            var item = lib[list];
            if(item && items.indexOf(list) < 0)
            {
                if(!ignoreDpds && item.dpds)
                {
                    getItemList(lib, item.dpds, items, ignoreDpds);
                }
                if(item.src || !ignoreCombine) items.push(list);
            }
        }

        return items;
    };

1201 1202
    var loadPackage = function (){
        loadData(PKG_JSON, function(pkg) {
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
            $('.zui-version').text('v' + pkg.version);
            pkgLibs.standard = getBuildList(pkg, pkg.builds.standard, pkg.lib);
            pkgLibs.lite = getBuildList(pkg, pkg.builds.lite, pkg.lib);
            pkgLibs.separate = getBuildList(pkg, pkg.builds.separate, pkg.lib);
        });
    };

    var displayPkgLibTable = function($table) {
        if(!$table.length) return;
        loadData(PKG_JSON, function(data){
            var $tbody = $('<tbody></tbody>');

            var getChildCompsList = function(val){return data.lib[val].name;};
            var $tr, $td;
            for(var itemName in data.lib)
            {
                var item = data.lib[itemName];
                if(item.custom) continue;

                var childComps = '';
                if(!item.src && item.dpds)
                {
                    var childList = getItemList(data.lib, item.dpds, null, true, true);
                    childComps = '合并组件包含:';
                    childComps += $.map(childList, getChildCompsList).join('');
                }

                $tr = $('<tr/>');

                $td = $('<td/>');
                $td.attr('title', item.desc);
                $td.html('<strong>' + item.name + '</strong> (' + itemName + ((item.pver) ? (' v' + item.pver) : '') +')');
                $tr.append($td);

                $.each(pkgLibs, function(idx, sLib)
                {
                    $td = $('<td class="text-center"/>');
                    if(sLib.indexOf(itemName) > -1)
                    {
                        $td.addClass('success').html('<i class="text-success icon-ok"></i>');
                    }
                    else
                    {
                        $td.html('<i class="text-muted icon-remove"></i>');
                    }
                    $tr.append($td);
                });

                $td = $('<td/>');
                $td.html(item.ver ? (' v' + item.ver + '+') : childComps);
                $tr.append($td);

                $tbody.append($tr);
            }
            $table.find('tbody').remove();
            $table.append($tbody);
            $table.datatable({rowHover: false, fixedHeaderOffset: 200});
1260 1261 1262
        });
    };

C
Catouse 已提交
1263
    $(function() {
1264 1265
        documentTitle = window.document.title;

C
Catouse 已提交
1266 1267 1268 1269
        var stopPropagation = function(e) {
            e.stopPropagation();
        }

C
Catouse 已提交
1270 1271
        $window = $(window);
        $body = $('body');
C
Catouse 已提交
1272
        $navbar = $('#navbar');
C
Catouse 已提交
1273 1274
        $grid = $('#grid');
        $header = $('#header');
C
Catouse 已提交
1275
        $chaptersCols = $grid.find('.col');
C
Catouse 已提交
1276 1277
        $page = $('#page');
        $pageHeader = $('#pageHeader');
C
Catouse 已提交
1278
        $pageLoader = $('#pageLoader');
C
Catouse 已提交
1279 1280
        $pageContainer = $('#pageContainer');
        $pageContent = $('#pageContent');
C
Catouse 已提交
1281 1282 1283
        $chapters = $grid.find('.chapter');
        $queryInput = $('#searchInput');
        $chapterHeadings = $grid.find('.chapter-heading');
C
Catouse 已提交
1284
        $sectionTemplate = $('#sectionTemplate').attr('id', null);
C
Catouse 已提交
1285
        $pageBody = $('#pageBody');
C
Catouse 已提交
1286 1287 1288 1289 1290 1291
        $.each(chapters, function(chapterId, chapter){
            chapterId = chapterId.toLowerCase();
            chapter.$ = $('#chapter-' + chapterId);
            chapter.id = chapterId;
            chapter.$sections = $('#sections-' + chapterId);
        });
C
Catouse 已提交
1292

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

C
Catouse 已提交
1295
        $body.toggleClass(PAGE_SHOW_FULL, $.zui.store.get(PAGE_SHOW_FULL, false));
C
Catouse 已提交
1296 1297

        // check storage
C
Catouse 已提交
1298
        storageEnable = $.zui.store && $.zui.store.enable;
C
Catouse 已提交
1299 1300 1301 1302 1303 1304

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

        // Setup ajax
        $.ajaxSetup({cache: false});
1305

C
Catouse 已提交
1306
        // Load index.json
C
Catouse 已提交
1307
        loadData(INDEX_JSON, function(data){
C
Catouse 已提交
1308
            var firstLoad = !sectionsShowed;
1309

C
Catouse 已提交
1310
            displaySection(data);
C
Catouse 已提交
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

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

                var hash = window.location.hash
                if(hash) {
1322
                    openPageUrl(hash);
C
Catouse 已提交
1323 1324 1325
                } else {
                    $queryInput.focus();
                }
1326 1327

                loadPackage();
C
Catouse 已提交
1328 1329
            }
        });
C
Catouse 已提交
1330 1331

        // Bind events
1332
        var oldActivePreivewId;
1333
        var cancelClickInPage;
C
Catouse 已提交
1334
        $(document).on('click', function(e){
1335 1336 1337 1338
            if(cancelClickInPage) {
                cancelClickInPage = false;
                return;
            }
C
Catouse 已提交
1339 1340 1341 1342
            if($body.hasClass('page-show')) {
                closePage();
                return;
            }
C
Catouse 已提交
1343 1344 1345
            if(!$body.attr('data-query')) {
                chooseSection();
            }
1346 1347 1348 1349 1350
        }).on('click', 'a[href^="#"]', function(){
            openPageUrl($(this).attr('href'));
        });
        $page.on('click', function(e){
            cancelClickInPage = true;
C
Catouse 已提交
1351 1352
        });
        $grid.on('click', '.card-heading', function(e) {
C
Catouse 已提交
1353
            var $card = $(this).closest('.card');
C
Catouse 已提交
1354 1355
            if(!$card.hasClass('choosed')) {
                chooseSection($card, true);
C
Catouse 已提交
1356 1357 1358
            } else {
                $card.toggleClass('open');
            }
C
Catouse 已提交
1359
            stopPropagation(e);
1360 1361
        }).on('click', '.chapter-heading > h4 > .name', function(){
            $queryInput.focus().val('@' + $(this).closest('.chapter').data('id')).change();
C
Catouse 已提交
1362
        }).on('click', '.card', function(e){
C
Catouse 已提交
1363
            chooseSection($(this), true);
C
Catouse 已提交
1364 1365
            stopPropagation(e);
        }).on('click', '.card-heading > h5 > .name, .card-heading > .icon', function(e){
C
Catouse 已提交
1366
            openSection($(this).closest('.section'));
C
Catouse 已提交
1367
            stopPropagation(e);
C
Catouse 已提交
1368 1369 1370 1371
        }).on('click', '.topics > li > a', function(e){
            var $a = $(this);
            openPageUrl($a.attr('href'));
            e.preventDefault();
C
Catouse 已提交
1372
            stopPropagation(e);
C
Catouse 已提交
1373 1374 1375 1376
        }).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');
1377 1378 1379 1380 1381 1382 1383 1384 1385
        }).on('mouseenter', '#section-control-icons .section-search > ul > li > a', function(){
            oldActivePreivewId = $('#section-control-icons').data('preview');
            chooseIcon($(this).closest('li'));
        }).on('mouseleave', '#section-control-icons .section-search > ul > li > a', function(){
            if(oldActivePreivewId) {
                chooseIcon($('#control-icons-' + oldActivePreivewId));
            }
        }).on('click', '#section-control-icons .section-search > ul > li > a', function(){
            oldActivePreivewId = $(this).closest('li').data('id');
C
Catouse 已提交
1386 1387
        });

C
Catouse 已提交
1388
        $pageContent.on('click', 'section > header > h3', function(){
C
Catouse 已提交
1389
            togglePageSection($(this).closest('section'));
C
Catouse 已提交
1390 1391 1392 1393 1394
        }).on('mouseenter', 'section > header > h3', function(){
            $(this).closest('section').addClass('hover');
        }).on('mouseleave', 'section > header > h3', function(){
            $(this).closest('section').removeClass('hover');
        });
C
Catouse 已提交
1395
        $page.on('click', '#pageTogger', function(){
C
Catouse 已提交
1396
            togglePageSection();
C
Catouse 已提交
1397 1398
        });

C
Catouse 已提交
1399 1400 1401
        $pageContent.on('resize', resizePage);
        $window.resize(resizePage);

C
Catouse 已提交
1402 1403
        $pageHeader.on('click', '.path-close-btn', function(){
            closePage();
C
Catouse 已提交
1404 1405
        }).on('click', '.path-max-btn', function(){
            $body.toggleClass(PAGE_SHOW_FULL);
C
Catouse 已提交
1406
            setTimeout(resizePage, 300);
C
Catouse 已提交
1407
            $.zui.store.set(PAGE_SHOW_FULL, $body.hasClass(PAGE_SHOW_FULL));
C
Catouse 已提交
1408 1409
        });

C
Catouse 已提交
1410 1411 1412
        var scrollHeight = $('#navbar').outerHeight();
        var lastScrollTop;
        $window.on('scroll', function(e){
C
Catouse 已提交
1413
            var isScrollAnimating = $body.data('isScrollAnimating');
C
Catouse 已提交
1414
            if(isScrollAnimating) {
C
Catouse 已提交
1415
                $window.scrollTop(1);
C
Catouse 已提交
1416
                return;
C
Catouse 已提交
1417 1418 1419
            }
            lastScrollTop = $window.scrollTop();
            if(lastScrollTop > scrollHeight && !$body.hasClass('compact-mode')) {
C
Catouse 已提交
1420
                toggleCompactMode(true);
C
Catouse 已提交
1421
            } else if(!$body.hasClass('page-show') && $body.hasClass('compact-mode')) {
C
Catouse 已提交
1422
                if(lastScrollTop < 1) {
C
Catouse 已提交
1423
                    toggleCompactMode(false);
C
Catouse 已提交
1424 1425 1426 1427
                } else {
                    $header.toggleClass('with-shadow', lastScrollTop > 20);
                }
            }
C
Catouse 已提交
1428 1429
        }).on('keydown', function(e){
            var code = e.which;
C
Catouse 已提交
1430
            // console.log('keydown', code);
C
Catouse 已提交
1431
            var isPageNotShow = !$body.hasClass('page-show');
C
Catouse 已提交
1432
            var isInputFocus = $body.hasClass('input-query-focus');
1433 1434 1435 1436 1437 1438
            if(code === 9) { // Tab
                if(!$body.hasClass('input-query-focus')) {
                    $queryInput.focus();
                    e.preventDefault();
                }
            } else if(code === 13) { // Enter
C
Catouse 已提交
1439 1440
                if(isPageNotShow && isChoosedSection()) {
                    openSection();
C
Catouse 已提交
1441 1442 1443
                }
            } else if(code === 27) { // Esc
                if(!closePage()) {
C
Catouse 已提交
1444
                    if(!isInputFocus) {
1445
                        $queryInput.focus();
C
Catouse 已提交
1446
                    }
1447
                    lastQueryString = '';
1448
                    query();
C
Catouse 已提交
1449
                }
C
Catouse 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
            // } else if(code === 32) { // Space
            //     if(!isInputFocus){
            //         if(closePage()) {
            //         } else if(!$body.hasClass('compact-mode')) {
            //             toggleCompactMode(true);
            //         } else if(isChoosedSection()) {
            //             openSection();
            //         }
            //         e.preventDefault();
            //     }
C
Catouse 已提交
1460
            } else if(code === 37) { // Left
C
Catouse 已提交
1461
                // if(!$body.hasClass('input-query-focus')){
1462 1463
                    chooseLeftSection();
                    e.preventDefault();
C
Catouse 已提交
1464
                // }
C
Catouse 已提交
1465
            } else if(code === 39) { // Right
C
Catouse 已提交
1466
                // if(!$body.hasClass('input-query-focus')){
1467 1468
                    chooseRightSection();
                    e.preventDefault();
C
Catouse 已提交
1469
                // }
C
Catouse 已提交
1470
            } else if(code === 38) { // Top
C
Catouse 已提交
1471 1472
                if(isPageNotShow) {
                    choosePrevSection();
C
Catouse 已提交
1473
                    e.preventDefault();
C
Catouse 已提交
1474 1475 1476
                } else {
                    scrollToThis($pageBody, 'up');
                }
C
Catouse 已提交
1477
            } else if(code === 40) { // Down
C
Catouse 已提交
1478 1479
                if(isPageNotShow) {
                    chooseNextSection();
C
Catouse 已提交
1480
                    e.preventDefault();
C
Catouse 已提交
1481 1482 1483
                } else {
                    scrollToThis($pageBody);
                }
C
Catouse 已提交
1484 1485 1486 1487 1488 1489
                e.preventDefault();
            }
        });

        $pageBody.on('scroll', function(e){
            $page.toggleClass('with-shadow', $pageBody.scrollTop() > 20);
C
Catouse 已提交
1490
        });
C
Catouse 已提交
1491

1492
        $search = $('#search');
1493

1494
        $queryInput.focus().on('change keyup paste input propertychange', function(){
C
Catouse 已提交
1495
            var val = $queryInput.val();
C
Catouse 已提交
1496 1497 1498
            if(val === lastQueryString) return;
            lastQueryString = val;
            $search.toggleClass('with-query-text', val.length > 0);
C
Catouse 已提交
1499 1500
            clearTimeout($queryInput.data(LAST_QUERY_ID));
            $queryInput.data(LAST_QUERY_ID, setTimeout(function(){
C
Catouse 已提交
1501 1502
                if(lastQueryString === $queryInput.data('queryString')) return;
                query(lastQueryString);
C
Catouse 已提交
1503
            }, 150));
C
Catouse 已提交
1504 1505 1506 1507 1508 1509 1510 1511
        }).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 已提交
1512

C
Catouse 已提交
1513 1514
        $('#searchHelpBtn').on('click', function(e){
            if($search.hasClass('with-query-text')) {
1515
                lastQueryString = '';
C
Catouse 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
                query();
                $queryInput.focus();
                $search.removeClass('with-query-text');
            } else {
                // query('#help');
                openSection(['resource', 'help']);
                $(this).blur();
            }
            stopPropagation(e);
        });

C
Catouse 已提交
1527
        $('[data-toggle="tooltip"]').tooltip({container: 'body'});
C
Catouse 已提交
1528
    });
1529 1530 1531 1532

    $.doc = {
        query: query,
        openSection: openSection,
C
Catouse 已提交
1533
        closePage: closePage,
C
Catouse 已提交
1534
        loadData: loadData,
1535 1536
        mutePageLoading: mutePageLoading,
        displayPkgLibTable: displayPkgLibTable
1537
    };
C
Catouse 已提交
1538
}(window, jQuery));